问:
Get reference to (Mock)ResourceResolverFactory
I have a Sling model class containing a reference to a service of mine:

```<code>@OSGiService
PlanService planService;
</code>```

This service has a reference to ResourceResolverFactory, to get a ResourceResolver with the "admin user":

```<code>@Reference
private ResourceResolverFactory resolverFactory;
</code>```

I'm writing a unit test to test adaptTo on my model class. I'm trying to inject the reference to PlanService like this:

```<code>@Rule
public final OsgiContext osgiContext = new OsgiContext();

osgiContext.registerInjectActivateService(new PlanServiceImpl());
</code>```

But I don't know how to inject the reference to the ResourceResolverFactory.

I've tried like this:

```<code>osgiContext.registerInjectActivateService(new MockResourceResolverFactory());
</code>```

But I get this error:

```<code>org.apache.sling.testing.mock.osgi.NoScrMetadataException: No OSGi SCR metadata found in classpath at OSGI-INF/org.apache.sling.testing.resourceresolver.MockResourceResolverFactory.xml
</code>```

I couldn't find in the documentation and among all the mocking options available how to inject this service and get the reference automatically. Any help would be very helpful, thank you!

EDIT:
Thanks to Jérémie's answer, the ResourceResolverFactory is injected in the PlanService. However, I'm now facing this issue:

```<code>[main] WARN org.apache.sling.models.impl.ModelAdapterFactory - Required properties [c.r.o.c.s.j.PlanService c.r.o.c.m.Plan.planService] on model class class c.r.o.c.m.Plan were not able to be injected.
</code>```

I've tried to use the same line than for the ResourceResolverFactory:

```<code>osgiContext.registerService(PlanService.class, new PlanServiceImpl());
</code>```

And also to add

```<code>MockModelAdapterFactory mockModelAdapterFactory = new MockModelAdapterFactory();
     mockModelAdapterFactory.addModelsForPackage("c.r.o.c.m");

osgiContext.registerService(ModelAdapterFactory.class, mockModelAdapterFactory);
</code>```

But it's still the same problem...

EDIT 2: registering it with SlingContext instead of OsgiContext fixed the issue:

```<code>@Rule
public final SlingContext slingContext = new SlingContext(ResourceResolverType.RESOURCERESOLVER_MOCK);

@Mock
PlanService planServiceMock;

slingContext.registerService(PlanService.class, planServiceMock);
</code>```

答:
I had the same issue, than I used the guide on https://sling.apache.org/documentation/development/osgi-mock.html and I made in the following way. Now it works for me:</p>

```<code>    BundleContext bundleContext = MockOsgi.newBundleContext();
    //register the service
    bundleContext.registerService(OtherService.class.getName(), new OtherService(), null);
    // get service instance
    ServiceReference ref = bundleContext.getServiceReference(OtherService.class.getName());
    OtherService service = (OtherService)bundleContext.getService(ref);
</code>```

Body:
I have a Sling model class containing a reference to a service of mine:

@OSGiService
PlanService planService;

This service has a reference to ResourceResolverFactory, to get a ResourceResolver with the "admin user":

@Reference
private ResourceResolverFactory resolverFactory;

I'm writing a unit test to test adaptTo on my model class. I'm trying to inject the reference to PlanService like this:

@Rule
public final OsgiContext osgiContext = new OsgiContext();

osgiContext.registerInjectActivateService(new PlanServiceImpl());

But I don't know how to inject the reference to the ResourceResolverFactory.

I've tried like this:

osgiContext.registerInjectActivateService(new MockResourceResolverFactory());

But I get this error:

org.apache.sling.testing.mock.osgi.NoScrMetadataException: No OSGi SCR metadata found in classpath at OSGI-INF/org.apache.sling.testing.resourceresolver.MockResourceResolverFactory.xml

I couldn't find in the documentation and among all the mocking options available how to inject this service and get the reference automatically. Any help would be very helpful, thank you!

EDIT:
Thanks to Jérémie's answer, the ResourceResolverFactory is injected in the PlanService. However, I'm now facing this issue:

[main] WARN org.apache.sling.models.impl.ModelAdapterFactory - Required properties [c.r.o.c.s.j.PlanService c.r.o.c.m.Plan.planService] on model class class c.r.o.c.m.Plan were not able to be injected.

I've tried to use the same line than for the ResourceResolverFactory:

osgiContext.registerService(PlanService.class, new PlanServiceImpl());

And also to add

MockModelAdapterFactory mockModelAdapterFactory = new MockModelAdapterFactory();
     mockModelAdapterFactory.addModelsForPackage("c.r.o.c.m");

osgiContext.registerService(ModelAdapterFactory.class, mockModelAdapterFactory);

But it's still the same problem...

EDIT 2: registering it with SlingContext instead of OsgiContext fixed the issue:

@Rule
public final SlingContext slingContext = new SlingContext(ResourceResolverType.RESOURCERESOLVER_MOCK);

@Mock
PlanService planServiceMock;

slingContext.registerService(PlanService.class, planServiceMock);

Body:
I had the same issue, than I used the guide on https://sling.apache.org/documentation/development/osgi-mock.html and I made in the following way. Now it works for me:

    BundleContext bundleContext = MockOsgi.newBundleContext();
    //register the service
    bundleContext.registerService(OtherService.class.getName(), new OtherService(), null);
    // get service instance
    ServiceReference ref = bundleContext.getServiceReference(OtherService.class.getName());
    OtherService service = (OtherService)bundleContext.getService(ref);


来源: stackexchange

问:
How to trigger a build only if changes happen on particular set of files
How do I tell Jenkins/Hudson to trigger a build only for changes on a particular project in my Git tree?</p>

答:
While this doesn't affect single jobs, you can use this script to ignore certain steps if the latest commit did not contain any changes:</p>

```<code>/*
 * Check a folder if changed in the latest commit.
 * Returns true if changed, or false if no changes.
 */
def checkFolderForDiffs(path) {
    try {
        // git diff will return 1 for changes (failure) which is caught in catch, or
        // 0 meaning no changes
        sh "git diff --quiet --exit-code HEAD~1..HEAD ${path}"
        return false
    } catch (err) {
        return true
    }
}

if ( checkFolderForDiffs('api/') ) {
    //API folder changed, run steps here
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
While this doesn't affect single jobs, you can use this script to ignore certain steps if the latest commit did not contain any changes:

/*
 * Check a folder if changed in the latest commit.
 * Returns true if changed, or false if no changes.
 */
def checkFolderForDiffs(path) {
    try {
        // git diff will return 1 for changes (failure) which is caught in catch, or
        // 0 meaning no changes
        sh "git diff --quiet --exit-code HEAD~1..HEAD ${path}"
        return false
    } catch (err) {
        return true
    }
}

if ( checkFolderForDiffs('api/') ) {
    //API folder changed, run steps here
}

ContentLicense: CC BY-SA 3.0


问:
How to make the web site design more flexible
I wanna to ask the following question about the design of any web application.

When maximizing ,, minimizing , zooming the browser ,, i note many problems happen to my web application design for example the horizontal menu like the one exists in SO site when minimizing the window  the items of the menu in my website go down the other .. and other things make the site sucks and distracts the design .. how to make the design more flexible with the changes in monitor size , the preferences of the browser , maximizing ,and minimizing the browser ,, how to make the site design more flexible about all those issues .

Please any instructions , advice should i take care to reduce these errors.

答:
Use percentage based widths for dimensions of your page and elements rather than pixels

Use em for your font sizes rather than px or pt

Try not to use images for navigation or if you do, make them expandable using the sliding doors method - http://www.alistapart.com/articles/slidingdoors/

Read up on liquid layouts - http://www.maxdesign.com.au/articles/liquid/ http://www.alistapart.com/articles/negativemargins/

ContentLicense: CC BY-SA 2.5


问:
How to assign sequence number for a column with duplicated rows
I have a dataset where I want to assign sequence number to a column with duplicated rows, for example:

```<code>variable_1
   x
   x
   y
   y
   x
   x
   x
   z
   z
   z
</code>```

How do I get the result like this:

```<code>variable_1   sequence
     x          1
     y          2
     x          3
     z          4
</code>```

I tried using unique, but I would miss the sequence number for x showing up the second time.

答:
A dplyr solution:

```<code>library(dplyr)

