问:
Query for references of a stored procedure in MS SQL Server
I need to search for the references of all stored procedures in an undocumented database. Some of the links are broken so something like the below will throw errors

```<code>SELECT
    DB_NAME()       AS REFERENCING_DB,
    t.SCHEMA_NAME   AS REFERENCING_SCHEMA,
    t.OBJECT_NAME   AS REFERENCING_OBJECT,
    t.type_desc     AS REFERENCING_TYPE_DESC,
    --,'' AS SEPERATOR1
    CASE
       WHEN ISNULL(ref.referenced_database_name, DB_NAME()) = ''
          THEN '?'
          ELSE ISNULL(ref.referenced_database_name, DB_NAME())
    END AS [REFERENCED_DB],
    ref.referenced_schema_name  AS REFERENCED_SCHEMA,
    ref.referenced_entity_name  AS REFERENCED_OBJECT,
    ref.referenced_minor_name   AS REFERENCED_MINOR_OBJECT,
    obj.type_desc               AS REFERENCED_TYPE_DESC,
    ref.referenced_class_desc   AS REFERENCED_CLASS_DESC,
    ref.is_caller_dependent     AS REFERENCED_IS_CALLER_DEPENDENT
FROM
    (SELECT
         o.name AS OBJECT_NAME, o.TYPE_DESC, s.name AS SCHEMA_NAME
     FROM
         sys.objects o
     LEFT JOIN
         sys.schemas s on o.schema_id = s.schema_id
    ) t
CROSS APPLY
    sys.dm_sql_referenced_entities('[' + t.SCHEMA_NAME + '].[' + t.OBJECT_NAME + ']', 'OBJECT') ref
LEFT JOIN
    sys.objects obj ON ref.referenced_id = obj.object_id
</code>```

Error:

Msg 942, Level 14, State 4, Line 231

  Database 'BlahBlahBlah' cannot be opened because it is offline.

Any help getting around this or ideas for tools to search dependencies in SQL Server would be great to know!

答:
Current work around for quickly finding dependencies...</p>

```<code>------------------------------------------------------------------
--because of the possibility of an object in this database reference a broken link... we have to batch through each object we wish to lookup it's references...
------------------------------------------------------------------
SET NOCOUNT ON;

if OBJECT_ID('tempdb..#ReferencingLookup') is not null
    drop table #ReferencingLookup;
CREATE TABLE tempdb..#ReferencingLookup(
    [REFERENCING_DB]                    [nvarchar](1000) NULL,
    [REFERENCING_SCHEMA]                [nvarchar](1000) NULL,
    [REFERENCING_OBJECT]                [nvarchar](1000) NULL,
    [REFERENCING_TYPE_DESC]             [nvarchar](1000) NULL,
    [REFERENCED_DB]                     [nvarchar](1000) NULL,
    [REFERENCED_SCHEMA]                 [nvarchar](1000) NULL,
    [REFERENCED_OBJECT]                 [nvarchar](1000) NULL,
    [REFERENCED_MINOR_OBJECT]           [nvarchar](1000) NULL,
    [REFERENCED_TYPE_DESC]              [nvarchar](1000) NULL,
    [REFERENCED_CLASS_DESC]             [nvarchar](1000) NULL,
    [REFERENCED_IS_CALLER_DEPENDENT]    [bit] NOT NULL
) ON [PRIMARY]

DECLARE @REFERENCING_SCHEMA varchar(1000), @REFERENCING_OBJECT varchar(1000), @REFERENCING_TYPE_DESC nvarchar(1000);

DECLARE referencing_cursor CURSOR FOR
select  distinct REFERENCING_SCHEMA,REFERENCING_OBJECT,REFERENCING_TYPE_DESC
from
(
    select
        t.SCHEMA_NAME       as REFERENCING_SCHEMA
        ,t.OBJECT_NAME      as REFERENCING_OBJECT
        ,t.type_desc        as REFERENCING_TYPE_DESC
    FROM
    (
        select o.name as OBJECT_NAME,o.TYPE_DESC,s.name as SCHEMA_NAME
        from sys.objects        o
        left join sys.schemas   s   on  o.schema_id =   s.schema_id

    )   t
)   a

OPEN referencing_cursor

FETCH NEXT FROM referencing_cursor
INTO @REFERENCING_SCHEMA, @REFERENCING_OBJECT, @REFERENCING_TYPE_DESC

declare @ref_type as varchar(1000) = 'OBJECT'

WHILE @@FETCH_STATUS = 0
BEGIN

        declare @concat_refs as varchar(1000) = '[' + @REFERENCING_SCHEMA + '].[' + @REFERENCING_OBJECT + ']'

        begin try

            print @concat_refs

            insert into #ReferencingLookup
            select
             DB_NAME()          as REFERENCING_DB
            ,t.SCHEMA_NAME      as REFERENCING_SCHEMA
            ,t.OBJECT_NAME      as REFERENCING_OBJECT
            ,t.type_desc        as REFERENCING_TYPE_DESC

            --,'' as SEPERATOR1

            ,case when isnull(ref.referenced_database_name,DB_NAME()) = '' then '?' else isnull(ref.referenced_database_name,DB_NAME()) end     as [REFERENCED_DB]
            ,ref.referenced_schema_name         as REFERENCED_SCHEMA
            ,ref.referenced_entity_name         as REFERENCED_OBJECT
            ,ref.referenced_minor_name          as REFERENCED_MINOR_OBJECT

            ,obj.type_desc                      as REFERENCED_TYPE_DESC
            ,ref.referenced_class_desc          as REFERENCED_CLASS_DESC
            ,ref.is_caller_dependent            as REFERENCED_IS_CALLER_DEPENDENT

            FROM
            (
                select o.name as OBJECT_NAME,o.TYPE_DESC,s.name as SCHEMA_NAME
                from sys.objects        o
                left join sys.schemas   s   on  o.schema_id =   s.schema_id
                where s.name = @REFERENCING_SCHEMA and o.name = @REFERENCING_OBJECT
            )                                                                                t
            cross apply sys.dm_sql_referenced_entities(@concat_refs, @ref_type)     ref
            left join sys.objects                                                                               obj on  ref.referenced_id   =   obj.object_id

        end try
        begin catch
            select ERROR_MESSAGE();
        end catch

        FETCH NEXT FROM referencing_cursor
        INTO @REFERENCING_SCHEMA, @REFERENCING_OBJECT, @REFERENCING_TYPE_DESC

END
CLOSE referencing_cursor;
DEALLOCATE referencing_cursor;

------------------------------------------------------------------
------------------------------------------------------------------

--peak a boo at the results...

select *
,'[' + REFERENCED_DB  +'].[' + REFERENCED_SCHEMA + '].[' + REFERENCED_OBJECT + ']' as REFERENCED_OBJECT_FULLY_SPECIFIED
from #ReferencingLookup
</code>```

Body:
I need to search for the references of all stored procedures in an undocumented database. Some of the links are broken so something like the below will throw errors

SELECT
    DB_NAME()       AS REFERENCING_DB,
    t.SCHEMA_NAME   AS REFERENCING_SCHEMA,
    t.OBJECT_NAME   AS REFERENCING_OBJECT,
    t.type_desc     AS REFERENCING_TYPE_DESC,
    --,'' AS SEPERATOR1
    CASE
       WHEN ISNULL(ref.referenced_database_name, DB_NAME()) = ''
          THEN '?'
          ELSE ISNULL(ref.referenced_database_name, DB_NAME())
    END AS [REFERENCED_DB],
    ref.referenced_schema_name  AS REFERENCED_SCHEMA,
    ref.referenced_entity_name  AS REFERENCED_OBJECT,
    ref.referenced_minor_name   AS REFERENCED_MINOR_OBJECT,
    obj.type_desc               AS REFERENCED_TYPE_DESC,
    ref.referenced_class_desc   AS REFERENCED_CLASS_DESC,
    ref.is_caller_dependent     AS REFERENCED_IS_CALLER_DEPENDENT
FROM
    (SELECT
         o.name AS OBJECT_NAME, o.TYPE_DESC, s.name AS SCHEMA_NAME
     FROM
         sys.objects o
     LEFT JOIN
         sys.schemas s on o.schema_id = s.schema_id
    ) t
CROSS APPLY
    sys.dm_sql_referenced_entities('[' + t.SCHEMA_NAME + '].[' + t.OBJECT_NAME + ']', 'OBJECT') ref
LEFT JOIN
    sys.objects obj ON ref.referenced_id = obj.object_id

Error:

Msg 942, Level 14, State 4, Line 231

  Database 'BlahBlahBlah' cannot be opened because it is offline.

Any help getting around this or ideas for tools to search dependencies in SQL Server would be great to know!

Body:
Current work around for quickly finding dependencies...

------------------------------------------------------------------
--because of the possibility of an object in this database reference a broken link... we have to batch through each object we wish to lookup it's references...
------------------------------------------------------------------
SET NOCOUNT ON;

if OBJECT_ID('tempdb..#ReferencingLookup') is not null
    drop table #ReferencingLookup;
CREATE TABLE tempdb..#ReferencingLookup(
    [REFERENCING_DB]                    [nvarchar](1000) NULL,
    [REFERENCING_SCHEMA]                [nvarchar](1000) NULL,
    [REFERENCING_OBJECT]                [nvarchar](1000) NULL,
    [REFERENCING_TYPE_DESC]             [nvarchar](1000) NULL,
    [REFERENCED_DB]                     [nvarchar](1000) NULL,
    [REFERENCED_SCHEMA]                 [nvarchar](1000) NULL,
    [REFERENCED_OBJECT]                 [nvarchar](1000) NULL,
    [REFERENCED_MINOR_OBJECT]           [nvarchar](1000) NULL,
    [REFERENCED_TYPE_DESC]              [nvarchar](1000) NULL,
    [REFERENCED_CLASS_DESC]             [nvarchar](1000) NULL,
    [REFERENCED_IS_CALLER_DEPENDENT]    [bit] NOT NULL
) ON [PRIMARY]

DECLARE @REFERENCING_SCHEMA varchar(1000), @REFERENCING_OBJECT varchar(1000), @REFERENCING_TYPE_DESC nvarchar(1000);

DECLARE referencing_cursor CURSOR FOR
select  distinct REFERENCING_SCHEMA,REFERENCING_OBJECT,REFERENCING_TYPE_DESC
from
(
    select
        t.SCHEMA_NAME       as REFERENCING_SCHEMA
        ,t.OBJECT_NAME      as REFERENCING_OBJECT
        ,t.type_desc        as REFERENCING_TYPE_DESC
    FROM
    (
        select o.name as OBJECT_NAME,o.TYPE_DESC,s.name as SCHEMA_NAME
        from sys.objects        o
        left join sys.schemas   s   on  o.schema_id =   s.schema_id

    )   t
)   a

OPEN referencing_cursor

FETCH NEXT FROM referencing_cursor
INTO @REFERENCING_SCHEMA, @REFERENCING_OBJECT, @REFERENCING_TYPE_DESC

declare @ref_type as varchar(1000) = 'OBJECT'

