问:
Vertical align element to bottom
I have several element I want to equalize. For this I'm using a basic function that reads the biggest height and sets it to all those elements.

On each element I have a couple of inner elements. The last one of this inner elements I want to vertical align to the bottom.

```<code>-------MainElement------
|  _________________   |
| |                 |  |
| | First Elem      |  |
| |_________________|  |
|  _________________   |
| |                 |  |
| | Second Elem     |  |
| |_________________|  |
|                      |
|                      |
|                      |
|                      |
|  _________________   |
| |       Last      |  |
| | Vertical Bottom |  |
| |_________________|  |
|-----------------------
</code>```

The first element and the second one might have variable height depending on its content (text and image), but the last one will be always fixed

If I try to vertical align the last element using a position absolute, then this breaks my equalize function that sets an inline height css property to the element.

```<code>-------MainElement------
|  _________________   |
| |                 |  |
| | First Elem      |  |
| |_________________|  |
|  _________________   |
| | Second overlaps |  |
| |_________________|  |
| |       Last      |  |
| | Vertical Bottom |  |
| |_________________|  |
|-----------------------
</code>```

If I try using display table, and then table-cell to the inner elements this also breaks, since each innerelements shares the total available width as if they were all elements of the same row.

```<code>-------MainElement------
|  _____________         |
| |First|2nd   |         |
| |Ele  |Elem  |         |
| |     |      |         |
| |     |      |_______  |
| |     |      |Vert   | |
| |     |      |Bottom | |
| |_____|______|_______| |
|-------------------------
</code>```

Due to support for old browsers, I can't use display flex which is great actually but doesn't behave nicely with IE =(

If there a way to accomplish this?

答:
You can use flexbox: Define the container as a flexcontainer with these settings:

```<code>.container {
  display: flex;
  flex-direction: column;
  justify-items: space-between;
}
</code>```

...and then add margin-top: auto to the last child element

Title: Vertical align element to bottom

Body:
I have several element I want to equalize. For this I'm using a basic function that reads the biggest height and sets it to all those elements.

On each element I have a couple of inner elements. The last one of this inner elements I want to vertical align to the bottom.

-------MainElement------
|  _________________   |
| |                 |  |
| | First Elem      |  |
| |_________________|  |
|  _________________   |
| |                 |  |
| | Second Elem     |  |
| |_________________|  |
|                      |
|                      |
|                      |
|                      |
|  _________________   |
| |       Last      |  |
| | Vertical Bottom |  |
| |_________________|  |
|-----------------------

The first element and the second one might have variable height depending on its content (text and image), but the last one will be always fixed

If I try to vertical align the last element using a position absolute, then this breaks my equalize function that sets an inline height css property to the element.

-------MainElement------
|  _________________   |
| |                 |  |
| | First Elem      |  |
| |_________________|  |
|  _________________   |
| | Second overlaps |  |
| |_________________|  |
| |       Last      |  |
| | Vertical Bottom |  |
| |_________________|  |
|-----------------------

If I try using display table, and then table-cell to the inner elements this also breaks, since each innerelements shares the total available width as if they were all elements of the same row.

-------MainElement------
|  _____________         |
| |First|2nd   |         |
| |Ele  |Elem  |         |
| |     |      |         |
| |     |      |_______  |
| |     |      |Vert   | |
| |     |      |Bottom | |
| |_____|______|_______| |
|-------------------------

Due to support for old browsers, I can't use display flex which is great actually but doesn't behave nicely with IE =(

If there a way to accomplish this?

Body:
You can use flexbox: Define the container as a flexcontainer with these settings:

.container {
  display: flex;
  flex-direction: column;
  justify-items: space-between;
}

...and then add margin-top: auto to the last child element


来源: stackexchange

问:
Find closest value to determined multiplicated value
I have two values. One is static and equals 24

```<code>int A = 24;
</code>```

and I have entries list :

```<code>[0, 21, 45, 76, 98]
</code>```

All of occurences comes in loop and I want to get closest value which divides on A :

```<code>0 - 24
21 - 24
45 - 48
76 - 72
98 - 96
</code>```

How to calculate this?

答:
You can do like this :

iterate until your are as near as possible of the value (when distance is less than A/2

```<code>private static int closestTo(int a, int i) {
    int res = a;
    while (Math.abs(res - i) > (a / 2.0) && res< i + a) {
        res += a;
    }
    return res;
}
</code>```

And use like

```<code>public static void main(String[] args) {
    int A = 24;
    int[] tab = new int[]{0, 21, 45, 76, 98};
    for (int i : tab) {
        System.out.println(i + " - " + closestTo(A, i));
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have two values. One is static and equals 24

int A = 24;

and I have entries list :

[0, 21, 45, 76, 98]

All of occurences comes in loop and I want to get closest value which divides on A :

0 - 24
21 - 24
45 - 48
76 - 72
98 - 96

How to calculate this?

Body:
You can do like this :

iterate until your are as near as possible of the value (when distance is less than A/2

private static int closestTo(int a, int i) {
    int res = a;
    while (Math.abs(res - i) > (a / 2.0) && res< i + a) {
        res += a;
    }
    return res;
}

And use like

public static void main(String[] args) {
    int A = 24;
    int[] tab = new int[]{0, 21, 45, 76, 98};
    for (int i : tab) {
        System.out.println(i + " - " + closestTo(A, i));
    }
}


问:
How do I do full-text searching in Ruby on Rails?
I would like to do full-text searching of data in my Ruby on Rails application.  What options exist?</p>

答: You can use Ferret (which is Lucene written in Ruby). It integrates seamless with Rails using the acts_as_ferret mixin. Take a look at "How to Integrate Ferret With Rails". A alternative is Sphinx.</p>

OwnerDisplayName: sock

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: marcospereira


问:
Plugin on CRM 2016 throwing strange Exception
I have a plugin which works fine on test system but on production it is throwing an strange exception. The plugin is registered on pre and post event of contact creation.  </p>

<p>Below is the exception  </p>

```<code>Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: System.BadImageFormatException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #1C99C823Detail:
<OrganizationServiceFault xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/xrm/2011/Contracts">
 <ActivityId>607632be-97ab-4704-961c-7f552681a51e</ActivityId>
 <ErrorCode>-2147220970</ErrorCode>
 <ErrorDetails xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic" />
 <Message>System.BadImageFormatException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #1C99C823</Message>
 <Timestamp>2017-12-05T14:44:03.5336134Z</Timestamp>
 <ExceptionRetriable>true</ExceptionRetriable>
 <ExceptionSource>PluginExecution</ExceptionSource>
 <InnerFault>
 <ActivityId>607632be-97ab-4704-961c-7f552681a51e</ActivityId>
 <ErrorCode>-2147220970</ErrorCode>
 <ErrorDetails xmlns:d3p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic" />
 <Message>System.BadImageFormatException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #6482593B</Message>
 <Timestamp>2017-12-05T14:44:03.5336134Z</Timestamp>
 <ExceptionRetriable>false</ExceptionRetriable>
 <ExceptionSource i:nil="true" />
 <InnerFault i:nil="true" />
 <OriginalException i:nil="true" />
 <TraceText i:nil="true" />
 </InnerFault>
 <OriginalException>System.BadImageFormatException
</code>```

答:
As you can see the exception is a BadimageFormatException which could be several things: https://msdn.microsoft.com/en-us/library/k7137bfe.aspx

You might get better details if you turn on plugin tracing and view the Plugin Trace Logs inside Dynamics CRM. Here is a good article: https://www.powerobjects.com/2016/07/05/debugging-your-plug-ins-with-the-plug-in-trace-log/

You can add trace statements into  your code.  My guess is the assembly's target needs to change.

Body:
I have a plugin which works fine on test system but on production it is throwing an strange exception. The plugin is registered on pre and post event of contact creation.

Below is the exception

Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: System.BadImageFormatException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #1C99C823Detail:
<OrganizationServiceFault xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/xrm/2011/Contracts">
 <ActivityId>607632be-97ab-4704-961c-7f552681a51e</ActivityId>
 <ErrorCode>-2147220970</ErrorCode>
 <ErrorDetails xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic" />
 <Message>System.BadImageFormatException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #1C99C823</Message>
 <Timestamp>2017-12-05T14:44:03.5336134Z</Timestamp>
 <ExceptionRetriable>true</ExceptionRetriable>
 <ExceptionSource>PluginExecution</ExceptionSource>
 <InnerFault>
 <ActivityId>607632be-97ab-4704-961c-7f552681a51e</ActivityId>
 <ErrorCode>-2147220970</ErrorCode>
 <ErrorDetails xmlns:d3p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic" />
 <Message>System.BadImageFormatException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #6482593B</Message>
 <Timestamp>2017-12-05T14:44:03.5336134Z</Timestamp>
 <ExceptionRetriable>false</ExceptionRetriable>
 <ExceptionSource i:nil="true" />
 <InnerFault i:nil="true" />
 <OriginalException i:nil="true" />
 <TraceText i:nil="true" />
 </InnerFault>
 <OriginalException>System.BadImageFormatException


问:
Laravel asset() method not working if I installed in sub-directory instead of absolute url

This is not finding the assets from the public directory.

I installed laravel in subdirectory like:

http://localhost/yourproject

how can I fix this?

答:
The asset() helper uses the app url.  This is defined in .env.

```<code>APP_URL=http://localhost/yourproject
</code>```

Body:
The asset() helper uses the app url.  This is defined in .env.

APP_URL=http://localhost/yourproject


问:
how to import export docker compose?
I am still new in docker and all container things.
I have server with full access at
1.1.1.1 and I installed docker there. (without docker compose)
In the other place my friend have server 2.2.2.2 and he installed docker and docker compose there.

At 2.2.2.2 server, my friend build 3 container : container A (Git), container B(unknown), container C(unknown).
I can access content of container A (Git) with browsers.

My question is: can I import container A to my server in 1.1.1.1? I have user access to download Git, but what I want is to import the container, not Git (content inside the container).
Any hint? what should I do? Or it is impossible to do if I don't have access to the command console?

答:
If you want to move the running container instance then I would recommend you to run the below command

```<code>$ docker ps
 CONTAINER ID    IMAGE             COMMAND       CREATED       STATUS       NAMES
 c3f279d17e0a   ubuntu:12.04      /bin/bash      7 days ago    Up 25 hours desperate_dubinsky
 197387f1b436   ubuntu:12.04      /bin/bash      7 days ago    Up 25 hours focused_hamilton

$ docker commit c3f279d17e0a  svendowideit/testimage:version3
</code>```

This would create the image on the host machine and then run the below command to save the image as tar file to upload it into another host.

```<code>$ docker save -o testimage.tar svendowideit/testimage:version3
</code>```

On scp the tar image to another host run the below command to extract the tar and save it as docker images.

```<code> $ docker images
 REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE

 $ docker load --input testimage.tar
 Loaded image: svendowideit/testimage:version3

 $ docker images
 REPOSITORY             TAG                 IMAGE ID            CREATED             SIZE
 svendowideit/testimage version3            769b9341d937        7 weeks ago         2.489 MB
</code>```

Now you can make use of docker run command to bring up the docker instance of the saved images.

Title: how to import export docker compose?

Body:
If you want to move the running container instance then I would recommend you to run the below command

$ docker ps
 CONTAINER ID    IMAGE             COMMAND       CREATED       STATUS       NAMES
 c3f279d17e0a   ubuntu:12.04      /bin/bash      7 days ago    Up 25 hours desperate_dubinsky
 197387f1b436   ubuntu:12.04      /bin/bash      7 days ago    Up 25 hours focused_hamilton

$ docker commit c3f279d17e0a  svendowideit/testimage:version3

This would create the image on the host machine and then run the below command to save the image as tar file to upload it into another host.

$ docker save -o testimage.tar svendowideit/testimage:version3

On scp the tar image to another host run the below command to extract the tar and save it as docker images.

 $ docker images
 REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE

 $ docker load --input testimage.tar
 Loaded image: svendowideit/testimage:version3

 $ docker images
 REPOSITORY             TAG                 IMAGE ID            CREATED             SIZE
 svendowideit/testimage version3            769b9341d937        7 weeks ago         2.489 MB

Now you can make use of docker run command to bring up the docker instance of the saved images.


问:
crc 16 implementation that accepts different polynomial
Is it possible to have a crc16 implementation that accept different polynomial ? I mean by different polynomial the same function that can calculate crc16 with, one time, polynomial 0xA001 and an other time polynomial 0x1D0F (for exemple).

I have this code, in C, that work fine for little endian, with modbus polynomial (0xA001). I choose to initialise crc 16 at 0xFFFF :

```<code>uint16_t _crc16_update(uint8_t *Trame, uint32_t NbOctets, uint16_t Polynome)
{
  uint16_t u16CRC;

  int_t i;
  int_t j;

  u16CRC = 0xFFFF;

  for (i = NbOctets - 1; i >= 0; i--)
  {
    u16CRC = u16CRC ^ Trame[i];
    for (j = 0; j < 8; ++j)
    {
      if (u16CRC & 1)
      u16CRC = (u16CRC >> 1) ^ Polynome;
      else
      u16CRC = (u16CRC >> 1);
    }
  }

  return u16CRC;
}
</code>```

But when I execute this code with other polynomial, as 0x1D0F, result is wrong regards on this crc 16 online calculator.

Am I trying to do something impossible ?

答:
Is it possible to have a crc16 implementation that accept different polynomial ?

No. The CRC generators must use the same bits at every step of the algorithm or the outputs will not match. See https://en.wikipedia.org/wiki/Cyclic_redundancy_check for a description.

Body:
Is it possible to have a crc16 implementation that accept different polynomial ? I mean by different polynomial the same function that can calculate crc16 with, one time, polynomial 0xA001 and an other time polynomial 0x1D0F (for exemple).

I have this code, in C, that work fine for little endian, with modbus polynomial (0xA001). I choose to initialise crc 16 at 0xFFFF :

uint16_t _crc16_update(uint8_t *Trame, uint32_t NbOctets, uint16_t Polynome)
{
  uint16_t u16CRC;

  int_t i;
  int_t j;

  u16CRC = 0xFFFF;

  for (i = NbOctets - 1; i >= 0; i--)
  {
    u16CRC = u16CRC ^ Trame[i];
    for (j = 0; j < 8; ++j)
    {
      if (u16CRC & 1)
      u16CRC = (u16CRC >> 1) ^ Polynome;
      else
      u16CRC = (u16CRC >> 1);
    }
  }

  return u16CRC;
}

But when I execute this code with other polynomial, as 0x1D0F, result is wrong regards on this crc 16 online calculator.

Am I trying to do something impossible ?


问:
How to bind a dictionary with an HTML
 tag in angular?
So I know nothing about angularJS and I haven't found any good explanation on how to bind a dictionary with an html tag so that every change in the dictionary produces a change in the number inside the
 tag. For example if I have multiple dictionaries inside an array (one for each player)

```<code>var players = [{bambu:0, clouds:0, fruits:0}, {bambu:0, clouds:0, fruits:0} , {bambu:0, clouds:0, fruits:0}]
</code>```

I want to display the number associated with bambu in a
 tag

```<code><p id="player_0_bambu" class="number_of_cards"> </p>
</code>```

I want to change it dinamically like angular does.

I tried to do a

```<code>while (true){
    for (var r=0; r< num_players;r++){
        for (var c=0; c< colores.length;c++){
            $("#player_"+r+"_"+colores[c]).html(players[r][colores[c]])

        }
    }
}
</code>```

but a while true just crashes javascript, so I turned to angular but I find it difficult to understand.

Thank you for your help!

答:
Not sure why angular would be an option but judging by your description you just loop through the players array and use the values from the object at hand to query for
 tags.

```<code>var players = [{ bambu:0, clouds:0, fruits:0 },  {bambu:0, clouds:0, fruits:0 } , { bambu:0, clouds:0, fruits:0} ]

players.forEach(player => {
  Object.keys(player).forEach(key => {
    const val = player[key];

    document.querySelector(`#player_${val}_${key}`).innerHTML = val;
  });
});
</code>```

Title: How to bind a dictionary with an HTML <p> tag in angular?

Body:
So I know nothing about angularJS and I haven't found any good explanation on how to bind a dictionary with an html tag so that every change in the dictionary produces a change in the number inside the
 tag. For example if I have multiple dictionaries inside an array (one for each player)

var players = [{bambu:0, clouds:0, fruits:0}, {bambu:0, clouds:0, fruits:0} , {bambu:0, clouds:0, fruits:0}]

I want to display the number associated with bambu in a
 tag

I want to change it dinamically like angular does.

I tried to do a

while (true){
    for (var r=0; r< num_players;r++){
        for (var c=0; c< colores.length;c++){
            $("#player_"+r+"_"+colores[c]).html(players[r][colores[c]])

        }
    }
}

but a while true just crashes javascript, so I turned to angular but I find it difficult to understand.

Thank you for your help!

Body:
Not sure why angular would be an option but judging by your description you just loop through the players array and use the values from the object at hand to query for <p/> tags.

var players = [{ bambu:0, clouds:0, fruits:0 },  {bambu:0, clouds:0, fruits:0 } , { bambu:0, clouds:0, fruits:0} ]

players.forEach(player => {
  Object.keys(player).forEach(key => {
    const val = player[key];

    document.querySelector(`#player_${val}_${key}`).innerHTML = val;
  });
});