df = read.table(text = "
variable_1
x
x
y
y
x
x
x
z
z
z
", header=T, stringsAsFactors=F)

df %>%
  mutate(flag = if_else(variable_1 != lag(variable_1), 1, 0, missing = 1),  # flag row when variable changes
         sequence = cumsum(flag)) %>%                                       # create a group using the flags
  distinct(variable_1, sequence)                                            # get unique values

#   variable_1 sequence
# 1          x        1
# 2          y        2
# 3          x        3
# 4          z        4
</code>```

Body:
I have a dataset where I want to assign sequence number to a column with duplicated rows, for example:

variable_1
   x
   x
   y
   y
   x
   x
   x
   z
   z
   z

How do I get the result like this:

variable_1   sequence
     x          1
     y          2
     x          3
     z          4

I tried using unique, but I would miss the sequence number for x showing up the second time.

Body:
A dplyr solution:

library(dplyr)

df = read.table(text = "
variable_1
x
x
y
y
x
x
x
z
z
z
", header=T, stringsAsFactors=F)

df %>%
  mutate(flag = if_else(variable_1 != lag(variable_1), 1, 0, missing = 1),  # flag row when variable changes
         sequence = cumsum(flag)) %>%                                       # create a group using the flags
  distinct(variable_1, sequence)                                            # get unique values

#   variable_1 sequence
# 1          x        1
# 2          y        2
# 3          x        3
# 4          z        4


问:
Dynamically insert values extracted from a string to a table with multiple instances
I'm currently faced with the following conundrum.

I need to convert this:

```<code>@string = 'TM_15 <= 0.574803 AND TM_3 <= 0.4 AND TM_9 <= 0.298738 AND TM_8 <= 0.30605
AND TM_16 <= 0.367816 AND TM_12 <= 0.341463 AND TM_10 <= 0.379487 AND TM_4 <= 0.44186
AND TM_2 <= 0.45 AND TM_7 <= 0.247525 AND TM_1 <= 0.6 AND TM_13 <= 0.28 AND TM_5 <= 0.285714
AND TM_11 <= 0.6 AND TM_6 <= 0.448276 AND TM_15 <= 0.285047 AND TM_14 <= 0.6
AND TM_12 <= 0.248366 AND TM_5 <= 0.245399 AND TM_16 <= 0.09375 AND TM_3 <= 0.372093
AND TM_15 <= 0.199713 AND TM_10 <= 0.326996 AND TM_9 <= 0.248731 AND TM_8 <= 0.279412
AND TM_13 <= 0.248577 AND TM_4 <= 0.311475 AND TM_2 <= 0.145833 AND TM_7 <= 0.213483
AND TM_11 <= 0.199029 AND TM_4 <= 0.165289'
</code>```

into something that resembles this:

```<code>TM_0    TM_1        TM_2        TM_3        TM_4        TM_5    ... and on to 16
        <= 0.6      <= 0.45     <= 0.4      <= 0.44186  <= 0.285714
                    <= 0.145833 <= 0.372093 <= 0.311475 <= 0.245399
                                            <= 0.165289
</code>```

I've managed to strip out the values into their respective columns and values. I just cant seem to insert into a table/table variable where it will be as small as possible. I dont want to land up having a massive table with over 30 entries for one string. Ideally for the example string value above there should ve a max table column count of 17 and a row count of 4. where the left over space is either null or blank.

reason being after that is done the column will be reduced to the smallest value present.

please post any suggestions or ideas.

thanks

答:
Absolutely no idea why you are doing this, but you can get the output in your question using the string splitting function of you choice as mentioned in the comments by Sean Lange and a pivot, from which you can insert into a table etc:

```<code>declare @string nvarchar(1000) = 'TM_15 <= 0.574803 AND TM_3 <= 0.4 AND TM_9 <= 0.298738 AND TM_8 <= 0.30605
AND TM_16 <= 0.367816 AND TM_12 <= 0.341463 AND TM_10 <= 0.379487 AND TM_4 <= 0.44186
AND TM_2 <= 0.45 AND TM_7 <= 0.247525 AND TM_1 <= 0.6 AND TM_13 <= 0.28 AND TM_5 <= 0.285714
AND TM_11 <= 0.6 AND TM_6 <= 0.448276 AND TM_15 <= 0.285047 AND TM_14 <= 0.6
AND TM_12 <= 0.248366 AND TM_5 <= 0.245399 AND TM_16 <= 0.09375 AND TM_3 <= 0.372093
AND TM_15 <= 0.199713 AND TM_10 <= 0.326996 AND TM_9 <= 0.248731 AND TM_8 <= 0.279412
AND TM_13 <= 0.248577 AND TM_4 <= 0.311475 AND TM_2 <= 0.145833 AND TM_7 <= 0.213483
AND TM_11 <= 0.199029 AND TM_4 <= 0.165289'

select r
      ,[TM_0]
      ,[TM_1]
      ,[TM_2]
      ,[TM_3]
      ,[TM_4]
      ,[TM_5]
      ,[TM_6]
      ,[TM_7]
      ,[TM_8]
      ,[TM_9]
      ,[TM_10]
      ,[TM_11]
      ,[TM_12]
      ,[TM_13]
      ,[TM_14]
      ,[TM_15]
      ,[TM_16]
from (
    select row_number() over (partition by left(s.item,charindex(' ',s.item,1)-1) order by s.rn) as r
          ,left(s.item,charindex(' ',s.item,1)-1) as c
          ,substring(s.item,charindex(' ',s.item,1)+1,9999) as v
    from dbo.fn_StringSplitMax(@string,'and ',null) as s
    ) as s
pivot (max(s.v) for c in([TM_0]
                        ,[TM_1]
                        ,[TM_2]
                        ,[TM_3]
                        ,[TM_4]
                        ,[TM_5]
                        ,[TM_6]
                        ,[TM_7]
                        ,[TM_8]
                        ,[TM_9]
                        ,[TM_10]
                        ,[TM_11]
                        ,[TM_12]
                        ,[TM_13]
                        ,[TM_14]
                        ,[TM_15]
                        ,[TM_16]
                        )
      ) as p
order by r
</code>```

Output:

```<code>+---+------+---------+--------------+----------------+---------------+----------------+--------------+----------------+----------------+--------------+--------------+--------------+--------------+--------------+-----------+--------------+--------------+
| r | TM_0 |  TM_1   |     TM_2     |      TM_3      |     TM_4      |      TM_5      |     TM_6     |      TM_7      |      TM_8      |     TM_9     |    TM_10     |    TM_11     |    TM_12     |    TM_13     |   TM_14   |    TM_15     |    TM_16     |
+---+------+---------+--------------+----------------+---------------+----------------+--------------+----------------+----------------+--------------+--------------+--------------+--------------+--------------+-----------+--------------+--------------+
| 1 | NULL | <= 0.6  | <= 0.45      | <= 0.4         | <= 0.44186    | <= 0.285714    | <= 0.448276  | <= 0.247525    | <= 0.30605     | <= 0.298738  | <= 0.379487  | <= 0.6       | <= 0.341463  | <= 0.28      | <= 0.6    | <= 0.574803  | <= 0.367816  |
| 2 | NULL | NULL    | <= 0.145833  | <= 0.372093    | <= 0.311475   | <= 0.245399    | NULL         | <= 0.213483    | <= 0.279412    | <= 0.248731  | <= 0.326996  | <= 0.199029  | <= 0.248366  | <= 0.248577  | NULL      | <= 0.285047  | <= 0.09375   |
| 3 | NULL | NULL    | NULL         | NULL           | <= 0.165289   | NULL           | NULL         | NULL           | NULL           | NULL         | NULL         | NULL         | NULL         | NULL         | NULL      | <= 0.199713  | NULL         |
+---+------+---------+--------------+----------------+---------------+----------------+--------------+----------------+----------------+--------------+--------------+--------------+--------------+--------------+-----------+--------------+--------------+
</code>```

String split function:

```<code>create function [dbo].[fn_StringSplitMax]
(
 @str nvarchar(max) = ' '           -- String to split.
,@delimiter as nvarchar(max) = ','  -- Delimiting value to split on.  Can be multiple characters.
,@num as int = null                 -- nth value will be returned.  NULL returns all.
)
returns table
as
return
    with s as
    (       -- Convert the string to an XML value, replacing the delimiter with XML tags
        select convert(xml,'<x>' + replace((select @str for xml path('')),@delimiter,'</x><x>') + '</x>').query('.') as s
    )
    select rn
          ,item     -- Select the values from the generated XML value by CROSS APPLYing to the XML nodes
    from(select row_number() over (order by (select null)) as rn
               ,n.x.value('.','nvarchar(max)') as item
         from s
             cross apply s.nodes('x') as n(x)
        ) a
    where rn = @num
       or @num is null;
</code>```

Body:
I'm currently faced with the following conundrum.

I need to convert this:

@string = 'TM_15 <= 0.574803 AND TM_3 <= 0.4 AND TM_9 <= 0.298738 AND TM_8 <= 0.30605
AND TM_16 <= 0.367816 AND TM_12 <= 0.341463 AND TM_10 <= 0.379487 AND TM_4 <= 0.44186
AND TM_2 <= 0.45 AND TM_7 <= 0.247525 AND TM_1 <= 0.6 AND TM_13 <= 0.28 AND TM_5 <= 0.285714
AND TM_11 <= 0.6 AND TM_6 <= 0.448276 AND TM_15 <= 0.285047 AND TM_14 <= 0.6
AND TM_12 <= 0.248366 AND TM_5 <= 0.245399 AND TM_16 <= 0.09375 AND TM_3 <= 0.372093
AND TM_15 <= 0.199713 AND TM_10 <= 0.326996 AND TM_9 <= 0.248731 AND TM_8 <= 0.279412
AND TM_13 <= 0.248577 AND TM_4 <= 0.311475 AND TM_2 <= 0.145833 AND TM_7 <= 0.213483
AND TM_11 <= 0.199029 AND TM_4 <= 0.165289'

into something that resembles this:

TM_0    TM_1        TM_2        TM_3        TM_4        TM_5    ... and on to 16
        <= 0.6      <= 0.45     <= 0.4      <= 0.44186  <= 0.285714
                    <= 0.145833 <= 0.372093 <= 0.311475 <= 0.245399
                                            <= 0.165289

I've managed to strip out the values into their respective columns and values. I just cant seem to insert into a table/table variable where it will be as small as possible. I dont want to land up having a massive table with over 30 entries for one string. Ideally for the example string value above there should ve a max table column count of 17 and a row count of 4. where the left over space is either null or blank.

reason being after that is done the column will be reduced to the smallest value present.

please post any suggestions or ideas.

thanks

Body:
Absolutely no idea why you are doing this, but you can get the output in your question using the string splitting function of you choice as mentioned in the comments by Sean Lange and a pivot, from which you can insert into a table etc:

declare @string nvarchar(1000) = 'TM_15 <= 0.574803 AND TM_3 <= 0.4 AND TM_9 <= 0.298738 AND TM_8 <= 0.30605
AND TM_16 <= 0.367816 AND TM_12 <= 0.341463 AND TM_10 <= 0.379487 AND TM_4 <= 0.44186
AND TM_2 <= 0.45 AND TM_7 <= 0.247525 AND TM_1 <= 0.6 AND TM_13 <= 0.28 AND TM_5 <= 0.285714
AND TM_11 <= 0.6 AND TM_6 <= 0.448276 AND TM_15 <= 0.285047 AND TM_14 <= 0.6
AND TM_12 <= 0.248366 AND TM_5 <= 0.245399 AND TM_16 <= 0.09375 AND TM_3 <= 0.372093
AND TM_15 <= 0.199713 AND TM_10 <= 0.326996 AND TM_9 <= 0.248731 AND TM_8 <= 0.279412
AND TM_13 <= 0.248577 AND TM_4 <= 0.311475 AND TM_2 <= 0.145833 AND TM_7 <= 0.213483
AND TM_11 <= 0.199029 AND TM_4 <= 0.165289'

select r
      ,[TM_0]
      ,[TM_1]
      ,[TM_2]
      ,[TM_3]
      ,[TM_4]
      ,[TM_5]
      ,[TM_6]
      ,[TM_7]
      ,[TM_8]
      ,[TM_9]
      ,[TM_10]
      ,[TM_11]
      ,[TM_12]
      ,[TM_13]
      ,[TM_14]
      ,[TM_15]
      ,[TM_16]
from (
    select row_number() over (partition by left(s.item,charindex(' ',s.item,1)-1) order by s.rn) as r
          ,left(s.item,charindex(' ',s.item,1)-1) as c
          ,substring(s.item,charindex(' ',s.item,1)+1,9999) as v
    from dbo.fn_StringSplitMax(@string,'and ',null) as s
    ) as s
pivot (max(s.v) for c in([TM_0]
                        ,[TM_1]
                        ,[TM_2]
                        ,[TM_3]
                        ,[TM_4]
                        ,[TM_5]
                        ,[TM_6]
                        ,[TM_7]
                        ,[TM_8]
                        ,[TM_9]
                        ,[TM_10]
                        ,[TM_11]
                        ,[TM_12]
                        ,[TM_13]
                        ,[TM_14]
                        ,[TM_15]
                        ,[TM_16]
                        )
      ) as p
order by r

Output:

+---+------+---------+--------------+----------------+---------------+----------------+--------------+----------------+----------------+--------------+--------------+--------------+--------------+--------------+-----------+--------------+--------------+
| r | TM_0 |  TM_1   |     TM_2     |      TM_3      |     TM_4      |      TM_5      |     TM_6     |      TM_7      |      TM_8      |     TM_9     |    TM_10     |    TM_11     |    TM_12     |    TM_13     |   TM_14   |    TM_15     |    TM_16     |
+---+------+---------+--------------+----------------+---------------+----------------+--------------+----------------+----------------+--------------+--------------+--------------+--------------+--------------+-----------+--------------+--------------+
| 1 | NULL | <= 0.6  | <= 0.45      | <= 0.4         | <= 0.44186    | <= 0.285714    | <= 0.448276  | <= 0.247525    | <= 0.30605     | <= 0.298738  | <= 0.379487  | <= 0.6       | <= 0.341463  | <= 0.28      | <= 0.6    | <= 0.574803  | <= 0.367816  |
| 2 | NULL | NULL    | <= 0.145833  | <= 0.372093    | <= 0.311475   | <= 0.245399    | NULL         | <= 0.213483    | <= 0.279412    | <= 0.248731  | <= 0.326996  | <= 0.199029  | <= 0.248366  | <= 0.248577  | NULL      | <= 0.285047  | <= 0.09375   |
| 3 | NULL | NULL    | NULL         | NULL           | <= 0.165289   | NULL           | NULL         | NULL           | NULL           | NULL         | NULL         | NULL         | NULL         | NULL         | NULL      | <= 0.199713  | NULL         |
+---+------+---------+--------------+----------------+---------------+----------------+--------------+----------------+----------------+--------------+--------------+--------------+--------------+--------------+-----------+--------------+--------------+

String split function:

create function [dbo].[fn_StringSplitMax]
(
 @str nvarchar(max) = ' '           -- String to split.
,@delimiter as nvarchar(max) = ','  -- Delimiting value to split on.  Can be multiple characters.
,@num as int = null                 -- nth value will be returned.  NULL returns all.
)
returns table
as
return
    with s as
    (       -- Convert the string to an XML value, replacing the delimiter with XML tags
        select convert(xml,'<x>' + replace((select @str for xml path('')),@delimiter,'</x><x>') + '</x>').query('.') as s
    )
    select rn
          ,item     -- Select the values from the generated XML value by CROSS APPLYing to the XML nodes
    from(select row_number() over (order by (select null)) as rn
               ,n.x.value('.','nvarchar(max)') as item
         from s
             cross apply s.nodes('x') as n(x)
        ) a
    where rn = @num
       or @num is null;


问:
Moving commits branched from master onto a previous commit in master
I'm attempting to move commits from branch "feature" to a new branch, which is forked from an earlier commit than "feature".

Suppose my tree looks like this:

```<code>master   A - B - C
                  \
feature            D - E
</code>```

I'd like to move my feature commits D and E to a new branch derived from commit A, so that my tree looks like this:

```<code>desired    D - E
          /
master   A - B - C
                  \
feature             D - E
</code>```

I created branch "desired" from A and attempted to rebase commits in "feature" onto the tip of "desired", but doing so pulled in commits B and C. Why didn't this rebase work, and how can I move these commits?

答:
You should do something like</p>

```<code>git rebase --onto A C E
</code>```

Body:
I'm attempting to move commits from branch "feature" to a new branch, which is forked from an earlier commit than "feature".

Suppose my tree looks like this:

master   A - B - C
                  \
feature            D - E

I'd like to move my feature commits D and E to a new branch derived from commit A, so that my tree looks like this:

desired    D - E
          /
master   A - B - C
                  \
feature             D - E

I created branch "desired" from A and attempted to rebase commits in "feature" onto the tip of "desired", but doing so pulled in commits B and C. Why didn't this rebase work, and how can I move these commits?

Body:
You should do something like

git rebase --onto A C E


问:
SVGs in Chrome sometimes don't render
THIRD EDIT: here's a working test case. It looks like it has something to do with caching the svg spritesheet. If I configure cache control on my server so that there's no caching of the SVG, the behavior occurs. Feel free to view source (it's all in the one file, but I don't want to include it all here).

https://stuff.spherical.fish/svgtest.html

SECOND EDIT: The fix listed below (directly injecting the  elements in the index.html instead of using an external spritesheet) just stopped working in Chrome v49 (which my beta channel browser just updated to). v48 has the intermittent rendering issue, but v49 pretty consistently doesn't render anything that's referred follows a <svg><use></use></svg> pattern; but only in a big, complicated angular page. A boring simple test case works fine. Added a bounty for anyone who can directly point me at a known issue or wherever this might be coming from. It is most assuredly not file-not-found, as it's still an intermittent bug, and the whole page renders just fine in firefox and safari.

EDIT: this definitely has something to do with referring to an external resource. When I embed the SVGs directly in index.html and refer to them in with <use xlink:href="#id"></use> they work fine, but if I refer to an external file in the <use> element, they only load sometimes.

I have some weird behavior in chrome (only - this doesn't happen on opera, firefox, safari); I've been seeing it since at least the early 40s, version-wise.

My behavior is in the middle of an ng-repeated angular structure. Everything is the same - there's a bunch of divs flexboxed together. There's also an SVG element that looks like:

```<code><svg class="icon-3">
  <use xlink:href="/assets/trellis-icons.svg#icon-users"></use>
</svg>
</code>```

pretty straightforward.

The thing is, for some of these repeated elements, the icon doesn't render. Inspecting the element in the chrome dev tools indicates that the rendered SVG's <use> element has a height and width, whereas the non-rendered one has a zero height and width.

It's not like there's any real difference here; I've even manually edited the DOM to make one of the offending entries match one of the rendered ones completely, but the svg still doesn't render. Here's a relevant screenshot.

You can see below (and ignore my padding issues with the button) the first row doesn't have the little heads and word bubble icons. This is an intermittent problem - if I reload the page, it may be fine, or maybe none of the icons will load.

I'm wondering: is there some kind of obscure issue associated with using sprite sheets (all the SVGs that exhibit this behavior are in the same big SVG file and are referenced by #id) loading asynchronously or something?

If this is really unknown / new behavior, I'll work on engineering a test case, but building something that probably relies on some kind of concurrency bug is kind of hard. So I figured I'd ask around first.

EDIT to add: This behavior does not happen if I export the individual svg out as a standalone and use it in an  fashion. It does still fail if I do an svg use on the icon in a single standalone file.

EDIT: per @kaiido's request, here is the relevant svg in question.

```<code><svg xmlns="http://www.w3.org/2000/svg">
  <!-- thirty other symbols snipped -->
  <symbol id="icon-users" viewBox="0 0 512 512">
    <path d="m352 397c-15-16-78-32-109-48c-21-11-32-33-32-53c0-10 7-19 13-26c5-6 9-14 13-24c8-4 18-12 18-31c0-12-2-19-5-24c1-11 2-22 3-34c4-45-42-90-89-90c-47 0-92 45-88 90c1 12 2 23 3 34c-4 5-5 12-5 24c0 19 9 27 18 31c4 10 8 18 13 24c6 7 13 16 13 26c0 20-11 42-32 53c-18 9-48 19-72 28l0 68l354 0c0 0 0-32-16-48z m146-7c-21-8-46-16-62-24c-17-8-25-27-25-43c0-8 5-15 10-21c4-5 8-12 11-20c7-3 15-10 15-25c0-10-2-16-5-20c1-9 2-18 3-27c3-37-34-76-73-76c-38 0-75 39-72 76c1 9 2 18 3 27c-3 4-5 10-5 20c0 16 8 22 15 25c3 8 7 15 11 20c4 6 10 13 10 21c0 10-4 22-11 31c30 11 43 22 53 33c19 19 19 58 19 58l103 0z"/>
  </symbol>
</svg>
</code>```

答:
Attribute xlink:href is deprecated since SVG 2 (proof link).
New versions of Chrome work strange with this attribute.

If you use xlink:href (for ancient browsers) and href (for new browsers)
everything will work fine everywhere.

Title: SVGs in Chrome sometimes don't render

Body:
THIRD EDIT: here's a working test case. It looks like it has something to do with caching the svg spritesheet. If I configure cache control on my server so that there's no caching of the SVG, the behavior occurs. Feel free to view source (it's all in the one file, but I don't want to include it all here).

https://stuff.spherical.fish/svgtest.html

SECOND EDIT: The fix listed below (directly injecting the  elements in the index.html instead of using an external spritesheet) just stopped working in Chrome v49 (which my beta channel browser just updated to). v48 has the intermittent rendering issue, but v49 pretty consistently doesn't render anything that's referred follows a <svg><use></use></svg> pattern; but only in a big, complicated angular page. A boring simple test case works fine. Added a bounty for anyone who can directly point me at a known issue or wherever this might be coming from. It is most assuredly not file-not-found, as it's still an intermittent bug, and the whole page renders just fine in firefox and safari.

EDIT: this definitely has something to do with referring to an external resource. When I embed the SVGs directly in index.html and refer to them in with <use xlink:href="#id"></use> they work fine, but if I refer to an external file in the <use> element, they only load sometimes.

I have some weird behavior in chrome (only - this doesn't happen on opera, firefox, safari); I've been seeing it since at least the early 40s, version-wise.

My behavior is in the middle of an ng-repeated angular structure. Everything is the same - there's a bunch of divs flexboxed together. There's also an SVG element that looks like:

<svg class="icon-3">
  <use xlink:href="/assets/trellis-icons.svg#icon-users"></use>
</svg>

pretty straightforward.

The thing is, for some of these repeated elements, the icon doesn't render. Inspecting the element in the chrome dev tools indicates that the rendered SVG's <use> element has a height and width, whereas the non-rendered one has a zero height and width.

It's not like there's any real difference here; I've even manually edited the DOM to make one of the offending entries match one of the rendered ones completely, but the svg still doesn't render. Here's a relevant screenshot.

You can see below (and ignore my padding issues with the button) the first row doesn't have the little heads and word bubble icons. This is an intermittent problem - if I reload the page, it may be fine, or maybe none of the icons will load.

I'm wondering: is there some kind of obscure issue associated with using sprite sheets (all the SVGs that exhibit this behavior are in the same big SVG file and are referenced by #id) loading asynchronously or something?

If this is really unknown / new behavior, I'll work on engineering a test case, but building something that probably relies on some kind of concurrency bug is kind of hard. So I figured I'd ask around first.

EDIT to add: This behavior does not happen if I export the individual svg out as a standalone and use it in an  fashion. It does still fail if I do an svg use on the icon in a single standalone file.

EDIT: per @kaiido's request, here is the relevant svg in question.

<svg xmlns="http://www.w3.org/2000/svg">

  <symbol id="icon-users" viewBox="0 0 512 512">
    <path d="m352 397c-15-16-78-32-109-48c-21-11-32-33-32-53c0-10 7-19 13-26c5-6 9-14 13-24c8-4 18-12 18-31c0-12-2-19-5-24c1-11 2-22 3-34c4-45-42-90-89-90c-47 0-92 45-88 90c1 12 2 23 3 34c-4 5-5 12-5 24c0 19 9 27 18 31c4 10 8 18 13 24c6 7 13 16 13 26c0 20-11 42-32 53c-18 9-48 19-72 28l0 68l354 0c0 0 0-32-16-48z m146-7c-21-8-46-16-62-24c-17-8-25-27-25-43c0-8 5-15 10-21c4-5 8-12 11-20c7-3 15-10 15-25c0-10-2-16-5-20c1-9 2-18 3-27c3-37-34-76-73-76c-38 0-75 39-72 76c1 9 2 18 3 27c-3 4-5 10-5 20c0 16 8 22 15 25c3 8 7 15 11 20c4 6 10 13 10 21c0 10-4 22-11 31c30 11 43 22 53 33c19 19 19 58 19 58l103 0z"/>
  </symbol>
</svg>


问:
Selenium Compound Class Name [unable to insert a value]
I am currently having a hard time inserting a value into a field which is within a Frame, I have tried removing the spaces in the class name but it didn't work

class="ng-pristine ng-valid ng-scope ng-empty input-sm form-control nc-pristine ng-valid-required ng-touched"

<textarea ng-if="$ctrl.fieldType.isTextarea($ctrl.field.fieldType, $ctrl.field.isHtmlFormatted)" ng-model="$ctrl.field.value" ng-change="$ctrl.onChange()" ng-required="$ctrl.field.isRequired" ng-class="{
    'input-sm': true,
    'form-control': true,
    'nc-pristine': $ctrl.getPristine(),
    'nc-not-pristine': $ctrl.getNotPristine()
   }" class="ng-pristine ng-valid ng-scope ng-empty input-sm form-control nc-pristine ng-valid-required ng-touched"></textarea>```
</div>
</div>
</p>

<p>I have tried in Chrome Developer tool and it worked with this javascript code</p>

<p><strong>Chrome Console Developper Javascript</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-html lang-html prettyprint-override"><code>document.getElementsByClassName('ng-pristine ng-valid ng-scope ng-empty input-sm form-control nc-pristine ng-valid-required ng-touched')[0].value='Hello World';</code>```

In Selenium I tried with these 2 ways none of them work:

Using Javascript

```<code>IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("document.getElementsByClassName('ng-pristine ng-valid ng-scope ng-empty input-sm form-control nc-pristine ng-valid-required ng-touched')[0].value='Hello World';");
</code>```

Error Message:

```<code> System.InvalidOperationException occurred
  HResult=0x80131509
  Message=unknown error: Cannot set property 'value' of undefined
  (Session info: chrome=62.0.3202.94)
  (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.15063 x86_64)
  Source=WebDriver
  StackTrace:
   at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
   at OpenQA.Selenium.Remote.RemoteWebDriver.ExecuteScriptCommand(String script, String commandName, Object[] args)
   at OpenQA.Selenium.Remote.RemoteWebDriver.ExecuteScript(String script, Object[] args)
   at ConsoleApp5.Program.Main(String[] args)
</code>```

Using cssSelector, removing the spacing in the Class Name and replacing it with dots

```<code>driver.FindElement(By.CssSelector("ng-pristine.ng-valid.ng-scope.ng-empty.input-sm.form-control.nc-pristine.ng-valid-required.ng-touched")).SendKeys("Hello World");
</code>```

Error Message

```<code>  OpenQA.Selenium.NoSuchElementException occurred
  HResult=0x80131500
  Message=no such element: Unable to locate element: {"method":"css selector","selector":"ng-pristine.ng-valid.ng-scope.ng-empty.input-sm.form-control.nc-pristine.ng-valid-required.ng-touched"}
  (Session info: chrome=62.0.3202.94)
  (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.15063 x86_64)
  Source=WebDriver
  StackTrace:
   at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
   at OpenQA.Selenium.Remote.RemoteWebDriver.FindElement(String mechanism, String value)
   at OpenQA.Selenium.Remote.RemoteWebDriver.FindElementByCssSelector(String cssSelector)
   at OpenQA.Selenium.By.<>c__DisplayClass23_0.<CssSelector>b__0(ISearchContext context)
   at OpenQA.Selenium.By.FindElement(ISearchContext context)
   at OpenQA.Selenium.Remote.RemoteWebDriver.FindElement(By by)
</code>```

答:
Here is more HTML Code below

       <nc-form-group-template ng-repeat="i in [$index, $index + 1]" ng-if="fields[i]" section-id="a1gg0000002ARlMAAW" guid="a1gg0000002ARlMAAW338C1B4330ED4993A7B3178099C70517" field="fields[i]" context-id="a38g0000001juVQAAY" ,="" enable-field-access="$ctrl.enableFieldAccess" class="ng-scope ng-isolate-scope">

   <nc-field-label-template section-id="a1gg0000002ARlMAAW" field="$ctrl.field" inline-help-text="" label="Other Loan Purpose" is-required="$ctrl.field.isRequired" enable-field-access="$ctrl.enableFieldAccess" class="ng-isolate-scope">

    Other Loan Purpose

     This field will be hidden from the user.

 </nc-field-label-template>
   <nc-editable-field-template ng-if="!$ctrl.isReadOnly()" section-id="a1gg0000002ARlMAAW" guid="a1gg0000002ARlMAAW338C1B4330ED4993A7B3178099C70517" field="$ctrl.field" context-id="a38g0000001juVQAAY" class="ng-scope ng-isolate-scope">

    <nc-editable-field section-id="a1gg0000002ARlMAAW" guid="a1gg0000002ARlMAAW338C1B4330ED4993A7B3178099C70517" field="$ctrl.field" context-id="a38g0000001juVQAAY" class="ng-isolate-scope">

  <textarea ng-if="$ctrl.fieldType.isTextarea($ctrl.field.fieldType, $ctrl.field.isHtmlFormatted)" ng-model="$ctrl.field.value" ng-change="$ctrl.onChange()" ng-required="$ctrl.field.isRequired" ng-class="{
    'input-sm': true,
    'form-control': true,
    'nc-pristine': $ctrl.getPristine(),
    'nc-not-pristine': $ctrl.getNotPristine()
   }" class="ng-pristine ng-valid ng-scope ng-empty input-sm form-control nc-pristine ng-valid-required ng-touched"></textarea>```

