问:
Sum() slows down my query
I am using sum() inside case statement. But this slows down my query. Is there any other way for this. This is the query. Please help me.

```<code>SELECT (SUM(PRI_INS_AGING) + SUM(SEC_INS_AGING) + SUM(TER_INS_AGING)) AS INS_AGING,SUM(PAT_AGING) AS PAT_AGING FROM
                (SELECT
        CASE WHEN L.RESP_PARTY =1 AND VP.STATUS IN(3,5) AND VP.PRIMARY_PAID =0 AND VP.PRIMARY_PENDING >0 AND C.PRIMARY_PAYER_ID >0 AND C.HIDEN=0 THEN SUM(L.AMOUNT) ELSE 0 END AS PRI_INS_AGING,
        CASE WHEN L.RESP_PARTY =2 AND VP.STATUS IN(6,7,5) AND VP.SECONDARY_PAID =0 AND VP.SECONDARY_PENDING >0 AND VP.PRIMARY_PENDING <=0 AND C.SECONDARY_PAYER_ID >0 AND C.HIDEN=0 THEN SUM(L.AMOUNT) ELSE 0 END AS SEC_INS_AGING,
        CASE WHEN L.RESP_PARTY =3 AND VP.STATUS IN(8,9,5) AND VP.TERTIARY_PAID =0 AND VP.TERTIARY_PENDING >0 AND VP.PRIMARY_PENDING <=0 AND VP.SECONDARY_PENDING <=0 AND C.TERTIARY_PAYER_ID >0 AND C.HIDEN=0 THEN SUM(L.AMOUNT) ELSE 0 END AS TER_INS_AGING,
        CASE WHEN L.RESP_PARTY =4 THEN SUM(L.AMOUNT) ELSE 0 END AS PAT_AGING
        FROM VISIT_PROCEDURE VP
        JOIN CLAIM C
        ON (C.CLAIM_ID = VP.CLAIM_ID AND C.CLINIC_ID = VP.CLINIC_ID)
        JOIN LEDGER L
        ON (L.CLAIM_ID = L.CLAIM_ID AND VP.CLINIC_ID = L.CLINIC_ID)
        WHERE C.CLINIC_ID = 34847 AND L.TYPE IN(1,8,9,10,11) AND L.ACTIVE=1
        GROUP BY VP.PROCEDURE_ID,L.TYPE,L.RESP_PARTY,L.ACTIVE)T1
</code>```

Thanks
Sunil

答:
without extra dissecting your SQL, look into your join on LEDGER... you have it doing the CLAIM_ID on the same value...

```<code>JOIN LEDGER L   ON L.CLAIM_ID = L.CLAIM_ID AND VP.CLINIC_ID = L.CLINIC_ID
</code>```

Should the "L.Claim_ID" be joined to a "VP.Claim_ID"??? or something else?

Ok, so with a little bit of time, I came up with this... I would swap the query around some.  In addition, make sure you have an index ON your CLAIM table on Clinic_ID AND Hiden.  Also, your inner query is breaking down the SUM of distinct parts of insurance claims, yet you are not doing anything ELSE with them except summing them in the outer.  I would change to just sum ONCE at the outer for the given conditions

```<code>SELECT STRAIGHT_JOIN
      SUM( IF(   L.RESP_PARTY = 1
             AND VP.STATUS IN(3,5)
             AND VP.PRIMARY_PAID = 0
             AND VP.PRIMARY_PENDING > 0
             AND C.PRIMARY_PAYER_ID > 0, L.AMOUNT, 0 )

           +
           IF(   L.RESP_PARTY = 2
             AND VP.STATUS IN(6,7,5)
             AND VP.SECONDARY_PAID = 0
             AND VP.SECONDARY_PENDING > 0
             AND VP.PRIMARY_PENDING <= 0
             AND C.SECONDARY_PAYER_ID > 0, L.AMOUNT, 0 )

           +
           IF(   L.RESP_PARTY = 3
             AND VP.STATUS IN(8,9,5)
             AND VP.TERTIARY_PAID = 0
             AND VP.TERTIARY_PENDING > 0
             AND VP.PRIMARY_PENDING <= 0
             AND VP.SECONDARY_PENDING <= 0
             AND C.TERTIARY_PAYER_ID > 0, L.AMOUNT, 0 ) ) as INS_AGING,

      SUM( IF( L.RESP_PARTY = 4, L.AMOUNT, 0 )) as PAT_AGING

   FROM
      CLAIM C
         JOIN VISIT_PROCEDURE VP
            ON C.CLAIM_ID = VP.CLAIM_ID
           AND C.CLINIC_ID = VP.CLINIC_ID

             JOIN LEDGER L
                ON VP.CLINIC_ID = L.CLINIC_ID
               AND VP.CLAIM_ID = L.CLAIM_ID
               AND L.TYPE IN ( 1, 8, 9, 10, 11 )
               AND L.ACTIVE = 1
   WHERE
          C.CLINIC_ID = 34847
      AND C.HIDEN = 0
</code>```

Title: Sum() slows down my query

Body:
I am using sum() inside case statement. But this slows down my query. Is there any other way for this. This is the query. Please help me.

SELECT (SUM(PRI_INS_AGING) + SUM(SEC_INS_AGING) + SUM(TER_INS_AGING)) AS INS_AGING,SUM(PAT_AGING) AS PAT_AGING FROM
                (SELECT
        CASE WHEN L.RESP_PARTY =1 AND VP.STATUS IN(3,5) AND VP.PRIMARY_PAID =0 AND VP.PRIMARY_PENDING >0 AND C.PRIMARY_PAYER_ID >0 AND C.HIDEN=0 THEN SUM(L.AMOUNT) ELSE 0 END AS PRI_INS_AGING,
        CASE WHEN L.RESP_PARTY =2 AND VP.STATUS IN(6,7,5) AND VP.SECONDARY_PAID =0 AND VP.SECONDARY_PENDING >0 AND VP.PRIMARY_PENDING <=0 AND C.SECONDARY_PAYER_ID >0 AND C.HIDEN=0 THEN SUM(L.AMOUNT) ELSE 0 END AS SEC_INS_AGING,
        CASE WHEN L.RESP_PARTY =3 AND VP.STATUS IN(8,9,5) AND VP.TERTIARY_PAID =0 AND VP.TERTIARY_PENDING >0 AND VP.PRIMARY_PENDING <=0 AND VP.SECONDARY_PENDING <=0 AND C.TERTIARY_PAYER_ID >0 AND C.HIDEN=0 THEN SUM(L.AMOUNT) ELSE 0 END AS TER_INS_AGING,
        CASE WHEN L.RESP_PARTY =4 THEN SUM(L.AMOUNT) ELSE 0 END AS PAT_AGING
        FROM VISIT_PROCEDURE VP
        JOIN CLAIM C
        ON (C.CLAIM_ID = VP.CLAIM_ID AND C.CLINIC_ID = VP.CLINIC_ID)
        JOIN LEDGER L
        ON (L.CLAIM_ID = L.CLAIM_ID AND VP.CLINIC_ID = L.CLINIC_ID)
        WHERE C.CLINIC_ID = 34847 AND L.TYPE IN(1,8,9,10,11) AND L.ACTIVE=1
        GROUP BY VP.PROCEDURE_ID,L.TYPE,L.RESP_PARTY,L.ACTIVE)T1

Thanks
Sunil

Body:
without extra dissecting your SQL, look into your join on LEDGER... you have it doing the CLAIM_ID on the same value...

JOIN LEDGER L   ON L.CLAIM_ID = L.CLAIM_ID AND VP.CLINIC_ID = L.CLINIC_ID

Should the "L.Claim_ID" be joined to a "VP.Claim_ID"??? or something else?

Ok, so with a little bit of time, I came up with this... I would swap the query around some.  In addition, make sure you have an index ON your CLAIM table on Clinic_ID AND Hiden.  Also, your inner query is breaking down the SUM of distinct parts of insurance claims, yet you are not doing anything ELSE with them except summing them in the outer.  I would change to just sum ONCE at the outer for the given conditions

SELECT STRAIGHT_JOIN
      SUM( IF(   L.RESP_PARTY = 1
             AND VP.STATUS IN(3,5)
             AND VP.PRIMARY_PAID = 0
             AND VP.PRIMARY_PENDING > 0
             AND C.PRIMARY_PAYER_ID > 0, L.AMOUNT, 0 )

           +
           IF(   L.RESP_PARTY = 2
             AND VP.STATUS IN(6,7,5)
             AND VP.SECONDARY_PAID = 0
             AND VP.SECONDARY_PENDING > 0
             AND VP.PRIMARY_PENDING <= 0
             AND C.SECONDARY_PAYER_ID > 0, L.AMOUNT, 0 )

           +
           IF(   L.RESP_PARTY = 3
             AND VP.STATUS IN(8,9,5)
             AND VP.TERTIARY_PAID = 0
             AND VP.TERTIARY_PENDING > 0
             AND VP.PRIMARY_PENDING <= 0
             AND VP.SECONDARY_PENDING <= 0
             AND C.TERTIARY_PAYER_ID > 0, L.AMOUNT, 0 ) ) as INS_AGING,

      SUM( IF( L.RESP_PARTY = 4, L.AMOUNT, 0 )) as PAT_AGING

   FROM
      CLAIM C
         JOIN VISIT_PROCEDURE VP
            ON C.CLAIM_ID = VP.CLAIM_ID
           AND C.CLINIC_ID = VP.CLINIC_ID

             JOIN LEDGER L
                ON VP.CLINIC_ID = L.CLINIC_ID
               AND VP.CLAIM_ID = L.CLAIM_ID
               AND L.TYPE IN ( 1, 8, 9, 10, 11 )
               AND L.ACTIVE = 1
   WHERE
          C.CLINIC_ID = 34847
      AND C.HIDEN = 0


来源: stackexchange

问:
left and right sidebars overlapping main content using position:fixed
I'm new to CSS.
trying to study some layouts and ran into this issue.

I'm trying to prevent the left and right sidebar(aside) from scrolling. No matter how much I scroll the main, it will always stay there; I've set its position to fixed and it looked all fine. the issue is, the main content is overlapping with the right sidebar(aside) when resizing. I've tried position: relative and absolute to the right and changing it to div but nothing happens.
the goal is - when my chrome browser shrinks, it should show the Horizontal/vertical scrollbars without any overlapping of main contents. no matter how long my main content is, the sidebars should always be there! Thank you in advance!

Here is my code

body, html {
    font-family: Helvetica;
    background-color: rgba(0, 0, 0);
}
#sidebar {
    position: fixed;
    width: 400px;
    height: 100%;
    margin-top: 120px;
    top: 0;
}
.left {
    left: 0;
    bottom: 0;
    background-color: rgb(82, 50, 50);
}
.content {
    display: inline-block;
    background-color: rgb(255, 255, 255);
    margin-top: 120px;
    top: 0;
    width: 800px;
    height:100%;
    margin-left: 400px;
    margin-right: 400px;
}
.right {
    right: 0;
    bottom: 0;
    background-color: rgb(255, 217, 0);
}