问:
How NSValueTransformer works?
In sample iPhoneCoreDataRecipes, UIImage can be saved to database with core data tech.

NSValueTransformer is used to do conversion from UIImage to NSData, and vice verse.

But the question is that there is no obvious invocation of NSValueTransformer to do such converting in source codes. So just wonder that how this works ?

A interesting discussion can be referred here

答: The NSValueTransformer is specified in the Recipes.xcdatamodel of the project.  If you open the .xcdatamodel in xcode, then click on Image  and then the image property (the type is transformable) and you can specify the  Value Transformer Class name in the gui tool.  </p>

Title: How NSValueTransformer works?


问:
Creating a new column with an if function in R
I am currently dealing with data on NFL Teams. Basically what I am trying to do here is create a new column titled Conference. I am trying to create an if function that generates the conference based off the Team in the Team column. My data set is called NFL_DATA and the column i am interested in is Team so I am using NFL_DATA$Team. Basically I am trying to say if NFL_DATA$TEAM == 'Philadelphia Eagles' or 'Dallas Cowboys' or 'New York Giants' or 'Washington Redskins' Then it will equal NFC East. Then in the conference column NFC East will appear for any of these teams. I am trying to do this for all 8 conferences. Any help would be greatly appreciated!!

So Far this is what I have and Im sure this is off:

```<code>Conference <- function(NFL_DATA$Team) {
  if (NFL_DATA$Team == 'Phiadelphia Eagles' | 'Dallas Cowboys' | 'New York Giants' | 'Washington Redskins') y <- "NFC EAST"
}
</code>```

答:
No need for a function here:</p>

```<code>east <- c('Phiadelphia Eagles', 'Dallas Cowboys', 'New York Giants', 'Washington Redskins')

transform(NFL_DATA, Conference = ifelse(Team %in% east, "NFC EAST", "something else")
</code>```

Body:
I am currently dealing with data on NFL Teams. Basically what I am trying to do here is create a new column titled Conference. I am trying to create an if function that generates the conference based off the Team in the Team column. My data set is called NFL_DATA and the column i am interested in is Team so I am using NFL_DATA$Team. Basically I am trying to say if NFL_DATA$TEAM == 'Philadelphia Eagles' or 'Dallas Cowboys' or 'New York Giants' or 'Washington Redskins' Then it will equal NFC East. Then in the conference column NFC East will appear for any of these teams. I am trying to do this for all 8 conferences. Any help would be greatly appreciated!!

So Far this is what I have and Im sure this is off:

Conference <- function(NFL_DATA$Team) {
  if (NFL_DATA$Team == 'Phiadelphia Eagles' | 'Dallas Cowboys' | 'New York Giants' | 'Washington Redskins') y <- "NFC EAST"
}

Body:
No need for a function here:

east <- c('Phiadelphia Eagles', 'Dallas Cowboys', 'New York Giants', 'Washington Redskins')