Body:
I am currently having a hard time inserting a value into a field which is within a Frame, I have tried removing the spaces in the class name but it didn't work

class="ng-pristine ng-valid ng-scope ng-empty input-sm form-control nc-pristine ng-valid-required ng-touched"

<textarea ng-if="$ctrl.fieldType.isTextarea($ctrl.field.fieldType, $ctrl.field.isHtmlFormatted)" ng-model="$ctrl.field.value" ng-change="$ctrl.onChange()" ng-required="$ctrl.field.isRequired" ng-class="{
    'input-sm': true,
    'form-control': true,
    'nc-pristine': $ctrl.getPristine(),
    'nc-not-pristine': $ctrl.getNotPristine()
   }" class="ng-pristine ng-valid ng-scope ng-empty input-sm form-control nc-pristine ng-valid-required ng-touched"></textarea>

I have tried in Chrome Developer tool and it worked with this javascript code

Chrome Console Developper Javascript

document.getElementsByClassName('ng-pristine ng-valid ng-scope ng-empty input-sm form-control nc-pristine ng-valid-required ng-touched')[0].value='Hello World';

In Selenium I tried with these 2 ways none of them work:

Using Javascript

IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("document.getElementsByClassName('ng-pristine ng-valid ng-scope ng-empty input-sm form-control nc-pristine ng-valid-required ng-touched')[0].value='Hello World';");