WHILE @@FETCH_STATUS = 0
BEGIN

        declare @concat_refs as varchar(1000) = '[' + @REFERENCING_SCHEMA + '].[' + @REFERENCING_OBJECT + ']'

        begin try

            print @concat_refs

            insert into #ReferencingLookup
            select
             DB_NAME()          as REFERENCING_DB
            ,t.SCHEMA_NAME      as REFERENCING_SCHEMA
            ,t.OBJECT_NAME      as REFERENCING_OBJECT
            ,t.type_desc        as REFERENCING_TYPE_DESC

            --,'' as SEPERATOR1

            ,case when isnull(ref.referenced_database_name,DB_NAME()) = '' then '?' else isnull(ref.referenced_database_name,DB_NAME()) end     as [REFERENCED_DB]
            ,ref.referenced_schema_name         as REFERENCED_SCHEMA
            ,ref.referenced_entity_name         as REFERENCED_OBJECT
            ,ref.referenced_minor_name          as REFERENCED_MINOR_OBJECT

            ,obj.type_desc                      as REFERENCED_TYPE_DESC
            ,ref.referenced_class_desc          as REFERENCED_CLASS_DESC
            ,ref.is_caller_dependent            as REFERENCED_IS_CALLER_DEPENDENT

            FROM
            (
                select o.name as OBJECT_NAME,o.TYPE_DESC,s.name as SCHEMA_NAME
                from sys.objects        o
                left join sys.schemas   s   on  o.schema_id =   s.schema_id
                where s.name = @REFERENCING_SCHEMA and o.name = @REFERENCING_OBJECT
            )                                                                                t
            cross apply sys.dm_sql_referenced_entities(@concat_refs, @ref_type)     ref
            left join sys.objects                                                                               obj on  ref.referenced_id   =   obj.object_id

        end try
        begin catch
            select ERROR_MESSAGE();
        end catch

        FETCH NEXT FROM referencing_cursor
        INTO @REFERENCING_SCHEMA, @REFERENCING_OBJECT, @REFERENCING_TYPE_DESC

END
CLOSE referencing_cursor;
DEALLOCATE referencing_cursor;

------------------------------------------------------------------
------------------------------------------------------------------

--peak a boo at the results...

select *
,'[' + REFERENCED_DB  +'].[' + REFERENCED_SCHEMA + '].[' + REFERENCED_OBJECT + ']' as REFERENCED_OBJECT_FULLY_SPECIFIED
from #ReferencingLookup


来源: stackexchange

问:
Can I have a reference to a nested bean in Spring?
I want to have a bean of type com.a.A which has several addressable properties of type com.a.B.

```<code><bean id="myCompound" class="com.a.A">
    <property name="first">
        <bean class="com.a.B"/> <!-- Anything else needed here? -->
    </property>
     <property name="second">
        <bean class="com.a.B"/> <!-- Anything else needed here? -->
    </property>
</code>```

In addressable I mean, that I would like to be able to have a reference to either one of these nested beans, from another bean:

```<code><bean id="myCollaborator" class="com.a.C">
    <property name="target" ref="myCompound.first"/>
</bean>
</code>```

This structure doesn't work, and it seems to me that Spring does not resolve compound properties in <ref> elements. Is that so? Can someone think of a way to work around this?

答:
Here's a simple workaround.</p>

```<code><bean id="firstB" class="com.a.B"/>
<bean id="secondB" class="com.a.B"/>

<bean id="myCompound" class="com.a.A">
    <property name="first" ref="firstB"/>
    <property name="second" ref="secondB"/>
</bean>

<bean id="myCollaborator" class="com.a.C">
    <property name="target" ref="firstB"/>
</bean>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to have a bean of type com.a.A which has several addressable properties of type com.a.B.

<bean id="myCompound" class="com.a.A">
    <property name="first">
        <bean class="com.a.B"/>
    </property>
     <property name="second">
        <bean class="com.a.B"/>
    </property>

In addressable I mean, that I would like to be able to have a reference to either one of these nested beans, from another bean:

<bean id="myCollaborator" class="com.a.C">
    <property name="target" ref="myCompound.first"/>
</bean>

This structure doesn't work, and it seems to me that Spring does not resolve compound properties in <ref> elements. Is that so? Can someone think of a way to work around this?

Body:
Here's a simple workaround.

<bean id="firstB" class="com.a.B"/>
<bean id="secondB" class="com.a.B"/>

<bean id="myCompound" class="com.a.A">
    <property name="first" ref="firstB"/>
    <property name="second" ref="secondB"/>
</bean>

<bean id="myCollaborator" class="com.a.C">
    <property name="target" ref="firstB"/>
</bean>


问:
SAS Proc Report page break for columns
I'm hoping someone would be able to help me with this problem. I am trying to make a report using proc report with ods pdf. The problem is when I use the page option with the intention of displaying the columns to the right on a new page, they appear right below the columns on the left on the same page instead of on a new page. Here is a sample code:

```<code>filename _pdf_ "&path.\_&sysdate9..pdf";
 ods pdf file=_pdf_ newfile=none startpage=no style=styles.Profile pdftoc=1 bookmarkgen/*notoc*//*Defined in Step 1 above*/;
ods pdf startpage=now;

proc report data=sashelp.cars(obs=10);
  column make model type origin drivetrain msrp invoice enginesize;
  define make/display style(column)=[width=4cm asis=on just=l] style(hdr)=[asis=on just=l];
    define model /display style(column)=[width=4cm asis=on just=l] style(hdr)=[asis=on just=l];
    define type / display style(column)=[width=8cm asis=on just=l] style(hdr)=[asis=on just=l];
    define origin / display style(column)=[width=5cm asis=on just=c] style(hdr)=[asis=on just=l];
    define drivetrain/display page style(column)=[width=4cm asis=on just=l] style(hdr)=[asis=on just=l];
    define msrp /display style(column)=[width=4cm asis=on just=l] style(hdr)=[asis=on just=l];
    define invoice / display style(column)=[width=8cm asis=on just=l] style(hdr)=[asis=on just=l];
    define enginesize / display style(column)=[width=5cm asis=on just=c] style(hdr)=[asis=on just=l];
 run;

ods pdf close;
</code>```

My output is:

The idea is to display drivetrain, msrp, invoice and engine size on a new page. I'm using sas 9.4. I have read the documentation in case I'm missing some option but can't seem to figure it out. Would appreciate any help.

答:
Couple of things:

update the startpage=no to yes

Adjust the width for type, origin, invoice, enginesize variables.. I set it to 4 and it ran fine

ContentLicense: CC BY-SA 4.0

Title: SAS Proc Report page break for columns

Body:
I'm hoping someone would be able to help me with this problem. I am trying to make a report using proc report with ods pdf. The problem is when I use the page option with the intention of displaying the columns to the right on a new page, they appear right below the columns on the left on the same page instead of on a new page. Here is a sample code:

filename _pdf_ "&path.\_&sysdate9..pdf";
 ods pdf file=_pdf_ newfile=none startpage=no style=styles.Profile pdftoc=1 bookmarkgen/*notoc*//*Defined in Step 1 above*/;
ods pdf startpage=now;

proc report data=sashelp.cars(obs=10);
  column make model type origin drivetrain msrp invoice enginesize;
  define make/display style(column)=[width=4cm asis=on just=l] style(hdr)=[asis=on just=l];
    define model /display style(column)=[width=4cm asis=on just=l] style(hdr)=[asis=on just=l];
    define type / display style(column)=[width=8cm asis=on just=l] style(hdr)=[asis=on just=l];
    define origin / display style(column)=[width=5cm asis=on just=c] style(hdr)=[asis=on just=l];
    define drivetrain/display page style(column)=[width=4cm asis=on just=l] style(hdr)=[asis=on just=l];
    define msrp /display style(column)=[width=4cm asis=on just=l] style(hdr)=[asis=on just=l];
    define invoice / display style(column)=[width=8cm asis=on just=l] style(hdr)=[asis=on just=l];
    define enginesize / display style(column)=[width=5cm asis=on just=c] style(hdr)=[asis=on just=l];
 run;

ods pdf close;

My output is:

The idea is to display drivetrain, msrp, invoice and engine size on a new page. I'm using sas 9.4. I have read the documentation in case I'm missing some option but can't seem to figure it out. Would appreciate any help.


问:
How to give active class to clicked button in Yii2
I am a new member in Yii2. I integrated new template with by default Yii2 advanced template. I need to use active class to clicked menu from side bar. Below my code. How can I do it? Please help me</p>

```<code><li class="">
   <?= Html::a('<i class="glyphicon glyphicon-education"></i><span>Суд жараёни</span>', ['law1/']) ?>
</li>
<li class="">
   <?= Html::a('<i class="glyphicon glyphicon-check"></i><span>МИБ</span>', ['law2/']) ?>
</li>
<li class="">
   <?= Html::a('<i class="glyphicon glyphicon-ruble"></i><span>Прократура</span>', ['law3/']) ?>
</li>
<li class="">
   <?= Html::a('<i class="glyphicon glyphicon-bitcoin"></i><span>Банк</span>', ['law4/']) ?>
</li>
</code>```

答:
Some Simple Approaches

You can compare the controller/route/action to the URL and if they match add an active class with a yii2 helper:

Simple add class to html link:

```<code><?php
use yii\helpers\Html;
$controller =  Yii::$app->controller->id;
$options = ['class' => ['btn btn-md btn-default']];
if ($controller == 'batch') {
    Html::addCssClass($options, ['active']);
}
echo $link = Html::a('SomeLink', ['batch/view'], $options);
echo $link = Html::a('SomeLink', ['batch/view'],);
?>
</code>```

If using a nav widget, you can leverage the active and visible properties:

```<code><?php
use mdm\admin\components\Helper;
$controller =  Yii::$app->controller->id;
echo kartik\sidenav\SideNav::widget([
    'type' => SideNav::TYPE_DEFAULT,
    'items' => [
        [
            'url' => ['supplier/index'],
            'label' => 'Suppliers',
            //'icon' => 'th-list',
            'active' => $controller == 'supplier',
            'visible' => Helper::checkRoute('supplier/index'),
        ],
        [
            'url' => ['site/index'],
            'label' => 'Sites',
            //'icon' => 'th-list',
            'active' => $controller == 'site',
            'visible' => Helper::checkRoute('site/index'),
        ],
    ],
]);
?>
</code>```

Body:
I am a new member in Yii2. I integrated new template with by default Yii2 advanced template. I need to use active class to clicked menu from side bar. Below my code. How can I do it? Please help me

   <?= Html::a('Суд жараёни', ['law1/']) ?>

   <?= Html::a('МИБ', ['law2/']) ?>

   <?= Html::a('Прократура', ['law3/']) ?>

   <?= Html::a('Банк', ['law4/']) ?>

Body:
Some Simple Approaches

You can compare the controller/route/action to the URL and if they match add an active class with a yii2 helper:

Simple add class to html link:

<?php
use yii\helpers\Html;
$controller =  Yii::$app->controller->id;
$options = ['class' => ['btn btn-md btn-default']];
if ($controller == 'batch') {
    Html::addCssClass($options, ['active']);
}
echo $link = Html::a('SomeLink', ['batch/view'], $options);
echo $link = Html::a('SomeLink', ['batch/view'],);
?>

If using a nav widget, you can leverage the active and visible properties:

<?php
use mdm\admin\components\Helper;
$controller =  Yii::$app->controller->id;
echo kartik\sidenav\SideNav::widget([
    'type' => SideNav::TYPE_DEFAULT,
    'items' => [
        [
            'url' => ['supplier/index'],
            'label' => 'Suppliers',
            //'icon' => 'th-list',
            'active' => $controller == 'supplier',
            'visible' => Helper::checkRoute('supplier/index'),
        ],
        [
            'url' => ['site/index'],
            'label' => 'Sites',
            //'icon' => 'th-list',
            'active' => $controller == 'site',
            'visible' => Helper::checkRoute('site/index'),
        ],
    ],
]);
?>


问:
Is there an R function that will rank dates/times by other column criteria?
I am interested in changing the date column in dataf into ordered numbers (earliest date=1, second earliest=2... and so on) corresponding to id as in results$order. If an id only shows up once, I would like the order to be 1.

```<code>date=c("2012-02-18", "2013-03-01", "2013-04-11", "2013-06-06", "2013-09-20", "2013-07-02")
datef=strptime(date, format="%Y-%m-%d")
dataf=data.frame(id=c(20, 20, 20, 21, 21, 22),
              date=datef,
              service=c("web", "phone", "person", "phone", "web", "web"))
> dataf
  id       date service
1 20 2012-02-18     web
2 20 2013-03-01   phone
3 20 2013-04-11  person
4 21 2013-06-06   phone
5 21 2013-09-20     web
6 22 2013-07-02     web
</code>```

I am having a hard time even finding the correct wording to search for an answer to this dilemma. Am I looking to coerce? or index? the dataf$dates  into results$order below?

```<code>results=data.frame(id=c(20, 20, 20, 21, 21, 22),
                   order=c(1,2,3,1,2,1),
                   service=c("web", "phone", "person", "phone", "web", "web"))