transform(NFL_DATA, Conference = ifelse(Team %in% east, "NFC EAST", "something else")


问:
How can row size error in MYSQL version 5.7 at the time of table creation be solved?
I am trying to create a table in my database using the following mysql query. But I am getting some row size error.

```<code>create table PJC_TXN_XFACE_STAGE_ALL (rowid int AUTO_INCREMENT,error_flag varchar(50),error_message varchar(500),Transaction_Type VARCHAR(100),
Business_Unit_Name VARCHAR(2),
Business_Unit_ID double,
Transaction_Source VARCHAR(240),
Transaction_Source_ID double,
Document VARCHAR(240),
Document_ID double,
Document_Entry VARCHAR(240),
Document_Entry_ID double,
Expenditure_Batch VARCHAR(50),
Batch_Ending_Date VARCHAR(100),
Batch_Description VARCHAR(250),
Expenditure_Item_Date VARCHAR(100),
Person_Number VARCHAR(30),
Person_Name VARCHAR(2000),
Person_ID double,
Human_Resources_Assignment VARCHAR(80),
Human_Resources_Assignment_ID double,
Project_Number VARCHAR(25),
Project_Name VARCHAR(240),
Project_ID double,
Task_Number VARCHAR(100),
Task_Name VARCHAR(255),
Task_ID double,
Expenditure_Type VARCHAR(240),
Expenditure_Type_ID double,
Expenditure_Organization VARCHAR(240),
Expenditure_Organization_ID double,
Quantity double,
Unit_of_Measure VARCHAR(80),
Unit_of_Measure_Code VARCHAR(30),
Work_Type VARCHAR(240),
Work_Type_ID double,
Billable VARCHAR(1),
Capitalizable VARCHAR(1),
Accrual_Batch VARCHAR(1),
Original_Transaction_Reference VARCHAR(120),
Unmatched_Negative_Transaction VARCHAR(1),
Reversed_Original_Transaction VARCHAR(120),
Expenditure_Item_Comment VARCHAR(240),
Accounting_Date VARCHAR(100),
Transaction_Currency_Code VARCHAR(15),
Transaction_Currency VARCHAR(80),
Raw_Cost_in_Transaction_Currency double,
Burdened_Cost_in_Transaction_Currency double,
Raw_Cost_Credit_CCID double,
Raw_Cost_Credit_Account VARCHAR(2000),
Raw_Cost_Debit_CCID double,
Raw_Cost_Debit_Account VARCHAR(2000),
Burdened_Cost_Credit_CCID double,
Burdened_Cost_Credit_Account VARCHAR(2000),
Burdened_Cost_Debit_CCID double,
Burdened_Cost_Debit_Account VARCHAR(2000),
Burden_Cost_Credit_CCID double,
Burden_Cost_Credit_Account VARCHAR(2000),
Burden_Cost_Debit_CCID double,
Burden_Cost_Debit_Account VARCHAR(2000),
Provider_Ledger_Currency_Code VARCHAR(15),
Provider_Ledger_Currency VARCHAR(80),
Raw_Cost_in_Provider_Ledger_Currency double,
Burdened_Cost_in_Provider_Ledger_Currency double,
Provider_Ledger_Conversion_Rate_Type VARCHAR(30),
Provider_Ledger_Conversion_Rate_Date VARCHAR(100),
Provider_Ledger_Conversion_Date_Type VARCHAR(4),
Provider_Ledger_Currency_Conversion_Rate double,
Provider_Ledger_Currency_Conversion_Rounding_Limit double,
Converted VARCHAR(1),
Context_Category VARCHAR(40),
User_Defined_Attribute_1 VARCHAR(150),
User_Defined_Attribute_2 VARCHAR(150),
User_Defined_Attribute_3 VARCHAR(150),
User_Defined_Attribute_4 VARCHAR(150),
User_Defined_Attribute_5 VARCHAR(150),
User_Defined_Attribute_6 VARCHAR(150),
User_Defined_Attribute_7 VARCHAR(150),
User_Defined_Attribute_8 VARCHAR(150),
User_Defined_Attribute_9 VARCHAR(150),
User_Defined_Attribute_10 VARCHAR(150),
Reserved_Attribute_1 VARCHAR(150),
Reserved_Attribute_2 VARCHAR(150),
Reserved_Attribute_3 VARCHAR(150),
Reserved_Attribute_4 VARCHAR(150),
Reserved_Attribute_5 VARCHAR(150),
Reserved_Attribute_6 VARCHAR(150),
Reserved_Attribute_7 VARCHAR(150),
Reserved_Attribute_8 VARCHAR(150),
Reserved_Attribute_9 VARCHAR(150),
Reserved_Attribute_10 VARCHAR(150),
Attribute_Category VARCHAR(30),
Attribute_1 VARCHAR(150),
Attribute_2 VARCHAR(150),
Attribute_3 VARCHAR(150),
Attribute_4 VARCHAR(150),
Attribute_5 VARCHAR(150),
Attribute_6 VARCHAR(150),
Attribute_7 VARCHAR(150),
Attribute_8 VARCHAR(150),
Attribute_9 VARCHAR(150),
Attribute_10 VARCHAR(150),
 PRIMARY KEY(rowid));
</code>```

Error:

Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs

答:
Do not splay an array across columns.

For example, you are allowing for 10 attributes.  Have you thought about what to do when you need 11?  Instead of having 10 columns, have a separate table with any number of attributes for each PJC_TXN_XFACE_STAGE_ALL.

Ditto for costs and maybe other things.

Dates should be in DATE datatype, not VARCHAR(100)

I see cases of number, name, id -- shouldn't those be in another table, with only the id here?

The 8-byte DOUBLE is rarely a good datatype for an ID.  What do the IDs look like?

Say NOT NULL where appropriate.

If that does not shrink the schema enough to fit into the limitation; let's see the new CREATE TABLE and we can look for more fixes.  (There are other techniques that I have yet to mention.)

Body:
I am trying to create a table in my database using the following mysql query. But I am getting some row size error.

create table PJC_TXN_XFACE_STAGE_ALL (rowid int AUTO_INCREMENT,error_flag varchar(50),error_message varchar(500),Transaction_Type VARCHAR(100),
Business_Unit_Name VARCHAR(2),
Business_Unit_ID double,
Transaction_Source VARCHAR(240),
Transaction_Source_ID double,
Document VARCHAR(240),
Document_ID double,
Document_Entry VARCHAR(240),
Document_Entry_ID double,
Expenditure_Batch VARCHAR(50),
Batch_Ending_Date VARCHAR(100),
Batch_Description VARCHAR(250),
Expenditure_Item_Date VARCHAR(100),
Person_Number VARCHAR(30),
Person_Name VARCHAR(2000),
Person_ID double,
Human_Resources_Assignment VARCHAR(80),
Human_Resources_Assignment_ID double,
Project_Number VARCHAR(25),
Project_Name VARCHAR(240),
Project_ID double,
Task_Number VARCHAR(100),
Task_Name VARCHAR(255),
Task_ID double,
Expenditure_Type VARCHAR(240),
Expenditure_Type_ID double,
Expenditure_Organization VARCHAR(240),
Expenditure_Organization_ID double,
Quantity double,
Unit_of_Measure VARCHAR(80),
Unit_of_Measure_Code VARCHAR(30),
Work_Type VARCHAR(240),
Work_Type_ID double,
Billable VARCHAR(1),
Capitalizable VARCHAR(1),
Accrual_Batch VARCHAR(1),
Original_Transaction_Reference VARCHAR(120),
Unmatched_Negative_Transaction VARCHAR(1),
Reversed_Original_Transaction VARCHAR(120),
Expenditure_Item_Comment VARCHAR(240),
Accounting_Date VARCHAR(100),
Transaction_Currency_Code VARCHAR(15),
Transaction_Currency VARCHAR(80),
Raw_Cost_in_Transaction_Currency double,
Burdened_Cost_in_Transaction_Currency double,
Raw_Cost_Credit_CCID double,
Raw_Cost_Credit_Account VARCHAR(2000),
Raw_Cost_Debit_CCID double,
Raw_Cost_Debit_Account VARCHAR(2000),
Burdened_Cost_Credit_CCID double,
Burdened_Cost_Credit_Account VARCHAR(2000),
Burdened_Cost_Debit_CCID double,
Burdened_Cost_Debit_Account VARCHAR(2000),
Burden_Cost_Credit_CCID double,
Burden_Cost_Credit_Account VARCHAR(2000),
Burden_Cost_Debit_CCID double,
Burden_Cost_Debit_Account VARCHAR(2000),
Provider_Ledger_Currency_Code VARCHAR(15),
Provider_Ledger_Currency VARCHAR(80),
Raw_Cost_in_Provider_Ledger_Currency double,
Burdened_Cost_in_Provider_Ledger_Currency double,
Provider_Ledger_Conversion_Rate_Type VARCHAR(30),
Provider_Ledger_Conversion_Rate_Date VARCHAR(100),
Provider_Ledger_Conversion_Date_Type VARCHAR(4),
Provider_Ledger_Currency_Conversion_Rate double,
Provider_Ledger_Currency_Conversion_Rounding_Limit double,
Converted VARCHAR(1),
Context_Category VARCHAR(40),
User_Defined_Attribute_1 VARCHAR(150),
User_Defined_Attribute_2 VARCHAR(150),
User_Defined_Attribute_3 VARCHAR(150),
User_Defined_Attribute_4 VARCHAR(150),
User_Defined_Attribute_5 VARCHAR(150),
User_Defined_Attribute_6 VARCHAR(150),
User_Defined_Attribute_7 VARCHAR(150),
User_Defined_Attribute_8 VARCHAR(150),
User_Defined_Attribute_9 VARCHAR(150),
User_Defined_Attribute_10 VARCHAR(150),
Reserved_Attribute_1 VARCHAR(150),
Reserved_Attribute_2 VARCHAR(150),
Reserved_Attribute_3 VARCHAR(150),
Reserved_Attribute_4 VARCHAR(150),
Reserved_Attribute_5 VARCHAR(150),
Reserved_Attribute_6 VARCHAR(150),
Reserved_Attribute_7 VARCHAR(150),
Reserved_Attribute_8 VARCHAR(150),
Reserved_Attribute_9 VARCHAR(150),
Reserved_Attribute_10 VARCHAR(150),
Attribute_Category VARCHAR(30),
Attribute_1 VARCHAR(150),
Attribute_2 VARCHAR(150),
Attribute_3 VARCHAR(150),
Attribute_4 VARCHAR(150),
Attribute_5 VARCHAR(150),
Attribute_6 VARCHAR(150),
Attribute_7 VARCHAR(150),
Attribute_8 VARCHAR(150),
Attribute_9 VARCHAR(150),
Attribute_10 VARCHAR(150),
 PRIMARY KEY(rowid));

Error:

Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs


问:
End of File Exception on ObjectInputStream.readObject
My application streams twitter data and writes them to files.

```<code>while(true){
        Status status = queue.poll();

        if (status == null) {
            Thread.sleep(100);
        }

        if(status!=null){
            list.add(status);
        }

        if(list.size()==10){
            FileOutputStream fos = null;
            ObjectOutputStream out = null;
            try {
                String uuid = UUID.randomUUID().toString();
                String filename = "C:/path/"+topic+"-"+uuid+".ser";
                fos = new FileOutputStream(filename);
                out = new ObjectOutputStream(fos);
                out.writeObject(list);
                tweetsDownloaded += list.size();
                if(tweetsDownloaded % 100==0)
                    System.out.println(tweetsDownloaded+" tweets downloaded");
            //  System.out.println("File: "+filename+" written.");
                out.close();
            } catch (IOException e) {

                e.printStackTrace();
            }

            list.clear();
    }
</code>```

I have this code which gets data from files.

```<code>while(true){
    File[] files = folder.listFiles();

    if(files != null){
        Arrays.sort(//sorting...);

        //Here we manage each single file, from data-load until the deletion
        for(int i = 0; i<files.length; i++){
            loadTweets(files[i].getAbsolutePath());
            //TODO manageStatuses
            files[i].delete();
            statusList.clear();
        }

    }

}
</code>```

The method loadTweets() does the following operations:

```<code>private static void loadTweets(String filename) {

    FileInputStream fis = null;
    ObjectInputStream in = null;
    try{
        fis = new FileInputStream(filename);
        in = new ObjectInputStream(fis);
        statusList = (List<Status>) in.readObject();
        in.close();
    }
    catch(IOException | ClassNotFoundException ex){
        ex.printStackTrace();
    }

}
</code>```

Unfortunately, I don't know why sometimes it throws a

EOFException

when running this line

```<code>statusList = (List<Status>) in.readObject();
</code>```

Anybody knows how I can solve this? Thank you.

答:
I've seen that you're passing the file correctly with the getAbsolutePath() based on a previous question of yours

From what I've read that can be a couple of things, one of them the file being null.

Explaining this idea, you might have written the file but something caused the file to have nothing inside, this might cause an EOFException. The file in fact exists it's just empty

EDIT

Try to enclose the code in while(in.available() > 0)

It would look like this

```<code>private static void loadTweets(String filename) {

    FileInputStream fis = null;
    ObjectInputStream in = null;
    try{
        fis = new FileInputStream(filename);
        in = new ObjectInputStream(fis);
        while(in.available() > 0) {
            statusList = (List<Status>) in.readObject();
        }
        in.close();
    }
    catch(IOException | ClassNotFoundException ex){
        ex.printStackTrace();
    }
}
</code>```

Body:
My application streams twitter data and writes them to files.

while(true){
        Status status = queue.poll();

        if (status == null) {
            Thread.sleep(100);
        }

        if(status!=null){
            list.add(status);
        }

        if(list.size()==10){
            FileOutputStream fos = null;
            ObjectOutputStream out = null;
            try {
                String uuid = UUID.randomUUID().toString();
                String filename = "C:/path/"+topic+"-"+uuid+".ser";
                fos = new FileOutputStream(filename);
                out = new ObjectOutputStream(fos);
                out.writeObject(list);
                tweetsDownloaded += list.size();
                if(tweetsDownloaded % 100==0)
                    System.out.println(tweetsDownloaded+" tweets downloaded");
            //  System.out.println("File: "+filename+" written.");
                out.close();
            } catch (IOException e) {

                e.printStackTrace();
            }

            list.clear();
    }

I have this code which gets data from files.

while(true){
    File[] files = folder.listFiles();

    if(files != null){
        Arrays.sort(//sorting...);

        //Here we manage each single file, from data-load until the deletion
        for(int i = 0; i<files.length; i++){
            loadTweets(files[i].getAbsolutePath());
            //TODO manageStatuses
            files[i].delete();
            statusList.clear();
        }

    }

}

The method loadTweets() does the following operations:

private static void loadTweets(String filename) {

    FileInputStream fis = null;
    ObjectInputStream in = null;
    try{
        fis = new FileInputStream(filename);
        in = new ObjectInputStream(fis);
        statusList = (List<Status>) in.readObject();
        in.close();
    }
    catch(IOException | ClassNotFoundException ex){
        ex.printStackTrace();
    }

}

Unfortunately, I don't know why sometimes it throws a

EOFException

when running this line

statusList = (List<Status>) in.readObject();

Anybody knows how I can solve this? Thank you.

Body:
I've seen that you're passing the file correctly with the getAbsolutePath() based on a previous question of yours

From what I've read that can be a couple of things, one of them the file being null.

Explaining this idea, you might have written the file but something caused the file to have nothing inside, this might cause an EOFException. The file in fact exists it's just empty

EDIT

Try to enclose the code in while(in.available() > 0)

It would look like this

private static void loadTweets(String filename) {

    FileInputStream fis = null;
    ObjectInputStream in = null;
    try{
        fis = new FileInputStream(filename);
        in = new ObjectInputStream(fis);
        while(in.available() > 0) {
            statusList = (List<Status>) in.readObject();
        }
        in.close();
    }
    catch(IOException | ClassNotFoundException ex){
        ex.printStackTrace();
    }
}


问:
Why doesn't J2ObjC translate field with @Weak as __weak but __unsafe_unretained?
As we know, __unsafe_unretained is not as safe as __weak, so why doesn't J2ObjC translate field with @Weak as __weak but __unsafe_unretained?

答:
Two reasons:

__weak only works in ARC code, and the JRE emulation library is not built with ARC due to a noticeable performance cost.

In Objective C, one can test whether a __weak field has been released by testing whether it's nil. Since there's no way to do that in Java for normal references, code that depends on this behavior is platform-dependent (ie, won't work the same on Android).

J2ObjC supports the java.lang.reflect package, so if you want a cross-platform way of using weak references, use WeakReference instead of @Weak.


问:
Django Tastypie Advanced Filtering: How to do complex lookups with Q objects
I have a basic Django model like:

```<code>class Business(models.Model):
    name = models.CharField(max_length=200, unique=True)
    email = models.EmailField()
    phone = models.CharField(max_length=40, blank=True, null=True)
    description = models.TextField(max_length=500)
</code>```

I need to execute a complex query on the above model like:

```<code>qset = (
    Q(name__icontains=query) |
    Q(description__icontains=query) |
    Q(email__icontains=query)
    )
results = Business.objects.filter(qset).distinct()
</code>```

I have tried the following using tastypie with no luck:

```<code>def build_filters(self, filters=None):
    if filters is None:
        filters = {}
    orm_filters = super(BusinessResource, self).build_filters(filters)

    if('query' in filters):
        query = filters['query']
        print query
        qset = (
                Q(name__icontains=query) |
                Q(description__icontains=query) |
                Q(email__icontains=query)
                )
        results = Business.objects.filter(qset).distinct()
        orm_filters = {'query__icontains': results}

    return orm_filters
</code>```

and in class Meta for tastypie I have filtering set as:

```<code>filtering = {
        'name: ALL,
        'description': ALL,
        'email': ALL,
        'query': ['icontains',],
    }
</code>```

Any ideas to how I can tackle this?

Thanks
 - Newton

答:
Taking the idea in astevanovic's answer and cleaning it up a bit, the following should work and is more succinct.

The main difference is that apply_filters is made more robust by using None as the key instead of custom (which could conflict with a column name).

```<code>def build_filters(self, filters=None):
    if filters is None:
        filters = {}
    orm_filters = super(BusinessResource, self).build_filters(filters)

    if 'query' in filters:
        query = filters['query']
        qset = (
                Q(name__icontains=query) |
                Q(description__icontains=query) |
                Q(email__icontains=query)
                )
        orm_filters.update({None: qset}) # None is used as the key to specify that these are non-keyword filters

    return orm_filters

def apply_filters(self, request, applicable_filters):
    return self.get_object_list(request).filter(*applicable_filters.pop(None, []), **applicable_filters)
    # Taking the non-keyword filters out of applicable_filters (if any) and applying them as positional arguments to filter()
</code>```

Body:
I have a basic Django model like:

class Business(models.Model):
    name = models.CharField(max_length=200, unique=True)
    email = models.EmailField()
    phone = models.CharField(max_length=40, blank=True, null=True)
    description = models.TextField(max_length=500)

I need to execute a complex query on the above model like:

qset = (
    Q(name__icontains=query) |
    Q(description__icontains=query) |
    Q(email__icontains=query)
    )
results = Business.objects.filter(qset).distinct()

I have tried the following using tastypie with no luck:

def build_filters(self, filters=None):
    if filters is None:
        filters = {}
    orm_filters = super(BusinessResource, self).build_filters(filters)

    if('query' in filters):
        query = filters['query']
        print query
        qset = (
                Q(name__icontains=query) |
                Q(description__icontains=query) |
                Q(email__icontains=query)
                )
        results = Business.objects.filter(qset).distinct()
        orm_filters = {'query__icontains': results}

    return orm_filters

and in class Meta for tastypie I have filtering set as:

filtering = {
        'name: ALL,
        'description': ALL,
        'email': ALL,
        'query': ['icontains',],
    }

Any ideas to how I can tackle this?

Thanks
 - Newton

Body:
Taking the idea in astevanovic's answer and cleaning it up a bit, the following should work and is more succinct.

The main difference is that apply_filters is made more robust by using None as the key instead of custom (which could conflict with a column name).

def build_filters(self, filters=None):
    if filters is None:
        filters = {}
    orm_filters = super(BusinessResource, self).build_filters(filters)

    if 'query' in filters:
        query = filters['query']
        qset = (
                Q(name__icontains=query) |
                Q(description__icontains=query) |
                Q(email__icontains=query)
                )
        orm_filters.update({None: qset}) # None is used as the key to specify that these are non-keyword filters

    return orm_filters

def apply_filters(self, request, applicable_filters):
    return self.get_object_list(request).filter(*applicable_filters.pop(None, []), **applicable_filters)
    # Taking the non-keyword filters out of applicable_filters (if any) and applying them as positional arguments to filter()


问:
How to loop scroll event
My question is probably very easy. How to loop this function?
Now, scroll event works only once. I'm looking for solution how to enable else function (smooth scroll goes from red div to blue div)

Here is js code:

```<code>var o = true;

if (o === true) {
$('div').scroll(function () {
        if(o){
      $('div').animate({
          scrollTop: $("#red").offset().top
      }, 1000);
      o=false;
     }
});
}

else {
$('div').scroll(function () {
        if(o === false ){
      $('div').animate({
          scrollTop: $("#blue").offset().top
      }, 1000);
      o=true;
     document.write(o);
    }
});
}
</code>```

HTML + CSS + JS:
https://jsfiddle.net/g2jafoay/6/

What I'm looking for: when you scroll down, there is animation which take you to red div. So, I want to add animation which takes you to blue div after scroll up

答:
Remember when code is executed. That is: When it is reached.

We can simplify your code to

```<code>let a = true;
if (a) {
  functionA();
} else {
  functionB();
}
</code>```

Obviously, when we reach this code, functionA is going to be executed. We never execute functionB, because, well, this code is never executed again.

Using this information, and looking at your code, we see that you are only attaching the first scroll handler, which has the behaviour of scrolling to the red div. The scroll handler is executed on every scroll event. If you would succeed in executing your code like it is now, you would end up with an infinite number of scroll handlers that try to scroll to the red div and an infinite number of scroll handlers that try to scroll to the blue div.

What we want to do is create only one scroll handler that has all the relevant logic inside the handler. Or, in other words, the decision is made in the scroll handler instead of the surrounding code.

```<code>let onRed = true;
$('div').on('scroll', () => {
  let scrollTarget;
  if (onRed) {
    scrollTarget = $('#blue');
  } else {
    scrollTarget = $('#red');
  }

  $('div').animate({
    scrollTop: scrollTarget.offset().top
  }, 1000);
  onRed = !onRed;
});
</code>```

Title: How to loop scroll event

Body:
My question is probably very easy. How to loop this function?
Now, scroll event works only once. I'm looking for solution how to enable else function (smooth scroll goes from red div to blue div)

Here is js code:

var o = true;

if (o === true) {
$('div').scroll(function () {
        if(o){
      $('div').animate({
          scrollTop: $("#red").offset().top
      }, 1000);
      o=false;
     }
});
}

else {
$('div').scroll(function () {
        if(o === false ){
      $('div').animate({
          scrollTop: $("#blue").offset().top
      }, 1000);
      o=true;
     document.write(o);
    }
});
}

HTML + CSS + JS:
https://jsfiddle.net/g2jafoay/6/

What I'm looking for: when you scroll down, there is animation which take you to red div. So, I want to add animation which takes you to blue div after scroll up

Body:
Remember when code is executed. That is: When it is reached.

We can simplify your code to

let a = true;
if (a) {
  functionA();
} else {
  functionB();
}

Obviously, when we reach this code, functionA is going to be executed. We never execute functionB, because, well, this code is never executed again.

Using this information, and looking at your code, we see that you are only attaching the first scroll handler, which has the behaviour of scrolling to the red div. The scroll handler is executed on every scroll event. If you would succeed in executing your code like it is now, you would end up with an infinite number of scroll handlers that try to scroll to the red div and an infinite number of scroll handlers that try to scroll to the blue div.

What we want to do is create only one scroll handler that has all the relevant logic inside the handler. Or, in other words, the decision is made in the scroll handler instead of the surrounding code.

let onRed = true;
$('div').on('scroll', () => {
  let scrollTarget;
  if (onRed) {
    scrollTarget = $('#blue');
  } else {
    scrollTarget = $('#red');
  }

  $('div').animate({
    scrollTop: scrollTarget.offset().top
  }, 1000);
  onRed = !onRed;
});


问:
If not multiple conditions with certain values
I have 2 variables:

1) $key : this variable can either contain the word Unknown or not.

2) $val : this variable can contain 0,0 or some other values

I want to run a script in case that $key not containing Unknown AND $val not equal 0,0. So skip the script if BOTH variables have the above mentioned values ONLY.

So I have the following code:

```<code>if(strpos($key, 'Unknown') !== false && $val == '0,0') {
   /* do nothing! */
}
else {
   /* continue script */
}
</code>```

So is there a better way to achieve the above without having this empty if condition

答:
You can exit the code block early:</p>

```<code>if(strpos($key, 'Unknown') !== false && $val == '0,0') {
   return;
}

/* continue script */
</code>```

Body:
I have 2 variables:

1) $key : this variable can either contain the word Unknown or not.

2) $val : this variable can contain 0,0 or some other values