Error Message:

 System.InvalidOperationException occurred
  HResult=0x80131509
  Message=unknown error: Cannot set property 'value' of undefined
  (Session info: chrome=62.0.3202.94)
  (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.15063 x86_64)
  Source=WebDriver
  StackTrace:
   at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
   at OpenQA.Selenium.Remote.RemoteWebDriver.ExecuteScriptCommand(String script, String commandName, Object[] args)
   at OpenQA.Selenium.Remote.RemoteWebDriver.ExecuteScript(String script, Object[] args)
   at ConsoleApp5.Program.Main(String[] args)

Using cssSelector, removing the spacing in the Class Name and replacing it with dots

driver.FindElement(By.CssSelector("ng-pristine.ng-valid.ng-scope.ng-empty.input-sm.form-control.nc-pristine.ng-valid-required.ng-touched")).SendKeys("Hello World");

Error Message

  OpenQA.Selenium.NoSuchElementException occurred
  HResult=0x80131500
  Message=no such element: Unable to locate element: {"method":"css selector","selector":"ng-pristine.ng-valid.ng-scope.ng-empty.input-sm.form-control.nc-pristine.ng-valid-required.ng-touched"}
  (Session info: chrome=62.0.3202.94)
  (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.15063 x86_64)
  Source=WebDriver
  StackTrace:
   at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
   at OpenQA.Selenium.Remote.RemoteWebDriver.FindElement(String mechanism, String value)
   at OpenQA.Selenium.Remote.RemoteWebDriver.FindElementByCssSelector(String cssSelector)
   at OpenQA.Selenium.By.<>c__DisplayClass23_0.<CssSelector>b__0(ISearchContext context)
   at OpenQA.Selenium.By.FindElement(ISearchContext context)
   at OpenQA.Selenium.Remote.RemoteWebDriver.FindElement(By by)

Body:
Here is more HTML Code below

<div class="row ng-scope" ng-repeat="field in $ctrl.getFields() as fields" ng-if="$index % 2 == 0">
       <!-- ngRepeat: i in [$index, $index + 1] --><!-- ngIf: fields[i] --><nc-form-group-template ng-repeat="i in [$index, $index + 1]" ng-if="fields[i]" section-id="a1gg0000002ARlMAAW" guid="a1gg0000002ARlMAAW338C1B4330ED4993A7B3178099C70517" field="fields[i]" context-id="a38g0000001juVQAAY" ,="" enable-field-access="$ctrl.enableFieldAccess" class="ng-scope ng-isolate-scope">
  <div class="form-group col-xs-6">
   <nc-field-label-template section-id="a1gg0000002ARlMAAW" field="$ctrl.field" inline-help-text="" label="Other Loan Purpose" is-required="$ctrl.field.isRequired" enable-field-access="$ctrl.enableFieldAccess" class="ng-isolate-scope">
  <div class="row content-label">
   <div class="col-xs-12">
    <span ng-show="$ctrl.inlineHelpText" popover="popover" data-toggle="popover" data-content="" class="fa fa-info-circle slds-show--inline ng-hide" data-original-title="" title="">
    </span>
    <label ng-bind="$ctrl.label" class="form-control-static input-sm slds-show--inline ng-binding" ng-class="{'is-required': $ctrl.isRequired, 'pull-left': $ctrl.enableFieldAccess}">Other Loan Purpose</label>
    <span class="slds-p-left--medium">
     <!-- ngIf: !$ctrl.field.isVisible && $ctrl.enableFieldAccess -->
     <span class="slds-assistive-text">This field will be hidden from the user.</span>
    </span>
    <!-- ngIf: $ctrl.enableFieldAccess -->
   </div>
  </div>
 </nc-field-label-template>
   <!-- ngIf: !$ctrl.isReadOnly() --><nc-editable-field-template ng-if="!$ctrl.isReadOnly()" section-id="a1gg0000002ARlMAAW" guid="a1gg0000002ARlMAAW338C1B4330ED4993A7B3178099C70517" field="$ctrl.field" context-id="a38g0000001juVQAAY" class="ng-scope ng-isolate-scope">
  <div class="row">
   <div class="col-xs-12 content-body">
    <nc-editable-field section-id="a1gg0000002ARlMAAW" guid="a1gg0000002ARlMAAW338C1B4330ED4993A7B3178099C70517" field="$ctrl.field" context-id="a38g0000001juVQAAY" class="ng-isolate-scope">

  <!-- ngIf: $ctrl.fieldType.isTextarea($ctrl.field.fieldType, $ctrl.field.isHtmlFormatted) --><textarea ng-if="$ctrl.fieldType.isTextarea($ctrl.field.fieldType, $ctrl.field.isHtmlFormatted)" ng-model="$ctrl.field.value" ng-change="$ctrl.onChange()" ng-required="$ctrl.field.isRequired" ng-class="{
    'input-sm': true,
    'form-control': true,
    'nc-pristine': $ctrl.getPristine(),
    'nc-not-pristine': $ctrl.getNotPristine()
   }" class="ng-pristine ng-valid ng-scope ng-empty input-sm form-control nc-pristine ng-valid-required ng-touched"></textarea><!-- end ngIf: $ctrl.fieldType.isTextarea($ctrl.field.fieldType, $ctrl.field.isHtmlFormatted) -->


问:
How to get values from within brackets?
I have a value Mac(user, name)

How do i use perl reg expression to do a check on values inside the brackets.

Value: Mac(user,name)
Remove Mac.. and Do a check on (user,name) to check if it contains 'user'...?

Thanks for help!! :D

答:
What about:

```<code>#!/usr/bin/perl
use strict;
use warnings;
use 5.10.1;

my $input = q!Mac(user, name)!;

my ($user, $name) = $input =~ /^.*?\((.+?),\s*(.+?)\)$/;

say "user=$user , name=$name";
</code>```