> results
  id order service
1 20     1     web
2 20     2   phone
3 20     3  person
4 21     1   phone
5 21     2     web
6 22     1     web
</code>```

Body:
I am interested in changing the date column in dataf into ordered numbers (earliest date=1, second earliest=2... and so on) corresponding to id as in results$order. If an id only shows up once, I would like the order to be 1.

date=c("2012-02-18", "2013-03-01", "2013-04-11", "2013-06-06", "2013-09-20", "2013-07-02")
datef=strptime(date, format="%Y-%m-%d")
dataf=data.frame(id=c(20, 20, 20, 21, 21, 22),
              date=datef,
              service=c("web", "phone", "person", "phone", "web", "web"))
> dataf
  id       date service
1 20 2012-02-18     web
2 20 2013-03-01   phone
3 20 2013-04-11  person
4 21 2013-06-06   phone
5 21 2013-09-20     web
6 22 2013-07-02     web

I am having a hard time even finding the correct wording to search for an answer to this dilemma. Am I looking to coerce? or index? the dataf$dates  into results$order below?

results=data.frame(id=c(20, 20, 20, 21, 21, 22),
                   order=c(1,2,3,1,2,1),
                   service=c("web", "phone", "person", "phone", "web", "web"))

> results
  id order service
1 20     1     web
2 20     2   phone
3 20     3  person
4 21     1   phone
5 21     2     web
6 22     1     web

Body:
With dplyr:

library(dplyr)
dataf %>% group_by(id) %>% mutate(order = rank(date))
# # A tibble: 6 x 4
# # Groups:   id [3]
#      id date                service order
#   <dbl> <dttm>              <fct>   <dbl>
# 1    20 2012-02-18 00:00:00 web         1
# 2    20 2013-03-01 00:00:00 phone       2
# 3    20 2013-04-11 00:00:00 person      3
# 4    21 2013-06-06 00:00:00 phone       1
# 5    21 2013-09-20 00:00:00 web         2
# 6    22 2013-07-02 00:00:00 web         1


问:
python __init__ method in inherited class
I would like to give a daughter class some extra attributes without having to explicitly call a new method. So is there a way of giving the inherited class an __init__ type method which does not override the __init__ method of the parent class?

I have written the code below purely to illustrate my question (hence the poor naming of attributes etc).

```<code>class initialclass():
    def __init__(self):
        self.attr1 = 'one'
        self.attr2 = 'two'

class inheritedclass(initialclass):
    def __new__(self):
        self.attr3 = 'three'

    def somemethod(self):
        print 'the method'

a = inheritedclass()

for each in a.__dict__:
    print each

#I would like the output to be:
attr1
attr2
attr3
</code>```

Thank you

答:
Just call a designated method from the parent's init, if it exists:</p>

```<code>class initialclass():
    def __init__(self):
        self.attr1 = 'one'
        self.attr2 = 'two'
        if hasattr(self, 'init_subclass'):
            self.init_subclass()

class inheritedclass(initialclass):
    def init_subclass(self):
        self.attr3 = 'three'
</code>```

Body:
I would like to give a daughter class some extra attributes without having to explicitly call a new method. So is there a way of giving the inherited class an __init__ type method which does not override the __init__ method of the parent class?

I have written the code below purely to illustrate my question (hence the poor naming of attributes etc).

class initialclass():
    def __init__(self):
        self.attr1 = 'one'
        self.attr2 = 'two'

class inheritedclass(initialclass):
    def __new__(self):
        self.attr3 = 'three'

    def somemethod(self):
        print 'the method'

a = inheritedclass()

for each in a.__dict__:
    print each

#I would like the output to be:
attr1
attr2
attr3

Thank you

Body:
Just call a designated method from the parent's init, if it exists:

class initialclass():
    def __init__(self):
        self.attr1 = 'one'
        self.attr2 = 'two'
        if hasattr(self, 'init_subclass'):
            self.init_subclass()

class inheritedclass(initialclass):
    def init_subclass(self):
        self.attr3 = 'three'


问:
Adding Amazon IP to Cpanel
I want to add a new IP address to Cpanel. I allocated a new address on Amazon, and attached it to the server. Then from whm > IP Functions > Add a New IP Address: I typed the private IP, selected the subnet 255.255.255.255 and added it. But when I open Show or Delete Current IP Addresses, I get the error: Not Routable.

This is a screenshot of Cpanel
https://ibb.co/BgGqJD1

答: You have to use the EC2 instance's public IP address. The private one can't be routed to from outside the instance. You have to make a public IP first though, as EC2 instances are not given one by default.</p>

Title: Adding Amazon IP to Cpanel


问:
remove items at multiple indexes in an array
code below removes only the first item in the array with color property set to "black"

```<code>struct car {
    let model: String
    let color: String
}

var myCars :[car] = [
    car(name:"model X", color: "black"),
    car(name:"model Y", color: "blue"),
    car(name:"roadster", color: "red"),
    car(name:"model S", color: "black"),
    car(name:"model 3", color: "black")
]

let delList = myCars.index(where: {$0.color == "black"})
myCars.remove(at: delList)
</code>```

i want delete all the items in the array with the color property set to "black"

答:
You can try</p>

```<code>print("Before: \(myCars)")
myCars.removeAll(where: {$0.color == "black"})
print("After: \(myCars)")
</code>```

Body:
code below removes only the first item in the array with color property set to "black"

struct car {
    let model: String
    let color: String
}

var myCars :[car] = [
    car(name:"model X", color: "black"),
    car(name:"model Y", color: "blue"),
    car(name:"roadster", color: "red"),
    car(name:"model S", color: "black"),
    car(name:"model 3", color: "black")
]

let delList = myCars.index(where: {$0.color == "black"})
myCars.remove(at: delList)

i want delete all the items in the array with the color property set to "black"

Body:
You can try

print("Before: \(myCars)")
myCars.removeAll(where: {$0.color == "black"})
print("After: \(myCars)")


问:
How to process multidimensional array from jQuery Sortable (nested list)?
I'm working with jQuery Sortable to create some block of codes with nested list ( for loop and function block), then I got this json string use JSON.stringify on console.log(jsonString):

```<code>{
  "codes": [
    [
      {
        "id": "code_run",
        "code": "run",
        "name": "code_when_run"
      },
      {
        "id": "",
        "code": "loop",
        "name": "code_block_repeat",
        "children": [
          [
            {
              "id": "",
              "code": "up",
              "name": "code_arrow_up"
            },
            {
              "id": "",
              "code": "up",
              "name": "code_arrow_up"
            }
          ]
        ]
      }
    ]
  ]
}
</code>```

Here's my code from the jQuery sortable's example :

```<code>let oldContainer, codeBlockId, codeBlockItem;

$("ol.nest_workspace").sortable({
    group: 'nested',
    onDragStart: function ($item, container, _super) {
    // Duplicate items of the no drop area
    if(!container.options.drop)
      $item.clone().insertAfter($item);
    _super($item, container);
  },
    afterMove: function (placeholder, container) {

        if(oldContainer != container){
            if(oldContainer)
                oldContainer.el.removeClass("active");
            container.el.addClass("active");

            oldContainer = container;
        }
    },
    onDrop: function ($item, container, _super) {
        container.el.removeClass("active");

        $item.addClass("block_code_on_workspace");

        var data = group.sortable("serialize").get();

    var jsonString = JSON.stringify({"codes":data}, null, '\t');
        console.log(jsonString);
        _super($item, container);

    },

});
</code>```

How can I process the sub array (children[]) ?

I have plan to make it all block as a real codes, so it could execute with another function.

I may expect the text output printed some function like moveUp(), or if its loop with some function inside, then would be like :

```<code>for (var i = 0; i < 3; i++) {
  moveUp();
}
</code>```

Any help or suggest would be great, thanks!

答:
I've found a solution for my problem, here's the code :

```<code>$("ol.nest_workspace").sortable({
    group: 'nested',
    onDragStart: function ($item, container, _super) {
    // Duplicate items of the no drop area
    if(!container.options.drop)
      $item.clone().insertAfter($item);
            if($item.hasClass('RepeatCode')){
                $item.attr('id','block_loop_function_drag');
            }
    _super($item, container);
  },
    afterMove: function (placeholder, container) {

        if(oldContainer != container){
            if(oldContainer)
                oldContainer.el.removeClass("active");
            container.el.addClass("active");

            oldContainer = container;
        }
    },
    onDrop: function ($item, container, _super) {
        $(".coding-script").empty();
        container.el.removeClass("active");

        $item.addClass("block_code_on_workspace");
        $hasID = document.getElementById('block_loop_function_drag');

        var data = group.sortable("serialize").get();
        // console.log(data);

        for(var i = 0; i < data[0].length; i++){

            if($hasID){
                $item.attr('id','block_loop_function_'+i+'');
            }

            var obj = data[0][i];
            if(obj.hasOwnProperty("children")){

                var objChildren = obj.children[0];

                console.log(obj.code +'-'+i);
                ConvertToCodeScripts(obj.code, i);

                for(var j = 0; j < objChildren.length; j++){
                    console.log('loop-'+i+'-'+objChildren[j].code);
                    ConvertToCodeScripts('loop-'+i+'-'+objChildren[j].code, i);
                }

            }
            else{
                console.log(obj.code);
                ConvertToCodeScripts(obj.code, i);
            }
            console.log('lha - '+i);
        }
        _super($item, container);

    },
});
</code>```

But let me know if you guys have a better solution.

Cheers

Body:
I'm working with jQuery Sortable to create some block of codes with nested list ( for loop and function block), then I got this json string use JSON.stringify on console.log(jsonString):

{
  "codes": [
    [
      {
        "id": "code_run",
        "code": "run",
        "name": "code_when_run"
      },
      {
        "id": "",
        "code": "loop",
        "name": "code_block_repeat",
        "children": [
          [
            {
              "id": "",
              "code": "up",
              "name": "code_arrow_up"
            },
            {
              "id": "",
              "code": "up",
              "name": "code_arrow_up"
            }
          ]
        ]
      }
    ]
  ]
}

Here's my code from the jQuery sortable's example :

let oldContainer, codeBlockId, codeBlockItem;

$("ol.nest_workspace").sortable({
    group: 'nested',
    onDragStart: function ($item, container, _super) {
    // Duplicate items of the no drop area
    if(!container.options.drop)
      $item.clone().insertAfter($item);
    _super($item, container);
  },
    afterMove: function (placeholder, container) {

        if(oldContainer != container){
            if(oldContainer)
                oldContainer.el.removeClass("active");
            container.el.addClass("active");

            oldContainer = container;
        }
    },
    onDrop: function ($item, container, _super) {
        container.el.removeClass("active");

        $item.addClass("block_code_on_workspace");

        var data = group.sortable("serialize").get();

    var jsonString = JSON.stringify({"codes":data}, null, '\t');
        console.log(jsonString);
        _super($item, container);

    },

});

How can I process the sub array (children[]) ?

I have plan to make it all block as a real codes, so it could execute with another function.

I may expect the text output printed some function like moveUp(), or if its loop with some function inside, then would be like :

for (var i = 0; i < 3; i++) {
  moveUp();
}

Any help or suggest would be great, thanks!

Body:
I've found a solution for my problem, here's the code :

$("ol.nest_workspace").sortable({
    group: 'nested',
    onDragStart: function ($item, container, _super) {
    // Duplicate items of the no drop area
    if(!container.options.drop)
      $item.clone().insertAfter($item);
            if($item.hasClass('RepeatCode')){
                $item.attr('id','block_loop_function_drag');
            }
    _super($item, container);
  },
    afterMove: function (placeholder, container) {

        if(oldContainer != container){
            if(oldContainer)
                oldContainer.el.removeClass("active");
            container.el.addClass("active");

            oldContainer = container;
        }
    },
    onDrop: function ($item, container, _super) {
        $(".coding-script").empty();
        container.el.removeClass("active");

        $item.addClass("block_code_on_workspace");
        $hasID = document.getElementById('block_loop_function_drag');

        var data = group.sortable("serialize").get();
        // console.log(data);

        for(var i = 0; i < data[0].length; i++){

            if($hasID){
                $item.attr('id','block_loop_function_'+i+'');
            }

            var obj = data[0][i];
            if(obj.hasOwnProperty("children")){

                var objChildren = obj.children[0];

                console.log(obj.code +'-'+i);
                ConvertToCodeScripts(obj.code, i);

                for(var j = 0; j < objChildren.length; j++){
                    console.log('loop-'+i+'-'+objChildren[j].code);
                    ConvertToCodeScripts('loop-'+i+'-'+objChildren[j].code, i);
                }

            }
            else{
                console.log(obj.code);
                ConvertToCodeScripts(obj.code, i);
            }
            console.log('lha - '+i);
        }
        _super($item, container);

    },
});

But let me know if you guys have a better solution.

Cheers


问:
How does UpSampling2D layer work in Keras?
How does the UpSampling2D layer work in Keras? According to official documentation:

Repeats the rows and columns of the data by size[0] and size[1] respectively.

So, if size=(2, 2), how does it repeat the rows and columns of the input matrix? Could you please explain the procedure with an example?

答:
If

Repeats the rows and columns of the data by size[0] and size[1] respectively.

does not help, then maybe an example would be helpful:

```<code>>>> import numpy as np
>>> from keras.layers import UpSampling2D
>>> from keras.models import Sequential
>>> model = Sequential()
>>> model.add(UpSampling2D(size=(2,2), input_shape=(3,3,1)))