I want to run a script in case that $key not containing Unknown AND $val not equal 0,0. So skip the script if BOTH variables have the above mentioned values ONLY.

So I have the following code:

if(strpos($key, 'Unknown') !== false && $val == '0,0') {
   /* do nothing! */
}
else {
   /* continue script */
}

So is there a better way to achieve the above without having this empty if condition

Body:
You can exit the code block early:

if(strpos($key, 'Unknown') !== false && $val == '0,0') {
   return;
}

/* continue script */


问:
Easiest way to select or type over text in a text box in protractor?
In a protractor test I have an <input type="text"/> that is pre-filled with a value, and I'd like to erase that value and type a new one. Ideally I'd be able to just say something like

// Some way to select all the text in the text box so `
// sendKeys` will type over it.
element(by.css("input.myInput")).selectAll();

element(by.css("input.myInput")).sendKeys("my new value");
```

But selectAll doesn't exist and I can't find anything helpful in the API docs.

Any ideas?

答:
Similar to glepretre, my solution is given the input formcontrol is named 'Name' but this worked for me </p>

```<code>newValue = getNewValue();
element(by.css('input[formControlName=Name]')).clear();
element(by.css('input[formControlName=Name]')).sendKeys(newValue)
.then(function () {....});
</code>```

Body:
In a protractor test I have an <input type="text"/> that is pre-filled with a value, and I'd like to erase that value and type a new one. Ideally I'd be able to just say something like

// Some way to select all the text in the text box so `
// sendKeys` will type over it.
element(by.css("input.myInput")).selectAll();