#wrapper {
    margin-left:0;
    margin-right:0;
    max-width: 1600px;
    border:1px solid white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
    <aside id="sidebar" class="left">
    </aside>
    <div class="content">
        Lorem ipsum blah blah (cutted: about 100lines)
    </div>

    <aside id="sidebar" class="right">
    </aside>
</div></code>```

答:
You need to give the .content a dynamic width instead of the static one you've set.
Try this

```<code>.content {
    width: calc(100% - 400px - 400px); /* where 400px and 400px are the width of the sidebars */
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm new to CSS.
trying to study some layouts and ran into this issue.

I'm trying to prevent the left and right sidebar(aside) from scrolling. No matter how much I scroll the main, it will always stay there; I've set its position to fixed and it looked all fine. the issue is, the main content is overlapping with the right sidebar(aside) when resizing. I've tried position: relative and absolute to the right and changing it to div but nothing happens.
the goal is - when my chrome browser shrinks, it should show the Horizontal/vertical scrollbars without any overlapping of main contents. no matter how long my main content is, the sidebars should always be there! Thank you in advance!

Here is my code

body, html {
    font-family: Helvetica;
    background-color: rgba(0, 0, 0);
}
#sidebar {
    position: fixed;
    width: 400px;
    height: 100%;
    margin-top: 120px;
    top: 0;
}
.left {
    left: 0;
    bottom: 0;
    background-color: rgb(82, 50, 50);
}
.content {
    display: inline-block;
    background-color: rgb(255, 255, 255);
    margin-top: 120px;
    top: 0;
    width: 800px;
    height:100%;
    margin-left: 400px;
    margin-right: 400px;
}
.right {
    right: 0;
    bottom: 0;
    background-color: rgb(255, 217, 0);
}

#wrapper {
    margin-left:0;
    margin-right:0;
    max-width: 1600px;
    border:1px solid white;
}

        Lorem ipsum blah blah (cutted: about 100lines)

Body:
You need to give the .content a dynamic width instead of the static one you've set.
Try this

.content {
    width: calc(100% - 400px - 400px); /* where 400px and 400px are the width of the sidebars */
}


问:
Logs are not getting generated with slf4j
I started facing issue since I have upgraded to 2.17.1 version , earlier my version was 2.1 and everything is working properly , since i have upgraded the version logs are not getting generated to log file

I have following configuration in my pom.xml

```<code>    <groupId>org.slf4j</groupId>
              <artifactId>log4j-over-slf4j</artifactId>
              <version>2.0.0-alpha6</version>
            </dependency>
         <dependency>
              <groupId>org.apache.logging.log4j</groupId>
              <artifactId>log4j-slf4j-impl</artifactId>
              <version>2.17.1</version>
            </dependency>
        <dependency>
              <groupId>org.apache.logging.log4j</groupId>
              <artifactId>log4j-api</artifactId>
              <version>2.17.1</version>
            </dependency>

            <dependency>
              <groupId>org.apache.logging.log4j</groupId>
              <artifactId>log4j-core</artifactId>
              <version>2.17.1</version>
            </dependency>
</code>```

My logback.xml has following content:

```<code>    <?xml version="1.0" encoding="UTF-8"?>
            <Configuration status="warn" name="MyApp" packages="">
                <Appenders>
                    <RollingRandomAccessFile name="RollingRandomAccessFile" fileName="/lcc/lccapp/logs/lcc-publisher/producer.log"
                                             filePattern="/lcc/lccapp/logs/lcc-publisher/producer-%d{MM-dd-yyyy}-%i.zip" immediateFlush="false">
                        <PatternLayout>
                            <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
                        </PatternLayout>
                        <Policies>
                            <TimeBasedTriggeringPolicy interval="1" />
                        </Policies>
                        <DefaultRolloverStrategy max="100"/>
                    </RollingRandomAccessFile>
                </Appenders>
                <Loggers>
                    <Root level="info">
                        <AppenderRef ref="RollingRandomAccessFile"/>
                    </Root>
                </Loggers>
            </Configuration>
</code>```

What i see in boot.log is:

```<code>    Starting the lcc-publisher application
    Application directory is /lcc/lccapp/apps/lcc-publisher
    SLF4J: No SLF4J providers were found.
    SLF4J: Defaulting to no-operation (NOP) logger implementation
    SLF4J: See http://www.slf4j.org/codes.html#noProviders for further details.
    SLF4J: Class path contains SLF4J bindings targeting slf4j-api versions prior to 1.8.
    SLF4J: Ignoring binding found at [jar:file:/lcc/lccapp/apps/lcc-publisher/lib/log4j-slf4j-impl-2.17.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
    SLF4J: See http://www.slf4j.org/codes.html#ignoredBindings for an explanation.
    Current dir using System:/lcc/lccapp/apps/tcc-publisher

</code>```

Application is running without any issues , but logs are not getting written to log files.

答:
Have you seen this page?
Log4j 2 SLF4J Binding. Starting with Log4J 2.11.1, there are two separate implementations of Log4J 2's SLF4J binding, depending on your version of SLF4J.

Your use of log4j-over-slf4j version 2.0.0-alpha6 means your SLF4J API version (slf4j-api) is also 2.0.0-alpha6. Thus, according to the link above, you need to change your use of log4j-slf4j-impl to log4j-slf4j18-impl.

A couple of other things about the SLF4J version you're using:

Are you sure you want to use SLF4J 2.x instead of 1.x? The fact that they are shipping a 2.x implies there are breaking changes in the API. So I don't think it can be guaranteed that any current version of Log4J is going to be compatible, especially since it's not finalized. 2.0.0 is still shipping alpha versions.

Are you sure you want to use an alpha version of SLF4J instead of a stable release? Whatever works right now, it may break next time someone upgrades your SLF4J.

Incidentally, log4j-slf4j-impl brings in log4j-api transitively, so you should not need to explicitly declare log4j-api as a dependency. This is one fewer entry you need to manually maintain, and one fewer <version></version> you have to worry about keeping in sync.

Body:
I started facing issue since I have upgraded to 2.17.1 version , earlier my version was 2.1 and everything is working properly , since i have upgraded the version logs are not getting generated to log file

I have following configuration in my pom.xml

    <groupId>org.slf4j</groupId>
              <artifactId>log4j-over-slf4j</artifactId>
              <version>2.0.0-alpha6</version>
            </dependency>
         <dependency>
              <groupId>org.apache.logging.log4j</groupId>
              <artifactId>log4j-slf4j-impl</artifactId>
              <version>2.17.1</version>
            </dependency>
        <dependency>
              <groupId>org.apache.logging.log4j</groupId>
              <artifactId>log4j-api</artifactId>
              <version>2.17.1</version>
            </dependency>

            <dependency>
              <groupId>org.apache.logging.log4j</groupId>
              <artifactId>log4j-core</artifactId>
              <version>2.17.1</version>
            </dependency>

My logback.xml has following content:

    <?xml version="1.0" encoding="UTF-8"?>
            <Configuration status="warn" name="MyApp" packages="">
                <Appenders>
                    <RollingRandomAccessFile name="RollingRandomAccessFile" fileName="/lcc/lccapp/logs/lcc-publisher/producer.log"
                                             filePattern="/lcc/lccapp/logs/lcc-publisher/producer-%d{MM-dd-yyyy}-%i.zip" immediateFlush="false">
                        <PatternLayout>
                            <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
                        </PatternLayout>
                        <Policies>
                            <TimeBasedTriggeringPolicy interval="1" />
                        </Policies>
                        <DefaultRolloverStrategy max="100"/>
                    </RollingRandomAccessFile>
                </Appenders>
                <Loggers>
                    <Root level="info">
                        <AppenderRef ref="RollingRandomAccessFile"/>
                    </Root>
                </Loggers>
            </Configuration>