>>> x = np.arange(9).reshape(1,3,3,1)
>>> x[0,:,:,0]  # this is what x looks like initially
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> y = model.predict(x)
>>> y[0,:,:,0] # this is what it looks like after upsampling
array([[0., 0., 1., 1., 2., 2.],
       [0., 0., 1., 1., 2., 2.],
       [3., 3., 4., 4., 5., 5.],
       [3., 3., 4., 4., 5., 5.],
       [6., 6., 7., 7., 8., 8.],
       [6., 6., 7., 7., 8., 8.]], dtype=float32)
</code>```

Body:
If

Repeats the rows and columns of the data by size[0] and size[1] respectively.

does not help, then maybe an example would be helpful:

>>> import numpy as np
>>> from keras.layers import UpSampling2D
>>> from keras.models import Sequential
>>> model = Sequential()
>>> model.add(UpSampling2D(size=(2,2), input_shape=(3,3,1)))

>>> x = np.arange(9).reshape(1,3,3,1)
>>> x[0,:,:,0]  # this is what x looks like initially
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> y = model.predict(x)
>>> y[0,:,:,0] # this is what it looks like after upsampling
array([[0., 0., 1., 1., 2., 2.],
       [0., 0., 1., 1., 2., 2.],
       [3., 3., 4., 4., 5., 5.],
       [3., 3., 4., 4., 5., 5.],
       [6., 6., 7., 7., 8., 8.],
       [6., 6., 7., 7., 8., 8.]], dtype=float32)


问:
Why it's impossible to do in-object collision detection?
Is there a particular reason why Apple would choose to only allow collision detection through the world, rather than allowing individual objects to detect when they collide with other things? This seems like a horrible design choice, but since I haven't found much complaining I'm guessing there is something I'm missing. So, is there?</p>

答:
Some great comments here and not sure why either.  They base the whole thing on nodes and names of nodes - seems like it could be better as looking things up after the fact is slower.  Here is how I handled it, similar to what others are saying.

Since I have a bunch of missiles, I just name the node = "Missi" + String(format: "%04d", vIndex), name = "Explo" + String(format: "%04d", vIndex), etc., that way I can prefix what I'm looking for and go directly to my array of nodes and do my thing.  I have hundreds of things going, but the collision function is pretty small.

```<code>func physicsWorld(_ world: SCNPhysicsWorld, didBegin contact: SCNPhysicsContact)
    {
        guard let nodeNameA = contact.nodeA.name else { return }
        guard let nodeNameB = contact.nodeB.name else { return }

        //print("CONTACT: \(nodeNameA) \(nodeNameB)")
        if(nodeNameA.prefix(5) == "Explo" && nodeNameB.prefix(5) == "Enemy")
        {
            gameControl.defenseMissileHit(vIndex: Int(nodeNameB.suffix(4))!)
        }
        if(nodeNameA.prefix(5) == "Enemy" && nodeNameB.prefix(5) == "Explo")
        {
            gameControl.defenseMissileHit(vIndex: Int(nodeNameA.suffix(4))!)
        }

        if(nodeNameA.prefix(5) == "Explo" && nodeNameB.prefix(5) == "Missi")
        {
            //print("HIT")
            gameControl.enemyMissileHit(vIndex: Int(nodeNameB.suffix(4))!)
        }
        if(nodeNameA.prefix(5) == "Missi" && nodeNameB.prefix(5) == "Explo")
        {
            //print("HIT")
            gameControl.enemyMissileHit(vIndex: Int(nodeNameA.suffix(4))!)
        }
    }
</code>```

I don't subclass nodes, I create classes such as DefenseObject with the stuff I want, then create an array that I can directly access or loop through.

```<code>var defenseObjects:                     [Int:DefenseObject] = [:]

class DefenseObject: ObjectBase
{
    var index: Int = 0                              // Index of object
    var name: String = ""                           // Object name
    var isActive: Bool = false                      // Object is active
    init(vGameType: gameTypes, vCount: Int, position: SCNVector3)
    {
        super.init(vGameType: vGameType, vIndex: vCount)
        isActive = true
        name = "Enemy" + String(format: "%04d", vIndex)
    }
}
</code>```

Then I can go right to the index and do defenseObjects[NDex].call().  I also don't try to cleanup the nodes during a wave, I set an isActive switch and hide them.  At the end of the wave, I clean 'em up.

Hope that helps.

Body:
Some great comments here and not sure why either.  They base the whole thing on nodes and names of nodes - seems like it could be better as looking things up after the fact is slower.  Here is how I handled it, similar to what others are saying.

Since I have a bunch of missiles, I just name the node = "Missi" + String(format: "%04d", vIndex), name = "Explo" + String(format: "%04d", vIndex), etc., that way I can prefix what I'm looking for and go directly to my array of nodes and do my thing.  I have hundreds of things going, but the collision function is pretty small.

func physicsWorld(_ world: SCNPhysicsWorld, didBegin contact: SCNPhysicsContact)
    {
        guard let nodeNameA = contact.nodeA.name else { return }
        guard let nodeNameB = contact.nodeB.name else { return }

        //print("CONTACT: \(nodeNameA) \(nodeNameB)")
        if(nodeNameA.prefix(5) == "Explo" && nodeNameB.prefix(5) == "Enemy")
        {
            gameControl.defenseMissileHit(vIndex: Int(nodeNameB.suffix(4))!)
        }
        if(nodeNameA.prefix(5) == "Enemy" && nodeNameB.prefix(5) == "Explo")
        {
            gameControl.defenseMissileHit(vIndex: Int(nodeNameA.suffix(4))!)
        }

        if(nodeNameA.prefix(5) == "Explo" && nodeNameB.prefix(5) == "Missi")
        {
            //print("HIT")
            gameControl.enemyMissileHit(vIndex: Int(nodeNameB.suffix(4))!)
        }
        if(nodeNameA.prefix(5) == "Missi" && nodeNameB.prefix(5) == "Explo")
        {
            //print("HIT")
            gameControl.enemyMissileHit(vIndex: Int(nodeNameA.suffix(4))!)
        }
    }

I don't subclass nodes, I create classes such as DefenseObject with the stuff I want, then create an array that I can directly access or loop through.

var defenseObjects:                     [Int:DefenseObject] = [:]

class DefenseObject: ObjectBase
{
    var index: Int = 0                              // Index of object
    var name: String = ""                           // Object name
    var isActive: Bool = false                      // Object is active
    init(vGameType: gameTypes, vCount: Int, position: SCNVector3)
    {
        super.init(vGameType: vGameType, vIndex: vCount)
        isActive = true
        name = "Enemy" + String(format: "%04d", vIndex)
    }
}

Then I can go right to the index and do defenseObjects[NDex].call().  I also don't try to cleanup the nodes during a wave, I set an isActive switch and hide them.  At the end of the wave, I clean 'em up.

Hope that helps.


问:
If a var in JavaScript is defined twice, which definition should the interpreter take?
I'm new to JavaScript and am trying to understand the concepts of hoisting and scope.

Case 1

var name;

function logName(num) {
  console.log(name, num);
}

logName(1);
name = "Auro";
logName(2);```
</div>
</div>
</p>

<p>and I have the following output in the console</p>

```Auro 1
Auro 2
```

<p>If I understand <code>hoisting</code> correctly, JS engine hoists the declaration of a variable first and then automatically assigns a value <code>undefined</code> to it. Only when it encounters the assignment (<code>=</code>) operator, does it actually assign the intended value to it.</p>

<p>If my understanding above is correct, then the first time the <code>logName</code> function was called, the variable <code>name</code> should have printed undefined, but it is printing the value.</p>

<p><strong>Case 2</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var name;

function logName(num) {
  console.log(name, num);
}

logName(1);
name = "Auro";
logName(2);
name = "Baner";</code>```

Output in the console:

```<code>Baner 1
Auro 2
</code>```

This confuses me even more. Here the first call to the function logName picked the later assignment to the variable and printed Baner, however, the second call picked the previous assignment, that is Auro.

What is going on here? What am I missing?

答:
As addition to other answers I can say, that just not use var but use ES6  let or const instead and 'surprising behaviour' will disappear.

let name;

function logName(num) {
  console.log(name, num);
}

logName(1);
name = "Auro";
logName(2);
name = "Baner";```

Body:
I'm new to JavaScript and am trying to understand the concepts of hoisting and scope.

Case 1

var name;

function logName(num) {
  console.log(name, num);
}

logName(1);
name = "Auro";
logName(2);

and I have the following output in the console

Auro 1
Auro 2

If I understand hoisting correctly, JS engine hoists the declaration of a variable first and then automatically assigns a value undefined to it. Only when it encounters the assignment (=) operator, does it actually assign the intended value to it.

If my understanding above is correct, then the first time the logName function was called, the variable name should have printed undefined, but it is printing the value.

Case 2

var name;

function logName(num) {
  console.log(name, num);
}

logName(1);
name = "Auro";
logName(2);
name = "Baner";

Output in the console:

Baner 1
Auro 2

This confuses me even more. Here the first call to the function logName picked the later assignment to the variable and printed Baner, however, the second call picked the previous assignment, that is Auro.

What is going on here? What am I missing?


问:
How do I remove border bottom of input field?
Can anyone tell me how do I remove border-bottom of the input field when I start writing?

.car-list-input {
  font-family: 'Source Sans Pro', sans-serif;
  border-radius: 3px;
  font-size: 14px;
  font-weight: 400 !important;
  height: 35px;
  position: relative;
  border-left: 2px solid #e0e6e8;
  border-right: 2px solid #e0e6e8;
  border-top: 2px solid #e0e6e8;
  border-bottom: 0px;
}