output:

```<code>user=user , name=name
</code>```

Title: How to get values from within brackets?

Body:
What about:

#!/usr/bin/perl
use strict;
use warnings;
use 5.10.1;

my $input = q!Mac(user, name)!;

my ($user, $name) = $input =~ /^.*?\((.+?),\s*(.+?)\)$/;

say "user=$user , name=$name";

output:

user=user , name=name


问:
Print string values in object list
Im currently trying to make an addressbook application that holds some person data in an object which is then added to a list. Im currently making a method to try and list the data when prompted but the information isnt showing, does anyone know how I can go about fixing this?

```<code>namespace AddressBook
{
    class Student : Person
    {
    public String StudentID { get; set; }
    public String grade { get; set; }

    public List<Student> studentList = new List<Student>();

 public void addStudent(string firstName, string lastName, string address, string city, string country, string postcode, string StudentID, string grade )
    {
        Student student = new Student();
        student.firstName = firstName;
        student.lastName = lastName;
        student.address = address;
        student.city = city;
        student.country = country;
        student.postcode = postcode;
        student.StudentID = StudentID;
        student.grade = grade;
        studentList.Add(student);
    }

 public void listStudentData()
    {
        String fname ="", lname="", add="", city="", country="", post="", id="", grd = "";
        String[,] index = { { "First name: ", "Last Name: ", "Address: ", "City: ", "Country: ", "Postcode: ", "StudentID: ", "Grade: " }, { fname, lname, add, city, country, post, id, grd }, };
        for (int i = 0; i < studentList.Count; i++)
        {
            fname = (studentList[i].firstName.ToString());
            lname = (studentList[i].lastName.ToString());
            add = (studentList[i].address.ToString());
            city = (studentList[i].city.ToString());
            country = (studentList[i].country.ToString());
            post = (studentList[i].postcode.ToString());
            id = (studentList[i].StudentID.ToString());
            grd = (studentList[i].grade.ToString());
            Console.WriteLine(index[0, i] + index[1,i]);
        }
        Console.WriteLine("");
    }

}
</code>```

}

The format I want to print out is
"First Name: John"
"Last Name: Smith" etc

however the current format is:
"First Name: "

Any advice would be much appreciated

答:
It seems a strange design choice to have the studentList be a member of your Student class. It belongs as a member of your program or form.

But for the specific problem, look at this line:

```<code>String[,] index = { { "First name: ", "Last Name: ", "Address: ", "City: ", "Country: ", "Postcode: ", "StudentID: ", "Grade: " }, { fname, lname, add, city, country, post, id, grd }, };
</code>```

At this point, all of those attribute variables (fname, lname, etc) are empty strings.  You later assign values to those variables:

```<code>fname = (studentList[i].firstName.ToString());
//...
</code>```

However, this doesn't change the contents of the array!

I'll use just the fname variable to explain what happened. fname is a reference to a string object in memory. Initially it refers to an empty string. You also have the index array that includes a number of references, and you set one of them to refer to the same empty-string object as the fname reference. However, this is a copy of that reference. Both fname and the index position refer to the same object in memory, but they are independent variables. Now you assign a new value to fname. The fname variable refers to a different string in memory. However, the position in index was not changed and still refers to the same empty string it had in the beginning.

To fix this, what you might want to do is overload the .ToString() method of your Student class (and maybe the Person and other derived classes, as well). That would look something like this:

```<code>public override string ToString()
{
    return string.Format("First name: {0}\nLast Name: {1}\nAddress: {2}\nCity: {3}\nCountry: {4}\nPostcode: {5}\nStudentID: {6}\nGrade: {7}\n",
        firstName,
        lastName,
        address,
        city,
        country,
        postcode,
        StudentID,
        grade);
}
</code>```

This is useful for a number of reasons (not the least of which is helping you inspect Student objects in the debugger), but for this question it will allow you to re-write the listStudentData() to look like this:

```<code>public void listStudentData()
{
    foreach(var student in studentList)
    {
        Console.WriteLine(student);
    }
}
</code>```

In a larger, more complex program where you might need several different ways of displaying a person, instead of (or in addition to) overriding ToString() you would add a PersonFormatter static class that had a number of public methods for converting a Person or Student to a string with various outputs.

Title: Print string values in object list

Body:
Im currently trying to make an addressbook application that holds some person data in an object which is then added to a list. Im currently making a method to try and list the data when prompted but the information isnt showing, does anyone know how I can go about fixing this?

namespace AddressBook
{
    class Student : Person
    {
    public String StudentID { get; set; }
    public String grade { get; set; }

    public List<Student> studentList = new List<Student>();

 public void addStudent(string firstName, string lastName, string address, string city, string country, string postcode, string StudentID, string grade )
    {
        Student student = new Student();
        student.firstName = firstName;
        student.lastName = lastName;
        student.address = address;
        student.city = city;
        student.country = country;
        student.postcode = postcode;
        student.StudentID = StudentID;
        student.grade = grade;
        studentList.Add(student);
    }

 public void listStudentData()
    {
        String fname ="", lname="", add="", city="", country="", post="", id="", grd = "";
        String[,] index = { { "First name: ", "Last Name: ", "Address: ", "City: ", "Country: ", "Postcode: ", "StudentID: ", "Grade: " }, { fname, lname, add, city, country, post, id, grd }, };
        for (int i = 0; i < studentList.Count; i++)
        {
            fname = (studentList[i].firstName.ToString());
            lname = (studentList[i].lastName.ToString());
            add = (studentList[i].address.ToString());
            city = (studentList[i].city.ToString());
            country = (studentList[i].country.ToString());
            post = (studentList[i].postcode.ToString());
            id = (studentList[i].StudentID.ToString());
            grd = (studentList[i].grade.ToString());
            Console.WriteLine(index[0, i] + index[1,i]);
        }
        Console.WriteLine("");
    }

}

}

The format I want to print out is
"First Name: John"
"Last Name: Smith" etc

however the current format is:
"First Name: "

Any advice would be much appreciated

Body:
It seems a strange design choice to have the studentList be a member of your Student class. It belongs as a member of your program or form.

But for the specific problem, look at this line:

String[,] index = { { "First name: ", "Last Name: ", "Address: ", "City: ", "Country: ", "Postcode: ", "StudentID: ", "Grade: " }, { fname, lname, add, city, country, post, id, grd }, };

At this point, all of those attribute variables (fname, lname, etc) are empty strings.  You later assign values to those variables:

fname = (studentList[i].firstName.ToString());
//...

However, this doesn't change the contents of the array!

I'll use just the fname variable to explain what happened. fname is a reference to a string object in memory. Initially it refers to an empty string. You also have the index array that includes a number of references, and you set one of them to refer to the same empty-string object as the fname reference. However, this is a copy of that reference. Both fname and the index position refer to the same object in memory, but they are independent variables. Now you assign a new value to fname. The fname variable refers to a different string in memory. However, the position in index was not changed and still refers to the same empty string it had in the beginning.

To fix this, what you might want to do is overload the .ToString() method of your Student class (and maybe the Person and other derived classes, as well). That would look something like this:

public override string ToString()
{
    return string.Format("First name: {0}\nLast Name: {1}\nAddress: {2}\nCity: {3}\nCountry: {4}\nPostcode: {5}\nStudentID: {6}\nGrade: {7}\n",
        firstName,
        lastName,
        address,
        city,
        country,
        postcode,
        StudentID,
        grade);
}

This is useful for a number of reasons (not the least of which is helping you inspect Student objects in the debugger), but for this question it will allow you to re-write the listStudentData() to look like this:

public void listStudentData()
{
    foreach(var student in studentList)
    {
        Console.WriteLine(student);
    }
}

In a larger, more complex program where you might need several different ways of displaying a person, instead of (or in addition to) overriding ToString() you would add a PersonFormatter static class that had a number of public methods for converting a Person or Student to a string with various outputs.


问:
Recompose multiple renderComponent
I have a recompose filter that needs to render two components and pass props from a redux connect to the second component

However the code below never renders the second renderComponent - which is a real shame. Is there a way to get the below working, or should I opt for a regular React component?

```<code>import { compose, renderComponent } from "recompose"
import { connect } from "react-redux"

import Filters from "./filter/filter"
import Wrestlers from "./container"

const defaultState = state => ({
  collection: state.roster,
})

export default compose(
  renderComponent(Filters),
  connect(defaultState),
  renderComponent(Wrestlers),
)(Wrestlers)
</code>```

答:
renderComponent always discards the second argument (the base component) and renders the first argument. If you want to render then both, just create a new component and render them. Probably something like:

```<code>const Parent = ({ collection }) => (
  // You can return an array here if you are using React 16
  <div>
    <Filters />
    <Wrestlers collection={collection} />
  <div>
)

export default connect(defaultState)(Parent)
</code>```

Title: Recompose multiple renderComponent

Body:
I have a recompose filter that needs to render two components and pass props from a redux connect to the second component

However the code below never renders the second renderComponent - which is a real shame. Is there a way to get the below working, or should I opt for a regular React component?

import { compose, renderComponent } from "recompose"
import { connect } from "react-redux"

import Filters from "./filter/filter"
import Wrestlers from "./container"

const defaultState = state => ({
  collection: state.roster,
})

export default compose(
  renderComponent(Filters),
  connect(defaultState),
  renderComponent(Wrestlers),
)(Wrestlers)

Body:
renderComponent always discards the second argument (the base component) and renders the first argument. If you want to render then both, just create a new component and render them. Probably something like:

const Parent = ({ collection }) => (
  // You can return an array here if you are using React 16
  <div>
    <Filters />
    <Wrestlers collection={collection} />
  <div>
)

export default connect(defaultState)(Parent)


问:
pass userData from callback-begin to callback-end
How to appropriately cache userData that is generated from user's callbackBegin() and send it to user's callbackEnd().

Simple version  (No userData - demo)

I want to create a complex database that support callback.  For MCVE, let's say it is MyArray.

Here is a simple array class that supports callback but no userData.

```<code>#include <iostream>
template<class Derived>class MyArray{           //library - I design it.
    public: void push_back(int s){
        static_cast<Derived*>(this)->callbackBegin(s);
        //do something about array
        static_cast<Derived*>(this)->callbackEnd(s);
    }
    //other fields / functions
};
class Callback : public MyArray<Callback>{      //user's class
    public: void callbackBegin(int s){
        std::cout<<"callbackBegin"<<std::endl;
    }
    public: void callbackEnd(int s){
        std::cout<<"callbackEnd"<<std::endl;
    }
};
int main() {
    Callback c;
    c.push_back(5); //print: callbackBegin callbackEnd
    return 0;
}
</code>```

It works correctly.

The next step : I want to pass some userData from Callback::callbackBegin() to Callback::callbackEnd().

For example, userData is a clock time when Callback::callbackBegin() is called.

My poor solution (void*& userdata : demo)

Here is my attempt to implement it :-

```<code>#include <iostream>
#include <time.h>
template<class Derived>class MyArray{
    public: void push_back(int s){
        void* userData=nullptr;                                 //#
        static_cast<Derived*>(this)->callbackBegin(s,userData); //# ugly
        //do something about array
        static_cast<Derived*>(this)->callbackEnd(s,userData);   //# ugly
    }
};
class Callback : public MyArray<Callback>{
    public: void callbackBegin(int s,void*& userData){          //#
        userData=new clock_t(clock());                          //# danger
        std::cout<<"callbackBegin"<<std::endl;
    }
    public: void callbackEnd(int s,void*& userData){            //#
        clock_t* userDataTyped=static_cast<clock_t*>(userData);
        clock_t clock2=clock();
        clock_t different=clock2 - (*userDataTyped);
        std::cout<<"callbackEnd time(second)="
                 <<((float)different)/CLOCKS_PER_SEC<<std::endl;
        delete userDataTyped;                                   //# danger
    }
};
int main() {
    Callback c;
    c.push_back(5); //print: callbackBegin callbackEnd time(second)=8.5e-05
    return 0;
}
</code>```