What i see in boot.log is:

    Starting the lcc-publisher application
    Application directory is /lcc/lccapp/apps/lcc-publisher
    SLF4J: No SLF4J providers were found.
    SLF4J: Defaulting to no-operation (NOP) logger implementation
    SLF4J: See http://www.slf4j.org/codes.html#noProviders for further details.
    SLF4J: Class path contains SLF4J bindings targeting slf4j-api versions prior to 1.8.
    SLF4J: Ignoring binding found at [jar:file:/lcc/lccapp/apps/lcc-publisher/lib/log4j-slf4j-impl-2.17.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
    SLF4J: See http://www.slf4j.org/codes.html#ignoredBindings for an explanation.
    Current dir using System:/lcc/lccapp/apps/tcc-publisher

Application is running without any issues , but logs are not getting written to log files.


问:
Generated constants for enum values
I'd need to store some properties of the enum's entries in their constants. For example indicate whether a color is cold or warm.

```<code>enum Colors
{
  Yellow, // warm
  Blue,   // cold
  Gray,   // cold
  Red,    // warm
  // etc.
}
</code>```

In C++ I would define a macro to generate bitmasks for the constants.
Something like:

```<code>#define WARM 1
#define COLD 0

#define MAKECOLOR(index, type) ((index << 8) | type)

enum Colors
{
  Yellow = MAKECOLOR(0, WARM),
  Blue   = MAKECOLOR(1, COLD),
  Gray   = MAKECOLOR(2, COLD),
  Red    = MAKECOLOR(3, WARM),
  // etc.
}
</code>```

In C# this is not possible because there are no macros. I want to avoid writing bitmask expressions directly in the enum. Like this:

```<code>  ...
  Gray   = ((2 << 8) | 0),
  ...
</code>```

Any ideas?

P.S.

Yes, I'm a syntactic sugar freak. :D

答:
You should use attributes at the enum values. Read this article, it's pretty good:

http://www.codeproject.com/KB/cs/enumwithdescription.aspx

Hope it helps!

ContentLicense: CC BY-SA 3.0

Title: Generated constants for enum values

Body:
I'd need to store some properties of the enum's entries in their constants. For example indicate whether a color is cold or warm.

enum Colors
{
  Yellow, // warm
  Blue,   // cold
  Gray,   // cold
  Red,    // warm
  // etc.
}

In C++ I would define a macro to generate bitmasks for the constants.
Something like:

#define WARM 1
#define COLD 0

#define MAKECOLOR(index, type) ((index << 8) | type)

enum Colors
{
  Yellow = MAKECOLOR(0, WARM),
  Blue   = MAKECOLOR(1, COLD),
  Gray   = MAKECOLOR(2, COLD),
  Red    = MAKECOLOR(3, WARM),
  // etc.
}

In C# this is not possible because there are no macros. I want to avoid writing bitmask expressions directly in the enum. Like this:

  ...
  Gray   = ((2 << 8) | 0),
  ...

Any ideas?

P.S.

Yes, I'm a syntactic sugar freak. :D


问:
extract elements of tuple from a pandas series
I have a pandas series with data of type tuple as list elements. The length of the tuple is exactly 2 and there are a bunch of NaNs. I am trying to split each list in the tuple into its own column.

```<code>import pandas as pd
import numpy as np

df = pd.DataFrame({'val': [([1,2,3],[4,5,6]),
                           ([7,8,9],[10,11,12]),
                           np.nan]
                 })
</code>```

Expected Output:

答:
You could also convert the column to a list and cast it to the DataFrame constructor (fill None with np.nan as well):

```<code>out = pd.DataFrame(df['val'].tolist(), columns=['x','y']).fillna(np.nan)
</code>```

Output:

```<code>           x             y
0  [1, 2, 3]     [4, 5, 6]
1  [7, 8, 9]  [10, 11, 12]
2        NaN           NaN
</code>```

Body:
I have a pandas series with data of type tuple as list elements. The length of the tuple is exactly 2 and there are a bunch of NaNs. I am trying to split each list in the tuple into its own column.

import pandas as pd
import numpy as np

df = pd.DataFrame({'val': [([1,2,3],[4,5,6]),
                           ([7,8,9],[10,11,12]),
                           np.nan]
                 })

Expected Output:

Body:
You could also convert the column to a list and cast it to the DataFrame constructor (fill None with np.nan as well):

out = pd.DataFrame(df['val'].tolist(), columns=['x','y']).fillna(np.nan)

Output:

           x             y
0  [1, 2, 3]     [4, 5, 6]
1  [7, 8, 9]  [10, 11, 12]
2        NaN           NaN


问:
How can you add a trendline to a seaborn's lineplot?
Here's what I'm trying to recreate in Seaborn (this was done with Matplotlib)

I see in Seaborn you could use a regplot() but this one is for scatter charts. Anyway, if I try to use it, it won't work because the x are datetime, so I did a mixture of Seaborn and Matplotlib, it works, but I don't like it, I think there must be a better way, Seaborn only.

```<code>x = range(0, len(hom.fecha))

plt.figure(figsize=(12, 9))
plt.style.use('fivethirtyeight')

chart = sns.lineplot(x='fecha', y='n', data=df,
                     hue='sexo', markers=True)
chart.set(title='Personas Migrantes', ylabel='# Personas', xlabel="Fecha")

# Linear regressions for each sex
z = np.polyfit(x, hom.n, 1)
p = np.poly1d(z)
plt.plot(hom.fecha, p(x), c="b", ls=":")

z = np.polyfit(x, muj.n, 1)
p = np.poly1d(z)
plt.plot(hom.fecha, p(x), c="r", ls=':')
</code>```

I get this picture:

Which I think is much more pleasant than the first one, but I just don't get how to add the trend lines using only seaborn.

Any idea?

=== EDIT ===

If I use regplot() it throws an exception...

```<code>sns.regplot(x="fecha", y="n", data=df)
</code>```

This one... (it plots something tho, like a scatter chart, with points)

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-70-0f60957abc3f> in <module>
----> 1 sns.regplot(x="fecha", y="n", data=df)

blah blah blah

TypeError: unsupported operand type(s) for *: 'Timestamp' and 'float'
</code>```

答:
I see this is a year old, but I just ran into and solved a similar problem so I'll leave the solution here.

The issue with your regplot is that you are using a column name as your x-axis, but (I assume), "fecha" is actually the name of your index and not the name of a column.  If you were to take this line:

```<code>sns.regplot(x="fecha", y="n", data=df)
</code>```

and change it to:

```<code>sns.regplot(x=df.index, y="n", data=df)
</code>```

Then I would expect it to work.  You may also want to take out the confidence interval which is drawn by default (add paramter ci=False) and change the color to be red or blue or whatever.

I know it's probably too late to help you, but I hope it helps someone!

Body:
Here's what I'm trying to recreate in Seaborn (this was done with Matplotlib)

I see in Seaborn you could use a regplot() but this one is for scatter charts. Anyway, if I try to use it, it won't work because the x are datetime, so I did a mixture of Seaborn and Matplotlib, it works, but I don't like it, I think there must be a better way, Seaborn only.

x = range(0, len(hom.fecha))

plt.figure(figsize=(12, 9))
plt.style.use('fivethirtyeight')

chart = sns.lineplot(x='fecha', y='n', data=df,
                     hue='sexo', markers=True)
chart.set(title='Personas Migrantes', ylabel='# Personas', xlabel="Fecha")

# Linear regressions for each sex
z = np.polyfit(x, hom.n, 1)
p = np.poly1d(z)
plt.plot(hom.fecha, p(x), c="b", ls=":")

z = np.polyfit(x, muj.n, 1)
p = np.poly1d(z)
plt.plot(hom.fecha, p(x), c="r", ls=':')

I get this picture:

Which I think is much more pleasant than the first one, but I just don't get how to add the trend lines using only seaborn.

Any idea?

=== EDIT ===

If I use regplot() it throws an exception...

sns.regplot(x="fecha", y="n", data=df)

This one... (it plots something tho, like a scatter chart, with points)

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-70-0f60957abc3f> in <module>
----> 1 sns.regplot(x="fecha", y="n", data=df)

blah blah blah

TypeError: unsupported operand type(s) for *: 'Timestamp' and 'float'

Body:
I see this is a year old, but I just ran into and solved a similar problem so I'll leave the solution here.

The issue with your regplot is that you are using a column name as your x-axis, but (I assume), "fecha" is actually the name of your index and not the name of a column.  If you were to take this line:

sns.regplot(x="fecha", y="n", data=df)

and change it to:

sns.regplot(x=df.index, y="n", data=df)

Then I would expect it to work.  You may also want to take out the confidence interval which is drawn by default (add paramter ci=False) and change the color to be red or blue or whatever.

I know it's probably too late to help you, but I hope it helps someone!


问:
How to plot multiple samples on ggplot in R?
I've run a for loop and taken multiple samples of data. I want to take the data I just got and turn in into a histogram using ggplot.

Here is my code:

for (i in 1:1000){
  sample[1000]
  sample[i] <- mean(pop$y[sample.int(nrow(pop),5, replace = FALSE)])

}

ggplot(sample, aes(x = sample)) + geom_histogram(bins = 40)```

I get this error message:
"Error: data must be a data frame, or other object coercible by fortify(), not a numeric vector. Run rlang::last_error() to see where the error occurred."

Is there a way for me to take the sample array I have now and turn it into a histogram using ggplot? Anything helps. Thanks!

答:
I ran into errors because sample is a function. I changed the object name to samp.

I created some arbitrary data to represent pop$y, as well.

```<code>library(tidyverse)

set.seed(435) # repeatability with rnorm
pop = data.frame(y = rnorm(100, 10, 2)) # create pop data

# storage for the loop
samp = vector(length = 1000) # this can't be in the loop

for (i in 1:1000){
  samp[i] <- mean(pop$y[sample.int(nrow(pop),5, replace = FALSE)])
}

ggplot(data.frame(samp = samp), aes(x = samp)) +
   geom_histogram(bins = 40)
</code>```

It was a few minor changes to what you had. This is the histogram that was produced based on these inputs.

Body:
I've run a for loop and taken multiple samples of data. I want to take the data I just got and turn in into a histogram using ggplot.

Here is my code:

for (i in 1:1000){
  sample[1000]
  sample[i] <- mean(pop$y[sample.int(nrow(pop),5, replace = FALSE)])

}

ggplot(sample, aes(x = sample)) + geom_histogram(bins = 40)

I get this error message:
"Error: data must be a data frame, or other object coercible by fortify(), not a numeric vector. Run rlang::last_error() to see where the error occurred."

Is there a way for me to take the sample array I have now and turn it into a histogram using ggplot? Anything helps. Thanks!

Body:
I ran into errors because sample is a function. I changed the object name to samp.

I created some arbitrary data to represent pop$y, as well.

library(tidyverse)

set.seed(435) # repeatability with rnorm
pop = data.frame(y = rnorm(100, 10, 2)) # create pop data

# storage for the loop
samp = vector(length = 1000) # this can't be in the loop

for (i in 1:1000){
  samp[i] <- mean(pop$y[sample.int(nrow(pop),5, replace = FALSE)])
}

ggplot(data.frame(samp = samp), aes(x = samp)) +
   geom_histogram(bins = 40)

It was a few minor changes to what you had. This is the histogram that was produced based on these inputs.


答:
One way using pandas.Series.apply:

```<code>new_df = df["val"].apply(pd.Series)
print(new_df)
</code>```

Output:

```<code>           0             1
0  [1, 2, 3]     [4, 5, 6]
1  [7, 8, 9]  [10, 11, 12]
2        NaN           NaN
</code>```

Title: extract elements of tuple from a pandas series

Body:
One way using pandas.Series.apply:

new_df = df["val"].apply(pd.Series)
print(new_df)

Output:

           0             1
0  [1, 2, 3]     [4, 5, 6]
1  [7, 8, 9]  [10, 11, 12]
2        NaN           NaN


问:
Problem with "this" in JS
Consider the following code:

```<code>    var table = function () {

        return {
            _init: function (tableId) {
                this.tableId = tableId;
                this.table = $("#" + tableId);
            },

            removeStripes: function() {
                this.table.find(".alt").removeClass("alt");
            },

            addStripes: function () {
                this.table.find("tbody tr:even").addClass("alt");
            },

            resetStripes: function() {
                this.removeStripes();
                this.addStripes();
            },

            sort: function (options) {
                this.table.tablesorter(options);
                this.table.bind("sortEnd", this.resetStripes);
            },

        }

    }

var newTable = new table();
newTable._init("tableId");
var options = {};
newTable.sort(options);
</code>```

The browser says this.removeStripes called by this.resetStripes, on one of the last lines) is not a function. I guess there is some error with this, but I can't figure out where it is. Any idea, anyone?

答:
As you are declaring methods with anonymous functions, this is not anymore in the table function scope.

You should use:

```<code> removeStripes: function() {
   // ...
 }.bind(this)
</code>```

on all of your methods.

Title: Problem with "this" in JS

Body:
Consider the following code:

    var table = function () {

        return {
            _init: function (tableId) {
                this.tableId = tableId;
                this.table = $("#" + tableId);
            },

            removeStripes: function() {
                this.table.find(".alt").removeClass("alt");
            },

            addStripes: function () {
                this.table.find("tbody tr:even").addClass("alt");
            },

            resetStripes: function() {
                this.removeStripes();
                this.addStripes();
            },

            sort: function (options) {
                this.table.tablesorter(options);
                this.table.bind("sortEnd", this.resetStripes);
            },

        }

    }

var newTable = new table();
newTable._init("tableId");
var options = {};
newTable.sort(options);

The browser says this.removeStripes called by this.resetStripes, on one of the last lines) is not a function. I guess there is some error with this, but I can't figure out where it is. Any idea, anyone?

Body:
As you are declaring methods with anonymous functions, this is not anymore in the table function scope.

You should use:

 removeStripes: function() {
   // ...
 }.bind(this)