.car-list-input:focus {
  border-color: #25c16f;
  outline: 0;
  box-shadow: none;
  border-bottom: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" placeholder="Enter the location of your vehicle" id="location" onchange="locationApproved()" autocomplete="off" class="form-control car-list-input"></code>```

答:
I'm not sure if you mean padding or margin. Here are two examples:

margin-bottom:

https://jsfiddle.net/q049negk/

.car-list-input {
  font-family: 'Source Sans Pro', sans-serif;
  border-radius: 3px;
  font-size: 14px;
  font-weight: 400 !important;
  height: 35px;
  position: relative;
  border-left: 2px solid #e0e6e8;
  border-right: 2px solid #e0e6e8;
  border-top: 2px solid #e0e6e8;
  border-bottom: 0px;
  margin-bottom: 50px;
}

.car-list-input:focus {
  border-color: #25c16f;
  outline: 0;
  box-shadow: none;
  border-bottom: solid 2px #25c16f;
  margin-bottom: 0px;
}

.square {
  height: 60px;
  width: 60px;
  background: red;
  margin: 0;
  padding: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" placeholder="Enter the location of your vehicle" id="location" onchange="locationApproved()" autocomplete="off" class="form-control car-list-input">
<div class="square">
</div></code>```

padding-bottom:

https://jsfiddle.net/q049negk/1/

.car-list-input {
  font-family: 'Source Sans Pro', sans-serif;
  border-radius: 3px;
  font-size: 14px;
  font-weight: 400 !important;
  height: 35px;
  position: relative;
  border-left: 2px solid #e0e6e8;
  border-right: 2px solid #e0e6e8;
  border-top: 2px solid #e0e6e8;
  border-bottom: 0px;
  padding-bottom: 50px;
}

.car-list-input:focus {
  border-color: #25c16f;
  outline: 0;
  box-shadow: none;
  border-bottom: solid 2px #25c16f;
  padding-bottom: 0px;
}

.square {
  height: 60px;
  width: 60px;
  background: red;
  margin: 0;
  padding: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" placeholder="Enter the location of your vehicle" id="location" onchange="locationApproved()" autocomplete="off" class="form-control car-list-input">
<div class="square">
</div></code>```

Here are MDN links for both:

margin-bottom

padding-bottom

Body:
Can anyone tell me how do I remove border-bottom of the input field when I start writing?

.car-list-input {
  font-family: 'Source Sans Pro', sans-serif;
  border-radius: 3px;
  font-size: 14px;
  font-weight: 400 !important;
  height: 35px;
  position: relative;
  border-left: 2px solid #e0e6e8;
  border-right: 2px solid #e0e6e8;
  border-top: 2px solid #e0e6e8;
  border-bottom: 0px;
}

.car-list-input:focus {
  border-color: #25c16f;
  outline: 0;
  box-shadow: none;
  border-bottom: 0px;
}

<input type="text" placeholder="Enter the location of your vehicle" id="location" onchange="locationApproved()" autocomplete="off" class="form-control car-list-input">

Body:
I'm not sure if you mean padding or margin. Here are two examples:

margin-bottom:

https://jsfiddle.net/q049negk/

.car-list-input {
  font-family: 'Source Sans Pro', sans-serif;
  border-radius: 3px;
  font-size: 14px;
  font-weight: 400 !important;
  height: 35px;
  position: relative;
  border-left: 2px solid #e0e6e8;
  border-right: 2px solid #e0e6e8;
  border-top: 2px solid #e0e6e8;
  border-bottom: 0px;
  margin-bottom: 50px;
}

.car-list-input:focus {
  border-color: #25c16f;
  outline: 0;
  box-shadow: none;
  border-bottom: solid 2px #25c16f;
  margin-bottom: 0px;
}

.square {
  height: 60px;
  width: 60px;
  background: red;
  margin: 0;
  padding: 0;
}

<input type="text" placeholder="Enter the location of your vehicle" id="location" onchange="locationApproved()" autocomplete="off" class="form-control car-list-input">
<div class="square">
</div>

padding-bottom:

https://jsfiddle.net/q049negk/1/

.car-list-input {
  font-family: 'Source Sans Pro', sans-serif;
  border-radius: 3px;
  font-size: 14px;
  font-weight: 400 !important;
  height: 35px;
  position: relative;
  border-left: 2px solid #e0e6e8;
  border-right: 2px solid #e0e6e8;
  border-top: 2px solid #e0e6e8;
  border-bottom: 0px;
  padding-bottom: 50px;
}

.car-list-input:focus {
  border-color: #25c16f;
  outline: 0;
  box-shadow: none;
  border-bottom: solid 2px #25c16f;
  padding-bottom: 0px;
}

.square {
  height: 60px;
  width: 60px;
  background: red;
  margin: 0;
  padding: 0;
}

<input type="text" placeholder="Enter the location of your vehicle" id="location" onchange="locationApproved()" autocomplete="off" class="form-control car-list-input">
<div class="square">
</div>

Here are MDN links for both:

margin-bottom

padding-bottom


问:
SQL ZOO List each continent and the name of the country that comes first alphabetically
Im confused why it could not be

```<code>Select x.continent, x.name
From world x
Where x.name <= ALL (select y.name from world y where x.name=y.name)
ORDER BY name
</code>```

Can anyone please explain to me why it has to be x.continent=y.continent and not x.name=y.name ?

Table

答:
```<code> select A.continent, A.name
 from
 (Select  x.continent, x.name, RANK() OVER(PARTITION BY x.continent ORDER BY x.name
 asc)AS Rank
 From world x
 group by  x.continent, x.name)A
 where
 Rank = 1
</code>```

Body:
Im confused why it could not be

Select x.continent, x.name
From world x
Where x.name <= ALL (select y.name from world y where x.name=y.name)
ORDER BY name

Can anyone please explain to me why it has to be x.continent=y.continent and not x.name=y.name ?

Table


问:
Reassign Pandas DataFrame column values
I have a csv that has incorrect datetime formatting. I've worked out how to convert those values into the format I need, but now I need to reassign all the values in a column to the new, converted values.

For example, I'm hoping that there's something I can put into the following FOR loop that will insert the values back into the dataframe at the correct location:

```<code>for i in df[df.columns[1]]:
    t = pd.Timestamp(i)
    short_date = t.date().strftime('%m/%d/%Y').lstrip('0')
    # Insert back into dataframe?
</code>```

As always, your help is very much appreciated!

Part of the column in question:
Part of the dataframe in question:

```<code>Created Date
2019-02-27 22:55:16
2019-01-29 22:57:12
2018-11-29 00:13:31
2019-01-30 21:35:15
2018-12-20 21:14:45
2018-11-01 16:20:15
2019-04-11 16:38:07
2019-01-24 00:23:17
2018-12-21 19:30:10
2018-12-19 22:33:04
2018-11-07 19:54:19
2019-05-10 21:15:00
</code>```

答:
To reassign a column, no need for a loop.  Something like this should work:

```<code>df["column"] = new_column
</code>```

new_column is either a Series of matching length, or something that can be broadcasted1 to that length.  You can find more details in the docs.

That said, if pd.Timestamp can already parse your data, there is no need for "formatting".  The formatting is not associated with a timestamp instance.  You can choose a particular formatting when you are converting to string with something like df["timestamp"].dt.strftime("%m/%d/%Y").

On the other hand, if you want to change the precision of your timestamp, you can do something like this:

```<code>df["timestamp"] = df["timestamp"].astype("datetime64[D]")
</code>```

Here, all time information will be rounded to a resolution of days.  The letter between the [ and ] is the resolution.  Again, all this and more is discussed in the docs.

1 Broadcasting is a concept from numpy where you can operate between different but compatibly shaped arrays.  Again, everything is covered in the docs.

Title: Reassign Pandas DataFrame column values

Body:
I have a csv that has incorrect datetime formatting. I've worked out how to convert those values into the format I need, but now I need to reassign all the values in a column to the new, converted values.

For example, I'm hoping that there's something I can put into the following FOR loop that will insert the values back into the dataframe at the correct location:

for i in df[df.columns[1]]:
    t = pd.Timestamp(i)
    short_date = t.date().strftime('%m/%d/%Y').lstrip('0')
    # Insert back into dataframe?

As always, your help is very much appreciated!

Part of the column in question:
Part of the dataframe in question:

Created Date
2019-02-27 22:55:16
2019-01-29 22:57:12
2018-11-29 00:13:31
2019-01-30 21:35:15
2018-12-20 21:14:45
2018-11-01 16:20:15
2019-04-11 16:38:07
2019-01-24 00:23:17
2018-12-21 19:30:10
2018-12-19 22:33:04
2018-11-07 19:54:19
2019-05-10 21:15:00

Body:
To reassign a column, no need for a loop.  Something like this should work:

df["column"] = new_column

new_column is either a Series of matching length, or something that can be broadcasted1 to that length.  You can find more details in the docs.

That said, if pd.Timestamp can already parse your data, there is no need for "formatting".  The formatting is not associated with a timestamp instance.  You can choose a particular formatting when you are converting to string with something like df["timestamp"].dt.strftime("%m/%d/%Y").

On the other hand, if you want to change the precision of your timestamp, you can do something like this:

df["timestamp"] = df["timestamp"].astype("datetime64[D]")

Here, all time information will be rounded to a resolution of days.  The letter between the [ and ] is the resolution.  Again, all this and more is discussed in the docs.

1 Broadcasting is a concept from numpy where you can operate between different but compatibly shaped arrays.  Again, everything is covered in the docs.


问:
Array of greater elements
I'd like to create a method that recieves an array and a value to compare. It should return the numbers which are greater than the value compared in the form of an array.

For instance, greaterThan([3, 4, 5, 6], 4]) should return [5, 6] and greaterThan([3, 4, 5, 6], 5]) should return [6].

Since the length of the result array is dynamic, I've incremented the size each time it finds a larger element.

```<code>static String greaterThan(int[] vectorCompare, int valueCompare)
{
    Arrays.sort(vectorCompare);         // make it faster

    int size = 0;

    int[] result = new int[size];

    for (int value : vectorCompare)
    {
        if (valueCompare < value)
        {
            size++;
        }
    }

    int[] resultCopy = Arrays.copyOf(result, size);

    // what to do next?

    return Arrays.toString(resultCopy);

}
</code>```

Any tips for me? I thought of using ArrayList but I'm kinda stuck.

答:
You don't need to sort it, just collect the elements in a list and call toString on the contents. You can sort the list of collected values afterwards if the order is important.

    static String greaterThan(int[] vector, int compare) {
        List<Integer> greater = new ArrayList<>();

        for (int i : vector) {
            if (i > compare) {
                 greater.add(i);
            }
        }

        return greater.toString();
    }
```

Title: Array of greater elements

Body:
I'd like to create a method that recieves an array and a value to compare. It should return the numbers which are greater than the value compared in the form of an array.

For instance, greaterThan([3, 4, 5, 6], 4]) should return [5, 6] and greaterThan([3, 4, 5, 6], 5]) should return [6].

Since the length of the result array is dynamic, I've incremented the size each time it finds a larger element.

static String greaterThan(int[] vectorCompare, int valueCompare)
{
    Arrays.sort(vectorCompare);         // make it faster

    int size = 0;

    int[] result = new int[size];

    for (int value : vectorCompare)
    {
        if (valueCompare < value)
        {
            size++;
        }
    }

    int[] resultCopy = Arrays.copyOf(result, size);

    // what to do next?

    return Arrays.toString(resultCopy);

}

Any tips for me? I thought of using ArrayList but I'm kinda stuck.


问:
How do create a variable length array in C in Visual Studio 2010 enviroment?
I want to create a variable length array for my code in the Visual Studio 2010 environment.

I had tried the code using the array of length x, as it is passing by the user. But I am facing the error as:

"error C2466:cannot allocate an array of constant size 0" ,"error C2133: 'v_X_array' : unknown size".

```<code>func1(int x)
{
    int v_X_array[x];
    int i;
    for (i=0; i<x; i++)
    {
        v_X_array[i] = i;
    }
}
</code>```

I expect the answer as v_X_array[0] = 0, v_X_array[1] =1, v_X_array[2]=2 ... v_X_array[10]=10 ; for x = 10;

How can I do this?

Note: as calloc and malloc should not be used.

答:
You can't allocate an array of an unknown size.
So you need to allocate it dynamically "at run-time".
you can make this allocation using "new" in C++ or "malloc" in C.

For example:

In C++ if you want to allocate an array of an unknown size you should do the following:

```<code>int* v_X_array = new int[x];
int i;
for (i=0; i<x; i++)
{
    v_X_array[i] = i;
}
</code>```

The reason that we use integer pointer is that "new" returns the base address of the array "the address of the first element", so the only thing that can store addresses is pointers.

In C if you want to allocate an array of an unknown size you should do the following:

```<code>    int* v_X_array = (int*) malloc(x*sizeof(int));
    int i;
    for(i=0; i<x; i++)
    {
        v_X_array[i] = i;
    }