element(by.css("input.myInput")).sendKeys("my new value");

But selectAll doesn't exist and I can't find anything helpful in the API docs.

Any ideas?

Body:
Similar to glepretre, my solution is given the input formcontrol is named 'Name' but this worked for me

newValue = getNewValue();
element(by.css('input[formControlName=Name]')).clear();
element(by.css('input[formControlName=Name]')).sendKeys(newValue)
.then(function () {....});


问:
Can't submit apps to AppStore: ERROR ITMS-90534: "Invalid Toolchain

ERROR ITMS-90534: "Invalid Toolchain.

New apps and app updates must be built with the public (GM) versions of Xcode 6 or later, macOS, and iOS SDK or later. Don't submit apps built with beta software including beta macOS builds." ERROR ITMS-90534: "Invalid Toolchain. New apps and app updates must be built with the public (GM) versions of Xcode 6 or later, macOS, and iOS SDK or later. Don't submit apps built with beta software including beta macOS builds."

I found this error during upload IPA to account.

答:
Right-Click on the archive file (.xcarchive) > Show Package Contents > Products > Applications > Right-Click on the app file > Show Package Contents > Double-Click on Info.plist to edit it

Remove b from the end of the value for DTXcodeBuild (for example change from 9C40b to 9C40)

Re-submit and it will work

ContentLicense: CC BY-SA 4.0


问:
Angular 4 structure for multi-user webapp
I'm trying to build a webapp with Angular 4 for the front end, where I have 3 types of users. I'm searching on advise as to what the best practices are in achieving this as I'm quite new to this. I'm sharing what I have so far:

```<code>v app
  v shared
    v main
      > app     //this is what u see before login/reg, after that you're redirected to the apropriate view
      > admin-view
         admin-component.html
         admin-component.css
         admin-component.ts
      > patient-view
        > my-profile
          >edit-profile
            //they all have html, css and ts
          >appointments-history
          >procedures-done
        > dentist-search
        > dentist-profile
        > change-password
    > models
    > services
    > util
    app-routing-module.ts
app.module.ts
</code>```

Now I haven't written everything down,such as each html, css and ts file, also the services, models and utils, I think they are pretty straight forward.

My questions are:
 1)  is app-routing module in the correct place, or should it be next to app.module.ts
     2) should I make separate app-routing modules for nested components like in patient view > my profile > edit profile, or is it fine to have them listed as children in the app-routing.module.ts.

What happens if I have repetitive components, such as change password component, also I have a search component that is the same for patient and dentist. Should I place those components in a separate folder and have:

```<code>>main
  >admin-view
  >app
  >dentist-view
  >patient-view
  >shared
</code>```

and just declare them as children in each components routing?
Also if I'm doing something totally wrong, please do tell, as I'm still learning but I want to follow the best conventions and practices.

Thank you in advance!

答:
is app-routing module in the correct place, or should it be next to app.module.ts

The angular-cli places the app-routing.module.ts file next to the app.module.ts file.

should I make separate app-routing modules for nested components like in patient view > my profile > edit profile, or is it fine to have them listed as children in the app-routing.module.ts.

If you want to support lazy-loaded modules, you should create a moduleNome-routing.module.ts for each lazy loaded module. Lazy loading for an application with user role specific views makes sense because users don't need the views that don't fit their role. Also, if your application starts to get big (let's say more than 10 routes in a routing module) it might be good to consider breaking that up into smaller lazy loaded modules so your application does not take too long to load.

If your app is small and you don't care about load times, then I'd think you should be okay with having all your routes in app-routing.module.ts.

Body:
I'm trying to build a webapp with Angular 4 for the front end, where I have 3 types of users. I'm searching on advise as to what the best practices are in achieving this as I'm quite new to this. I'm sharing what I have so far:

v app
  v shared
    v main
      > app     //this is what u see before login/reg, after that you're redirected to the apropriate view
      > admin-view
         admin-component.html
         admin-component.css
         admin-component.ts
      > patient-view
        > my-profile
          >edit-profile
            //they all have html, css and ts
          >appointments-history
          >procedures-done
        > dentist-search
        > dentist-profile
        > change-password
    > models
    > services
    > util
    app-routing-module.ts
app.module.ts

Now I haven't written everything down,such as each html, css and ts file, also the services, models and utils, I think they are pretty straight forward.

My questions are:
 1)  is app-routing module in the correct place, or should it be next to app.module.ts
     2) should I make separate app-routing modules for nested components like in patient view > my profile > edit profile, or is it fine to have them listed as children in the app-routing.module.ts.

What happens if I have repetitive components, such as change password component, also I have a search component that is the same for patient and dentist. Should I place those components in a separate folder and have:

>main
  >admin-view
  >app
  >dentist-view
  >patient-view
  >shared

and just declare them as children in each components routing?
Also if I'm doing something totally wrong, please do tell, as I'm still learning but I want to follow the best conventions and practices.

Thank you in advance!


问:
Slide in animation with CSS and JS
I'm trying to accomplish a slide-in effect like the one on this site.

I found a a good tutorial here, but I still need help with a couple of things. I have 9 sections following the same structure and logic. I will put only three on my snippet.

What I need its a way to set the space between sections at top:-28px after the animation it's over but still far enough before animation so they can be animated.

So far I animated the full section, but I would like to edit the JS and CSS in order to animate individually the picture, header and text (to feel more like in the example page).

jQuery(document).ready(function($){
(function($) {

  /**
   * Copyright 2012, Digital Fusion
   * Licensed under the MIT license.
   * http://teamdf.com/jquery-plugins/license/
   *
   * @author Sam Sehnert
   * @desc A small plugin that checks whether elements are within
   *     the user visible viewport of a web browser.
   *     only accounts for vertical position, not horizontal.
   */

  $.fn.visible = function(partial) {

      var $t            = $(this),
          $w            = $(window),
          viewTop       = $w.scrollTop(),
          viewBottom    = viewTop + $w.height(),
          _top          = $t.offset().top,
          _bottom       = _top + $t.height(),
          compareTop    = partial === true ? _bottom : _top,
          compareBottom = partial === true ? _top : _bottom;

    return ((compareBottom <= viewBottom) && (compareTop >= viewTop));

  };

})(jQuery);

 var win = $(window);

 var allMods = $(".full-module-scroll");

allMods.each(function(i, el) {
  var el = $(el);
  if (el.visible(true)) {
    el.addClass("already-visible");
  }
});

win.scroll(function(event) {

  allMods.each(function(i, el) {
    var el = $(el);
    if (el.visible(true)) {
      el.addClass("come-in");
    }
  });

});
var win = $(window);

var allMods = $(".full-module-scroll");

allMods.each(function(i, el) {
  var el = $(el);
  if (el.visible(true)) {
    el.addClass("already-visible");
  }
});

win.scroll(function(event) {

  allMods.each(function(i, el) {
    var el = $(el);
    if (el.visible(true)) {
      el.addClass("come-in");
    }
  });

});

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/*Animation*/
/*The important part*/
@import "compass/css3";

.full-module-scroll{
  width: 100%;
  min-height: 483px;
 }
.come-in {
  transform: translateY(150px); /*I would like to understand this better*/
  animation: come-in 0.8s ease forwards;
 }

.already-visible {
  transform: translateY(0);
  animation: none;
 }

@keyframes come-in {
  to { transform: translateY(0); }
 }

/*Styles*/
 #all-apps-container{
   display: inline-block;
   margin-bottom: 40px;
  }
.apps-text-container{
   display: inline-block;
   width: 60%;
  }
.apps-green-header{
    font-size: 30pt;
    color: #00A8A1;
    margin-bottom: 60px;
    margin-top: 120px;
  }
.apps-description {
    font-size: 15pt;
    line-height: 28pt;
    color: #666666;
  }
.apps-align-right{
   text-align: right;
   }
.apps-align-left{
   text-align: left;
   }
#sicem-web-container{
   position:relative;
   margin-top: 50px;
  }
#sicem-img-container {
   background-image : url(https://i.stack.imgur.com/Ze48o.png);
   background-repeat : no-repeat;
   position : relative;
   width: 200px;
   height: 483px;
   display: inline-block;
   float: right;
  }
#sicem-description{
   width: 581px;
   float: right;
  }
#movil-container {
    position: relative;
    margin-top: 120px;
  }
#movil-img-container {
   background-image : url(https://i.stack.imgur.com/sccj4.png);
   background-repeat : no-repeat;
   position : relative;
   width: 200px;
   height: 483px;
   display: inline-block;
   float: left;
  }
#movil-description{
    width: 513px;
    float: left;
  }</code>```

 Header

 Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...

 A nother header

 Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...

 Header

 Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...

```

答:
You could add the following css to all the elements you want to move:

```<code>transition: all 0.5s ease;
</code>```

Then you just have to change the css of the elements via javascript like:

```<code>document.getElementById(yourelementid).style=" width:100px; " //<-- Whatever you want
</code>```

Or you add the sice you want to have in your original css file and just change the style in html. Then you just delete the style from html like this:

```<code>css:
#yourdiv { width:100px; }

HTML: <div id="yourdiv" style="width:0px;"></div>

JavaScript:  document.getElementById(yourdiv).style="" // clear html style
</code>```

Maybe this will give you the effect

Title: Slide in animation with CSS and JS

Body:
I'm trying to accomplish a slide-in effect like the one on this site.

I found a a good tutorial here, but I still need help with a couple of things. I have 9 sections following the same structure and logic. I will put only three on my snippet.

What I need its a way to set the space between sections at top:-28px after the animation it's over but still far enough before animation so they can be animated.

So far I animated the full section, but I would like to edit the JS and CSS in order to animate individually the picture, header and text (to feel more like in the example page).