on all of your methods.


问:
Problems using ganache-cli command
It's saying that it doesn't recognize ganache-cli as a command, despite installing it and everything else as directed.

Using:

brownie v1.17.2

node v17.2.0 (npm v8.1.4)

nvm 0.39.0

Python 3.9.7

Ganache CLI v6.12.2 (ganache-core: 2.13.2)

As part of the Solidity course here, specifically lesson 5. Github repo here.

```<code>x@y brownie_simple_storage % brownie run scripts/deploy.py
Brownie v1.17.2 - Python development framework for Ethereum

BrownieSimpleStorageProject is the active project.

Launching 'ganache-cli --port 8545 --gasLimit 12000000 --accounts 10 --hardfork istanbul --mnemonic brownie'...
  File "brownie/_cli/__main__.py", line 64, in main
    importlib.import_module(f"brownie._cli.{cmd}").main()
  File "brownie/_cli/run.py", line 44, in main
    network.connect(CONFIG.argv["network"])
  File "brownie/network/main.py", line 50, in connect
    rpc.launch(active["cmd"], **active["cmd_settings"])
  File "brownie/network/rpc/__init__.py", line 93, in launch
    raise RPCProcessError(cmd, uri)
RPCProcessError: Unable to launch local RPC client.
Command: ganache-cli
URI: http://127.0.0.1:8545
</code>```

答: Most likely the issue you're dealing with is because ganache is already running in another active project, in order to have brownie recognize ganache is to make sure that's the only environment running ganache close to the project running the node. Which, is most likely the web3 simple storage file... not the newly created brownie file.</p>

Title: Problems using ganache-cli command

Body:
It's saying that it doesn't recognize ganache-cli as a command, despite installing it and everything else as directed.

Using:

brownie v1.17.2

node v17.2.0 (npm v8.1.4)

nvm 0.39.0

Python 3.9.7

Ganache CLI v6.12.2 (ganache-core: 2.13.2)

As part of the Solidity course here, specifically lesson 5. Github repo here.

x@y brownie_simple_storage % brownie run scripts/deploy.py
Brownie v1.17.2 - Python development framework for Ethereum

BrownieSimpleStorageProject is the active project.

Launching 'ganache-cli --port 8545 --gasLimit 12000000 --accounts 10 --hardfork istanbul --mnemonic brownie'...
  File "brownie/_cli/__main__.py", line 64, in main
    importlib.import_module(f"brownie._cli.{cmd}").main()
  File "brownie/_cli/run.py", line 44, in main
    network.connect(CONFIG.argv["network"])
  File "brownie/network/main.py", line 50, in connect
    rpc.launch(active["cmd"], **active["cmd_settings"])
  File "brownie/network/rpc/__init__.py", line 93, in launch
    raise RPCProcessError(cmd, uri)
RPCProcessError: Unable to launch local RPC client.
Command: ganache-cli
URI: http://127.0.0.1:8545


问:
How do I replace the list of nan with list of zeroes in a pandas dataframe cell
I have this dataframe. How do I replace the list of nan with list of zeroes?</p>
```<code>a   b
1   [nan, nan]
5   [nan, nan, nan]
0   [0, 0]
</code>```

答:
How about a list comprehension?</p>
```<code>df['b'] = [[0 if pd.isna(y) else y for y in x] for x in df['b']]
df

   a          b
0  1     [0, 0]
1  5  [0, 0, 0]
2  0     [0, 0]
</code>```

Body:
I have this dataframe. How do I replace the list of nan with list of zeroes?

a   b
1   [nan, nan]
5   [nan, nan, nan]
0   [0, 0]

Body:
How about a list comprehension?

df['b'] = [[0 if pd.isna(y) else y for y in x] for x in df['b']]
df

   a          b
0  1     [0, 0]
1  5  [0, 0, 0]
2  0     [0, 0]


问:
What DB to use for a windows application?
I am developing a small windows application in .net. What DB should I use?

DB Structure

Table 1 : Not more than 3 fields : 50+ records (Add, Delete)

Table 2 : Not more than 10 fields : 10-20 records (Add, Delete)

I thought of using XMLDatabase but some say its not advisable to use it. What are the reasons for this?
If it is OK to use XML files as the DB then can you suggest some tutorials or best practices? I have worked with XML files before. Is there anything different when it comes to using it as a DB?

I am also planning to distribute the application to my friends some time later and these guys are not programmers and they are less tech savvy.

So If I am using SQL server how can I deploy it in others machine? How can I add it to the setup file?

Update: Thanks for the answers. I am going for SQLite and here is a tutorial about SQLite and .net if someone is interested.

答: Something small like SQLite or you could get away with just using a built in SQLServer Express database in your app.</p>

OwnerDisplayName: Shoban

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Shoban

OwnerDisplayName: TheTXI


问:
How to trigger Elementor Popup based on specific url
I have a one page website with different sections and few simple popup which are triggered when user clicks on link/button on a page. I want same popup to open when user access website with a specific url example

www.example.com/#menu

www.example.com/#privacy-policy

I found setting under Elementor popup when arriving from specific URL but this option is not working for me.

I can do same using custom JavaScript unless it will not work with elementor feature.

I tried different combination of url such as https://www.example.com/#menu #menu https://example.com/#menu

its not working for any combination.

I did keep condition setting also as Entire site etc..

Just need a point as i could not find any specify article regarding this as most of the article are about how to trigger popup from link.

答:
Set a class on the section you want.

Go to Popup triggers

Check "On scroll to element" en put the class in.

Now the pop up show op when you scroll on the section.


问:
Zlib error when attempting to run npm install or yarn
I have just made some pulls from my library's from GitHub, I was using my windows computer to do the coding in VSCode. The code has no problem, although when I attempt to run npm install or yarn install to get the node_modules and the yarn.lock I get a weird error and the packages don't work. I'm using ZSH as the terminal for my Mac.

This is the error output:

```<code>niltonsf@Niltons-MacBook-Pro ignews.nosync % sudo yarn install
Password:
yarn install v1.22.15
[1/4]   Resolving packages...
[2/4]   Fetching packages...
error An unexpected error occurred: "https://registry.yarnpkg.com/acorn/-/acorn-7.4.1.tgz: incorrect data check".
info If you think this is a bug, please open a bug report with the information provided in "/Users/niltonsf/Desktop/ignews.nosync/yarn-error.log".
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
error https://registry.yarnpkg.com/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-11.1.2.tgz: incorrect data check
error https://registry.yarnpkg.com/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-11.1.2.tgz: incorrect data check
niltonsf@Niltons-MacBook-Pro ignews.nosync % npm install
npm WARN deprecated @types/next-auth@3.15.0: This is a stub types definition. next-auth provides its own type definitions, so you do not need this installed.
npm WARN deprecated querystring@0.2.1: The querystring API is considered Legacy. new code should use the URLSearchParams API instead.
npm WARN deprecated querystring@0.2.0: The querystring API is considered Legacy. new code should use the URLSearchParams API instead.
npm ERR! code Z_DATA_ERROR
npm ERR! errno -3
npm ERR! zlib: incorrect data check

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/niltonsf/.npm/_logs/2021-10-05T15_44_51_340Z-debug.log
niltonsf@Niltons-MacBook-Pro ignews.nosync %
</code>```

My versions from node, npm and yarn:

```<code>node: v14.18.0
npm: 6.14.15
yarn: 1.22.15
macos: Big Sur
</code>```

What I have attempted:

```<code>deleting the yarn.lock
running: npm cache verify and then npm cache clean --force
</code>```

This is the end of the log result:

```<code>1165 verbose stack     at PassThrough.Writable.write (internal/streams/writable.js:303:10)
1165 verbose stack     at PassThrough.ondata (internal/streams/readable.js:731:22)
1165 verbose stack     at PassThrough.emit (events.js:400:28)
1166 verbose cwd /Users/niltonsf/Desktop/github.nosync/ignews
1167 verbose Darwin 20.6.0
1168 verbose argv "/usr/local/Cellar/node@14/14.18.0/bin/node" "/usr/local/opt/node@14/bin/npm" "install"
1169 verbose node v14.18.0
1170 verbose npm  v6.14.15
1171 error code Z_DATA_ERROR
1172 error errno -3
1173 error zlib: incorrect data check
1174 verbose exit [ -3, true ]
</code>```

If I run the npm i or yarn in my windows computer I dont get any error

答:
For those using macbook with m1 chip I was having this issue and tried installing the following node versions with nvm but the error persisted:

v14.5.5

v14.16.0

v14.16.1

14.17.6

I tried cleaning cache and all the solutions mentioned here, I even tried different combinations of node and npm but no luck.

To fix the problem I had to run the command to switch architecture:
arch -x86_64 zsh

After that I was able to npm install with no issues.

Body:
I have just made some pulls from my library's from GitHub, I was using my windows computer to do the coding in VSCode. The code has no problem, although when I attempt to run npm install or yarn install to get the node_modules and the yarn.lock I get a weird error and the packages don't work. I'm using ZSH as the terminal for my Mac.

This is the error output:

niltonsf@Niltons-MacBook-Pro ignews.nosync % sudo yarn install
Password:
yarn install v1.22.15
[1/4]   Resolving packages...
[2/4]   Fetching packages...
error An unexpected error occurred: "https://registry.yarnpkg.com/acorn/-/acorn-7.4.1.tgz: incorrect data check".
info If you think this is a bug, please open a bug report with the information provided in "/Users/niltonsf/Desktop/ignews.nosync/yarn-error.log".
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
error https://registry.yarnpkg.com/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-11.1.2.tgz: incorrect data check
error https://registry.yarnpkg.com/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-11.1.2.tgz: incorrect data check
niltonsf@Niltons-MacBook-Pro ignews.nosync % npm install
npm WARN deprecated @types/next-auth@3.15.0: This is a stub types definition. next-auth provides its own type definitions, so you do not need this installed.
npm WARN deprecated querystring@0.2.1: The querystring API is considered Legacy. new code should use the URLSearchParams API instead.
npm WARN deprecated querystring@0.2.0: The querystring API is considered Legacy. new code should use the URLSearchParams API instead.
npm ERR! code Z_DATA_ERROR
npm ERR! errno -3
npm ERR! zlib: incorrect data check

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/niltonsf/.npm/_logs/2021-10-05T15_44_51_340Z-debug.log
niltonsf@Niltons-MacBook-Pro ignews.nosync %

My versions from node, npm and yarn:

node: v14.18.0
npm: 6.14.15
yarn: 1.22.15
macos: Big Sur

What I have attempted:

deleting the yarn.lock
running: npm cache verify and then npm cache clean --force

This is the end of the log result:

1165 verbose stack     at PassThrough.Writable.write (internal/streams/writable.js:303:10)
1165 verbose stack     at PassThrough.ondata (internal/streams/readable.js:731:22)
1165 verbose stack     at PassThrough.emit (events.js:400:28)
1166 verbose cwd /Users/niltonsf/Desktop/github.nosync/ignews
1167 verbose Darwin 20.6.0
1168 verbose argv "/usr/local/Cellar/node@14/14.18.0/bin/node" "/usr/local/opt/node@14/bin/npm" "install"
1169 verbose node v14.18.0
1170 verbose npm  v6.14.15
1171 error code Z_DATA_ERROR
1172 error errno -3
1173 error zlib: incorrect data check
1174 verbose exit [ -3, true ]

If I run the npm i or yarn in my windows computer I dont get any error


问:
curl -k or --insecure equivalent to Powershell Invoke-WebRequest not working
I am trying to execute:

```<code>$postParams = @{user='myUser';password='myPass'};
Invoke-WebRequest -Uri https://MYURL -Method POST -Body $postParams;
</code>```

And I am always getting 403 forbidden, in ubuntu or git terminal this works like a charm (with -k or --insecure):

```<code>curl -k -X POST "https://MYURL" -H "accept: */*" -H "Content-Type: application/json" -d "{ \"user\" : \"myUser\", \"password\" : \"myPass\"}"
</code>```

or

```<code>curl -X POST "https://MYURL" -H "accept: */*" -H "Content-Type: application/json" -d "{ \"user\" : \"myUser\", \"password\" : \"myPass\"}" --insecure
</code>```

After some research I tried two solutions:

Solution #1:

```<code>[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true };

$postParams = @{user='myUser';password='myPass'};
Invoke-WebRequest -Uri https://MYURL -Method POST -Body $postParams;
</code>```

Did not work still getting 403 forbidden.

Solution #2:

```<code>[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true };

$postParams = @{user='myUser';password='myPass'};
Invoke-WebRequest -Uri https://MYURL -Method POST -Body $postParams;

add-type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    public class TrustAllCertsPolicy : ICertificatePolicy {
        public bool CheckValidationResult(
            ServicePoint srvPoint, X509Certificate certificate,
            WebRequest request, int certificateProblem) {
            return true;
        }
    }
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy;

$postParams = @{user='myUser';password='myPass'};
Invoke-WebRequest -Uri https://MYURL -Method POST -Body $postParams;
</code>```

Did not work either, still getting 403 forbidden.

Any clues of what I might be doing wrong? Since it works ok in ubuntu and git terminal with -k or --insecure.

答:
The short answer, is Invoke-WebRequest is not an attempt to replace curl and simply does not support this feature.

So far, the only way I found without using other PS modules is something that should never be done (credit goes to: ref)

Run this before running the Invoke-WebRequest command. It may popup an internet explorer lock warning, but still lets the PS command run, ignoring an expired cert.

```<code>add-type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    public class TrustAllCertsPolicy : ICertificatePolicy {
        public bool CheckValidationResult(
            ServicePoint srvPoint, X509Certificate certificate,
            WebRequest request, int certificateProblem) {
            return true;
        }
    }
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPol
</code>```

Body:
I am trying to execute:

$postParams = @{user='myUser';password='myPass'};
Invoke-WebRequest -Uri https://MYURL -Method POST -Body $postParams;

And I am always getting 403 forbidden, in ubuntu or git terminal this works like a charm (with -k or --insecure):

curl -k -X POST "https://MYURL" -H "accept: */*" -H "Content-Type: application/json" -d "{ \"user\" : \"myUser\", \"password\" : \"myPass\"}"

or

curl -X POST "https://MYURL" -H "accept: */*" -H "Content-Type: application/json" -d "{ \"user\" : \"myUser\", \"password\" : \"myPass\"}" --insecure

After some research I tried two solutions:

Solution #1:

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true };

$postParams = @{user='myUser';password='myPass'};
Invoke-WebRequest -Uri https://MYURL -Method POST -Body $postParams;

Did not work still getting 403 forbidden.

Solution #2:

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true };

$postParams = @{user='myUser';password='myPass'};
Invoke-WebRequest -Uri https://MYURL -Method POST -Body $postParams;

add-type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    public class TrustAllCertsPolicy : ICertificatePolicy {
        public bool CheckValidationResult(
            ServicePoint srvPoint, X509Certificate certificate,
            WebRequest request, int certificateProblem) {
            return true;
        }
    }
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy;

$postParams = @{user='myUser';password='myPass'};
Invoke-WebRequest -Uri https://MYURL -Method POST -Body $postParams;

Did not work either, still getting 403 forbidden.

Any clues of what I might be doing wrong? Since it works ok in ubuntu and git terminal with -k or --insecure.

Body:
The short answer, is Invoke-WebRequest is not an attempt to replace curl and simply does not support this feature.

So far, the only way I found without using other PS modules is something that should never be done (credit goes to: ref)

Run this before running the Invoke-WebRequest command. It may popup an internet explorer lock warning, but still lets the PS command run, ignoring an expired cert.

add-type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    public class TrustAllCertsPolicy : ICertificatePolicy {
        public bool CheckValidationResult(
            ServicePoint srvPoint, X509Certificate certificate,
            WebRequest request, int certificateProblem) {
            return true;
        }
    }
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPol


问:
Signing iOS application for internal deployment with Push Notifcations
We have an iOS application which we create using Xamarin.

We are starting to use Apple Push Notification Services and I have updated our App Identifier in developer.apple.com to use the Push Notifications capability.

I have updated our Entitlements Plist with the one being used by our development and test environments with:

```<code><key>aps-environment</key>
<string>development</string>
</code>```

and this in the Plist that will be used for production:

```<code><key>aps-environment</key>
<string>production</string>
</code>```

I am able to deploy a signed application to a local device from within Visual Studio 2019 using "Manual Provisioning". I am also able to send push notifications to the installed app from Azure

Our test team downloads builds from AppCenter and we deploy to AppCenter using a YAML Pipeline.

I have looked inside the provisioning profile that is used by that pipelineto create the Test builds and it has

```<code><key>aps-environment</key>
<string>production</string>
</code>```

That does not match what is in the Entitlements PList and whilst the app builds and signs it will not open. Any attempts to open the app are given an error dialog saying

Unable to install because its integrity could not be verified

The aps-environment differs from the provisioning profile to the Entitlements.Plist. Does this explain that error?

Can I edit the XML of the provisioning profile and change the aps-environment?

If not how do choose from Apple Dev portal what provisioning profile to use in my automated build. I have the following types to choose from

AppStore

Ad hoc

Development

I'm assuming it is the development one. I tried using a development one but I need to pair that with the correct certificate need by the InstallAppleCertificate task.

When I switched to the development provisioning profile I got the following error trying to build and sign the application

No iOS signing identities match the specified provisioning profile
'ecc36e48-b330-4341-834f-34747ebc010e'

答:
Your test team should use Ad Hoc. Development is for debugging locally; Ad Hoc is for testers; and AppStore is for distribution to the public. The only way to test with an AppStore profile is via TestFlight. Development and Ad Hoc require the UUIDs to be set in the developer portal AND added to the profile. Anything not Development is considered "production" for APS.

Our test team downloads builds from AppCenter and we deploy to AppCenter using a YAML Pipeline.

Are you doing a iPhone | Ad Hoc build? In your csproj, do you have the correct entitlements and provisioning profile selected? Those are usually under the CodesignKey and CodesignEntitlements xml tags.

Body:
We have an iOS application which we create using Xamarin.

We are starting to use Apple Push Notification Services and I have updated our App Identifier in developer.apple.com to use the Push Notifications capability.

I have updated our Entitlements Plist with the one being used by our development and test environments with:

<key>aps-environment</key>
<string>development</string>

and this in the Plist that will be used for production:

<key>aps-environment</key>
<string>production</string>

I am able to deploy a signed application to a local device from within Visual Studio 2019 using "Manual Provisioning". I am also able to send push notifications to the installed app from Azure

Our test team downloads builds from AppCenter and we deploy to AppCenter using a YAML Pipeline.

I have looked inside the provisioning profile that is used by that pipelineto create the Test builds and it has

<key>aps-environment</key>
<string>production</string>

That does not match what is in the Entitlements PList and whilst the app builds and signs it will not open. Any attempts to open the app are given an error dialog saying

Unable to install because its integrity could not be verified

The aps-environment differs from the provisioning profile to the Entitlements.Plist. Does this explain that error?

Can I edit the XML of the provisioning profile and change the aps-environment?

If not how do choose from Apple Dev portal what provisioning profile to use in my automated build. I have the following types to choose from

AppStore

Ad hoc

Development

I'm assuming it is the development one. I tried using a development one but I need to pair that with the correct certificate need by the InstallAppleCertificate task.

When I switched to the development provisioning profile I got the following error trying to build and sign the application

No iOS signing identities match the specified provisioning profile
'ecc36e48-b330-4341-834f-34747ebc010e'


问:
how to know the full path of new created file?
see i have make one program which create one new file just using

```<code>fopen()
</code>```

Now i want to print full path of that file's in ma program.

How is that possible in linux with c programming?

答:
In main() you should get the full path of your executable as argv[0]. Your file is created there.

Also, AFAIK, fopen prototype is

```<code>FILE * fopen(const char *restrict filename, const char *restrict mode);
</code>```

So a plain

```<code>fopen()
</code>```