</code>```

The malloc function takes a single argument which specifies the number of bytes to be allocated and returns a void pointer so the casting (int*) is required.

For more explanations, look at the next section:

If we need to allocate an array of 20 integers it could be as follow: "malloc(20*sizeof(int))" where 20 is the number of allocated elements and sizeof(int) is the size of the type you want to allocate. If successful it returns a pointer to memory allocated. If it fails, it returns a null pointer.

Enter image description here

Body:
I want to create a variable length array for my code in the Visual Studio 2010 environment.

I had tried the code using the array of length x, as it is passing by the user. But I am facing the error as:

"error C2466:cannot allocate an array of constant size 0" ,"error C2133: 'v_X_array' : unknown size".

func1(int x)
{
    int v_X_array[x];
    int i;
    for (i=0; i<x; i++)
    {
        v_X_array[i] = i;
    }
}

I expect the answer as v_X_array[0] = 0, v_X_array[1] =1, v_X_array[2]=2 ... v_X_array[10]=10 ; for x = 10;

How can I do this?

Note: as calloc and malloc should not be used.

Body:
You can't allocate an array of an unknown size.
So you need to allocate it dynamically "at run-time".
you can make this allocation using "new" in C++ or "malloc" in C.

For example:

In C++ if you want to allocate an array of an unknown size you should do the following:

int* v_X_array = new int[x];
int i;
for (i=0; i<x; i++)
{
    v_X_array[i] = i;
}

The reason that we use integer pointer is that "new" returns the base address of the array "the address of the first element", so the only thing that can store addresses is pointers.

In C if you want to allocate an array of an unknown size you should do the following:

    int* v_X_array = (int*) malloc(x*sizeof(int));
    int i;
    for(i=0; i<x; i++)
    {
        v_X_array[i] = i;
    }

The malloc function takes a single argument which specifies the number of bytes to be allocated and returns a void pointer so the casting (int*) is required.

For more explanations, look at the next section:

If we need to allocate an array of 20 integers it could be as follow: "malloc(20*sizeof(int))" where 20 is the number of allocated elements and sizeof(int) is the size of the type you want to allocate. If successful it returns a pointer to memory allocated. If it fails, it returns a null pointer.

Enter image description here


问:
UITableVIew Fails To render UITableViewCell Currectly
When I am going to populate my tableView with different states one state act wrong, I'm sure that it cause by delay of tableView. please see video and picture first.

I populating my UITableView like:

```<code>func tableView(_ tableView: UITableView,
              cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellId")
    cell.state = myStates[indexPath.row]
}
</code>```

on my UITableViewCell:

```<code>var state: MyCustomDesignState? {
    didSet {
        self.button.set(state: self.state)
    }
}
</code>```

on my UIButton:

```<code>func set(state: MyCustomDesignState?) {
    switch state {
    case ...
    case .blackBack:
        self.backgroundColor = background
        self.setTitleColor(textColor, for: .normal)
        self.frame = CGRect.init(x: 40, y: 190 - 40, width: 180, height: 34)
        self.dropFlatShadow(color: #colorLiteral(red: 0.1008123383, green: 0.1008369699, blue: 0.1008091196, alpha: 1))
        self.clipsToBounds = true
        self.layer.cornerRadius = 5
    }
}
</code>```

this is what I want, and what I did get:

how my tableView looks like:

video to bug:

https://streamable.com/ki7vx

答:
If you have designed your cell in Storyboard, using leading and trailing constraints, those constraints will be "re-laid-out" by auto-layout.

So, using this line:

```<code>self.frame = CGRect.init(x: 40, y: 190 - 40, width: 180, height: 34)
</code>```

will only affect the frame until the next auto-layout pass -- such as when you scroll the tableView.

You probably only want to give the button a Leading constraint. If you want it wider than the text - that is, padding on the left and right - give your button Content Inset values.

Body:
When I am going to populate my tableView with different states one state act wrong, I'm sure that it cause by delay of tableView. please see video and picture first.

I populating my UITableView like:

func tableView(_ tableView: UITableView,
              cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellId")
    cell.state = myStates[indexPath.row]
}

on my UITableViewCell:

var state: MyCustomDesignState? {
    didSet {
        self.button.set(state: self.state)
    }
}

on my UIButton:

func set(state: MyCustomDesignState?) {
    switch state {
    case ...
    case .blackBack:
        self.backgroundColor = background
        self.setTitleColor(textColor, for: .normal)
        self.frame = CGRect.init(x: 40, y: 190 - 40, width: 180, height: 34)
        self.dropFlatShadow(color: #colorLiteral(red: 0.1008123383, green: 0.1008369699, blue: 0.1008091196, alpha: 1))
        self.clipsToBounds = true
        self.layer.cornerRadius = 5
    }
}

this is what I want, and what I did get:

how my tableView looks like:

video to bug:

https://streamable.com/ki7vx

Body:
If you have designed your cell in Storyboard, using leading and trailing constraints, those constraints will be "re-laid-out" by auto-layout.

So, using this line:

self.frame = CGRect.init(x: 40, y: 190 - 40, width: 180, height: 34)

will only affect the frame until the next auto-layout pass -- such as when you scroll the tableView.

You probably only want to give the button a Leading constraint. If you want it wider than the text - that is, padding on the left and right - give your button Content Inset values.


问:
Variable 'sql_mode' can't be set to the value of 'NO_AUTO_CREATE_USER'
I am using MySQL Workbench 8.0. I am trying to dump test data to DB including all the tables, stored procedures and views with data.

When I try to import it's says import finished with one error and the error is

Variable 'sql_mode' can't be set to the value of 'NO_AUTO_CREATE_USER'
  Operation failed with exitcode 1

Also after importing if I check the database, only tables have come but there are no stored procedures at all.

How would one fix this?

答: I found a workaround, if not the solution. Use Linux to get the sed utility, and run the two sed commands as mentioned in my previous comment. Also, I needed to use the mysqldump option: <code>--set-gtid-purged=OFF</code> </p>

Body: I found a workaround, if not the solution. Use Linux to get the sed utility, and run the two sed commands as mentioned in my previous comment. Also, I needed to use the mysqldump option: --set-gtid-purged=OFF


问:
Can I set target VM in azure powershell when adding inbound nat rule?
In an azure RM load-balancer I can create a nat rule FTP using powershell, but would also like to set the target virtual machine using powershell. The only way I know how to set the target is in the portal.

I have two VMs in the load balancer. I tried using Add-AzLoadBalancerInboundNatRuleConfig, but don't see a parameter for target VM.

My script:
$lb  |  Add-AzLoadBalancerInboundNatRuleConfig -Name $EndpointName -FrontendIPConfiguration $feip -Protocol "Tcp" -FrontendPort $i -BackendPort $i

If it's not possible to set the target in powershell, what alternatives are there besides the portal?

I found the answer. The key is to add the LoadBalancerInboundNatRuleId to the Ip Configuration.

Here's a function to get the LoadBalancerInboundNatRuleId that I created for this purpose:

```<code>Function natRuleID ($sourcePortName) {
return  "/subscriptions/$subscriptionID/resourceGroups/$rgName/providers/Microsoft.Network/loadBalancers/$lbName/InboundNatRules/$sourcePortName"
}
</code>```

And here is my sample script that adds two load balancer nat rules and then sets the target network interface for a virtual machine:

```<code># Add Load Balancer Nat Rules:
$lb = Get-AzLoadBalancer -Name $lbName -ResourceGroupName $rgName
$feip = Get-AzLoadBalancerFrontendIpConfig -Name $feipName -LoadBalancer $lb
$lb | Add-AzLoadBalancerInboundNatRuleConfig -Name $natRuleRdpName-FrontendIpConfiguration $feip -Protocol tcp -FrontendPort $rdpPortNumber -BackendPort 3389
$lb | Add-AzLoadBalancerInboundNatRuleConfig -Name $natRuleFtpName -FrontendIPConfiguration $feip -Protocol "Tcp" -FrontendPort $ftpPublicPortForImplicit990  -BackendPort 990
$lb | Set-AzLoadBalancer  #save the new LB rules

# Set nat rule targets:
Function natRuleID ($sourcePortName) {
    return  "/subscriptions/$subscriptionID/resourceGroups/$rgName/providers/Microsoft.Network/loadBalancers/$lbName/InboundNatRules/$sourcePortName"
    }
$rules = @()
$rules = $rules += natRuleID($natRuleFtpName)
$rules = $rules += natRuleID($natRuleRdpName)
$nic = Get-AzNetworkInterface -Name $nicName -ResourceGroupName $rgName
$nic | Set-AzNetworkInterfaceIpConfig -Name $ipConfigName  -LoadBalancerInboundNatRuleId $rules
$nic | Set-AzNetworkInterface #save the new ipConfig rules
</code>```

答:
You need to set it up on the NSG, below is a snippet sample from a script i created to do similar for RDP port.

```<code>Add-AzureRmNetworkSecurityRuleConfig -Name $ruleName -NetworkSecurityGroup $nsg -Access Allow -Description "Allowing RDP connection from current location" -DestinationAddressPrefix * -DestinationPortRange $port -Direction Inbound -Priority $priorityNew -Protocol * -SourceAddressPrefix $current_IP -SourcePortRange *
$hout = Set-AzureRmNetworkSecurityGroup -NetworkSecurityGroup $nsg
</code>```

Body:
In an azure RM load-balancer I can create a nat rule FTP using powershell, but would also like to set the target virtual machine using powershell. The only way I know how to set the target is in the portal.

I have two VMs in the load balancer. I tried using Add-AzLoadBalancerInboundNatRuleConfig, but don't see a parameter for target VM.

My script:
$lb  |  Add-AzLoadBalancerInboundNatRuleConfig -Name $EndpointName -FrontendIPConfiguration $feip -Protocol "Tcp" -FrontendPort $i -BackendPort $i

If it's not possible to set the target in powershell, what alternatives are there besides the portal?

I found the answer. The key is to add the LoadBalancerInboundNatRuleId to the Ip Configuration.

Here's a function to get the LoadBalancerInboundNatRuleId that I created for this purpose:

Function natRuleID ($sourcePortName) {
return  "/subscriptions/$subscriptionID/resourceGroups/$rgName/providers/Microsoft.Network/loadBalancers/$lbName/InboundNatRules/$sourcePortName"
}

And here is my sample script that adds two load balancer nat rules and then sets the target network interface for a virtual machine:

# Add Load Balancer Nat Rules:
$lb = Get-AzLoadBalancer -Name $lbName -ResourceGroupName $rgName
$feip = Get-AzLoadBalancerFrontendIpConfig -Name $feipName -LoadBalancer $lb
$lb | Add-AzLoadBalancerInboundNatRuleConfig -Name $natRuleRdpName-FrontendIpConfiguration $feip -Protocol tcp -FrontendPort $rdpPortNumber -BackendPort 3389
$lb | Add-AzLoadBalancerInboundNatRuleConfig -Name $natRuleFtpName -FrontendIPConfiguration $feip -Protocol "Tcp" -FrontendPort $ftpPublicPortForImplicit990  -BackendPort 990
$lb | Set-AzLoadBalancer  #save the new LB rules

# Set nat rule targets:
Function natRuleID ($sourcePortName) {
    return  "/subscriptions/$subscriptionID/resourceGroups/$rgName/providers/Microsoft.Network/loadBalancers/$lbName/InboundNatRules/$sourcePortName"
    }
$rules = @()
$rules = $rules += natRuleID($natRuleFtpName)
$rules = $rules += natRuleID($natRuleRdpName)
$nic = Get-AzNetworkInterface -Name $nicName -ResourceGroupName $rgName
$nic | Set-AzNetworkInterfaceIpConfig -Name $ipConfigName  -LoadBalancerInboundNatRuleId $rules
$nic | Set-AzNetworkInterface #save the new ipConfig rules

Body:
You need to set it up on the NSG, below is a snippet sample from a script i created to do similar for RDP port.

Add-AzureRmNetworkSecurityRuleConfig -Name $ruleName -NetworkSecurityGroup $nsg -Access Allow -Description "Allowing RDP connection from current location" -DestinationAddressPrefix * -DestinationPortRange $port -Direction Inbound -Priority $priorityNew -Protocol * -SourceAddressPrefix $current_IP -SourcePortRange *
$hout = Set-AzureRmNetworkSecurityGroup -NetworkSecurityGroup $nsg


问:
Managing elements of a dynamicly produced table
A button , onclick , adds a table row with three cells. In the first cell theres a textbox where you input an image url, the second cell contains a button.When pressed the button shows the image that the url refers to on the third cell.
Doing this for one row is simply, but i cant get it to work for subsequent rows because the id of each element would remain the same.
I need some tips and ideas.

Code sample:

```<code><script>
  var u = 1;

  function addRows() {
    var table = document.getElementById("t1");
    var row = table.insertRow(u);
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    var cell3 = row.insertCell(2);

    cell1.innerHTML = '<input id="ur" type="url" >';
    cell2.innerHTML = '<button onclick="document.getElementById(\'im1\').src = document.getElementById(\'ur\').value;">Add Image</button>';
    cell3.innerHTML = '<img id="im1" src="" alt="image">';

    u++;
  }
</script>
</code>```

Each row generates fine and if you put in a url or the name of a local image file it will display properly on the third cell.
But it only works on the first generated row.

答:
With this sort of thing you shouldn't be calling and duplicating ids but instead relying on Sibling properties. Nevertheless a quick hack would be to use your increment variable to give unique ids to the elements. </p>

```<code>var u = 1;

       function addRows(){
           var table = document.getElementById("t1");
           var row = table.insertRow(u);
           var cell1 = row.insertCell(0);
           var cell2 = row.insertCell(1);
           var cell3 = row.insertCell(2);

           cell1.innerHTML = '<input id="ur'+u'" type="url" >' ;
           cell2.innerHTML = '<button onclick="document.getElementById(\'im'+u'\').src = document.getElementById(\'ur'+u+'\').value;">Add Image</button>' ;
           cell3.innerHTML = '<img id="im'+u+'" src="" alt="image">' ;

           u++;
        }
    </script>
</code>```

Body:
A button , onclick , adds a table row with three cells. In the first cell theres a textbox where you input an image url, the second cell contains a button.When pressed the button shows the image that the url refers to on the third cell.
Doing this for one row is simply, but i cant get it to work for subsequent rows because the id of each element would remain the same.
I need some tips and ideas.

Code sample:

Each row generates fine and if you put in a url or the name of a local image file it will display properly on the third cell.
But it only works on the first generated row.

Body:
With this sort of thing you shouldn't be calling and duplicating ids but instead relying on Sibling properties. Nevertheless a quick hack would be to use your increment variable to give unique ids to the elements.

var u = 1;

       function addRows(){
           var table = document.getElementById("t1");
           var row = table.insertRow(u);
           var cell1 = row.insertCell(0);
           var cell2 = row.insertCell(1);
           var cell3 = row.insertCell(2);

           cell1.innerHTML = '<input id="ur'+u'" type="url" >' ;
           cell2.innerHTML = '<button onclick="document.getElementById(\'im'+u'\').src = document.getElementById(\'ur'+u+'\').value;">Add Image</button>' ;
           cell3.innerHTML = '<img id="im'+u+'" src="" alt="image">' ;

           u++;
        }
    </script>


问:
slick slider arrow click tracking
I'm wracking my head here. Slider works, that's not the issue. I've been ask to add event tracking to the arrow. So not on a slide change as the KPI is which arrow. So did the user click left or right.

This does't work:

    $('.slick-arrow').on('click', function () {
      var $this = $(this),
        $ariaLabel = $this.attr('aria-label');

      console.log('button');
    });```

The arrows are default, though I changed the css. Is there another way to track arrow clicks?

答:
I think this will help you track your button.

In GTM, create a user-defined variable of "auto-event variable" type and value would be the "aria-label" attribute like so:

Then create a trigger for the arrow clicks, you already have the right idea for targetting the element using the CSS classes, but this can be done in GTM, like so:

Note, if you don't see the "Click XXXX" variables, you can enable them under the "built-in variables" section in the variables screen.

Next create the event tag, you'll go to the tags page and create a new tag of type Google Analytics, then pick "event" for track type and fill in the category, action and label as you wish. Note, here I'm using the variable we created in the first step as the label, but you can put it anywhere to identify what kind of arrow it was. Make sure to also pick the trigger we created earlier as the trigger for this tag as well.

After this is all done, put the container in debug mode and you should see the tag fire and register an event in GA.

Title: slick slider arrow click tracking

Body:
I'm wracking my head here. Slider works, that's not the issue. I've been ask to add event tracking to the arrow. So not on a slide change as the KPI is which arrow. So did the user click left or right.

This does't work:

    $('.slick-arrow').on('click', function () {
      var $this = $(this),
        $ariaLabel = $this.attr('aria-label');

      console.log('button');
    });

The arrows are default, though I changed the css. Is there another way to track arrow clicks?


问:
Checking each of element in 2D matrix
I have 100x100 matrix in numpy which is made of 0's and 1's. I also have a canvas made of squares which are arranged 100x100. This canvas is in correspondence with matrix (first square to element[0,0], second to [1,0]... it goes row by row from left to right). I have to check each element from the matrix and if it's 0 the square has to be white and if it is 1 the square has to be black. I've tried some methods but none of them works. How can I check each elements of the matrix so I can decide if the color is black or white?

```<code>a=0
b=0
m=np.loadtxt("C:\\Users\\DELL\\Desktop\\preklopenie_obrazka.txt",
skiprows=1 )
for n in range(0,99):
    if m[a][b]==0.0:
        f='white'
    else:
        f='black'
    a+=1
    b+=1
</code>```

答:
You don't need a loop

```<code># create the canvas as a copy of the original matrix
canvas=m.copy()
# convert canvas to have 'object' type so it can contain different types
canvas=canvas.astype('object')
#replace the values with the colors
canvas[canvas==0]='white'
canvas[canvas==1]='black'
</code>```

canvas will now be a numpy array with white for all elements of m equal to 0 and black for all elements equal to 1.

Title: Checking each of element in 2D matrix

Body:
I have 100x100 matrix in numpy which is made of 0's and 1's. I also have a canvas made of squares which are arranged 100x100. This canvas is in correspondence with matrix (first square to element[0,0], second to [1,0]... it goes row by row from left to right). I have to check each element from the matrix and if it's 0 the square has to be white and if it is 1 the square has to be black. I've tried some methods but none of them works. How can I check each elements of the matrix so I can decide if the color is black or white?

a=0
b=0
m=np.loadtxt("C:\\Users\\DELL\\Desktop\\preklopenie_obrazka.txt",
skiprows=1 )
for n in range(0,99):
    if m[a][b]==0.0:
        f='white'
    else:
        f='black'
    a+=1
    b+=1

Body:
You don't need a loop

# create the canvas as a copy of the original matrix
canvas=m.copy()
# convert canvas to have 'object' type so it can contain different types
canvas=canvas.astype('object')
#replace the values with the colors
canvas[canvas==0]='white'
canvas[canvas==1]='black'

canvas will now be a numpy array with white for all elements of m equal to 0 and black for all elements equal to 1.


答:
checkout iamchoosinganame's answer, which is concise and uses numpy's awesome capabilities.

I'm leaving my answer here just for the sake of showing how to correctly loop, based on your code:

your code is mistakenly only checking the main diagonal of the matrix.

think about it: after you're done with a=1 and b=1, you increment both, so next iteration is a=2 and b=2, then a=3 and b=3... etc.

also - range is not inclusive on the end, so you want range(0,100) to get all the numbers up to 99

you want to use for twice (also, you don't have to increment the loop variable yourself):

m=np.loadtxt("C:\\Users\\DELL\\Desktop\\preklopenie_obrazka.txt", skiprows=1 )
for a in range(0,100):
    for b in range(0,100):
        if m[a][b]==0.0:
            f='white'
        else:
            f='black'
        print(f)  # CHANGE: just use f in whatever way you need
```

Title: Checking each of element in 2D matrix


问:
How do I include "XmlInclude" on a Class that inherits from a base class with working "XmlInclude" attributes?
I have multiple Projects in my solution and I am using overrides for any customization individual Clients request to keep code as organised as possible. In this specific override I am trying to inherit from a base class for serialization I am going to do but I am getting errors when trying to serializing.    </p>

```<code>//In the Base project serialization works 100%
namespace Template
{
    //[XmlInclude(typeof(StaticText))]
    //[XmlInclude(typeof(BoundText))]
    //[XmlInclude(typeof(StaticImage))]
    //[XmlInclude(typeof(BoundImage))]
    //[XmlInclude(typeof(Font))]
    public class objType
    {
        public float X { get; set; }
        public float Y { get; set; }
        public float Height { get; set; }
        public float Width { get; set; }
    }

    public class ObjMain()
    {
        public string ObjName { get; set; }
        public List<objType> ObjTypeItems { get; set; }
    }

    public class DoWork() {
        using (System.IO.TextReader tr = new System.IO.StringReader(templateXML))
        {
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(ObjMain));
            bg = (ObjMain)serializer.Deserialize(tr);
        }
    }
}

/*
<ObjMain>
    <ObjName>Section 1</ObjName>
    <ObjTypeItems>
        <objType xsi:type="StaticText">
            <X>32.5</X>
            <Y>4.35</Y>
            <Height>10</Height>
            <Width>20</Width>
            <TextFieldName>M</TextFieldName>
        </objType>
        <objType xsi:type="BountText">
            <X>32.5</X>
            <Y>4.35</Y>
            <Height>10</Height>
            <Width>20</Width>
            <TextFieldName>Mat</TextFieldName>
        </objType>
    </ObjTypeItems>
</ObjMain>
*/

namespace CustomTemplate
{
[XmlInclude(typeof(StaticText))]
    [XmlInclude(typeof(BoundText))]
    [XmlInclude(typeof(StaticImage))]
    [XmlInclude(typeof(BoundImage))]
    [XmlInclude(typeof(Font))]
    public class CustomObjType : objType
    {
        public string GroupName { get; set; }
    }

    public class CustomObjMain()
    {
        public string CObjName { get; set; }
        public List<CustomObjType> CObjTypeItems { get; set; }
    }

    public class DoWork() {
        using (System.IO.TextReader tr = new System.IO.StringReader(templateXML))
        {
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(CustomObjMain));//Error
            bg = (CustomObjMain)serializer.Deserialize(tr);
        }
    }

}