It also works correctly, but I believe it is a bad design (at various #) :-

new/delete in 2 places : potential memory leaking.

Strong pointer is preferred, but I don't know how to.

static_cast<clock_t*>(userData) is code-smell, at least for me.

(minor issue) an extra ugly parameter void*&

Question: What are design patterns / C++ magic to avoid such issues, while make MyArray concise, easy to use, maintainable (i.e. not much worse than the Simple version)?

Other notes:

In real cases, <5% of user's callback classes need userData.

Thus, I feel very reluctant to add void&* as an extra parameter.

Clarify: (edited) The minority cases usually need different types of userData e.g. Callback1 need clock_t,  Callback2 need std::string, etc.

Proposed solution should restrain from using std::function<> or virtual function, because the performance is a major concern here.

Thank.

答:
The C++ magic you're asking about is a known as a virtual method. Virtual method is one of the C++ native ways to implement the callback:

```<code> class MyArray{
      public:
        void push_back(int s) {
            const auto userData = callbackBegin(s); //# beautiful
            //do something about array
            callbackEnd(s, userData);               //# beautiful
        }
      private:
        virtual clock_t callbackBegin(int) const = 0;
        virtual void callbackEnd(int, const clock_t&) const = 0;
    };
    class Callback : public MyArray{
        clock_t  callbackBegin(int s) const final {
          std::cout<<"callbackBegin"<<std::endl;
          return clock(); //# safe
        }
        void callbackEnd(int s,const clock_t& userData) const final {            //#
           const auto different = clock() - userDataTyped;
           std::cout << "callbackEnd time(second)=";
           std::cout << different/CLOCKS_PER_SEC << std::endl;
          //# safe
       }
    };
</code>```

Another way is to pass two callable objects to the MyArray ctor and using those objects in the push_back method. The callable objects shall store calls to the relevant class Callback methods. Use std::function to implement those callable objects.

Body:
How to appropriately cache userData that is generated from user's callbackBegin() and send it to user's callbackEnd().

Simple version  (No userData - demo)

I want to create a complex database that support callback.  For MCVE, let's say it is MyArray.

Here is a simple array class that supports callback but no userData.

#include <iostream>
template<class Derived>class MyArray{           //library - I design it.
    public: void push_back(int s){
        static_cast<Derived*>(this)->callbackBegin(s);
        //do something about array
        static_cast<Derived*>(this)->callbackEnd(s);
    }
    //other fields / functions
};
class Callback : public MyArray<Callback>{      //user's class
    public: void callbackBegin(int s){
        std::cout<<"callbackBegin"<<std::endl;
    }
    public: void callbackEnd(int s){
        std::cout<<"callbackEnd"<<std::endl;
    }
};
int main() {
    Callback c;
    c.push_back(5); //print: callbackBegin callbackEnd
    return 0;
}

It works correctly.

The next step : I want to pass some userData from Callback::callbackBegin() to Callback::callbackEnd().

For example, userData is a clock time when Callback::callbackBegin() is called.

My poor solution (void*& userdata : demo)

Here is my attempt to implement it :-

#include <iostream>
#include <time.h>
template<class Derived>class MyArray{
    public: void push_back(int s){
        void* userData=nullptr;                                 //#
        static_cast<Derived*>(this)->callbackBegin(s,userData); //# ugly
        //do something about array
        static_cast<Derived*>(this)->callbackEnd(s,userData);   //# ugly
    }
};
class Callback : public MyArray<Callback>{
    public: void callbackBegin(int s,void*& userData){          //#
        userData=new clock_t(clock());                          //# danger
        std::cout<<"callbackBegin"<<std::endl;
    }
    public: void callbackEnd(int s,void*& userData){            //#
        clock_t* userDataTyped=static_cast<clock_t*>(userData);
        clock_t clock2=clock();
        clock_t different=clock2 - (*userDataTyped);
        std::cout<<"callbackEnd time(second)="
                 <<((float)different)/CLOCKS_PER_SEC<<std::endl;
        delete userDataTyped;                                   //# danger
    }
};
int main() {
    Callback c;
    c.push_back(5); //print: callbackBegin callbackEnd time(second)=8.5e-05
    return 0;
}

It also works correctly, but I believe it is a bad design (at various #) :-

new/delete in 2 places : potential memory leaking.

Strong pointer is preferred, but I don't know how to.

static_cast<clock_t*>(userData) is code-smell, at least for me.

(minor issue) an extra ugly parameter void*&

Question: What are design patterns / C++ magic to avoid such issues, while make MyArray concise, easy to use, maintainable (i.e. not much worse than the Simple version)?

Other notes:

In real cases, <5% of user's callback classes need userData.

Thus, I feel very reluctant to add void&* as an extra parameter.

Clarify: (edited) The minority cases usually need different types of userData e.g. Callback1 need clock_t,  Callback2 need std::string, etc.

Proposed solution should restrain from using std::function<> or virtual function, because the performance is a major concern here.

Thank.

Body:
The C++ magic you're asking about is a known as a virtual method. Virtual method is one of the C++ native ways to implement the callback:

 class MyArray{
      public:
        void push_back(int s) {
            const auto userData = callbackBegin(s); //# beautiful
            //do something about array
            callbackEnd(s, userData);               //# beautiful
        }
      private:
        virtual clock_t callbackBegin(int) const = 0;
        virtual void callbackEnd(int, const clock_t&) const = 0;
    };
    class Callback : public MyArray{
        clock_t  callbackBegin(int s) const final {
          std::cout<<"callbackBegin"<<std::endl;
          return clock(); //# safe
        }
        void callbackEnd(int s,const clock_t& userData) const final {            //#
           const auto different = clock() - userDataTyped;
           std::cout << "callbackEnd time(second)=";
           std::cout << different/CLOCKS_PER_SEC << std::endl;
          //# safe
       }
    };

Another way is to pass two callable objects to the MyArray ctor and using those objects in the push_back method. The callable objects shall store calls to the relevant class Callback methods. Use std::function to implement those callable objects.


问:
R: Predictions from a list of coxph objects on newdata
I am building a series of Cox regression models, and getting predictions from those models on new data. I am able to get the expected number of events in some cases, but not others.

For example, if the formula in the coxph call is written out, then the predictions are calculated. But, if the the formula is stored in an object and that object called, I get an error.  I also cannot get the predictions if I try to create them within a dplyr piped mutate function (for the function I am writing, this would be the most ideal place to get the predictions to work properly).

Any assistance is greatly appreciated!

Thank you,

Daniel

```<code>require(survival)
require(tidyverse)
n = 15

# creating tibble of tibbles.
results =
  tibble(id = 1:n) %>%
  group_by(id) %>%
  do(
    # creating tibble to evaluate model on
    tbl0 = tibble(time = runif(n), x = runif(n)),
    # creating tibble to build model on
    tbl =  tibble(time = runif(n), x = runif(n))
  ) %>%
  ungroup

#it works when the formula is added the the coxph function already written out
  map2(results$tbl, results$tbl0, ~ predict(coxph( Surv(time) ~ x, data = .x), newdata = .y, type = "expected"))

#but if the formula is previously defined, I get an error
  f = as.formula(Surv(time) ~ x)
  map2(results$tbl, results$tbl0, ~ predict(coxph( f, data = .x), newdata = .y, type = "expected"))

# I also get an error when I try to include in a dplyr pipe with mutate
  results %>%
    mutate(
     pred = map2(tbl, tbl0, ~ predict(coxph( f, data = .x), newdata = .y, type = "expected"))
    )
</code>```

答:
I figured it out (with the help of a friend).  If you define the formula as a string, and within the function call coerce it to a formula everything runs smoothly.  I am not sure why it works, but it does!</p>

```<code>#define the formula as a string, and call it in the function with as.formula(.)
  f = "Surv(time) ~ x"
  map2(results$tbl, results$tbl0, ~ predict(coxph( as.formula(f), data = .x), newdata = .y, type = "expected"))

#also works in a dplyr pipe with mutate
  results %>%
    mutate(
     pred = map2(tbl, tbl0, ~ predict(coxph( as.formula(f), data = .x), newdata = .y, type = "expected"))
    )
</code>```

Body:
I am building a series of Cox regression models, and getting predictions from those models on new data. I am able to get the expected number of events in some cases, but not others.

For example, if the formula in the coxph call is written out, then the predictions are calculated. But, if the the formula is stored in an object and that object called, I get an error.  I also cannot get the predictions if I try to create them within a dplyr piped mutate function (for the function I am writing, this would be the most ideal place to get the predictions to work properly).

Any assistance is greatly appreciated!

Thank you,

Daniel

require(survival)
require(tidyverse)
n = 15

# creating tibble of tibbles.
results =
  tibble(id = 1:n) %>%
  group_by(id) %>%
  do(
    # creating tibble to evaluate model on
    tbl0 = tibble(time = runif(n), x = runif(n)),
    # creating tibble to build model on
    tbl =  tibble(time = runif(n), x = runif(n))
  ) %>%
  ungroup

#it works when the formula is added the the coxph function already written out
  map2(results$tbl, results$tbl0, ~ predict(coxph( Surv(time) ~ x, data = .x), newdata = .y, type = "expected"))

#but if the formula is previously defined, I get an error
  f = as.formula(Surv(time) ~ x)
  map2(results$tbl, results$tbl0, ~ predict(coxph( f, data = .x), newdata = .y, type = "expected"))

# I also get an error when I try to include in a dplyr pipe with mutate
  results %>%
    mutate(
     pred = map2(tbl, tbl0, ~ predict(coxph( f, data = .x), newdata = .y, type = "expected"))
    )

Body:
I figured it out (with the help of a friend).  If you define the formula as a string, and within the function call coerce it to a formula everything runs smoothly.  I am not sure why it works, but it does!

#define the formula as a string, and call it in the function with as.formula(.)
  f = "Surv(time) ~ x"
  map2(results$tbl, results$tbl0, ~ predict(coxph( as.formula(f), data = .x), newdata = .y, type = "expected"))

#also works in a dplyr pipe with mutate
  results %>%
    mutate(
     pred = map2(tbl, tbl0, ~ predict(coxph( as.formula(f), data = .x), newdata = .y, type = "expected"))
    )


问:
How to get nested json object/value in scala
I have Elasticsearch Search response that is a deeply nested Json file and I am stuck as to how to get a particular value from it.  Please am new to Scala and programming in general and I have searched online and could not see any answer that explained it well.
This is the Json file and the value I want to get out is "getSum":"value"

```<code>Search_response: org.elasticsearch.action.search.SearchResponse = {
  "took" : 32,
  "timed_out" : false,
  "_shards" : {
    "total" : 3,
    "successful" : 3,
    "failed" : 0
  },
  "hits" : {
    "total" : 12,
    "max_score" : 1.0,
    "hits" : [ {
      "_index" : "myIndex",
      "_type" : "myType",
      "_id" : "4151202002020",
      "_score" : 1.0,
      "_source":{"pint":[{"printer":[{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"},{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"}],"Lam":[{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"},{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"},{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"}],"Kam":[{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"},{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"},{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"}],"Jas":[{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"}],"tiv":[{ourc""s:"wrer","sourceType":"rsd","Vag":"agaatttt363336"}],"timeLineSource:[{"LA":"DGAT","GATA":"JAS","timeline":9.111694,"GA":"SFWF2525252552552525"}
    }, {
       "_index" : "myIndex",
      "_type" : "myType",
      "_id" : "4151202002020",
      "_score" : 1.0,
       "_source":{"pint":[{"printer":[{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"},{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"}],"Lam":[{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"},{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"},{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"}],"Kam":[{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"},{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"},{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"}],"Jas":[{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"}],"tiv":[{ourc""s:"wrer","sourceType":"rsd","Vag":"agaatttt363336"}],"timeLineSource:[{"LA":"DGAT","GATA":"JAS","timeline":9.111694,"GA":"SFWF2525252552552525"}
    }, {
        "_index" : "myIndex",
      "_type" : "myType",
      "_id" : "4151202002020",
      "_score" : 1.0,
       "_source":{"pint":[{"printer":[{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"},{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"}],"Lam":[{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"},{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"},{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"}],"Kam":[{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"},{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"},{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"}],"Jas":[{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"}],"tiv":[{ourc""s:"wrer","sourceType":"rsd","Vag":"agaatttt363336"}],"timeLineSource:[{"LA":"DGAT","GATA":"JAS","timeline":9.111694,"GA":"SFWF2525252552552525"}
    }, {
  },
  "aggregations" : {
    "DAEY" : {
      "doc_count" : 59,
      "histogram" : {
        "buckets" : [ {
          "key_as_string" : "1978-02-22T00:00:00.000Z",
          "key" : 1503360000000,
          "doc_count" : 59,
          "nestedValue" : {
            "doc_count" : 177,
            "getSum" : {
              "value" : 768.0690221786499
            }
          },
        }
    }
  }
}
</code>```

This is what I tried

val getResult: String = searchResult.toString.stripMargin
val getValue = JsonParser.parse(getResult).asInstanceOf[JObject].values("aggregations").toString

答:
I finally used </p>

```<code>val getResult: String = searchResult.toString.stripMargin
val getValue = JsonParser.parse(getResult).asInstanceOf[JObject].values("aggregations").toString
val valueToDouble = getValue.split(" ").last.dropRight(13).toDouble
</code>```

Body:
I have Elasticsearch Search response that is a deeply nested Json file and I am stuck as to how to get a particular value from it.  Please am new to Scala and programming in general and I have searched online and could not see any answer that explained it well.
This is the Json file and the value I want to get out is "getSum":"value"

Search_response: org.elasticsearch.action.search.SearchResponse = {
  "took" : 32,
  "timed_out" : false,
  "_shards" : {
    "total" : 3,
    "successful" : 3,
    "failed" : 0
  },
  "hits" : {
    "total" : 12,
    "max_score" : 1.0,
    "hits" : [ {
      "_index" : "myIndex",
      "_type" : "myType",
      "_id" : "4151202002020",
      "_score" : 1.0,
      "_source":{"pint":[{"printer":[{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"},{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"}],"Lam":[{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"},{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"},{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"}],"Kam":[{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"},{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"},{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"}],"Jas":[{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"}],"tiv":[{ourc""s:"wrer","sourceType":"rsd","Vag":"agaatttt363336"}],"timeLineSource:[{"LA":"DGAT","GATA":"JAS","timeline":9.111694,"GA":"SFWF2525252552552525"}
    }, {
       "_index" : "myIndex",
      "_type" : "myType",
      "_id" : "4151202002020",
      "_score" : 1.0,
       "_source":{"pint":[{"printer":[{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"},{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"}],"Lam":[{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"},{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"},{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"}],"Kam":[{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"},{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"},{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"}],"Jas":[{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"}],"tiv":[{ourc""s:"wrer","sourceType":"rsd","Vag":"agaatttt363336"}],"timeLineSource:[{"LA":"DGAT","GATA":"JAS","timeline":9.111694,"GA":"SFWF2525252552552525"}
    }, {
        "_index" : "myIndex",
      "_type" : "myType",
      "_id" : "4151202002020",
      "_score" : 1.0,
       "_source":{"pint":[{"printer":[{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"},{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"}],"Lam":[{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"},{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"},{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"}],"Kam":[{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"},{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"},{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"}],"Jas":[{"sourceName":"3636636","sourceType":"Bin","Star":0.0,"Fun":"gatayay"}],"tiv":[{ourc""s:"wrer","sourceType":"rsd","Vag":"agaatttt363336"}],"timeLineSource:[{"LA":"DGAT","GATA":"JAS","timeline":9.111694,"GA":"SFWF2525252552552525"}
    }, {
  },
  "aggregations" : {
    "DAEY" : {
      "doc_count" : 59,
      "histogram" : {
        "buckets" : [ {
          "key_as_string" : "1978-02-22T00:00:00.000Z",
          "key" : 1503360000000,
          "doc_count" : 59,
          "nestedValue" : {
            "doc_count" : 177,
            "getSum" : {
              "value" : 768.0690221786499
            }
          },
        }
    }
  }
}

This is what I tried

val getResult: String = searchResult.toString.stripMargin
val getValue = JsonParser.parse(getResult).asInstanceOf[JObject].values("aggregations").toString

Body:
I finally used

val getResult: String = searchResult.toString.stripMargin
val getValue = JsonParser.parse(getResult).asInstanceOf[JObject].values("aggregations").toString
val valueToDouble = getValue.split(" ").last.dropRight(13).toDouble


问:
php - maintain session across curl requests
I have been able to use my current session in the process created by my curl request using the following code -

```<code>$query = http_build_query(array(
   "pcode"=>strtolower($code)
));
$url = $_SERVER['REQUEST_SCHEME'].":".PUBLIC_ROOT."xyz.php"."?".$query;

session_write_close();

$curl = curl_init($url);
$useragent = $_SERVER['HTTP_USER_AGENT'];
$strCookie = 'PHPSESSID=' . $_COOKIE['PHPSESSID'] . '; path=/';
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_GET, true);
curl_setopt($curl, CURLOPT_USERAGENT, $useragent);
curl_setopt($curl, CURLOPT_COOKIE, $strCookie );

$json_response = curl_exec($curl);
curl_close($curl);
</code>```

I used the following answer for the above code - https://stackoverflow.com/a/15374966/815929

Now the issue is that in the new process (created by the curl request), I need to set some session variables. However these session variables do not reflect in the calling process after curl_close().

I had some session vars in my calling script. I was able to use these session vars in the new process started by the curl request. This new process also set some new session vars. However when we are back to the calling process these new session vars are not reflected.

Are there additional curl options that I need to set to make this work?

答:
I'm struggling to imagine how this runs at all.

However these session variables do not reflect in the calling process after curl_close()

Using the default session handler, a second script should just timeout if it is called from something like....

```<code>session_start();
...
curl_exec(); // at this point session file is still locked
...
[session_close();]
</code>```

$strCookie = 'PHPSESSID=' . $_COOKIE['PHPSESSID'] . '; path=/';

eh? You don't specify a path for a cookie in an HTTP request (you do in a response). This will tell the script that the client has a cookie named "path".

Really this should be....

$strCookie = session_name() . "=" . session_id();

However these session variables do not reflect in the calling process after curl_close()

Did you reload the session from storage? (see also previous note about session file locking). Your code should do something like....

```<code>session_start();
...
session_close();
...
curl_exec();
...
session_start();
</code>```

it would be cleaner to switch to a non-blocking handler, or better yet don't pass state via the session - POST the data to the second script read the response from the output stream.

Body:
I have been able to use my current session in the process created by my curl request using the following code -

$query = http_build_query(array(
   "pcode"=>strtolower($code)
));
$url = $_SERVER['REQUEST_SCHEME'].":".PUBLIC_ROOT."xyz.php"."?".$query;

session_write_close();

$curl = curl_init($url);
$useragent = $_SERVER['HTTP_USER_AGENT'];
$strCookie = 'PHPSESSID=' . $_COOKIE['PHPSESSID'] . '; path=/';
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_GET, true);
curl_setopt($curl, CURLOPT_USERAGENT, $useragent);
curl_setopt($curl, CURLOPT_COOKIE, $strCookie );

$json_response = curl_exec($curl);
curl_close($curl);

I used the following answer for the above code - https://stackoverflow.com/a/15374966/815929

Now the issue is that in the new process (created by the curl request), I need to set some session variables. However these session variables do not reflect in the calling process after curl_close().

I had some session vars in my calling script. I was able to use these session vars in the new process started by the curl request. This new process also set some new session vars. However when we are back to the calling process these new session vars are not reflected.

Are there additional curl options that I need to set to make this work?

Body:
I'm struggling to imagine how this runs at all.

However these session variables do not reflect in the calling process after curl_close()

Using the default session handler, a second script should just timeout if it is called from something like....

session_start();
...
curl_exec(); // at this point session file is still locked
...
[session_close();]

$strCookie = 'PHPSESSID=' . $_COOKIE['PHPSESSID'] . '; path=/';

eh? You don't specify a path for a cookie in an HTTP request (you do in a response). This will tell the script that the client has a cookie named "path".

Really this should be....

$strCookie = session_name() . "=" . session_id();

However these session variables do not reflect in the calling process after curl_close()

Did you reload the session from storage? (see also previous note about session file locking). Your code should do something like....

session_start();
...
session_close();
...
curl_exec();
...
session_start();

it would be cleaner to switch to a non-blocking handler, or better yet don't pass state via the session - POST the data to the second script read the response from the output stream.


问:
How to implement admob on view controller?
In my app, I want to implement admob and now only I have started to learn about it. So any one please guide me and is there any nice tutorial or sample?</p>

答: Good thing to know, Mike.  They also left out one step in Interface Builder.  You need to select File's Owner, and drag from Ad View Controller to the new Ad View Object.  I simply cannot comprehend why Admob would leave out these details, especially when many new programmers join they're community all the time.  They really need help in the documentation & tutorials department.</p>


问:
GET-only api for Google Sheets or similar
I have a Tableau workbook that helps surface interesting cases in a large dataset.  Once an interesting case is identified, I'd like to add it to an external list that allows me to take action on it later.  Ideally, I'd like to use the URL action to drive a separate app, like Google Sheets, and add a line with the ID of the currently selected item.  Like this completely made-up example:

http://sheets.googleapis.com/SheetName?op=AddRow&data={id:123,title:"foo"}

I can do all of these things in Tableau to get the URL built how I want, but I am stuck with just an http GET, with no post payload.  I don't see any way to get google sheets to work with a simple GET request.

Questions:

Is there any way to get Google Sheets to behave how I want, where I
can add a row with just a GET request?  I can't find anything in the docs that would suggest this is possible.

Is there an alternative to Google Sheets that I can use that is authenticated?  (OneNote, for example, seems to have the same POST limitation)

Is there some sort of intermediary I can use to bridge the divide, like IFTTT?  I can't seem to figure out a way to kick off an IFTTT type of action with just a GET request from a browser.

答:
As @noogui explained, Google Sheets uses standard REST methods for interacting with sheets. You could write your own web application wrapper around Google Sheets, allowing a GET that would then interact with Google Sheets' POST method. The wrapper can be in any language that allows http calls.

You don't specify if you want the action to work only in Desktop or also in Server. If Desktop only, you could easily write your wrapper in Javascript and run it locally. If also running it in Server, choose your favorite web programming language, fire up an application server, and point your action URL to the wrapper.


问:
Scala - have List of String, must split by comma, and put into Map
I have a List of the form: ("string,num", "string,num", ...)

I have found solutions online for how to do this with a single string, but have not been able to adapt it to a list of strings.

Also, numerical values should be cast to Int/Double before being mapped.

I would appreciate any help.

答:
Probably not the best way to do that, but it should meet your needs</p>

```<code>yourlist.groupBy( _.split(',')(0) ).mapValues(v=>v(0).split(',')(1))
</code>```

Body:
Probably not the best way to do that, but it should meet your needs

yourlist.groupBy( _.split(',')(0) ).mapValues(v=>v(0).split(',')(1))


问:
importing data from firestore into bigQuery
I have upgraded my account to blaze which is one of the prerequisite. I have tried to followed the FAQ  Link BigQuery to Firebase. still not able to see any of the data from firestore or firebase-realtimeDatabase into bigQuery.

I see option in bigQuery to create Dataset. however after creating dataset it allows me to upload data from [file], [cloud storage], [bigQuery],[google Drive] . but not  firestore database.

Plesae help.

答:
You can now export data from Cloud Firestore to BigQuery with a Firebase Extension. See: https://firebase.google.com/products/extensions/firestore-bigquery-export

Also see David's answer on how to import/export data.

Outdated answer below:

There is no built-in support to import data from the Firebase Realtime Database or Cloud Firestore into BigQuery.

For now, if you want to import data, you'll have to write code to do so.


问:
Get Max value from range (multiple sheets) grouped by Name
I have 3 sheets that have the exact same format

Sheet1

```<code>A           B          C         D
George      10         2         8
Nick        15         89        0
Mike        13         1         50
Lucas       9         -5         12
</code>```

Sheet2

```<code>A           B          C         D
Nick        1          9         5
Mike        1          10        6
George      11         22        5
Lucas       10         5         2
Panos       55         0         1
</code>```

Sheet3

```<code>A            B         C         D
Panos        0         9         1
George       1         2         5
Nick         7         2         1
Lucas        1         5         1
</code>```

I want to query the range {'Sheet1'!A1:D5; 'Sheet2'!A1:D5; 'Sheet3'!A1:D5}

And get something like MAX(Col2:Col4) Group By Col1

Which would return something like:

```<code>George 22
Nick   89
Mike   50
Lucas  12
Panos  55
</code>```

I tried:

```<code>=sort(query({'Sheet1'!A1:D5; 'Sheet2'!A1:D5;'Sheet3'!A1:D5}, "select Col1, MAX(Col2:Col4) Group by Col1 Label MAX(Col2:Col4) '' " ),2, FALSE)
</code>```

and

```<code>=sort(query({'Sheet1'!A1:D5; 'Sheet2'!A1:D5;'Sheet3'!A1:D5}, "select Col1, MAX(MAX(Col2),MAX(Col3), MAX(Col4)) Group by Col1 " ),2, FALSE)
</code>```

Both didn't work. Any ideas?

答:
Another approach perhaps a bit simpler but needing two queries

```<code>=sort(unique(({Sheet1!A1:A5;Sheet2!A1:A5;Sheet3!A1:A5})))
</code>```

to get the names starting in (say) F2

Then this to get the maximum values for each name in (say) G2 and pulled down

```<code>max(query({Sheet1!A$1:D$5;Sheet2!A$1:D$5;Sheet3!A$1:D$5},"select max(Col2),max(Col3),max(Col4) where Col1='"&F2&"'"))
</code>```

Body:
I have 3 sheets that have the exact same format

Sheet1

A           B          C         D
George      10         2         8
Nick        15         89        0
Mike        13         1         50
Lucas       9         -5         12

Sheet2

A           B          C         D
Nick        1          9         5
Mike        1          10        6
George      11         22        5
Lucas       10         5         2
Panos       55         0         1

Sheet3

A            B         C         D
Panos        0         9         1
George       1         2         5
Nick         7         2         1
Lucas        1         5         1

I want to query the range {'Sheet1'!A1:D5; 'Sheet2'!A1:D5; 'Sheet3'!A1:D5}

And get something like MAX(Col2:Col4) Group By Col1

Which would return something like:

George 22
Nick   89
Mike   50
Lucas  12
Panos  55

I tried:

=sort(query({'Sheet1'!A1:D5; 'Sheet2'!A1:D5;'Sheet3'!A1:D5}, "select Col1, MAX(Col2:Col4) Group by Col1 Label MAX(Col2:Col4) '' " ),2, FALSE)

and

=sort(query({'Sheet1'!A1:D5; 'Sheet2'!A1:D5;'Sheet3'!A1:D5}, "select Col1, MAX(MAX(Col2),MAX(Col3), MAX(Col4)) Group by Col1 " ),2, FALSE)

Both didn't work. Any ideas?

Body:
Another approach perhaps a bit simpler but needing two queries

=sort(unique(({Sheet1!A1:A5;Sheet2!A1:A5;Sheet3!A1:A5})))

to get the names starting in (say) F2

Then this to get the maximum values for each name in (say) G2 and pulled down

max(query({Sheet1!A$1:D$5;Sheet2!A$1:D$5;Sheet3!A$1:D$5},"select max(Col2),max(Col3),max(Col4) where Col1='"&F2&"'"))


问:
Sybase - Windows 7
Moving from XP to Windows 7 with client side.

Running into a couple issues with Sybase 15.

1) "Interactive SQL" - many widgets in ie options are defective or missing

2) When running simple query get Swing/AVT widget exception error.

Anyone ran into or worked thru any issues moving to 7?

答:
Other versions of the Windows app, but not 7. As you may be aware 7 is only slightly more reliable than Vista.

Those messages are classically due to (a) Sybase Client (SybaseCentral; InteractiveSQL, the GUI utilities) all using the Java VM and (b) that not being successfuly installed.

Get the Sybase Client CD, and install again. Do not Customise, use the Default installation options. Watch the progress for errors. Ensure the JVM installation succeeds.  You may have to retrieve any missing files from the Windows 7 CD.

Otherwise open a Support Case.

Title: Sybase - Windows 7


问:
Why isn't the variable and its content visible in HTML
Okay I've tried multiple iterations of this code and its not working, I see [object Object] in the H3 tag

This is going to be fundamentally obvious and I'm just missing a core point, I've been scanning stack but can't seem to find why this is happening

So I need the item thats being retrieved from the year ID to be displayed inside the H3 tag, I used the alert function as a test to ensure the value from year was being taken correctly and it is

I've tried

```<code>var age ={};
    function ageinyear() {
        age = document.getElementById("year").value;
        var agetest = age;
    }</script>

<h3 id="userWelcome"><span id="splitColorHeading">
    Welcome <script> document.write(agetest)</script>,</span> to THE SESH</h3>
</code>```

No dice

```<code>var age;
    function ageinyear() {
        age = document.getElementById("year").value;
    }</script>

<h3 id="userWelcome"><span id="splitColorHeading">
    Welcome <script> document.write(age)</script>,</span> to THE SESH</h3>
</code>```

EDIT: I declared both variables inside the function as well as outside, both trying to make them global
Flexing my minuscule brain cells is this possibly due to no return statement, if so added one where I believed it would fit, still no luck

Still nothing,

Can anyone help a beginner out possibly showing and example or show me with my code what I'm missing as well as an explanation why

Many thanks!

More code:

```<code><div id="overlay">
<div id="text">Are you over 18 years old?</div>
<div id="off"><button onclick="off(), ageinyear()">Submit</button></div>
<div id="test"><form>
    <label>
        Name
        <input id="name" name="lblname" type="text" />
    </label>
    <label>
        Age
        <input id="year" name="lblyear" type="text" />
    </label>
</form>
</div>
</code>```

答:
you are trying to print object directly when you write document.write(age) the age variable is called age.toString() which return [object object].
Use

```<code>document.write(JSON.stringify(age))
</code>```

Body:
Okay I've tried multiple iterations of this code and its not working, I see [object Object] in the H3 tag

This is going to be fundamentally obvious and I'm just missing a core point, I've been scanning stack but can't seem to find why this is happening

So I need the item thats being retrieved from the year ID to be displayed inside the H3 tag, I used the alert function as a test to ensure the value from year was being taken correctly and it is

I've tried

var age ={};
    function ageinyear() {
        age = document.getElementById("year").value;
        var agetest = age;
    }</script>

    Welcome , to THE SESH

No dice

var age;
    function ageinyear() {
        age = document.getElementById("year").value;
    }</script>

    Welcome , to THE SESH

EDIT: I declared both variables inside the function as well as outside, both trying to make them global
Flexing my minuscule brain cells is this possibly due to no return statement, if so added one where I believed it would fit, still no luck

Still nothing,

Can anyone help a beginner out possibly showing and example or show me with my code what I'm missing as well as an explanation why

Many thanks!

More code:

Are you over 18 years old?

<button onclick="off(), ageinyear()">Submit</button>

<form>

        Name
        <input id="name" name="lblname" type="text" />

        Age
        <input id="year" name="lblyear" type="text" />

</form>

Body:
you are trying to print object directly when you write document.write(age) the age variable is called age.toString() which return [object object].
Use

document.write(JSON.stringify(age))


问:
Fatal error: Call to a member function run() on null in {path to the test file}
I am using PHPUnit 5.7.23 and phinx 0.9.1,

```<code>public function setUp(){
        $this->phinx = new PhinxApplication;
        $this->phinx->setAutoExit(false);
        $this->phinx->run(new StringInput('migrate'), new NullOutput);
        $this->phinx->run(new StringInput('seed:run'), new NullOutput);
    }

 public function tearDown(){

    $this->phinx->run(new StringInput('rollback -t 0'), new NullOutput);

}
</code>```

This it the code of my test file , every time when i add

```<code> public function testExampleFunction(){

        $this->assertTrue(true);
    }
</code>```

it fails on the line :

$this->phinx->run(new StringInput('rollback -t 0'), new NullOutput);

with the errror :

Fatal error: Call to a member function run() on null in {path to the
  test file}

when i change this:

```<code> public function tearDown()
    {

        if (!empty($this->phinx)) {
            $this->phinx->run(new StringInput('rollback -t 0'), new NullOutput);
        }

    }
</code>```

it passes but since there wasn't rollback, my next tests had crashed

答:
Are you using namespacing (PSR-4) ?
If so, you should have this line of code:

use Phinx\Console\PhinxApplication;

Body:
I am using PHPUnit 5.7.23 and phinx 0.9.1,

public function setUp(){
        $this->phinx = new PhinxApplication;
        $this->phinx->setAutoExit(false);
        $this->phinx->run(new StringInput('migrate'), new NullOutput);
        $this->phinx->run(new StringInput('seed:run'), new NullOutput);
    }

 public function tearDown(){

    $this->phinx->run(new StringInput('rollback -t 0'), new NullOutput);

}

This it the code of my test file , every time when i add

 public function testExampleFunction(){

        $this->assertTrue(true);
    }

it fails on the line :

$this->phinx->run(new StringInput('rollback -t 0'), new NullOutput);

with the errror :

Fatal error: Call to a member function run() on null in {path to the
  test file}

when i change this:

 public function tearDown()
    {

        if (!empty($this->phinx)) {
            $this->phinx->run(new StringInput('rollback -t 0'), new NullOutput);
        }

    }

it passes but since there wasn't rollback, my next tests had crashed