would not work (if we're talking about standard C).

Body:
see i have make one program which create one new file just using

fopen()

Now i want to print full path of that file's in ma program.

How is that possible in linux with c programming?

Body:
In main() you should get the full path of your executable as argv[0]. Your file is created there.

Also, AFAIK, fopen prototype is

FILE * fopen(const char *restrict filename, const char *restrict mode);

So a plain

fopen()

would not work (if we're talking about standard C).


问:
Incorrect syntax near '-'
i am trying to run a query in another server and  need to specify it in the select statement but the server name has got an '-' in it, like server-name.
this is producing the error in the title.
How can i fix it?</p>

答:
I also came across this error when I work with spring boot and MSSQL db. We may get this error, when we did not define the schema and the table name correctly.
I have included the below schema name with square brackets in the model class and I could overcome this issue.</p>
```<code>@Table(name = "FIELDS_PARAM",schema = "[sample-schema]")
</code>```

Title: Incorrect syntax near '-'

Body:
I also came across this error when I work with spring boot and MSSQL db. We may get this error, when we did not define the schema and the table name correctly.
I have included the below schema name with square brackets in the model class and I could overcome this issue.

@Table(name = "FIELDS_PARAM",schema = "[sample-schema]")


问:
Write a function index -- takes list and a number, and returns the index of the first element with the specified value
Wouldn't this question need 3 parameters instead of 2, being the list, index, and item being added?</p>

答:
You don't tell us what language you're working in but your function will have 2 parameters: the list and the value looked for, and 1 return type. If it is Java it might be:

```<code>public static int findIndex(String[] myList, String valueToLookFor) {
int indice;
// calculations here
return indice;
}
</code>```

I believe in some languages you can speak if IN parameters and OUT parameters in which case yes, there are 2 IN parameters plus 1 OUT parameter = 3.

Body:
You don't tell us what language you're working in but your function will have 2 parameters: the list and the value looked for, and 1 return type. If it is Java it might be:

public static int findIndex(String[] myList, String valueToLookFor) {
int indice;
// calculations here
return indice;
}

I believe in some languages you can speak if IN parameters and OUT parameters in which case yes, there are 2 IN parameters plus 1 OUT parameter = 3.


问:
Is there a good way to remove a element from a map?
I made an map called mymap where I would like to remove every element in it that is the biggest in order to find the second biggest. Is there a good way to remove the elements in the map. This is what I have done so far:

```<code>n = int(input())
mymap = map(int, input().split())
biggestnum  = max(mymap)
mymap.(biggestnum)
secondbiggestnum = max(mymap)
print(secondbiggestnum)
</code>```

What would be an efficient and easy way to remove all instances of biggestnum?

答:
map is a function in python. It takes two parameters:
map(function, iterables). The first parameter is a function and the second is an iterables. The function returns a map class object.
You can convert the map object to list or set.

```<code>mymap = map(int, input().split())
mylist = sorted(list(set(mymap)))
# if getting the same element as largest or second largest is not an issue
# then remove the set part and make it mylist = sorted(list(mymap))
print("max:", mylist[-1])
print("second max:", mylist[-2])
</code>```

Body:
I made an map called mymap where I would like to remove every element in it that is the biggest in order to find the second biggest. Is there a good way to remove the elements in the map. This is what I have done so far:

n = int(input())
mymap = map(int, input().split())
biggestnum  = max(mymap)
mymap.(biggestnum)
secondbiggestnum = max(mymap)
print(secondbiggestnum)

What would be an efficient and easy way to remove all instances of biggestnum?

Body:
map is a function in python. It takes two parameters:
map(function, iterables). The first parameter is a function and the second is an iterables. The function returns a map class object.
You can convert the map object to list or set.

mymap = map(int, input().split())
mylist = sorted(list(set(mymap)))
# if getting the same element as largest or second largest is not an issue
# then remove the set part and make it mylist = sorted(list(mymap))
print("max:", mylist[-1])
print("second max:", mylist[-2])


问:
How we can insert multiple paragraphs after the insertion of table in google docs using google docs api with PHP?
I am working on google docs api.I want to create a google docs with google docs api using PHP.AS per my requirement I want some paragraphs then insert a table and then again a paragraph as shown in below picture-

I am able to  insert texts like this -

```<code>$requests[] = new Google_Service_Docs_Request(array(
            'insertText' => [
                'text' => 'Paragraph 1',
                'location' => [
                    'index' => 1,
                ]
            ]
        ));
</code>```

I am also able to add table like this-

```<code>$requests [] = new Google_Service_Docs_Request([
    'insertTable' => [
        'rows' =>  4,
        'columns' =>  4,
        'endOfSegmentLocation' => [
          'segmentId' => ''
        ],
    ],
]);
</code>```

but after adding this table I want to add another paragraph as shown in pic.I have added another insertion text request after this table request like this -

```<code>$requests[] = new Google_Service_Docs_Request(array(
            'insertText' => array(
                'text' => "Paragraph 2",
                'endOfSegmentLocation' => array(
                    'segmentId' => '',
                    ),
            ),
        ));
</code>```

But like this i want to add more paragraphs after the insertion of table and for that I need index location but I am not able to do that. Can anybody help me on this how to add contents like this as shown in above pic.It would be a great huge help if anyone can help me through this.I want this in PHP.

答:
In your situation, I thought that when the contents are inserted with the reverse order, index can be ignored. In this case, how about the following sample script?

Sample script 1:

$documentId = "###"; // Please set the Google Document ID.

$requests = [
    new Google_Service_Docs_Request(array(
        'insertText' => [
            'text' => 'Paragraph 1',
            'location' => [
                'index' => 1,
            ]
        ]
    )),
    new Google_Service_Docs_Request([
        'insertTable' => [
            'rows' =>  4,
            'columns' =>  4,
            'location' => [
              'index' => 1
            ],
        ],
    ]),
    new Google_Service_Docs_Request(array(
        'insertText' => [
            'text' => 'Paragraph 2',
            'location' => [
                'index' => 1,
            ]
        ]
    ))
];
$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
    'requests' => array_reverse($requests)
));
$responses = $service->documents->batchUpdate($documentId, $batchUpdateRequest);
```
<h3>Sample script 2:</h3>
<p>Or, if you want to append the text of "Paragraph 2" after the text "Paragraph 1" and a table were inserted, you can append the text using the following script.</p>
<pre class="lang-php prettyprint-override"><code>$requests = [
    new Google_Service_Docs_Request(array(
        'insertText' => [
            'text' => "Paragraph 2", // or "\nParagraph 2"
            'endOfSegmentLocation' => [
                'segmentId' => ''
            ],
        ]
    )),
];
$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
    'requests' => array_reverse($requests)
));
$responses = $service->documents->batchUpdate($documentId, $batchUpdateRequest);
</code>```

By this request, Paragraph 2 can be appended to the document body. Also, In this case, index for putting the text can be ignored.

About 'text' => "Paragraph 2", when the paragraph is the same with the last paragraph, you can create new paragraph by 'text' => "\nParagraph 2".

Sample script 3:

If you want to insert the text by retrieving the index, you can also the following sample script.

$documentId = "###"; // Please set the Google Document ID.

$requests = [
    new Google_Service_Docs_Request(array(
        'insertText' => [
            'text' => 'Paragraph 1',
            'location' => [
                'index' => 1,
            ]
        ]
    )),
    new Google_Service_Docs_Request([
        'insertTable' => [
            'rows' =>  4,
            'columns' =>  4,
            'endOfSegmentLocation' => [
                'segmentId' => ''
            ],
        ],
    ]),
];
$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
    'requests' => array_reverse($requests)
));
$responses = $service->documents->batchUpdate($documentId, $batchUpdateRequest);

$obj = $service->documents->get($documentId);
$content = $obj->getBody()->getContent();
$requests = [
    new Google_Service_Docs_Request(array(
        'insertText' => [
            'text' => 'Paragraph 2',
            'location' => [
                'index' => end($content)->getEndIndex() - 1,
            ]
        ]
    ))
];
$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
    'requests' => $requests
));
$responses = $service->documents->batchUpdate($documentId, $batchUpdateRequest);
```

References:

Method: documents.batchUpdate

InsertTextRequest

Body:
I am working on google docs api.I want to create a google docs with google docs api using PHP.AS per my requirement I want some paragraphs then insert a table and then again a paragraph as shown in below picture-

I am able to  insert texts like this -

$requests[] = new Google_Service_Docs_Request(array(
            'insertText' => [
                'text' => 'Paragraph 1',
                'location' => [
                    'index' => 1,
                ]
            ]
        ));

I am also able to add table like this-

$requests [] = new Google_Service_Docs_Request([
    'insertTable' => [
        'rows' =>  4,
        'columns' =>  4,
        'endOfSegmentLocation' => [
          'segmentId' => ''
        ],
    ],
]);

but after adding this table I want to add another paragraph as shown in pic.I have added another insertion text request after this table request like this -

$requests[] = new Google_Service_Docs_Request(array(
            'insertText' => array(
                'text' => "Paragraph 2",
                'endOfSegmentLocation' => array(
                    'segmentId' => '',
                    ),
            ),
        ));

But like this i want to add more paragraphs after the insertion of table and for that I need index location but I am not able to do that. Can anybody help me on this how to add contents like this as shown in above pic.It would be a great huge help if anyone can help me through this.I want this in PHP.

Body:
In your situation, I thought that when the contents are inserted with the reverse order, index can be ignored. In this case, how about the following sample script?

Sample script 1:

$documentId = "###"; // Please set the Google Document ID.

$requests = [
    new Google_Service_Docs_Request(array(
        'insertText' => [
            'text' => 'Paragraph 1',
            'location' => [
                'index' => 1,
            ]
        ]
    )),
    new Google_Service_Docs_Request([
        'insertTable' => [
            'rows' =>  4,
            'columns' =>  4,
            'location' => [
              'index' => 1
            ],
        ],
    ]),
    new Google_Service_Docs_Request(array(
        'insertText' => [
            'text' => 'Paragraph 2',
            'location' => [
                'index' => 1,
            ]
        ]
    ))
];
$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
    'requests' => array_reverse($requests)
));
$responses = $service->documents->batchUpdate($documentId, $batchUpdateRequest);

Sample script 2:

Or, if you want to append the text of "Paragraph 2" after the text "Paragraph 1" and a table were inserted, you can append the text using the following script.

$requests = [
    new Google_Service_Docs_Request(array(
        'insertText' => [
            'text' => "Paragraph 2", // or "\nParagraph 2"
            'endOfSegmentLocation' => [
                'segmentId' => ''
            ],
        ]
    )),
];
$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
    'requests' => array_reverse($requests)
));
$responses = $service->documents->batchUpdate($documentId, $batchUpdateRequest);

By this request, Paragraph 2 can be appended to the document body. Also, In this case, index for putting the text can be ignored.

About 'text' => "Paragraph 2", when the paragraph is the same with the last paragraph, you can create new paragraph by 'text' => "\nParagraph 2".

Sample script 3:

If you want to insert the text by retrieving the index, you can also the following sample script.

$documentId = "###"; // Please set the Google Document ID.

$requests = [
    new Google_Service_Docs_Request(array(
        'insertText' => [
            'text' => 'Paragraph 1',
            'location' => [
                'index' => 1,
            ]
        ]
    )),
    new Google_Service_Docs_Request([
        'insertTable' => [
            'rows' =>  4,
            'columns' =>  4,
            'endOfSegmentLocation' => [
                'segmentId' => ''
            ],
        ],
    ]),
];
$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
    'requests' => array_reverse($requests)
));
$responses = $service->documents->batchUpdate($documentId, $batchUpdateRequest);

$obj = $service->documents->get($documentId);
$content = $obj->getBody()->getContent();
$requests = [
    new Google_Service_Docs_Request(array(
        'insertText' => [
            'text' => 'Paragraph 2',
            'location' => [
                'index' => end($content)->getEndIndex() - 1,
            ]
        ]
    ))
];
$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
    'requests' => $requests
));
$responses = $service->documents->batchUpdate($documentId, $batchUpdateRequest);

References:

Method: documents.batchUpdate

InsertTextRequest


问:
"External call transformation" lost configuration in "call transformation settings" on dataflow when a page is refreshed
I have a dataflow with an "external call transformation", I fill in all fields in configuration "call transformation settings", but when I refreshed the page my settings filled losted.

My filled settings

My filled settings

When I refreshed the page

When I refreshed the page

Has anyone had this problem?

答:
You need to Publish DataFlow activity in order to save Configuration. When data factory is not connected to any repository, it is said to operate in Live mode. In this mode, if you don't publish the changes, those will be lost once you refresh the page. It is essentially same as "Save" option.

Before page refresh, Publish Dataflow activity.

Refer - https://learn.microsoft.com/en-us/answers/questions/99957/what-does-publishing-do-in-azure-data-factory-do.html


问:
Regex string split with multiple conditions
(Javascript older version of Node.js)

Edit I have to clear up what I want.

I have multiple lines like these

```<code>var name1;