/*
<CustomObjMain>
    <CObjName>Section 1</CObjName>
    <ObjTypeItems>
        <CustomObjType xsi:type="StaticText">  <!--Error when with Serialization -->
            <X>32.5</X>
            <Y>4.35</Y>
            <Height>10</Height>
            <Width>20</Width>
            <TextFieldName>M</TextFieldName>
            <GroupName>MainGroup</GroupName>
        </CustomObjType>
        <CustomObjType xsi:type="BountText">
            <X>32.5</X>
            <Y>4.35</Y>
            <Height>10</Height>
            <Width>20</Width>
            <TextFieldName>Bar</TextFieldName>
            <GroupName>MainGroup</GroupName>
        </CustomObjType>
        <CustomObjType xsi:type="BountText">
            <X>32.5</X>
            <Y>4.35</Y>
            <Height>10</Height>
            <Width>20</Width>
            <TextFieldName>Foo</TextFieldName>
            <GroupName>SubGroupFoo</GroupName>
        </CustomObjType>
    </ObjTypeItems>
</CustomObjMain>
*/
</code>```

<p>My feeling is the class attributes is not inheriting with the base class. But I have also tried to add the attributes to the class that inherits from the base class but with no luck the error continues to show in the xml on the first line with the "xsi:type=" added to it. </p>

答:
Try following :</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApplication5
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            ObjMain objects = new ObjMain()
            {
                ObjName = "Main",
                objects = new List<ObjMain>() {
                    new objType1 { ObjName = "type 1" , X = 1.0F, Y = 2.0F, Height = 5F, Width = 10F},
                    new objType2 { ObjName = "type 2" , X = 1.5F, Y = 2.5F, Height = 5.5F, Width = 10.5F}
                }
            };

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            XmlWriter writer = XmlWriter.Create(FILENAME, settings);
            XmlSerializer serializer = new XmlSerializer(typeof(ObjMain));
            serializer.Serialize(writer, objects);

        }
    }
    public class objType1 : ObjMain
    {
        public float X { get; set; }
        public float Y { get; set; }
        public float Height { get; set; }
        public float Width { get; set; }
    }
    public class objType2 : ObjMain
    {
        public float X { get; set; }
        public float Y { get; set; }
        public float Height { get; set; }
        public float Width { get; set; }
    }

    [XmlInclude(typeof(objType1))]
    [XmlInclude(typeof(objType2))]
    public class ObjMain
    {
        public string ObjName { get; set; }
        [XmlElement()]
        public List<ObjMain> objects { get; set; }
    }
}
</code>```