jQuery(document).ready(function($){
(function($) {

  /**
   * Copyright 2012, Digital Fusion
   * Licensed under the MIT license.
   * http://teamdf.com/jquery-plugins/license/
   *
   * @author Sam Sehnert
   * @desc A small plugin that checks whether elements are within
   *     the user visible viewport of a web browser.
   *     only accounts for vertical position, not horizontal.
   */

  $.fn.visible = function(partial) {

      var $t            = $(this),
          $w            = $(window),
          viewTop       = $w.scrollTop(),
          viewBottom    = viewTop + $w.height(),
          _top          = $t.offset().top,
          _bottom       = _top + $t.height(),
          compareTop    = partial === true ? _bottom : _top,
          compareBottom = partial === true ? _top : _bottom;

    return ((compareBottom <= viewBottom) && (compareTop >= viewTop));

  };

})(jQuery);

 var win = $(window);

 var allMods = $(".full-module-scroll");

allMods.each(function(i, el) {
  var el = $(el);
  if (el.visible(true)) {
    el.addClass("already-visible");
  }
});

win.scroll(function(event) {

  allMods.each(function(i, el) {
    var el = $(el);
    if (el.visible(true)) {
      el.addClass("come-in");
    }
  });

});
var win = $(window);

var allMods = $(".full-module-scroll");

allMods.each(function(i, el) {
  var el = $(el);
  if (el.visible(true)) {
    el.addClass("already-visible");
  }
});

win.scroll(function(event) {

  allMods.each(function(i, el) {
    var el = $(el);
    if (el.visible(true)) {
      el.addClass("come-in");
    }
  });

});

});

/*Animation*/
/*The important part*/
@import "compass/css3";

.full-module-scroll{
  width: 100%;
  min-height: 483px;
 }
.come-in {
  transform: translateY(150px); /*I would like to understand this better*/
  animation: come-in 0.8s ease forwards;
 }

.already-visible {
  transform: translateY(0);
  animation: none;
 }

@keyframes come-in {
  to { transform: translateY(0); }
 }

/*Styles*/
 #all-apps-container{
   display: inline-block;
   margin-bottom: 40px;
  }
.apps-text-container{
   display: inline-block;
   width: 60%;
  }
.apps-green-header{
    font-size: 30pt;
    color: #00A8A1;
    margin-bottom: 60px;
    margin-top: 120px;
  }
.apps-description {
    font-size: 15pt;
    line-height: 28pt;
    color: #666666;
  }
.apps-align-right{
   text-align: right;
   }
.apps-align-left{
   text-align: left;
   }
#sicem-web-container{
   position:relative;
   margin-top: 50px;
  }
#sicem-img-container {
   background-image : url(https://i.stack.imgur.com/Ze48o.png);
   background-repeat : no-repeat;
   position : relative;
   width: 200px;
   height: 483px;
   display: inline-block;
   float: right;
  }
#sicem-description{
   width: 581px;
   float: right;
  }
#movil-container {
    position: relative;
    margin-top: 120px;
  }
#movil-img-container {
   background-image : url(https://i.stack.imgur.com/sccj4.png);
   background-repeat : no-repeat;
   position : relative;
   width: 200px;
   height: 483px;
   display: inline-block;
   float: left;
  }
#movil-description{
    width: 513px;
    float: left;
  }

 Header

 Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...

 A nother header

 Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...

 Header

 Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...

Body:
You could add the following css to all the elements you want to move:

transition: all 0.5s ease;

Then you just have to change the css of the elements via javascript like:

document.getElementById(yourelementid).style=" width:100px; " //<-- Whatever you want

Or you add the sice you want to have in your original css file and just change the style in html. Then you just delete the style from html like this:

css:
#yourdiv { width:100px; }

HTML: <div id="yourdiv" style="width:0px;"></div>

JavaScript:  document.getElementById(yourdiv).style="" // clear html style

Maybe this will give you the effect


问:
retrieve rows until their quantity sum is less then @quantity
I have table:
data(id, name, quantity)

I would like to write a stored procedure that will get @quantity and retrieve me the minimum rows that their quantity sum is bigger or equal to @quantity.

Example:

```<code>id    name    quantity
1     a       3
2     b       1
3     c       7
4     d       2
</code>```

For @quantity=5 good results can be:

```<code>1, a, 3
2, b, 1
3, c, 7
</code>```

OR

```<code>1, a, 3
4, d, 2
</code>```

OR

```<code>3, c, 7
</code>```

and so on. the sum of quantity in the rsults must be greater or equal to @quantity but I dont need extra rows.

答:
EDITED: explanation added

```<code>declare @goal int
set @goal = 5
;with numbered as
(
  -- this first query gives a sequential number to all records
  -- the biggest quantities are number 1,2,3 etc to the smallest quantities
  -- this ordering is because the minimum number of rows is most quickly
  -- achieved by combining the biggest quantities
  select id, name, quantity,
    row_number() over (order by quantity desc) rn
  from data
), cte as
(
  -- this is a common table expression
  -- it starts off with the record with the biggest quantity
  select id, name, quantity, rn, sumsofar = quantity
  from numbered
  where rn = 1

  union all

  -- this is the recursive part
  -- "CTE" references the previous record in the loop
  select b.*, sumsofar + b.quantity
  from numbered b
  inner join cte a on b.rn = a.rn+1  -- add the next record (as ordered)
  -- continue the loop only if the goal is not yet reached
  where a.sumsofar < @goal
)
-- this finally selects all the records that have been collected to satisfy the @goal
select * from cte

-- NOTE: if @goal cannot be reached even with all records added up, this just
--       returns all records
</code>```

This only works for SQL Server 2005+, due to using Common Table Expressions.

This should work better than the below, but the below also works in 2000 or you can compare the two in 2005/8 for what works best for you.

```<code>declare @goal int set @goal = 5

select c.*
from data c inner join
(
    select top 1 * from
    (
        -- find the pivotal a.id on which the goal is reached
        select a.id, a.quantity, sum(b.quantity) s
        from data a
        -- this works on the b records on quantity desc, and id asc
        inner join data b
          on b.quantity < a.quantity
          or (b.quantity=a.quantity and b.id > a.id)
        group by a.id, a.quantity
        having sum(b.quantity) >= @goal
        union all
        -- if ALL records together cannot satisfy the GOAL
        -- we add a id=-1 record to mark this fact
        select -1, null, null
    ) oneonly
    -- find the min required, or return the fake -1 ID
    ORDER BY case when id=-1 then 1 else 0 end, s ASC, id ASC
) d
  on c.quantity > d.quantity
  or (c.quantity=d.quantity and c.id <= d.id)
  or d.id = -1   -- this matches all rows in C
</code>```

Body:
I have table:
data(id, name, quantity)

I would like to write a stored procedure that will get @quantity and retrieve me the minimum rows that their quantity sum is bigger or equal to @quantity.

Example:

id    name    quantity
1     a       3
2     b       1
3     c       7
4     d       2

For @quantity=5 good results can be:

1, a, 3
2, b, 1
3, c, 7

OR

1, a, 3
4, d, 2

OR

3, c, 7

and so on. the sum of quantity in the rsults must be greater or equal to @quantity but I dont need extra rows.

Body:
EDITED: explanation added

declare @goal int
set @goal = 5
;with numbered as
(
  -- this first query gives a sequential number to all records
  -- the biggest quantities are number 1,2,3 etc to the smallest quantities
  -- this ordering is because the minimum number of rows is most quickly
  -- achieved by combining the biggest quantities
  select id, name, quantity,
    row_number() over (order by quantity desc) rn
  from data
), cte as
(
  -- this is a common table expression
  -- it starts off with the record with the biggest quantity
  select id, name, quantity, rn, sumsofar = quantity
  from numbered
  where rn = 1

  union all

  -- this is the recursive part
  -- "CTE" references the previous record in the loop
  select b.*, sumsofar + b.quantity
  from numbered b
  inner join cte a on b.rn = a.rn+1  -- add the next record (as ordered)
  -- continue the loop only if the goal is not yet reached
  where a.sumsofar < @goal
)
-- this finally selects all the records that have been collected to satisfy the @goal
select * from cte

-- NOTE: if @goal cannot be reached even with all records added up, this just
--       returns all records

This only works for SQL Server 2005+, due to using Common Table Expressions.

This should work better than the below, but the below also works in 2000 or you can compare the two in 2005/8 for what works best for you.

declare @goal int set @goal = 5

select c.*
from data c inner join
(
    select top 1 * from
    (
        -- find the pivotal a.id on which the goal is reached
        select a.id, a.quantity, sum(b.quantity) s
        from data a
        -- this works on the b records on quantity desc, and id asc
        inner join data b
          on b.quantity < a.quantity
          or (b.quantity=a.quantity and b.id > a.id)
        group by a.id, a.quantity
        having sum(b.quantity) >= @goal
        union all
        -- if ALL records together cannot satisfy the GOAL
        -- we add a id=-1 record to mark this fact
        select -1, null, null
    ) oneonly
    -- find the min required, or return the fake -1 ID
    ORDER BY case when id=-1 then 1 else 0 end, s ASC, id ASC
) d
  on c.quantity > d.quantity
  or (c.quantity=d.quantity and c.id <= d.id)
  or d.id = -1   -- this matches all rows in C


问:
Function parameters out of range in function
For a class project I have to make a hangman game. Following it's guidelines I have gotten this code:

```<code>def hangman(guessed, secret):
  word = ""
  wrongLetters = 0
  checkLetter = 0
  compareLetter = 0
  for i in range(len(secret)):
      if secret[checkLetter] == guessed[compareLetter]:
            word += guessed[compareLetter]
          compareLetter = 0
          checkLetter += 1
      elif secret[checkLetter] != guessed[compareLetter]:
          compareLetter += 1
          for i in range(len(secret) - 1):
              if secret[checkLetter] == guessed[compareLetter]:
                  word += guessed[checkLetter]
                  break
              elif secret[checkLetter] != guessed[compareLetter]:
                  compareLetter += 1
                  wrongLetters += 1
              elif wrongLetters == len(secret):
                  word += "-"
                  wrongLetters = 0
                  checkLetter += 1
                  compareLetter = 0
  print(word)
</code>```

My issue is that it tells me that if secret[checkLetter] == guessed[compareLetter]: under the second for statement is out of range of the string index. I believe it is because my function parameters are local. Any idea how to fix?

答:
There are probably more issues than I'm seeing at first glance, but here goes.

1) In the second for loop you will NEVER get to the last elif case.

2) You don't reset compareLetter when you get to the end of the list of guessed letters. Which means that eventually, it CAN get larger than than the length of 'guessed' which is what is causing your exception.

3) You have named both of your for loop iterators i. And you don't use them ever.

4) Your for loops go through the length of secret twice, nested. And again, you don't use the iterators.

As eiram_mahera pointed out, your codes logic is flawed. Look at what you are doing each loop, and compare that to what you WANT to be doing each loop. They are not the same thing.

Body:
For a class project I have to make a hangman game. Following it's guidelines I have gotten this code:

def hangman(guessed, secret):
  word = ""
  wrongLetters = 0
  checkLetter = 0
  compareLetter = 0
  for i in range(len(secret)):
      if secret[checkLetter] == guessed[compareLetter]:
            word += guessed[compareLetter]
          compareLetter = 0
          checkLetter += 1
      elif secret[checkLetter] != guessed[compareLetter]:
          compareLetter += 1
          for i in range(len(secret) - 1):
              if secret[checkLetter] == guessed[compareLetter]:
                  word += guessed[checkLetter]
                  break
              elif secret[checkLetter] != guessed[compareLetter]:
                  compareLetter += 1
                  wrongLetters += 1
              elif wrongLetters == len(secret):
                  word += "-"
                  wrongLetters = 0
                  checkLetter += 1
                  compareLetter = 0
  print(word)

My issue is that it tells me that if secret[checkLetter] == guessed[compareLetter]: under the second for statement is out of range of the string index. I believe it is because my function parameters are local. Any idea how to fix?