CONST    name2

   Let  nam;

leT     nam

  VAr n1  ;
</code>```

My desired outputs are

```<code>name1

name2

nam

nam

n1
</code>```

So I am trying codes like this.

```<code>/[^;]*/
</code>```

But I need help because I have multiple patterns. Some may have semicolons/space/null after the variable names, I need to omit those.

答:
Use regexp = /name[1-9]+/g

let arr = ['var person;', 'CONST    name2', '   Let  nam;', '  VAr n1  ;'];
var result = [];
for(var s of arr) {
    var split_array = s.replace(/  +/g, ' ').trim().split(' ');
    result.push(split_array[1].replace(';', ''))
}
console.log(result);```

Body:
(Javascript older version of Node.js)

Edit I have to clear up what I want.

I have multiple lines like these

var name1;

CONST    name2

   Let  nam;

leT     nam

  VAr n1  ;

My desired outputs are

name1

name2

nam

nam

n1

So I am trying codes like this.

/[^;]*/

But I need help because I have multiple patterns. Some may have semicolons/space/null after the variable names, I need to omit those.


问:
Pandas Multi Index Division
I have a Multi Index dataframe that looks like

```<code>                            Mid
Strike  Expiration  Symbol
167.5   2022-02-11  AAPL170 5.4
170     2022-02-11  AAPL170 3.1
        2022-02-18  AAPL170 4.525
        2022-02-25  AAPL170 5.25
        2022-03-04  AAPL170 6.00
172.5   2022-02-11  AAPL172 1.265
        2022-02-18  AAPL172 2.91
175     2022-02-11  AAPL175 0.265
        2022-02-18  AAPL175 1.695
</code>```

so it is a multi index with the index of strike expiration and symbol, and then mid is just a column name, and NOT an index. I have a few other columns but they are not important for now. These are sorted in increasing value from the first index, I'm hoping to divide each Mid row by the next row below it, but only within each individual strike index. Currently, I am doing

df['ratio'] = (df['mid'] / df['mid'].shift(-1))
```
<p>and it works to give me a new column of all the divisions, but I'm running into problems where, for example, the <code>167.5 2022-02-11</code> row is getting divided by the <code>170 2022-02-11</code> row, and I need those to remain separated by index.</p>
<p>My goal is after this division is done, to be able to search for any ratios that are above a cutoff, ex. 0.5, and output what was divided to a new dataframe, so something similar to</p>
```Strike  Expirations                Symbol    Ratio
170     2022-02-11 / 2022-02-18    AAPL170   0.685
```

If someone could advise on both parts, I'd greatly appreciate it but I primarily need the first part fixed.

答:
One way using pandas.DataFrame.groupby with pct_change:

```<code>new_df = df.groupby(level=0).pct_change(-1) + 1
print(new_df)
</code>```

Output:

```<code>                                Mid
Strike Expiration Symbol
167.5  2022-02-11 AAPL170       NaN
170.0  2022-02-11 AAPL170  0.685083
       2022-02-18 AAPL170  0.861905
       2022-02-25 AAPL170  0.875000
       2022-03-04 AAPL170       NaN
172.5  2022-02-11 AAPL172  0.434708
       2022-02-18 AAPL172       NaN
175.0  2022-02-11 AAPL175  0.156342
       2022-02-18 AAPL175       NaN
</code>```

For debugging, you can try something like:

```<code>for _, d in df.groupby(level=0):
    try:
        d.pct_change()
    except:
        print(d)
        break
</code>```

Title: Pandas Multi Index Division

Body:
I have a Multi Index dataframe that looks like

                            Mid
Strike  Expiration  Symbol
167.5   2022-02-11  AAPL170 5.4
170     2022-02-11  AAPL170 3.1
        2022-02-18  AAPL170 4.525
        2022-02-25  AAPL170 5.25
        2022-03-04  AAPL170 6.00
172.5   2022-02-11  AAPL172 1.265
        2022-02-18  AAPL172 2.91
175     2022-02-11  AAPL175 0.265
        2022-02-18  AAPL175 1.695

so it is a multi index with the index of strike expiration and symbol, and then mid is just a column name, and NOT an index. I have a few other columns but they are not important for now. These are sorted in increasing value from the first index, I'm hoping to divide each Mid row by the next row below it, but only within each individual strike index. Currently, I am doing

df['ratio'] = (df['mid'] / df['mid'].shift(-1))

and it works to give me a new column of all the divisions, but I'm running into problems where, for example, the 167.5 2022-02-11 row is getting divided by the 170 2022-02-11 row, and I need those to remain separated by index.

My goal is after this division is done, to be able to search for any ratios that are above a cutoff, ex. 0.5, and output what was divided to a new dataframe, so something similar to

Strike  Expirations                Symbol    Ratio
170     2022-02-11 / 2022-02-18    AAPL170   0.685

If someone could advise on both parts, I'd greatly appreciate it but I primarily need the first part fixed.

Body:
One way using pandas.DataFrame.groupby with pct_change:

new_df = df.groupby(level=0).pct_change(-1) + 1
print(new_df)

Output:

                                Mid
Strike Expiration Symbol
167.5  2022-02-11 AAPL170       NaN
170.0  2022-02-11 AAPL170  0.685083
       2022-02-18 AAPL170  0.861905
       2022-02-25 AAPL170  0.875000
       2022-03-04 AAPL170       NaN
172.5  2022-02-11 AAPL172  0.434708
       2022-02-18 AAPL172       NaN
175.0  2022-02-11 AAPL175  0.156342
       2022-02-18 AAPL175       NaN

For debugging, you can try something like:

for _, d in df.groupby(level=0):
    try:
        d.pct_change()
    except:
        print(d)
        break


问:
Disable records removal of standard table through maintenance view
There is a standard table T513 and customer master data table T7SK13, which is modified by customer using maintenance view V_T7SK13, with following tables/join conditions:

Is there a possibility to somehow disable removal of records from international table T513, but still allowing to add new records there?

I can remove the delete button for maintenance view using excl_cua_funct parameter of function view_maintenance_call, but this would also disable removal of records from customer table T7SK13, which still needs to work.

答:
You may find this useful. You add code that is called by
generated views that is called at particular events.
Like before delete. Event 03.

See the View V_TVIMF

You can use mod assistant to add a form routine.

Or add it use implicit enhancements. If that makes people feel better. ;)

Sm30 v_tvimf

V_t7sk13


问:
left and right sidebars overlapping main content using position:fixed
I'm new to CSS.
trying to study some layouts and ran into this issue.

I'm trying to prevent the left and right sidebar(aside) from scrolling. No matter how much I scroll the main, it will always stay there; I've set its position to fixed and it looked all fine. the issue is, the main content is overlapping with the right sidebar(aside) when resizing. I've tried position: relative and absolute to the right and changing it to div but nothing happens.
the goal is - when my chrome browser shrinks, it should show the Horizontal/vertical scrollbars without any overlapping of main contents. no matter how long my main content is, the sidebars should always be there! Thank you in advance!

Here is my code

body, html {
    font-family: Helvetica;
    background-color: rgba(0, 0, 0);
}
#sidebar {
    position: fixed;
    width: 400px;
    height: 100%;
    margin-top: 120px;
    top: 0;
}
.left {
    left: 0;
    bottom: 0;
    background-color: rgb(82, 50, 50);
}
.content {
    display: inline-block;
    background-color: rgb(255, 255, 255);
    margin-top: 120px;
    top: 0;
    width: 800px;
    height:100%;
    margin-left: 400px;
    margin-right: 400px;
}
.right {
    right: 0;
    bottom: 0;
    background-color: rgb(255, 217, 0);
}

#wrapper {
    margin-left:0;
    margin-right:0;
    max-width: 1600px;
    border:1px solid white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
    <aside id="sidebar" class="left">
    </aside>
    <div class="content">
        Lorem ipsum blah blah (cutted: about 100lines)
    </div>

    <aside id="sidebar" class="right">
    </aside>
</div></code>```

答:
The problem is you are using position: fixed and you are using px:

An element with position: fixed; is positioned relative to the
viewport, which means it always stays in the same place even if the
page is scrolled. The top, right, bottom, and left properties are used
to position the element.

By using the px, the element size will always be 400px even though the window size is very small. To prevent the content from overlapping to others and keep the same ratio with other elements, you should use % which is the percentage for the container's size and it will keep the same ratio between the aside and div no matter the window size.

Another soluation is to you media screen

The @media CSS at-rule can be used to apply part of a style sheet based on the result of one or more media queries. With it, you specify a media query and a block of CSS to apply to the document if and only if the media query matches the device on which the content is being used.

Check more here

If you want to prevent aside from scrolling, just use:

```<code>aside{
overflow: hideen
}

</code>```

Body:
I'm new to CSS.
trying to study some layouts and ran into this issue.

I'm trying to prevent the left and right sidebar(aside) from scrolling. No matter how much I scroll the main, it will always stay there; I've set its position to fixed and it looked all fine. the issue is, the main content is overlapping with the right sidebar(aside) when resizing. I've tried position: relative and absolute to the right and changing it to div but nothing happens.
the goal is - when my chrome browser shrinks, it should show the Horizontal/vertical scrollbars without any overlapping of main contents. no matter how long my main content is, the sidebars should always be there! Thank you in advance!

Here is my code

body, html {
    font-family: Helvetica;
    background-color: rgba(0, 0, 0);
}
#sidebar {
    position: fixed;
    width: 400px;
    height: 100%;
    margin-top: 120px;
    top: 0;
}
.left {
    left: 0;
    bottom: 0;
    background-color: rgb(82, 50, 50);
}
.content {
    display: inline-block;
    background-color: rgb(255, 255, 255);
    margin-top: 120px;
    top: 0;
    width: 800px;
    height:100%;
    margin-left: 400px;
    margin-right: 400px;
}
.right {
    right: 0;
    bottom: 0;
    background-color: rgb(255, 217, 0);
}

#wrapper {
    margin-left:0;
    margin-right:0;
    max-width: 1600px;
    border:1px solid white;
}

        Lorem ipsum blah blah (cutted: about 100lines)

Body:
The problem is you are using position: fixed and you are using px:

An element with position: fixed; is positioned relative to the
viewport, which means it always stays in the same place even if the
page is scrolled. The top, right, bottom, and left properties are used
to position the element.

By using the px, the element size will always be 400px even though the window size is very small. To prevent the content from overlapping to others and keep the same ratio with other elements, you should use % which is the percentage for the container's size and it will keep the same ratio between the aside and div no matter the window size.

Another soluation is to you media screen

The @media CSS at-rule can be used to apply part of a style sheet based on the result of one or more media queries. With it, you specify a media query and a block of CSS to apply to the document if and only if the media query matches the device on which the content is being used.