Body:
I have multiple Projects in my solution and I am using overrides for any customization individual Clients request to keep code as organised as possible. In this specific override I am trying to inherit from a base class for serialization I am going to do but I am getting errors when trying to serializing.

//In the Base project serialization works 100%
namespace Template
{
    //[XmlInclude(typeof(StaticText))]
    //[XmlInclude(typeof(BoundText))]
    //[XmlInclude(typeof(StaticImage))]
    //[XmlInclude(typeof(BoundImage))]
    //[XmlInclude(typeof(Font))]
    public class objType
    {
        public float X { get; set; }
        public float Y { get; set; }
        public float Height { get; set; }
        public float Width { get; set; }
    }

    public class ObjMain()
    {
        public string ObjName { get; set; }
        public List<objType> ObjTypeItems { get; set; }
    }

    public class DoWork() {
        using (System.IO.TextReader tr = new System.IO.StringReader(templateXML))
        {
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(ObjMain));
            bg = (ObjMain)serializer.Deserialize(tr);
        }
    }
}

/*
<ObjMain>
    <ObjName>Section 1</ObjName>
    <ObjTypeItems>
        <objType xsi:type="StaticText">
            <X>32.5</X>
            <Y>4.35</Y>
            <Height>10</Height>
            <Width>20</Width>
            <TextFieldName>M</TextFieldName>
        </objType>
        <objType xsi:type="BountText">
            <X>32.5</X>
            <Y>4.35</Y>
            <Height>10</Height>
            <Width>20</Width>
            <TextFieldName>Mat</TextFieldName>
        </objType>
    </ObjTypeItems>
</ObjMain>
*/

namespace CustomTemplate
{
[XmlInclude(typeof(StaticText))]
    [XmlInclude(typeof(BoundText))]
    [XmlInclude(typeof(StaticImage))]
    [XmlInclude(typeof(BoundImage))]
    [XmlInclude(typeof(Font))]
    public class CustomObjType : objType
    {
        public string GroupName { get; set; }
    }

    public class CustomObjMain()
    {
        public string CObjName { get; set; }
        public List<CustomObjType> CObjTypeItems { get; set; }
    }

    public class DoWork() {
        using (System.IO.TextReader tr = new System.IO.StringReader(templateXML))
        {
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(CustomObjMain));//Error
            bg = (CustomObjMain)serializer.Deserialize(tr);
        }
    }

}

/*
<CustomObjMain>
    <CObjName>Section 1</CObjName>
    <ObjTypeItems>
        <CustomObjType xsi:type="StaticText">
            <X>32.5</X>
            <Y>4.35</Y>
            <Height>10</Height>
            <Width>20</Width>
            <TextFieldName>M</TextFieldName>
            <GroupName>MainGroup</GroupName>
        </CustomObjType>
        <CustomObjType xsi:type="BountText">
            <X>32.5</X>
            <Y>4.35</Y>
            <Height>10</Height>
            <Width>20</Width>
            <TextFieldName>Bar</TextFieldName>
            <GroupName>MainGroup</GroupName>
        </CustomObjType>
        <CustomObjType xsi:type="BountText">
            <X>32.5</X>
            <Y>4.35</Y>
            <Height>10</Height>
            <Width>20</Width>
            <TextFieldName>Foo</TextFieldName>
            <GroupName>SubGroupFoo</GroupName>
        </CustomObjType>
    </ObjTypeItems>
</CustomObjMain>
*/

My feeling is the class attributes is not inheriting with the base class. But I have also tried to add the attributes to the class that inherits from the base class but with no luck the error continues to show in the xml on the first line with the "xsi:type=" added to it.

Body:
Try following :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApplication5
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            ObjMain objects = new ObjMain()
            {
                ObjName = "Main",
                objects = new List<ObjMain>() {
                    new objType1 { ObjName = "type 1" , X = 1.0F, Y = 2.0F, Height = 5F, Width = 10F},
                    new objType2 { ObjName = "type 2" , X = 1.5F, Y = 2.5F, Height = 5.5F, Width = 10.5F}
                }
            };

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            XmlWriter writer = XmlWriter.Create(FILENAME, settings);
            XmlSerializer serializer = new XmlSerializer(typeof(ObjMain));
            serializer.Serialize(writer, objects);

        }
    }
    public class objType1 : ObjMain
    {
        public float X { get; set; }
        public float Y { get; set; }
        public float Height { get; set; }
        public float Width { get; set; }
    }
    public class objType2 : ObjMain
    {
        public float X { get; set; }
        public float Y { get; set; }
        public float Height { get; set; }
        public float Width { get; set; }
    }

    [XmlInclude(typeof(objType1))]
    [XmlInclude(typeof(objType2))]
    public class ObjMain
    {
        public string ObjName { get; set; }
        [XmlElement()]
        public List<ObjMain> objects { get; set; }
    }
}


问:
Why is CreateReadStream not firing error event?
I am attempting to do some error handling for a csv file. When changing the name of the file to something that does not exists,

Error: ENOENT: no such file or directory, open 'testdat.csv' is displayed but the on error event is not fired.

Here is the current implementation:

```<code>const csv = require('csv-parser');
const fs = require('fs');

fs.createReadStream('testdat.csv')
    .pipe(csv())
    .on('open', () => {
    })
    .on('headers', (headers) => {
        validateHeader(headers);
    })
    .on('data', (data) => {
        temp.push(data);
    })
    .on('end', () => {
        validateData(temp);
    })
    .on('error', (err) => {
        console.log(err);
    });
</code>```

答:
You need to attach the error event handler before piping.</p>

```<code>const csv = require('csv-parser');
const fs = require('fs');

var readable = fs.createReadStream('testdat.csv');

readable.on('error', (err) => {
    console.log(err);
});

// pipe function returns different stream
var writable = readable.pipe(csv())

writable.on('error', (err) => {
    console.log(err);
});
</code>```

Body:
I am attempting to do some error handling for a csv file. When changing the name of the file to something that does not exists,

Error: ENOENT: no such file or directory, open 'testdat.csv' is displayed but the on error event is not fired.

Here is the current implementation:

const csv = require('csv-parser');
const fs = require('fs');

fs.createReadStream('testdat.csv')
    .pipe(csv())
    .on('open', () => {
    })
    .on('headers', (headers) => {
        validateHeader(headers);
    })
    .on('data', (data) => {
        temp.push(data);
    })
    .on('end', () => {
        validateData(temp);
    })
    .on('error', (err) => {
        console.log(err);
    });

Body:
You need to attach the error event handler before piping.

const csv = require('csv-parser');
const fs = require('fs');

var readable = fs.createReadStream('testdat.csv');

readable.on('error', (err) => {
    console.log(err);
});

// pipe function returns different stream
var writable = readable.pipe(csv())

writable.on('error', (err) => {
    console.log(err);
});


答:
This should work:

function addRow() {
  var table = document.getElementById("tab");

  var row          = document.createElement("tr");
  var buttonTd     = document.createElement("td");
  var button       = document.createElement("button");
  button.type      = "button";
  button.innerHTML = "Show image";
  buttonTd.appendChild(button);
  var textboxTd    = document.createElement("td");
  var textbox      = document.createElement("input");
  textbox.type     = "text";
  textboxTd.appendChild(textbox);
  var imageTd      = document.createElement("td");
  var image        = document.createElement("img");
  imageTd.appendChild(image);
  row.appendChild(textboxTd);
  row.appendChild(buttonTd);
  row.appendChild(imageTd);

  button.addEventListener("mousedown", function () {
    image.src = textbox.value;
  });

  table.appendChild(row);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table,tr,td {
  border: 1px solid black;
  border-collapse: collapse;
}</code>```

<button onclick="addRow()">Add Row</button>

```

Title: Managing elements of a dynamicly produced table

Body:
This should work:

function addRow() {
  var table = document.getElementById("tab");

  var row          = document.createElement("tr");
  var buttonTd     = document.createElement("td");
  var button       = document.createElement("button");
  button.type      = "button";
  button.innerHTML = "Show image";
  buttonTd.appendChild(button);
  var textboxTd    = document.createElement("td");
  var textbox      = document.createElement("input");
  textbox.type     = "text";
  textboxTd.appendChild(textbox);
  var imageTd      = document.createElement("td");
  var image        = document.createElement("img");
  imageTd.appendChild(image);
  row.appendChild(textboxTd);
  row.appendChild(buttonTd);
  row.appendChild(imageTd);

  button.addEventListener("mousedown", function () {
    image.src = textbox.value;
  });

  table.appendChild(row);
}

table,tr,td {
  border: 1px solid black;
  border-collapse: collapse;
}

<button onclick="addRow()">Add Row</button>

<table id="tab"></table>


问:
How to style the color of the sort icon through a theme override for MUIDataTable?
I am needing to override the color of the sort icon in a MUIDataTable. I am currently able to override basically everything else except this.

Through the debugger view I have tried quite a bit and cannot seem to touch on this icon.

This is what I am currently trying to call to get to it

```<code>MuiTableSortLabel: {
  icon: {
    color: "#eee",
  },
  iconDirectionAsc: {
    color: "#eee",
  },
  iconDirectionDesc: {
    color: "#eee",
  },
},
</code>```

I have this called as well within the overrides -

```<code>MuiSvgIcon: {
  root: {
    color: "#eee",
  },
},
</code>```

The sort icon is currently the default color (black) as this code does nothing to style the icon.
enter image description here

Update work around: This does not satisfy the overrides but is called in styles-

'@global': {
    'div > span > svg > path': {
      fill: '#eee'
    },

},

答:
This'll probably do it for you.

MUIDataTableHeadCell: {
  sortAction: {
    '& svg': {
      color: "#eee" // or whatever you need
    }
  }
}```

Body:
I am needing to override the color of the sort icon in a MUIDataTable. I am currently able to override basically everything else except this.

Through the debugger view I have tried quite a bit and cannot seem to touch on this icon.

This is what I am currently trying to call to get to it

MuiTableSortLabel: {
  icon: {
    color: "#eee",
  },
  iconDirectionAsc: {
    color: "#eee",
  },
  iconDirectionDesc: {
    color: "#eee",
  },
},

I have this called as well within the overrides -

MuiSvgIcon: {
  root: {
    color: "#eee",
  },
},

The sort icon is currently the default color (black) as this code does nothing to style the icon.
enter image description here

Update work around: This does not satisfy the overrides but is called in styles-

'@global': {
    'div > span > svg > path': {
      fill: '#eee'
    },

},