问:
R --- filling a matrix by row with undertermined NAs
I am trying to fill a matrix with a sample of data:

```<code>       Pays NbChambre Prix
1    GrÃ¨ce        56  390
2    GrÃ¨ce       471  468
3    GrÃ¨ce        93  427
4    GrÃ¨ce        56  369
5    GrÃ¨ce       286  499
6    GrÃ¨ce       282  526
7    GrÃ¨ce       310  587
8    GrÃ¨ce       300  534
9     Maroc       146  447
10    Maroc       250  482
11    Maroc       196  511
12    Maroc       324  532
13    Maroc       138  450
14    Maroc       400  569
15    Maroc       366  419
16    Maroc       300  421
17    Maroc       144  579
18    Maroc       330  598
19    Maroc       260  495
20    Maroc       170  730
21 Portugal       254  646
22 Portugal       140  652
23 Portugal       273  802
24 Portugal       260  761
25 Portugal       169 1101
26  Tunisie       225  434
27  Tunisie       225  489
28  Tunisie       250  436
29  Tunisie       550  399
30  Tunisie       800  477
31  Tunisie       150  375
32  Tunisie       425  486
33  Tunisie       366  447
34  Tunisie       200  473
35  Tunisie       130  495
36  Turquie       500  617
37  Turquie        50  489
38  Turquie       232  520
39  Turquie       110  534
</code>```

I need to fill a matrix with the values of the vector NbChambre BUT in a way
that each row is used for a certain Pays. The dimensions of the matrix would be

```<code>nrow=length(unique(Pays)),ncol=max(table(Pays))
</code>```

I need to find a way to fill the matrix such as R automatically puts
NA or 0 or whatever to finish a row when there is not enough data and then skip line to continue with the vector NbChambre. I'm relatively new to R so I really can't seem to find any way to do this.

The result should look like

```<code>    [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
[1,]   56  471   93   56  286  282  310  300  NA   NA    NA     NA
[2,]  146 250  196  324  138  400  366  300  144   330   260    170
[3,]  254  140   273  260  169 NA   NA   NA   NA    NA    NA    NA
[4,]
[5,]                             and so on
</code>```

I would really like if someone could help me, thank you!

Body:
I am trying to fill a matrix with a sample of data:

       Pays NbChambre Prix
1    GrÃ¨ce        56  390
2    GrÃ¨ce       471  468
3    GrÃ¨ce        93  427
4    GrÃ¨ce        56  369
5    GrÃ¨ce       286  499
6    GrÃ¨ce       282  526
7    GrÃ¨ce       310  587
8    GrÃ¨ce       300  534
9     Maroc       146  447
10    Maroc       250  482
11    Maroc       196  511
12    Maroc       324  532
13    Maroc       138  450
14    Maroc       400  569
15    Maroc       366  419
16    Maroc       300  421
17    Maroc       144  579
18    Maroc       330  598
19    Maroc       260  495
20    Maroc       170  730
21 Portugal       254  646
22 Portugal       140  652
23 Portugal       273  802
24 Portugal       260  761
25 Portugal       169 1101
26  Tunisie       225  434
27  Tunisie       225  489
28  Tunisie       250  436
29  Tunisie       550  399
30  Tunisie       800  477
31  Tunisie       150  375
32  Tunisie       425  486
33  Tunisie       366  447
34  Tunisie       200  473
35  Tunisie       130  495
36  Turquie       500  617
37  Turquie        50  489
38  Turquie       232  520
39  Turquie       110  534

I need to fill a matrix with the values of the vector NbChambre BUT in a way
that each row is used for a certain Pays. The dimensions of the matrix would be

nrow=length(unique(Pays)),ncol=max(table(Pays))

I need to find a way to fill the matrix such as R automatically puts
NA or 0 or whatever to finish a row when there is not enough data and then skip line to continue with the vector NbChambre. I'm relatively new to R so I really can't seem to find any way to do this.

The result should look like

    [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
[1,]   56  471   93   56  286  282  310  300  NA   NA    NA     NA
[2,]  146 250  196  324  138  400  366  300  144   330   260    170
[3,]  254  140   273  260  169 NA   NA   NA   NA    NA    NA    NA
[4,]
[5,]                             and so on

I would really like if someone could help me, thank you!

Body:
A solution with dplyr + tidyr:

library(dplyr)
library(tidyr)

df %>%
  select(-Prix) %>%
  group_by(Pays) %>%
  mutate(ID = row_number()) %>%
  spread(ID, NbChambre) %>%
  ungroup() %>%
  select(-Pays) %>%
  as.matrix()

Another method with data.table:

library(data.table)

setDT(df)[,ID := rowid(Pays)]
as.matrix(dcast(df, Pays ~ ID, value.var = "NbChambre")[,Pays := NULL])

Result:

    1   2   3   4   5   6   7   8   9  10  11  12
1  56 471  93  56 286 282 310 300  NA  NA  NA  NA
2 146 250 196 324 138 400 366 300 144 330 260 170
3 254 140 273 260 169  NA  NA  NA  NA  NA  NA  NA
4 225 225 250 550 800 150 425 366 200 130  NA  NA
5 500  50 232 110  NA  NA  NA  NA  NA  NA  NA  NA

Data:

df = structure(list(Pays = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L,
3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L
), .Label = c("GrÃ¨ce", "Maroc", "Portugal", "Tunisie", "Turquie"
), class = "factor"), NbChambre = c(56L, 471L, 93L, 56L, 286L,
282L, 310L, 300L, 146L, 250L, 196L, 324L, 138L, 400L, 366L, 300L,
144L, 330L, 260L, 170L, 254L, 140L, 273L, 260L, 169L, 225L, 225L,
250L, 550L, 800L, 150L, 425L, 366L, 200L, 130L, 500L, 50L, 232L,
110L), Prix = c(390L, 468L, 427L, 369L, 499L, 526L, 587L, 534L,
447L, 482L, 511L, 532L, 450L, 569L, 419L, 421L, 579L, 598L, 495L,
730L, 646L, 652L, 802L, 761L, 1101L, 434L, 489L, 436L, 399L,
477L, 375L, 486L, 447L, 473L, 495L, 617L, 489L, 520L, 534L)), .Names = c("Pays",
"NbChambre", "Prix"), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",
"14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24",
"25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35",
"36", "37", "38", "39"))


问:
Python Pandas: How to split a column on parenthesis from a column of dataframe?
I have a pandas data frame:

```<code>In [8]: test
 Out[8]:
           Product           Price
0      Berlin Stret (E10)     12
1      Paris Ave (C12)        34
2      5th Ave (D30)          56
</code>```

I am trying to split the column product in 2 columns such as

```<code>       Product      Room  Price
 0   Berlin Stret    E10   12
 1   Paris Ave       C12   34
 2   5th Ave         D30   56
</code>```

I tried to use

```<code>df['Product'], df['Room'] = df['Product'].str.split('()', 1).str
</code>```

答:
You can use regex with extract:

```<code>df[['product','room']]= df.Product.str.extract('(.)\s\((.\d+)', expand=True)
</code>```

Output (lower case product new column):

```<code>   Product  Price product room
0  A (E10)     12       A  E10
1  B (C12)     34       B  C12
2  C (D30)     56       C  D30
</code>```

Or use regex '|' with split:

```<code>df[['product','room']] = df.Product.str.split('\(|\)', expand=True).iloc[:,[0,1]]
</code>```

Output:

```<code>   Product  Price product room
0  A (E10)     12      A   E10
1  B (C12)     34      B   C12
2  C (D30)     56      C   D30
</code>```

Body:
I have a pandas data frame:

In [8]: test
 Out[8]:
           Product           Price
0      Berlin Stret (E10)     12
1      Paris Ave (C12)        34
2      5th Ave (D30)          56

I am trying to split the column product in 2 columns such as

       Product      Room  Price
 0   Berlin Stret    E10   12
 1   Paris Ave       C12   34
 2   5th Ave         D30   56

I tried to use

df['Product'], df['Room'] = df['Product'].str.split('()', 1).str

Body:
You can use regex with extract:

df[['product','room']]= df.Product.str.extract('(.)\s\((.\d+)', expand=True)

Output (lower case product new column):

   Product  Price product room
0  A (E10)     12       A  E10
1  B (C12)     34       B  C12
2  C (D30)     56       C  D30

Or use regex '|' with split:

df[['product','room']] = df.Product.str.split('\(|\)', expand=True).iloc[:,[0,1]]

Output:

   Product  Price product room
0  A (E10)     12      A   E10
1  B (C12)     34      B   C12
2  C (D30)     56      C   D30


问:
Advantages and disadvantages of floating point and fixed point representations
I have been trying for the last three days to understand the exact differences between floating and fixed point representations. I am confused reading the material and I'm unable to decide what is right and what is wrong.

One of the problems is with the meaning of few technical terms like 'precision', 'mantissa', 'denormalised', 'underflows' etcetera.

Can anyone give the differences with examples?

The points I have been able to find out until now (and able to understand clearly) are as follows :-

Floating point -

1. Advantage  Provides a very large range

2. Disadvantage Rounds off large numbers

Fixed point -

1. Advantage Numbers are represented exactly  (Used when 'money' is involved)

2. Disadvantage Provide a very limited range

But I know there are a lot more differences (Advantages and disadvantages mainly). Can anyone list them out with explanations?

答:
Fixed point is a representation of floating point number in integer format. So operations can be applied on the number just like on integers.
The advantage of using this is that floating point arithmetic is costlier (processing power). Newer processors have dedicated FPUs (floating point units) for handling that.

So fixed point arithmetic is when processing power is limited, and a little precision loss doesn't cause a havoc.


问:
PYTHON: Trouble Understanding this Fibonacci Code
I understand how Fibonacci works, its just this code is driving me crazy. I might be going through it wrong </p>

```<code>def fib1(n):
  if n == 1 or n == 2:
    return 1
  return fib1(n-1) + fib1(n-2)

for i in range(1,10):
  print(fib1(i))

output = 1 1 2 3 5 8 13 21 34
</code>```

<p>Okay, so starting with 1 it returns 1 then 2 returns 1 too, But then 3 gets sent to fib1(n-1) + (n-2) and it returns 2?, isnt (3-1)+(3-2) == 3? I might be formatting it wrong but please explain how it happens </p>

答:
So it's not like returning (3-1)+(3-2), it's making a recursive call, calling itself, by doing fib1(3-1) + fib1(3-2), which breaks down to be fib1(2) + fib1(1)  which returns 1+1

We can work it out by walking through fib1(4):

fibl1(4) --> fibl(4-1) + fibl(4-2)

fib1(4) -- > fibl(3) + fibl1(2)

fibl(4) -- > (fibl(3-1) + fibl(3-2)) + 1 (2 is a base case so it returns 1)

fibl(4) -- > (fibl(2) + fibl(1) ) + 1

fibl(4) -- > (1 + 1) + 1

fibl(4) -- > 3

Body:
I understand how Fibonacci works, its just this code is driving me crazy. I might be going through it wrong

def fib1(n):
  if n == 1 or n == 2:
    return 1
  return fib1(n-1) + fib1(n-2)

for i in range(1,10):
  print(fib1(i))

output = 1 1 2 3 5 8 13 21 34

Okay, so starting with 1 it returns 1 then 2 returns 1 too, But then 3 gets sent to fib1(n-1) + (n-2) and it returns 2?, isnt (3-1)+(3-2) == 3? I might be formatting it wrong but please explain how it happens


问:
awk : extracting a data which is on several lines
so I have a file that looks like this :