Check more here

If you want to prevent aside from scrolling, just use:

aside{
overflow: hideen
}


问:
Assume a machine has a 100K logical address. The physical address is 30K and the page size is 4K
Assume a machine has a 100K logical address. The physical address is 30K and
the page size is 4K. Give the best answer to each of the following that you can

答: It's implied they're powers of 2 due, so  100k -> 2^17, 30k -> 2^15, 4k -> 2^12. you can easily solve the rest yourself.</p>


问:
Sorting a list of strings with another list of strings
I am trying to sort an Event class by nearest geographical location. I have a list of event objects with the state the event takes place in event.state = 'Wyoming'. I also have a list of nearby states nearby = ['Wyoming', 'Colorado', 'Nebraska', 'South Dakota', 'etc']

I would like to implement a custom sort method

```<code>def sort_by_nearby_location():
  # Take event.state and compare to nearby states list and return sorted list
</code>```

Is there a method in python that would allow me sort my list of events by their state according to the order I have set in my nearby list? What would be the best way to tackle this type of probelem?

答:
sorted() takes a key argument. This argument can be a lambda or a function that transforms your original list element, for instance to the index of that element in your nearby list.

```<code>sorted(events, key=lambda event: nearby.index(event.state))
</code>```

Body:
I am trying to sort an Event class by nearest geographical location. I have a list of event objects with the state the event takes place in event.state = 'Wyoming'. I also have a list of nearby states nearby = ['Wyoming', 'Colorado', 'Nebraska', 'South Dakota', 'etc']

I would like to implement a custom sort method

def sort_by_nearby_location():
  # Take event.state and compare to nearby states list and return sorted list

Is there a method in python that would allow me sort my list of events by their state according to the order I have set in my nearby list? What would be the best way to tackle this type of probelem?

Body:
sorted() takes a key argument. This argument can be a lambda or a function that transforms your original list element, for instance to the index of that element in your nearby list.

sorted(events, key=lambda event: nearby.index(event.state))


问:
Blackberry HttpConnection Connector.open modes
This may be a stupid question, however I've never really put much thought into the purpose of a connector mode and just used the default (READ_WRITE). What are the differences between calling Connector.open with its three different modes.

1) Connector.READ
2) Connector.WRITE
3) Connector.READ_WRITE (Really only 1/2 since this is obviously both)

Also, what does the "Set end to end required/desired" mean. I am fairly sure I know but the documentation is hazy.

Thanks

答:
What are the differences between calling Connector.open with its three different modes.

Obviously you can not write to connection if it's opened with Connector.READ and vice versa.

There's also another point, check this: Maximum number of simultaneous connections. I remember I read somewhere that when you use Connector.READ_WRITE, then system uses 2 connection handles versus the only.

Also, what does the "Set end to end required/desired" mean.

Sorry, not sure what you mean here.

UPDATE:

Also, what does the "Set end to end required/desired" mean.

Check the API for javax.microedition.io.Connector. It was used by all developers before RIM rolled out the ConnectionFactory in API 5.0. There is an explanation about end-to-end flag:

```<code>TLS connections SSL or TLS can be set up in one of two modes:
1. Proxy mode
2. End-to-end mode
</code>```

Body:
What are the differences between calling Connector.open with its three different modes.

Obviously you can not write to connection if it's opened with Connector.READ and vice versa.

There's also another point, check this: Maximum number of simultaneous connections. I remember I read somewhere that when you use Connector.READ_WRITE, then system uses 2 connection handles versus the only.

Also, what does the "Set end to end required/desired" mean.

Sorry, not sure what you mean here.

UPDATE:

Also, what does the "Set end to end required/desired" mean.

Check the API for javax.microedition.io.Connector. It was used by all developers before RIM rolled out the ConnectionFactory in API 5.0. There is an explanation about end-to-end flag:

TLS connections SSL or TLS can be set up in one of two modes:
1. Proxy mode
2. End-to-end mode


问:
Not all of my constructors are being imported?
I'm making a heap class to be importable with heap.h and my constructors including bool types do not work, yet every other constructor and function imported works.

Here is what's in heap.h:

```<code>#ifndef __HEAP_INCLUDED__
#define __HEAP_INCLUDED__

#include <iostream>
#include <vector>

using namespace std;

class heap{
int capacity;
bool isMinHeap;  //1 is min heap -- ascending order
vector<int> * content;
public:
heap();
heap(bool t);
heap(vector<int> * input);
heap(vector<int> * input, bool t);

void print();
void prettyPrint();
int parent(int i);
int leftChild(int i);
int rightChild(int i);
int size();
int getMax();
void insert(int data);
void heapifyDown(int index);
void heapifyUp(int index);
int invalidChild(int index);
int deleteMax();
int deleteMin();
bool minDir();
int at(int index);
};

vector<int> * heapSort(vector<int> * input);

void swap(vector<int> * vec, int a, int b);

#endif
</code>```

Here are the defined constructors in heap.cpp. Note, all constructors work fine when I add a main to this file to test stuff:

```<code>class heap{
    vector<int> * content;
    int capacity = 256;
    bool isMinHeap;  //1 is min heap -- ascending order

    public:
    heap(){
        content = new vector<int>;
        isMinHeap = 0;
    }
    heap(bool t){
        content = new vector<int>;
        isMinHeap = t;
    }
    heap(vector<int> * input){
        content = input;
        isMinHeap = true;
        for(int i = content->size()/2; i >= 0; i--){
            heapifyDown(i);
        }
    }
    heap(vector<int> * input, bool t){
        content = input;
        isMinHeap = t;
        for(int i = content->size()/2; i >= 0; i--){
            heapifyDown(i);
        }
    }
//other functions below
}
</code>```

The constructors with bool do not work in main.cpp, which has #include "heap.h" at the top. The files are all in the same directory and I am compiling with this command: g++ heap.cpp main.cpp -o main. Why do two of my constructors not work?

The error I see is

```<code>/usr/bin/ld: /tmp/ccwomODk.o: in function `main':
main.cpp:(.text+0x4e2): undefined reference to `heap::heap(bool)'
collect2: error: ld returned 1 exit status
</code>```

-Wall does not elaborate on the issue. I'm pretty sure the issue is with my linking somewhere because the constructors work inside of heap.cpp when I use them in there.

答:
What you are doing with the class in the .cpp file is wrong. You are not allowed to define the class twice. There must only be one class heap { /*...*/ }; in the program (but it may be included in multiple .cpp files). Otherwise the one-definition-rule (ODR) is violated and the program has undefined behavior.

So remove everything you are showing from heap.cpp.

To define the constructors of heap in the heap.cpp file, you need to use this syntax:

```<code>#include "heap.h"

heap::heap() {
    /*...*/
}

heap::heap(bool t) {
    /*...*/
}

//...
</code>```

and so on. The other member functions must be defined in a similar way, e.g.:

```<code>void heap::print() {
    /*...*/
}
</code>```

Furthermore, if you want to have a default member initializer as in

```<code>int capacity = 256;
</code>```

add it in the declaration in the .h file instead.

I also want to add that having a pointer-to-std::vector as member is almost surely a wrong approach as well, but out-of-scope for the question.

Body:
I'm making a heap class to be importable with heap.h and my constructors including bool types do not work, yet every other constructor and function imported works.

Here is what's in heap.h:

#ifndef __HEAP_INCLUDED__
#define __HEAP_INCLUDED__

#include <iostream>
#include <vector>

using namespace std;

class heap{
int capacity;
bool isMinHeap;  //1 is min heap -- ascending order
vector<int> * content;
public:
heap();
heap(bool t);
heap(vector<int> * input);
heap(vector<int> * input, bool t);

void print();
void prettyPrint();
int parent(int i);
int leftChild(int i);
int rightChild(int i);
int size();
int getMax();
void insert(int data);
void heapifyDown(int index);
void heapifyUp(int index);
int invalidChild(int index);
int deleteMax();
int deleteMin();
bool minDir();
int at(int index);
};

vector<int> * heapSort(vector<int> * input);

void swap(vector<int> * vec, int a, int b);

#endif

Here are the defined constructors in heap.cpp. Note, all constructors work fine when I add a main to this file to test stuff:

class heap{
    vector<int> * content;
    int capacity = 256;
    bool isMinHeap;  //1 is min heap -- ascending order

    public:
    heap(){
        content = new vector<int>;
        isMinHeap = 0;
    }
    heap(bool t){
        content = new vector<int>;
        isMinHeap = t;
    }
    heap(vector<int> * input){
        content = input;
        isMinHeap = true;
        for(int i = content->size()/2; i >= 0; i--){
            heapifyDown(i);
        }
    }
    heap(vector<int> * input, bool t){
        content = input;
        isMinHeap = t;
        for(int i = content->size()/2; i >= 0; i--){
            heapifyDown(i);
        }
    }
//other functions below
}

The constructors with bool do not work in main.cpp, which has #include "heap.h" at the top. The files are all in the same directory and I am compiling with this command: g++ heap.cpp main.cpp -o main. Why do two of my constructors not work?

The error I see is

/usr/bin/ld: /tmp/ccwomODk.o: in function `main':
main.cpp:(.text+0x4e2): undefined reference to `heap::heap(bool)'
collect2: error: ld returned 1 exit status

-Wall does not elaborate on the issue. I'm pretty sure the issue is with my linking somewhere because the constructors work inside of heap.cpp when I use them in there.

Body:
What you are doing with the class in the .cpp file is wrong. You are not allowed to define the class twice. There must only be one class heap { /*...*/ }; in the program (but it may be included in multiple .cpp files). Otherwise the one-definition-rule (ODR) is violated and the program has undefined behavior.

So remove everything you are showing from heap.cpp.

To define the constructors of heap in the heap.cpp file, you need to use this syntax:

#include "heap.h"

heap::heap() {
    /*...*/
}

heap::heap(bool t) {
    /*...*/
}

//...

and so on. The other member functions must be defined in a similar way, e.g.:

void heap::print() {
    /*...*/
}

Furthermore, if you want to have a default member initializer as in

int capacity = 256;

add it in the declaration in the .h file instead.

I also want to add that having a pointer-to-std::vector as member is almost surely a wrong approach as well, but out-of-scope for the question.


问:
How can I close the solution explorer panel with a key-board shortcut in Visual Studio 2010?
I often need to jump from a file to another file that I don't have open to one somewhere in the project directory structure.  I often use Ctrl-Alt-L to open the solution explorer panel, but then I'd like to close it after I open the file I'm after.  Unfortunately Ctrl-Alt-L doesn't simply toggle the panel open/closed.  Is there another way to accomplish this.  Or how can I close the solution explorer panel with a key-board shortcut?</p>

答: Turn on Auto-Hide in the Solution Explorer panel, then press Ctrl + Tab and release only the Tab key, that will open this dialog with Active Tools and Active Files lists. Select your prefered item using the keyboard or mouse.