```<code>/translation="MDGVTQQNAALVQEATTAAASLEEQARNLTAAVAAFDLGDKQTV
                 LITPRAAVPALKRPALKASLPASSSHGNWETF"
                 /product="Methyl-accepting chemotaxis protein I (serine
                 chemoreceptor protein)"
 CDS             complement(471..590)
                 /db_xref="SEED:fig|1240086.14.peg.2"
                 /translation="MHQYQSAILAKICRYGGIEKPEITPASVYKLDSHWRYVI"
                 /product="hypothetical protein"
 CDS             717..2354
                 /db_xref="SEED:fig|1240086.14.peg.3"
                 /translation="MGFFVVLWGGASGFSLYSLKQVTTLLHDNSTQGRTYTYLVYGND
                 QYFRSVTRMARVMDYSQFSDAAIASLEEQAQQLTKAVEVFHLGSEYQTAAS
                 RTRPAGNMALKRPALSGMAPALPPARTASDEGSWEKF"
                 /product="Methyl-accepting chemotaxis protein I (serine
                 chemoreceptor protein)"
                 /product="macromolecule metabolism; macromolecule
                 degradation; degradation of proteins, peptides,
                 glycopeptides"
</code>```

I need to extract the text that is between quotes after a "/product=", so I need this :

```<code>Methyl-accepting chemotaxis protein I (serine chemoreceptor protein)
hypothetical protein
Methyl-accepting chemotaxis protein I (serine chemoreceptor protein)
macromolecule metabolism; macromolecule degradation; degradation of proteins, peptides, glycopeptides
</code>```

I have to use awk, so I wrote this :

```<code>awk '/\/product/ {split($0, a, "\""); printf a[2] "\n"}'
</code>```

but this only takes the info on the same line as "/product", and some times the info is on two or three lines.. I'm out of ideas as to how to get the entire info between the quotes, anyone can help?

答:
With GNU awk for multi-char RS and RT:</p>

```<code>$ gawk -v RS='/product="[^"]+"' -F'"' 'RT{$0=RT; gsub(/\s+/," "); print $2}' file
Methyl-accepting chemotaxis protein I (serine chemoreceptor protein)
hypothetical protein
Methyl-accepting chemotaxis protein I (serine chemoreceptor protein)
macromolecule metabolism; macromolecule degradation; degradation of proteins, peptides, glycopeptides
</code>```

Body:
so I have a file that looks like this :

/translation="MDGVTQQNAALVQEATTAAASLEEQARNLTAAVAAFDLGDKQTV
                 LITPRAAVPALKRPALKASLPASSSHGNWETF"
                 /product="Methyl-accepting chemotaxis protein I (serine
                 chemoreceptor protein)"
 CDS             complement(471..590)
                 /db_xref="SEED:fig|1240086.14.peg.2"
                 /translation="MHQYQSAILAKICRYGGIEKPEITPASVYKLDSHWRYVI"
                 /product="hypothetical protein"
 CDS             717..2354
                 /db_xref="SEED:fig|1240086.14.peg.3"
                 /translation="MGFFVVLWGGASGFSLYSLKQVTTLLHDNSTQGRTYTYLVYGND
                 QYFRSVTRMARVMDYSQFSDAAIASLEEQAQQLTKAVEVFHLGSEYQTAAS
                 RTRPAGNMALKRPALSGMAPALPPARTASDEGSWEKF"
                 /product="Methyl-accepting chemotaxis protein I (serine
                 chemoreceptor protein)"
                 /product="macromolecule metabolism; macromolecule
                 degradation; degradation of proteins, peptides,
                 glycopeptides"

I need to extract the text that is between quotes after a "/product=", so I need this :

Methyl-accepting chemotaxis protein I (serine chemoreceptor protein)
hypothetical protein
Methyl-accepting chemotaxis protein I (serine chemoreceptor protein)
macromolecule metabolism; macromolecule degradation; degradation of proteins, peptides, glycopeptides

I have to use awk, so I wrote this :

awk '/\/product/ {split($0, a, "\""); printf a[2] "\n"}'

but this only takes the info on the same line as "/product", and some times the info is on two or three lines.. I'm out of ideas as to how to get the entire info between the quotes, anyone can help?

Body:
With GNU awk for multi-char RS and RT:

$ gawk -v RS='/product="[^"]+"' -F'"' 'RT{$0=RT; gsub(/\s+/," "); print $2}' file
Methyl-accepting chemotaxis protein I (serine chemoreceptor protein)
hypothetical protein
Methyl-accepting chemotaxis protein I (serine chemoreceptor protein)
macromolecule metabolism; macromolecule degradation; degradation of proteins, peptides, glycopeptides


问:
populate drop down list with month/year
I have a date and I need to populate a drop-down with the months/years between that date and today. For instance, if that date is 10/14/2010 then the drop-down should contain October 2010, November 2010, December 2010, January 2011.

The way I'm thinking of doing this is to pass that date to a function, loop from today backwards step 1 month while adding each month to a collection until we reach that date and finally return a collection of strings. Then, populate the drop-down control on page load. Finally, use some ajax with a page method to parse back the string and trigger a partial page reload.

I'm just wondering if there's an easy way to do it.

Thanks.

答:
You can do something like this which is pretty much what you described except counting forward:</p>

```<code>private string[] FillDropDownWithDates(DateTime dt)
{
        DateTime dtnow = DateTime.Now;

        List<string> values =  new List<string>();

        if ( (dt <= dtnow))
        {
            values.Add(String.Format("{0:y}", dt));
        }
        while ( (dt = dt.AddMonths(1)) <= dtnow || ( dt.Month == dtnow.Month && dt.Year == dtnow.Year) )
        {
            values.Add(String.Format("{0:y}", dt));  // "March, 2008"                     YearMonth
        }

        return values.ToArray();

    }
</code>```

Title: populate drop down list with month/year

Body:
You can do something like this which is pretty much what you described except counting forward:

private string[] FillDropDownWithDates(DateTime dt)
{
        DateTime dtnow = DateTime.Now;

        List<string> values =  new List<string>();

        if ( (dt <= dtnow))
        {
            values.Add(String.Format("{0:y}", dt));
        }
        while ( (dt = dt.AddMonths(1)) <= dtnow || ( dt.Month == dtnow.Month && dt.Year == dtnow.Year) )
        {
            values.Add(String.Format("{0:y}", dt));  // "March, 2008"                     YearMonth
        }

        return values.ToArray();

    }


问:
Communication between an asynchronous model process and a controller on iOS
I'm new to MVC programming and I understand that if I want my controller to talk to my model I just have to create a var in my controller and use it.

What happens when I have a process going on in my model and I want to let my controller know it is done, how can I use my completion handler in that type of communication?

答:
You can use completion handler, as you created model as global variable

```<code>var yourModel = YourModel()
</code>```

call method in your model with completion handler.

method in your model like

```<code>// Method
func saveData(completion: @escaping(_ status: String) -> Void) {
   // Do your business logic here ......
   //...
   // end of business logic and call completion
   completion("Successfully saved")
}
</code>```

in your ViewController call the model method

```<code>yourModel.save(completion: {(status) in
 // user status here....
 print(status) // Successfully saved
})
</code>```

Body:
You can use completion handler, as you created model as global variable

var yourModel = YourModel()

call method in your model with completion handler.

method in your model like

// Method
func saveData(completion: @escaping(_ status: String) -> Void) {
   // Do your business logic here ......
   //...
   // end of business logic and call completion
   completion("Successfully saved")
}

in your ViewController call the model method

yourModel.save(completion: {(status) in
 // user status here....
 print(status) // Successfully saved
})


问:
PHP fopen does not working with directory variable
I have a php code that it creates a random name, then creates the directory, and then I need to create and write a text file inside the directory.
It creates the directory, but nothing when it need to create the text file.
This is what I have:

This create the random name

```<code>$letra1 = chr(rand(65,90));
$letra2 = chr(rand(97,122));
$letra3 = chr(rand(65,90));
$letra4 = chr(rand(97,122));
</code>```

This join all the characters:

```<code>$letras = $letra1 . $letra2 . $letra3 . $letra4;
</code>```

This creates de directory:

```<code>mkdir("a/$letras", 777);
</code>```

And here, where i think I have the problem, the fopen:

```<code>$archt = fopen("a/$letras/text.txt", "w") or die("");
$txt = "";
fclose($archt);
</code>```

I think it isn't a perms problem, I have given 777 to all directories...

I have tried a lot of stuf that I have been searched from stackoverflow but nothing is working for me and don't know what it will be?

答:
Since the "$letras" hides the variable

```<code>$dirLocation = "a/" . $letras;

mkdir($dirLocation, 0777);

$fileLocation = $dirLocation . "/text.txt";

$archt = fopen($fileLocation, "w") or die("");

$txt = "";

fclose($archt);
</code>```

Body:
I have a php code that it creates a random name, then creates the directory, and then I need to create and write a text file inside the directory.
It creates the directory, but nothing when it need to create the text file.
This is what I have:

This create the random name

$letra1 = chr(rand(65,90));
$letra2 = chr(rand(97,122));
$letra3 = chr(rand(65,90));
$letra4 = chr(rand(97,122));

This join all the characters:

$letras = $letra1 . $letra2 . $letra3 . $letra4;

This creates de directory:

mkdir("a/$letras", 777);

And here, where i think I have the problem, the fopen:

$archt = fopen("a/$letras/text.txt", "w") or die("");
$txt = "";
fclose($archt);

I think it isn't a perms problem, I have given 777 to all directories...

I have tried a lot of stuf that I have been searched from stackoverflow but nothing is working for me and don't know what it will be?

Body:
Since the "$letras" hides the variable

$dirLocation = "a/" . $letras;

mkdir($dirLocation, 0777);

$fileLocation = $dirLocation . "/text.txt";

$archt = fopen($fileLocation, "w") or die("");

$txt = "";

fclose($archt);


问:
Java Mosby Fragments
How can I access MvpFragment from MvpActivity.

Fragment, with current code -

```<code>class Fragment1: MvpFragment<IView, Presenter>(){
    override fun createPresenter(): Presenter {
        return Presenter(getActivity().getApplicationContext())
    }

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater!!.inflate(R.layout.activity_main, container, false)
    }
}
</code>```

Activity is-

```<code>class MainActivity : MvpActivity<IView, Presenter>(), IView {
    override fun createPresenter(): Presenter {
        return Presenter(getApplicationContext())
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    fun create_fragment(view: View){
        var frgmnt = getFragmentManager().beginTransaction()
        frgmnt.replace(R.id.containerZ, Fragment1())
    }
}
</code>```

答:
i think mosby uses support fragments so try this</p>

```<code>var frgmnt = getSupportFragmentManager().beginTransaction()
</code>```

Title: Java Mosby Fragments

Body:
How can I access MvpFragment from MvpActivity.

Fragment, with current code -

class Fragment1: MvpFragment<IView, Presenter>(){
    override fun createPresenter(): Presenter {
        return Presenter(getActivity().getApplicationContext())
    }

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater!!.inflate(R.layout.activity_main, container, false)
    }
}

Activity is-

class MainActivity : MvpActivity<IView, Presenter>(), IView {
    override fun createPresenter(): Presenter {
        return Presenter(getApplicationContext())
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    fun create_fragment(view: View){
        var frgmnt = getFragmentManager().beginTransaction()
        frgmnt.replace(R.id.containerZ, Fragment1())
    }
}

Body:
i think mosby uses support fragments so try this

var frgmnt = getSupportFragmentManager().beginTransaction()