问:
Question on a Maximum value/profit subarray problem in Java
Here is the array...

```<code>int[] array = new int[]{4,-1,-2,3,5,-7,1,0,0,-2,4};
</code>```

We need to see if we can buy the stock, from the day prior. So, we should be buying at -1 and selling at 5. This will give a profit of 6.

```<code>    int max = Integer.MIN_VALUE;
    int maxDiff = Integer.MIN_VALUE;
    int diff = 0;
    int bottom = array[0];

    for (int i = 1; i < array.length; i++) {
        diff += array[i] - array[i - 1];

        System.out.println(diff);
        if (diff > maxDiff) {
            maxDiff = diff;
            max = array[i];
        }

        if (array[i] < bottom) {
            bottom = array[i];
            diff = 0;
        }
    }

    int maxx = max - maxDiff;
    System.out.println("Buy at " + maxx + " Sell at " + max);
</code>```

This is saying I should buy at -7 and sell at 4. This would not be true.
If we buy at -7, the price would go up by 1, then stay the same, stay the same, go down by two, then up by 4. This does not earn us the most profit.

What am I doing wrong?

答:
Since the array contains price movements then assume a starting price and calculate min/max from that</p>

```<code>int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int price = 100;
int dayIn = 0;
int dayOut = 0;

for (int i = 0; i < array.length; i++) {
    price += array[i];
    if (price > max) {
        max = price;
        dayOut = i;
    }
    if (price < min) {
        min = price;
        dayIn = i;
    }
}
if (max > min && dayIn < dayOut) {
    System.out.printf("Buy for %d at day %d and sell on day %d for %d. Profit: %d\n", min, (dayIn + 1), (dayOut+1), max, max - min);
} else {
    System.out.println("No trade opportunity found");
}
</code>```

Body:
Here is the array...

int[] array = new int[]{4,-1,-2,3,5,-7,1,0,0,-2,4};

We need to see if we can buy the stock, from the day prior. So, we should be buying at -1 and selling at 5. This will give a profit of 6.

    int max = Integer.MIN_VALUE;
    int maxDiff = Integer.MIN_VALUE;
    int diff = 0;
    int bottom = array[0];

    for (int i = 1; i < array.length; i++) {
        diff += array[i] - array[i - 1];

        System.out.println(diff);
        if (diff > maxDiff) {
            maxDiff = diff;
            max = array[i];
        }

        if (array[i] < bottom) {
            bottom = array[i];
            diff = 0;
        }
    }

    int maxx = max - maxDiff;
    System.out.println("Buy at " + maxx + " Sell at " + max);

This is saying I should buy at -7 and sell at 4. This would not be true.
If we buy at -7, the price would go up by 1, then stay the same, stay the same, go down by two, then up by 4. This does not earn us the most profit.

What am I doing wrong?

Body:
Since the array contains price movements then assume a starting price and calculate min/max from that

int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int price = 100;
int dayIn = 0;
int dayOut = 0;

for (int i = 0; i < array.length; i++) {
    price += array[i];
    if (price > max) {
        max = price;
        dayOut = i;
    }
    if (price < min) {
        min = price;
        dayIn = i;
    }
}
if (max > min && dayIn < dayOut) {
    System.out.printf("Buy for %d at day %d and sell on day %d for %d. Profit: %d\n", min, (dayIn + 1), (dayOut+1), max, max - min);
} else {
    System.out.println("No trade opportunity found");
}


来源: stackexchange

问:
How to have source as rectangle for dragg
i have a requirement to have rectangle shape of fixed size and must be draggable to container, so that i can connect them.

i have searched alot but did not find any solution.

Question: single rectangle shape(fixed size) should be dragged to container

For full view Code pen:https://codepen.io/eabangalore/pen/LvzXxX

here is how:

Code Demo:

 <title>Hello, World! example for mxGraph</title>

```

Please help me thanks in advance!!!!!

答:
```<code>function addToolbarItem(graph, toolbar, prototype, image)
     {
        // Function that is executed when the image is dropped on
        // the graph. The cell argument points to the cell under
        // the mousepointer if there is one.
        var funct = function(graph, evt, cell)
        {
            graph.stopEditing(false);
            var pt = graph.getPointForEvent(evt);
            var vertex = graph.getModel().cloneCell(prototype);
            vertex.geometry.x = pt.x;
            vertex.geometry.y = pt.y;

            graph.setSelectionCells(graph.importCells([vertex], 0, 0, cell));
        }
        // Creates the image which is used as the drag icon (preview)
        var img = toolbar.addMode(null, image, funct);
        mxUtils.makeDraggable(img, graph, funct);
    }
</code>```

try this example

ContentLicense: CC BY-SA 4.0

Body:
i have a requirement to have rectangle shape of fixed size and must be draggable to container, so that i can connect them.

i have searched alot but did not find any solution.

Question: single rectangle shape(fixed size) should be dragged to container

For full view Code pen:https://codepen.io/eabangalore/pen/LvzXxX

here is how:

Code Demo:

 <title>Hello, World! example for mxGraph</title>

Please help me thanks in advance!!!!!

Body:
function addToolbarItem(graph, toolbar, prototype, image)
     {
        // Function that is executed when the image is dropped on
        // the graph. The cell argument points to the cell under
        // the mousepointer if there is one.
        var funct = function(graph, evt, cell)
        {
            graph.stopEditing(false);
            var pt = graph.getPointForEvent(evt);
            var vertex = graph.getModel().cloneCell(prototype);
            vertex.geometry.x = pt.x;
            vertex.geometry.y = pt.y;

            graph.setSelectionCells(graph.importCells([vertex], 0, 0, cell));
        }
        // Creates the image which is used as the drag icon (preview)
        var img = toolbar.addMode(null, image, funct);
        mxUtils.makeDraggable(img, graph, funct);
    }

try this example


问:
Create new variable with other variables on base of another variable
I have 4 date variables and 1 grouping variable. Based on the value in the grouping variable a date needs to be taken into a new variable.
My data looks like this: (https://www.dropbox.com/s/wlfv89qc1jzwfgk/vb.JPG)

I want to make a new variable based on the value of group. When group is A I need date1, when group is B I need date2, etc.

This is the code I've used:

```<code>if (tabel$group == A) {
  newvar <- tabel$date1
} else if (tabel$group == B) {
  newvar <- tabel$date2
} else if (tabel$group == C) {
  newvar <- tabel$date3
} else if (tabel$group == D) {
  newvar <- tabel$date4
}
</code>```

This code give me a warning message:

 (In if (tabel$group == 1) { :
  the condition has length > 1 and only the first element will be used

答:
You need to perform this row-wise...one option is to use nested ifelse()

```<code>newvar=ifelse(tabel$group=='A',tabel$date1,
              ifelse(tabel$group=='B',tabel$date2,
                     ifelse(tabel$group=='C',tabel$date3,tabel$date4))))
</code>```

Body:
I have 4 date variables and 1 grouping variable. Based on the value in the grouping variable a date needs to be taken into a new variable.
My data looks like this: (https://www.dropbox.com/s/wlfv89qc1jzwfgk/vb.JPG)

I want to make a new variable based on the value of group. When group is A I need date1, when group is B I need date2, etc.

This is the code I've used:

if (tabel$group == A) {
  newvar <- tabel$date1
} else if (tabel$group == B) {
  newvar <- tabel$date2
} else if (tabel$group == C) {
  newvar <- tabel$date3
} else if (tabel$group == D) {
  newvar <- tabel$date4
}

This code give me a warning message:

 (In if (tabel$group == 1) { :
  the condition has length > 1 and only the first element will be used

Body:
You need to perform this row-wise...one option is to use nested ifelse()

newvar=ifelse(tabel$group=='A',tabel$date1,
              ifelse(tabel$group=='B',tabel$date2,
                     ifelse(tabel$group=='C',tabel$date3,tabel$date4))))


问:
Subtracting months in Java
I am using two string variables to store two different dates. The dates are being stored in this format(May 28, 2019) and I need to find a difference in months.I am not able to figure if I need to first convert these dates to another format before doing the subtraction.

I am using getText() to get these dates from the following location
//span[@class='expiry_date']

答:
Coming to the point you gave
     To figure out if you need to first convert these dates to another format before doing the subtraction.
 Best approach you should take is that first convert dates to Java 8 LocalDate and then find the difference

Here is the sample code may be it can help you despite you have not shown your code effort.

```<code>    DateTimeFormatter customFormatter= DateTimeFormatter.ofPattern( "MMMM dd, yyyy",Locale.US);

    LocalDate date1 = LocalDate.parse( "April 01, 2019", customFormatter );
    LocalDate date2 = LocalDate.parse( "October 01, 2019", customFormatter );

    Period dateDifference = Period.between(date1, date2);
    System.out.println(dateDifference.toTotalMonths());
</code>```

Title: Subtracting months in Java

Body:
Coming to the point you gave
     To figure out if you need to first convert these dates to another format before doing the subtraction.
 Best approach you should take is that first convert dates to Java 8 LocalDate and then find the difference

Here is the sample code may be it can help you despite you have not shown your code effort.

    DateTimeFormatter customFormatter= DateTimeFormatter.ofPattern( "MMMM dd, yyyy",Locale.US);

    LocalDate date1 = LocalDate.parse( "April 01, 2019", customFormatter );
    LocalDate date2 = LocalDate.parse( "October 01, 2019", customFormatter );

    Period dateDifference = Period.between(date1, date2);
    System.out.println(dateDifference.toTotalMonths());


问:
Nodejs: how to check if spawn is successfull?
I am spawing a command from my express script, but I need to distinguish between error and success. I was looking for a child.on('success'...) function, but it doesn't exist.

This piece of code (of course) doesn't work.

```<code>app.get(myID+'/test/', function(req, res){
        var child = spawn('lbg');
        child.on('error', function(err) {
                console.log('Failed to start child process.');
                res.status(404).send("Cannot send test command");
                return;
        });
        res.json({statusMessage: "OK", statusCode: "200"});

 });
</code>```

In other words, I need to fire the correct response only, not both!

答:
app.get(myID+'/test/', function(req, res){
        var child = spawn('lbg');
        child.on('error', err => {
          if (err) {
             res.status(404).send("Cannot send test command");
          } else {
             res.status(200).send("Ok");
          }
        });
});```

Body:
I am spawing a command from my express script, but I need to distinguish between error and success. I was looking for a child.on('success'...) function, but it doesn't exist.

This piece of code (of course) doesn't work.

app.get(myID+'/test/', function(req, res){
        var child = spawn('lbg');
        child.on('error', function(err) {
                console.log('Failed to start child process.');
                res.status(404).send("Cannot send test command");
                return;
        });
        res.json({statusMessage: "OK", statusCode: "200"});

 });

In other words, I need to fire the correct response only, not both!


问:
Can I run the same cucumber suite on multiple devices using one maven command?
I have a cucumber/appium framework for testing on mobile devices. Now that cucumber and appium support parallel runs, I have it set up to distribute features to each connected device (junit only splits features, not scenarios). I achieve this using a DriverFactory class. This class works great, but parallel runs in this situation are only really useful if it's the same driver each time (e.g. ChromeDriver). My devices are added to a pool during the junit @BeforeClass method and my DriverFactory uses them one by one until empty.

My issue though is that, although quick, I sometimes want to run the entire suite on each connected device (just because a test passes on one device, doesn't make mean it would pass on the other devices).

I'm thinking that a batch file with multiple maven commands might do it but is there a way I can do it all with the one command?

I use maven-failsafe as I don't want the run to stop for failed tests, my pom setup is below, which splits the features across the devices if there's 2 devices connected

I have a single cucumber runner class. I haven't looked at Jenkins. I was first hoping to see if I could do all this from my mac considering I already have it working on a per feature basis.

This is my relevant maven-failsafe code. I can update the threadCount for however many devices I have connected (looking into doing this dynamically). I tried using suites instead of methods but it then runs the entire suite on only one device

```<code>                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                        <configuration>
                            <includes>
                                <include>**/RunCucumberTest.java</include>
                            </includes>
                            <parallel>methods</parallel>
                            <threadCount>2</threadCount>
                            <perCoreThreadCount>false</perCoreThreadCount>
                        </configuration>
                    </execution>
                </executions>
</code>```

Any help would be appreciated. If there's anything you need to know, please let me know or if there's any of my code that would help, I can post it here

答:
Yes, you can. For doing so you would need to have N No of WebDriver implementation in proportion to the multiple platfroms below -

For iOS Platform -> IOSDriver

For Android Platfrom -> AndroidDriver

For Web Platfrom -> WebDriver

Additionally you would need to write Thread-Safe code that guarantees safe execution by multiple threads at the same time. Also, you shall avoid static variables & methods.

Body:
I have a cucumber/appium framework for testing on mobile devices. Now that cucumber and appium support parallel runs, I have it set up to distribute features to each connected device (junit only splits features, not scenarios). I achieve this using a DriverFactory class. This class works great, but parallel runs in this situation are only really useful if it's the same driver each time (e.g. ChromeDriver). My devices are added to a pool during the junit @BeforeClass method and my DriverFactory uses them one by one until empty.

My issue though is that, although quick, I sometimes want to run the entire suite on each connected device (just because a test passes on one device, doesn't make mean it would pass on the other devices).

I'm thinking that a batch file with multiple maven commands might do it but is there a way I can do it all with the one command?

I use maven-failsafe as I don't want the run to stop for failed tests, my pom setup is below, which splits the features across the devices if there's 2 devices connected

I have a single cucumber runner class. I haven't looked at Jenkins. I was first hoping to see if I could do all this from my mac considering I already have it working on a per feature basis.

This is my relevant maven-failsafe code. I can update the threadCount for however many devices I have connected (looking into doing this dynamically). I tried using suites instead of methods but it then runs the entire suite on only one device

                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                        <configuration>
                            <includes>
                                <include>**/RunCucumberTest.java</include>
                            </includes>
                            <parallel>methods</parallel>
                            <threadCount>2</threadCount>
                            <perCoreThreadCount>false</perCoreThreadCount>
                        </configuration>
                    </execution>
                </executions>

Any help would be appreciated. If there's anything you need to know, please let me know or if there's any of my code that would help, I can post it here


问:
Return stored procedure result from a second stored procedure?
This is a question about some stored procedures running on MSSQL 8 (I think that's SQL Server 2000).

I have two stored procedures left by my predecessor at the company.

The "Modify" window for the first procedure looks something like this:

```<code>ALTER PROCEDURE [dbo].[Proc1]
    @ID,
    @someBool

AS
BEGIN

SELECT colA, colB, colC
FROM   myTable
WHERE  colA = @ID AND colB = @someBool

END
</code>```

The second procedure is very similar, being something along the lines of:

```<code>ALTER PROCEDURE [dbo].[Proc2]
    @ID

AS
BEGIN

SELECT colA, colB
FROM   myTable
WHERE  colA = @ID AND colB = FALSE

END
</code>```

Obviously, the real procedures are more complicated than this and require a lot more maintenance when changes are made.

Rather than maintaining these two queries separately, which pretty much sucks, I was wondering if there was any way to simply have Proc2 do something along the lines of:

```<code>ALTER PROCEDURE [dbo].[Proc2]
    @ID

AS
BEGIN

EXEC Proc1(@ID, FALSE)
"drop colC"
"return modified result"

END
</code>```

Any ideas on the best way to go about this?

答:
The difficulty is that stored procedures are non-relational. Therefore, apart from participating in an Insert statement,  they can't be leveraged in other queries; or to borrow some Linq vernacular they are not "composable".

You way want to consider table valued functions (which I believe are available as early as SQL Server 2000))

ContentLicense: CC BY-SA 3.0

Body:
This is a question about some stored procedures running on MSSQL 8 (I think that's SQL Server 2000).

I have two stored procedures left by my predecessor at the company.

The "Modify" window for the first procedure looks something like this:

ALTER PROCEDURE [dbo].[Proc1]
    @ID,
    @someBool

AS
BEGIN

SELECT colA, colB, colC
FROM   myTable
WHERE  colA = @ID AND colB = @someBool

END

The second procedure is very similar, being something along the lines of:

ALTER PROCEDURE [dbo].[Proc2]
    @ID

AS
BEGIN

SELECT colA, colB
FROM   myTable
WHERE  colA = @ID AND colB = FALSE

END

Obviously, the real procedures are more complicated than this and require a lot more maintenance when changes are made.

Rather than maintaining these two queries separately, which pretty much sucks, I was wondering if there was any way to simply have Proc2 do something along the lines of:

ALTER PROCEDURE [dbo].[Proc2]
    @ID

AS
BEGIN

EXEC Proc1(@ID, FALSE)
"drop colC"
"return modified result"

END

Any ideas on the best way to go about this?


问:
is SQLiteDatabase syncronous or async?
I have an app that opens a new intent. The new intent inserts some rows on the datadabase, then finish(); it and come back to the first screen where the data should have refreshed with the new row. The code I have do not work on execution but works when debuging... so maybe there is some lag somewhere... maybe? how to wait for the query to finish?

Here is my code:

on the first screen:

setting the adapter and onResume

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    v= inflater.inflate(R.layout.filters_fragment,container,false);

    createFragmentWidgets();

    myrecyclerview = (RecyclerView) v.findViewById(R.id.contact_recycleview);
    recyclerAdapter = new RecyclerViewAdapterFilters(getContext(), lstFilters);
    myrecyclerview.setLayoutManager(new LinearLayoutManager((getActivity())));
    myrecyclerview.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
    myrecyclerview.setAdapter(recyclerAdapter);

    return v;
}

@Override
public void onResume()
{
// After a pause OR at startup
    super.onResume();

    lstFilters = mydb.getAllFilters("BL");
    recyclerAdapter.notifyDataSetChanged();
}
</code>```

the getAllFilters method on the DB class

```<code>public List<Filter> getAllFilters(String type) {
    List<Filter> lstFilter  = new ArrayList<>();

    //hp = new HashMap();
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res =  db.rawQuery( "select * from " + FILTERS_TABLE_NAME+" where type='"+type+"'", null );
    res.moveToFirst();

    while(res.isAfterLast() == false){
        lstFilter.add(new Filter (res.getInt(res.getColumnIndex(FILTERS_COLUMN_ID)),
                res.getString(res.getColumnIndex(FILTERS_COLUMN_NAME)),
                res.getString(res.getColumnIndex(FILTERS_COLUMN_NUMBER)),
                res.getString(res.getColumnIndex(FILTERS_COLUMN_PHOTO)),
                res.getString(res.getColumnIndex(FILTERS_COLUMN_TYPE))));
        res.moveToNext();
    }

    res.close();
    db.close();

    return lstFilter;
}
</code>```

any ideas?

答: since you're replacing the contents of the list, call adapter.notifyDataSetChanged() to refresh the entire list.

Title: is SQLiteDatabase syncronous or async?

Body:
I have an app that opens a new intent. The new intent inserts some rows on the datadabase, then finish(); it and come back to the first screen where the data should have refreshed with the new row. The code I have do not work on execution but works when debuging... so maybe there is some lag somewhere... maybe? how to wait for the query to finish?

Here is my code:

on the first screen:

setting the adapter and onResume

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    v= inflater.inflate(R.layout.filters_fragment,container,false);

    createFragmentWidgets();

    myrecyclerview = (RecyclerView) v.findViewById(R.id.contact_recycleview);
    recyclerAdapter = new RecyclerViewAdapterFilters(getContext(), lstFilters);
    myrecyclerview.setLayoutManager(new LinearLayoutManager((getActivity())));
    myrecyclerview.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
    myrecyclerview.setAdapter(recyclerAdapter);

    return v;
}

@Override
public void onResume()
{
// After a pause OR at startup
    super.onResume();

    lstFilters = mydb.getAllFilters("BL");
    recyclerAdapter.notifyDataSetChanged();
}

the getAllFilters method on the DB class

public List<Filter> getAllFilters(String type) {
    List<Filter> lstFilter  = new ArrayList<>();

    //hp = new HashMap();
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res =  db.rawQuery( "select * from " + FILTERS_TABLE_NAME+" where type='"+type+"'", null );
    res.moveToFirst();

    while(res.isAfterLast() == false){
        lstFilter.add(new Filter (res.getInt(res.getColumnIndex(FILTERS_COLUMN_ID)),
                res.getString(res.getColumnIndex(FILTERS_COLUMN_NAME)),
                res.getString(res.getColumnIndex(FILTERS_COLUMN_NUMBER)),
                res.getString(res.getColumnIndex(FILTERS_COLUMN_PHOTO)),
                res.getString(res.getColumnIndex(FILTERS_COLUMN_TYPE))));
        res.moveToNext();
    }

    res.close();
    db.close();

    return lstFilter;
}

any ideas?


问:
How can I get images from "assets/resource/mat "?
I have some images in "assets/resource/mat" . I want to get this images and put them to array . But when I try to get this images I'm getting ArrayIndexOutOfBoundsException . I think that there is problem with Resource.LoadAll("mat") method . But I can't fix it . Please help me</p>

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class test : MonoBehaviour
{
    private string t;
    public Sprite[] Icons;

    void Start()
    {
        Object[] loadedIcons = Resources.LoadAll("mat");
        Icons = new Sprite[loadedIcons.Length];

        for (int x = 0; x < loadedIcons.Length; x++)
        {
            Icons[x] = (Sprite)loadedIcons[x];
            Debug.Log("Loading....");
        }

         GameObject sp = new GameObject();
         sp.GetComponent<SpriteRenderer>().sprite = Icons[0];
    }
}
</code>```

答:
I'm not sure but I guess you instead of Sprite first have to load a Texture2D and then create a Sprite from it.

Also note you used GetComponent<SpriteRenderer>() on a newly created empty GameObject so obviously there will never be a SpriteRenderer component attached. Instead use AddComponent.

```<code>Sprite[] Icons;
Texture2D LoadedTextures;

private void Start()
{
    LoadedTextures = (Texture2D[])Resources.LoadAll("mat", typeof(Texture2D));
    Icons = new Sprite[loadedIcons.Length];

    for (int x = 0; x < loadedIcons.Length; x++)
    {
        Icons[x] = Sprite.Create(
            LoadedTextures[x],
            new Rect(0.0f, 0.0f, LoadedTextures[x].width, LoadedTextures[x].height),
            new Vector2(0.5f, 0.5f),
            100.0f);
    }

     GameObject sp = new GameObject();

     // Note that here you created a new empty GameObject
     // so it obviously won't have any component of type SpriteRenderer
     // so add it instead of GetComponent
     sp.AddComponent<SpriteRenderer>().sprite = Icons[0];
}
</code>```

Body:
I have some images in "assets/resource/mat" . I want to get this images and put them to array . But when I try to get this images I'm getting ArrayIndexOutOfBoundsException . I think that there is problem with Resource.LoadAll("mat") method . But I can't fix it . Please help me

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class test : MonoBehaviour
{
    private string t;
    public Sprite[] Icons;

    void Start()
    {
        Object[] loadedIcons = Resources.LoadAll("mat");
        Icons = new Sprite[loadedIcons.Length];

        for (int x = 0; x < loadedIcons.Length; x++)
        {
            Icons[x] = (Sprite)loadedIcons[x];
            Debug.Log("Loading....");
        }

         GameObject sp = new GameObject();
         sp.GetComponent<SpriteRenderer>().sprite = Icons[0];
    }
}

Body:
I'm not sure but I guess you instead of Sprite first have to load a Texture2D and then create a Sprite from it.

Also note you used GetComponent<SpriteRenderer>() on a newly created empty GameObject so obviously there will never be a SpriteRenderer component attached. Instead use AddComponent.

Sprite[] Icons;
Texture2D LoadedTextures;

private void Start()
{
    LoadedTextures = (Texture2D[])Resources.LoadAll("mat", typeof(Texture2D));
    Icons = new Sprite[loadedIcons.Length];

    for (int x = 0; x < loadedIcons.Length; x++)
    {
        Icons[x] = Sprite.Create(
            LoadedTextures[x],
            new Rect(0.0f, 0.0f, LoadedTextures[x].width, LoadedTextures[x].height),
            new Vector2(0.5f, 0.5f),
            100.0f);
    }

     GameObject sp = new GameObject();

     // Note that here you created a new empty GameObject
     // so it obviously won't have any component of type SpriteRenderer
     // so add it instead of GetComponent
     sp.AddComponent<SpriteRenderer>().sprite = Icons[0];
}


问:
Cannot catch orientation changes from "upsidedown" to landscapes on iOS
I need to invalidate my collection view layout when screen orientation changes. Since iPhone X and others have safe area insets; I need my cells' subviews positioned according to screen safe area insets.

If you switch between left-right landscapes from portrait there is no problem. But if you switch from upsidedown I cannot catch the orientation change and automatically cannot

I tried two existing approaches.

First is using NotificationCenter. Second is overriding viewWillTransitionToSize:withTransitionCoordinator: function. It's all the same.

in CollectionViewController:

    NotificationCenter.default.addObserver(forName: UIDevice.orientationDidChangeNotification, object: nil, queue: nil) { (notif) in
      self.collectionViewLayout.invalidateLayout()
    }
```

<p>in Cell:</p>

<pre class="lang-swift prettyprint-override"><code>  override func layoutSubviews() {
    super.layoutSubviews()

    let orientation = UIDevice.current.orientation
    if let insets = UIApplication.shared.keyWindow?.safeAreaInsets {
      if orientation == .landscapeLeft {
        titleLabelLeadingConstraint.constant = insets.left + 20
        titleLabelTrailingConstraint.constant = 20
      } else if orientation == .landscapeRight {
        titleLabelLeadingConstraint.constant = 20
        titleLabelTrailingConstraint.constant = insets.right + 20
      } else {
        titleLabelLeadingConstraint.constant = 20
        titleLabelTrailingConstraint.constant = 20
      }
    }

    print("orin: \(orientation.rawValue) | left: \(titleLabelLeadingConstraint.constant) | right: \(titleLabelTrailingConstraint.constant)")

  }

</code>```

The print() function not being called when you switch from/to upsidedown. But collectionviewlayouts invalidateLayout() function is being called.

答:
As you've already tried, you can detect orientation change using viewWillTransitionToSize:withTransitionCoordinator:.

I don't know your first attempt, however, try this:

```<code>      override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
         //If you need to invalidate your collectionView layout, do it in this function
         super.viewWillTransition(to: size, with: coordinator)
         if UIDevice.current.orientation.isLandscape {
          //
         } else {
           //
         }
      }
</code>```

If you need to know the difference between landscapeLeft or Right, try your code in this way:

```<code>      override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
         //If you need to invalidate your collectionView layout, do it in this function
    super.viewWillTransition(to: size, with: coordinator)

     if let insets = UIApplication.shared.keyWindow?.safeAreaInsets {
        if UIDevice.current.orientation == .landscapeLeft {

        titleLabelLeadingConstraint.constant = insets.left + 20
        titleLabelTrailingConstraint.constant = 20

      } else if UIDevice.current.orientation == .landscapeRight {

        titleLabelLeadingConstraint.constant = 20
        titleLabelTrailingConstraint.constant = insets.right + 20

      } else {

        titleLabelLeadingConstraint.constant = 20
        titleLabelTrailingConstraint.constant = 20

      }
    }
  }
</code>```

NOTE: You don't need to register an observer

Body:
I need to invalidate my collection view layout when screen orientation changes. Since iPhone X and others have safe area insets; I need my cells' subviews positioned according to screen safe area insets.

If you switch between left-right landscapes from portrait there is no problem. But if you switch from upsidedown I cannot catch the orientation change and automatically cannot

I tried two existing approaches.

First is using NotificationCenter. Second is overriding viewWillTransitionToSize:withTransitionCoordinator: function. It's all the same.

in CollectionViewController:

    NotificationCenter.default.addObserver(forName: UIDevice.orientationDidChangeNotification, object: nil, queue: nil) { (notif) in
      self.collectionViewLayout.invalidateLayout()
    }

in Cell:

  override func layoutSubviews() {
    super.layoutSubviews()

    let orientation = UIDevice.current.orientation
    if let insets = UIApplication.shared.keyWindow?.safeAreaInsets {
      if orientation == .landscapeLeft {
        titleLabelLeadingConstraint.constant = insets.left + 20
        titleLabelTrailingConstraint.constant = 20
      } else if orientation == .landscapeRight {
        titleLabelLeadingConstraint.constant = 20
        titleLabelTrailingConstraint.constant = insets.right + 20
      } else {
        titleLabelLeadingConstraint.constant = 20
        titleLabelTrailingConstraint.constant = 20
      }
    }

    print("orin: \(orientation.rawValue) | left: \(titleLabelLeadingConstraint.constant) | right: \(titleLabelTrailingConstraint.constant)")

  }

The print() function not being called when you switch from/to upsidedown. But collectionviewlayouts invalidateLayout() function is being called.

Body:
As you've already tried, you can detect orientation change using viewWillTransitionToSize:withTransitionCoordinator:.

I don't know your first attempt, however, try this:

      override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
         //If you need to invalidate your collectionView layout, do it in this function
         super.viewWillTransition(to: size, with: coordinator)
         if UIDevice.current.orientation.isLandscape {
          //
         } else {
           //
         }
      }

If you need to know the difference between landscapeLeft or Right, try your code in this way:

      override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
         //If you need to invalidate your collectionView layout, do it in this function
    super.viewWillTransition(to: size, with: coordinator)

     if let insets = UIApplication.shared.keyWindow?.safeAreaInsets {
        if UIDevice.current.orientation == .landscapeLeft {

        titleLabelLeadingConstraint.constant = insets.left + 20
        titleLabelTrailingConstraint.constant = 20

      } else if UIDevice.current.orientation == .landscapeRight {

        titleLabelLeadingConstraint.constant = 20
        titleLabelTrailingConstraint.constant = insets.right + 20

      } else {

        titleLabelLeadingConstraint.constant = 20
        titleLabelTrailingConstraint.constant = 20

      }
    }
  }

NOTE: You don't need to register an observer


问:
Separating multiple `let` declarations followed by a single `let in`expression in OCaml
This question elaborates on OCaml syntax trap: multiple lets using separators.

In terms of programming imperative OCaml, how does one have multiple let statements that runs before a single let ... in without changing all declarations into expressions?

For example,

```<code>let f x = x + 1
let g x = x + 2
let h x = x + 3
</code>```

compiles with no problem, but

```<code>let f x = x + 1
let g x = x + 2
let h x = x + 3 in (Printf.printf "%d \n" (f (h (g 3))) ; ())
</code>```

doesn't work, because the first two are declarations whereas the last one is an expression. The same observation applies to variables. One way to correct this error is to nest change the first two lets into expressions and nest the let...in. However, this seems quite tedious and awkward:

```<code>let f x = x + 1 in
  let g x = x + 2 in
    let h x = x + 3 in (Printf.printf "%d \n" (f (h (g 3))) ; ())
</code>```

Alternatively, one could envision a long OCaml source code file starting with multiple let declarations of global variables, and a single let...in expression in the middle. In that case, it seems like a ;; is necessary to terminate the declarations on top so that the let... in works, but using the ;; is advised against by the documentation.

Is there another way to write this (more elegantly)?

答:
I don't know if it's more elegant, but

```<code>let f x = x + 1
let g x = x + 2
let _ = let h x = x + 3 in Printf.printf "%d \n" (f (h (g 3)))
</code>```

compiles and runs.

Body:
This question elaborates on OCaml syntax trap: multiple lets using separators.

In terms of programming imperative OCaml, how does one have multiple let statements that runs before a single let ... in without changing all declarations into expressions?

For example,

let f x = x + 1
let g x = x + 2
let h x = x + 3

compiles with no problem, but

let f x = x + 1
let g x = x + 2
let h x = x + 3 in (Printf.printf "%d \n" (f (h (g 3))) ; ())

doesn't work, because the first two are declarations whereas the last one is an expression. The same observation applies to variables. One way to correct this error is to nest change the first two lets into expressions and nest the let...in. However, this seems quite tedious and awkward:

let f x = x + 1 in
  let g x = x + 2 in
    let h x = x + 3 in (Printf.printf "%d \n" (f (h (g 3))) ; ())

Alternatively, one could envision a long OCaml source code file starting with multiple let declarations of global variables, and a single let...in expression in the middle. In that case, it seems like a ;; is necessary to terminate the declarations on top so that the let... in works, but using the ;; is advised against by the documentation.

Is there another way to write this (more elegantly)?

Body:
I don't know if it's more elegant, but

let f x = x + 1
let g x = x + 2
let _ = let h x = x + 3 in Printf.printf "%d \n" (f (h (g 3)))

compiles and runs.


问:
How to pass props to child components when using protected routes?
I'm currently developing a 'Train Ticket Reservation System' using ReactJS. Since users should login to access the services, I have used protected routes to render some components. Instead of using the default . So far I know how to send props with  using the render method. I want to know how to send props when using protected routes. Since the render method doesn't work with that.

This is my implementation of the protected route.

```<code>import React from 'react';
import auth from './auth';
import {Route, Redirect} from 'react-router-dom';

const ProtectedRoute = ({component: Component, ...rest}) => {

    return(
        <Route {...rest} render={props => {

            if(auth.isAuthenticated()){
                console.log(auth.isAuthenticated())
                return <Component {...props}/>
            }
            else{
                return <Redirect to={
                    {
                        pathname: '/',
                        state:{
                            from: props.location
                        }
                    }
                } />
            }
            }} />
    );

};

export default ProtectedRoute;
</code>```

This is how I used protected route for navigation

<ProtectedRoute  exact path="/Home/AboutUs" component={AboutUs}/>
```

答:
You can just pass props to the ProtectedRoute component.

i.e.

```<code><ProtectedRoute exact page="Home" path="/Home/AboutUs" component={AboutUs}/>
</code>```

To get the page props in the Component

Since you have used destructuring.

```<code>const ProtectedRoute = ({component: Component, ...rest}) => { ..... }
</code>```

Except component props the remaining props are assigned to the variable rest after the spread operator.

So you can get the props from the variable rest which is an object.

```<code><Component {...props} pageProps={rest.page} />  // pageProps="Home"
</code>```

Body:
I'm currently developing a 'Train Ticket Reservation System' using ReactJS. Since users should login to access the services, I have used protected routes to render some components. Instead of using the default . So far I know how to send props with  using the render method. I want to know how to send props when using protected routes. Since the render method doesn't work with that.

This is my implementation of the protected route.

import React from 'react';
import auth from './auth';
import {Route, Redirect} from 'react-router-dom';

const ProtectedRoute = ({component: Component, ...rest}) => {

    return(
        <Route {...rest} render={props => {

            if(auth.isAuthenticated()){
                console.log(auth.isAuthenticated())
                return <Component {...props}/>
            }
            else{
                return <Redirect to={
                    {
                        pathname: '/',
                        state:{
                            from: props.location
                        }
                    }
                } />
            }
            }} />
    );

};

export default ProtectedRoute;

This is how I used protected route for navigation

<ProtectedRoute  exact path="/Home/AboutUs" component={AboutUs}/>

Body:
You can just pass props to the ProtectedRoute component.

i.e.

<ProtectedRoute exact page="Home" path="/Home/AboutUs" component={AboutUs}/>

To get the page props in the Component

Since you have used destructuring.

const ProtectedRoute = ({component: Component, ...rest}) => { ..... }

Except component props the remaining props are assigned to the variable rest after the spread operator.

So you can get the props from the variable rest which is an object.

<Component {...props} pageProps={rest.page} />  // pageProps="Home"


问:
PIL rotate image colors (BGR -> RGB)
I have an image where the colors are BGR. How can I transform my PIL image to swap the B and R elements of each pixel in an efficient manner?</p>

答:
Adding a solution using the ellipsis

image = image[...,::-1]

In this case, the ellipsis ... is equivalent to :,: while ::-1 inverts the order of the last dimension (channels).

ContentLicense: CC BY-SA 2.5

Title: PIL rotate image colors (BGR -> RGB)


问:
What is the mcrypt_get_block alternative and how to use it
I have an old wordpress plugin built using symfony framework and which uses mcrypt_get_block_size('tripledes', 'ecb'). However, I have just upgraded php on my server to version 7.3 and now I am getting a Fatal error: Call to undefined function HealthShieldForm\mcrypt_encrypt().

I have read few articles where they suggest using openssl_encrypt(). Unfortunately I dont know where to begin in terms of replacing the functions with eachother and insure I am getting the same results.

My current code is this:

```<code>private function encrypt($data)
    {
        //Pad for PKCS7
        $blockSize = mcrypt_get_block_size('tripledes', 'ecb');
        $len = strlen($data);
        $pad = $blockSize - ($len % $blockSize);
        $data .= str_repeat(chr($pad), $pad);

        //Encrypt data
        $encData = mcrypt_encrypt('tripledes', $this->key, $data, 'ecb');

        return base64_encode($encData);
    }

    private function decrypt($data)
    {
        $data = base64_decode($data);

        $data = mcrypt_decrypt('tripledes', $this->key, $data, 'ecb');

        $block = mcrypt_get_block_size('tripledes', 'ecb');
        $len = strlen($data);
        $pad = ord($data[$len - 1]);

        return substr($data, 0, strlen($data) - $pad);
    }
</code>```

UPDATE

I have adapted Peter's example to reflect on my code:

```<code>function encrypt($data)
    {
        $ciphertext = openssl_encrypt($data, 'des-ede3-ecb', $this->key, OPENSSL_RAW_DATA);
        return base64_encode($ciphertext);
    }

    function decrypt($data)
    {
        $ciphertext = base64_decode($data);
        $plaintext = openssl_decrypt($ciphertext, 'des-ede3-ecb', $this->key, OPENSSL_RAW_DATA);
        return $plaintext;
    }
</code>```

However, now I am getting this error: Warning: openssl_encrypt(): Unknown cipher algorithm

答:
You are using ECB with PKCS#5 / 7 padding (not explicitly mentioned, but that's the padding that is manually applied). That padding is the default for OpenSSL, so you just have to use 'des-ede3' without OPENSSL_RAW_DATA and OPENSSL_ZERO_PADDING as options.

The only other problem that I see is if the key is too small or big. In that case the mcrypt lib will pad with zero bytes or prune the rightmost bytes. So you may need to do this yourself if encryption / decryption fails.

Good luck, and try and move away from this terrible protocol and code ASAP.

Body:
I have an old wordpress plugin built using symfony framework and which uses mcrypt_get_block_size('tripledes', 'ecb'). However, I have just upgraded php on my server to version 7.3 and now I am getting a Fatal error: Call to undefined function HealthShieldForm\mcrypt_encrypt().

I have read few articles where they suggest using openssl_encrypt(). Unfortunately I dont know where to begin in terms of replacing the functions with eachother and insure I am getting the same results.

My current code is this:

private function encrypt($data)
    {
        //Pad for PKCS7
        $blockSize = mcrypt_get_block_size('tripledes', 'ecb');
        $len = strlen($data);
        $pad = $blockSize - ($len % $blockSize);
        $data .= str_repeat(chr($pad), $pad);

        //Encrypt data
        $encData = mcrypt_encrypt('tripledes', $this->key, $data, 'ecb');

        return base64_encode($encData);
    }

    private function decrypt($data)
    {
        $data = base64_decode($data);

        $data = mcrypt_decrypt('tripledes', $this->key, $data, 'ecb');

        $block = mcrypt_get_block_size('tripledes', 'ecb');
        $len = strlen($data);
        $pad = ord($data[$len - 1]);

        return substr($data, 0, strlen($data) - $pad);
    }

UPDATE

I have adapted Peter's example to reflect on my code:

function encrypt($data)
    {
        $ciphertext = openssl_encrypt($data, 'des-ede3-ecb', $this->key, OPENSSL_RAW_DATA);
        return base64_encode($ciphertext);
    }

    function decrypt($data)
    {
        $ciphertext = base64_decode($data);
        $plaintext = openssl_decrypt($ciphertext, 'des-ede3-ecb', $this->key, OPENSSL_RAW_DATA);
        return $plaintext;
    }

However, now I am getting this error: Warning: openssl_encrypt(): Unknown cipher algorithm


问:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() when using cupy array
I have a code which I got from Numpy repeat for 2d array

Below one works fine with numpy array but throws
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() when using with cupy arrays.
For  the line ret_val[mask] = cp.repeat(arr.ravel(), rep.ravel()

I have tried to use logical operations already existing in cupy but they still throw errors.

def repeat2dvect(arr, rep):
    lens = cp.array(rep.sum(axis=-1))
    maxlen = lens.max()
    ret_val = cp.zeros((arr.shape[0], int(maxlen)))
    mask = (lens[:,None]>cp.arange(maxlen))
    ret_val[mask] = cp.repeat(arr.ravel(), rep.ravel())
    return ret_val
```

答:
Conguratulations on the first contribution to the StackOverflow :)

I replicated the error with the following code:

import cupy as cp

arr = cp.array([5, 1, 4], 'float32')
rep = cp.array([3, 2], 'int32')
result = cp.repeat(arr, rep)
```

```ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
```

This error message is kind of misleading: the reason why this code doesn't work is something quite different.

In short, you can't pass cp.ndarray as the second argument of cp.repeat().

Why? That's because the shape of result is determined based on the value of that argument.
If it were an ndarray, it would be problematic in CuPy (but not in NumPy) because the value of the array is in the GPU. In order to determine the output shape, CuPy would have to wait for the GPU to finish all of the queued computations, and then transfer the value to CPU. That would simply spoil the benefit of asynchronous computation. CuPy intentionally prohibits such operation.

In your particular case, you could for example manually convert rep to np.ndarray (by ret.get()) or calculate rep as np.ndarray from the beginning.

Body:
Conguratulations on the first contribution to the StackOverflow :)

I replicated the error with the following code:

import cupy as cp

arr = cp.array([5, 1, 4], 'float32')
rep = cp.array([3, 2], 'int32')
result = cp.repeat(arr, rep)

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

This error message is kind of misleading: the reason why this code doesn't work is something quite different.

In short, you can't pass cp.ndarray as the second argument of cp.repeat().

Why? That's because the shape of result is determined based on the value of that argument.
If it were an ndarray, it would be problematic in CuPy (but not in NumPy) because the value of the array is in the GPU. In order to determine the output shape, CuPy would have to wait for the GPU to finish all of the queued computations, and then transfer the value to CPU. That would simply spoil the benefit of asynchronous computation. CuPy intentionally prohibits such operation.

In your particular case, you could for example manually convert rep to np.ndarray (by ret.get()) or calculate rep as np.ndarray from the beginning.


问:
When typing a item code into one cell, how to get a description and price to automatically go into other cells
This is probably a really easy fix but I'm having trouble getting it to work.  I am a frequent user of functions in excel but haven't dabbled with VBA much.

I have a vendor that refuses to itemize their invoices.  It becomes very difficult for me when making a PO.  I have begun to itemize their invoices myself but as they get bigger and bigger this is consuming more of my time.  I would like to be able to type an item code into a cell and in the two cells to the right automatically populate the description and the price.

For example:

Type "Temporary Wire" in A2, and "Installing a Temporary Wire Gap Gate up to 100 foot wide" would automatically populate in B2, followed by "$650.00" automatically populating in C2.

答:
This is just a quick workaround that I thought of. You would add as many cases as you need, and it could become cumbersome after a while, but this should work. You would type the short versions in to Column A and then run the macro to assign the corresponding long values to Column B.

The advantage to this method is that it will likely run a little faster than if you search for a value every time a (certain) cell value changes.

You can also use the "Case Else" to handle accidental typos. Another way to improve input speed would be to change the Short Input to an integer and type a product number instead of the short version of the name. Even if the product numbers are only used by you, it would save you time.

```<code>Sub quickType()
    Dim x As Integer
    x = 1
    Dim shortInput As String
    Dim longOutput As String
    With ThisWorkbook.Worksheets("Sheet1")
        Do While .Range("A" & x).Value <> ""
            shortInput = .Range("A" & x).Value
            Select Case shortInput
                Case "Short Text"
                    longOutput = "This is the long version of the short text."
                Case "Other Text"
                    longOutput = "This is the long version of the other text."
                Case Else
                    longOutput = "Check for a typo."
            End Select
            .Range("B" & x).Value = longOutput
        x = x + 1
        Loop
    End With
End Sub
</code>```

Body:
This is just a quick workaround that I thought of. You would add as many cases as you need, and it could become cumbersome after a while, but this should work. You would type the short versions in to Column A and then run the macro to assign the corresponding long values to Column B.

The advantage to this method is that it will likely run a little faster than if you search for a value every time a (certain) cell value changes.

You can also use the "Case Else" to handle accidental typos. Another way to improve input speed would be to change the Short Input to an integer and type a product number instead of the short version of the name. Even if the product numbers are only used by you, it would save you time.

Sub quickType()
    Dim x As Integer
    x = 1
    Dim shortInput As String
    Dim longOutput As String
    With ThisWorkbook.Worksheets("Sheet1")
        Do While .Range("A" & x).Value <> ""
            shortInput = .Range("A" & x).Value
            Select Case shortInput
                Case "Short Text"
                    longOutput = "This is the long version of the short text."
                Case "Other Text"
                    longOutput = "This is the long version of the other text."
                Case Else
                    longOutput = "Check for a typo."
            End Select
            .Range("B" & x).Value = longOutput
        x = x + 1
        Loop
    End With
End Sub


问:
rel properties in html tags
I was reading about Google SEO suggestions and I had a question:

Can we write many Rel in the rel property??

How can we write many rel in it?With a blank space as my example that follows??

For example, something like this is ok?:

```<code><a rel="noindex nofollow" href="/mysite.com" target="_blank"></a>
</code>```

Thanks All in advance!!

答:
The W3c say at http://www.w3.org/TR/html401/struct/links.html#adef-rel:

This attribute describes the
  relationship from the current document
  to the anchor specified by the href
  attribute. The value of this attribute
  is a space-separated list of link
  types.

So, yes, you can.

Title: rel properties in html tags

Body:
I was reading about Google SEO suggestions and I had a question:

Can we write many Rel in the rel property??

How can we write many rel in it?With a blank space as my example that follows??

For example, something like this is ok?:

Thanks All in advance!!


问:
How to persist android app data to on-premise sql server
I have been tasked with building a new android app. I need to persist app data to an on-premise SQL Server. No data needs to be transferred from SQL Server to the android app, that is, I only need the C in CRUD. I'm not sure how I should set this up whatsoever. Can anybody help with the architecture? Will I need to persist the data to a local SqlLite DB first then run something to transfer to the on-premise SQL Server DB?

I've never used Azure or built a restful service in .NET. We have an old .NET web service (.asmx) that I would prefer to use for this. Is that possible?

答:
So there are a few elements to this question. I'll answer in three parts.

1. Web (REST)

You will need (like you mentioned) a RESTful service to connect outside requests to the on-premise SQL server. I believe you can use .NET (.asmx) to create such an API (there are many guides you can find online). You could also use something like ASP .NET Core or more modern technologies such as Node.js, Ruby on Rails, etc.

You are going to need one endpoint for the "C" of CRUD. Whether this will be a PUT or POST endpoint will depend on the specific details of your implementation and use case. See this SO answer: PUT vs. POST in REST

You will also likely need some kind of authentication system to ensure only authorized individuals are accessing your database. For this you could try something like Microsoft's Identity Framework, some more custom authentication scheme (see this), or other libraries.

2. Android

On the android side, you are going to need to access the API through the internet. The easiest way to do this would be utilizing some kind of networking library (I would recommend OkHttp). Since network requests (hitting an API) can take time, it is also highly advised to do this off of the main/UI thread. Doing this in Android is made much easier through the use of a threading library such as RxJava. There are many examples out there on how to use OkHttp with RxJava (see this answer for example).

3. Caching

This is sort of an extra credit part. If you would like to cache create operations on the Android device (for example if you didn't have network), you would then need to use on-device persistent storage. If this isn't a requirement, you can skip this. For on-device persistent storage, I would recommend looking into the Android Room persistence library (which also has great integration with RxJava).

Just to be clear, you will only need to persist the data to a local SqLite database in the instance where you want to cache create operations.

Good luck!


问:
List subscriptions for a given Azure account
I'm trying to list the subscriptions in an Azure account using azure-python-sdk.

I have followed this link in documentation.

https://learn.microsoft.com/en-us/python/api/azure-mgmt-subscription/azure.mgmt.subscription.operations.subscriptionsoperations?view=azure-python#list-custom-headers-none--raw-false----operation-config-

from azure.mgmt.subscription import SubscriptionClient
from msrestazure.azure_active_directory import UserPassCredentials

credentials = UserPassCredentials(username='xxxx', password='xxxx')
sub_client = SubscriptionClient(credentials)
subs = [sub.as_dict() for sub in sub_client.subscriptions.list()]
print(subs)

```

It is supposed to return a list of subscriptions.
However, I see only empty list returned every time I try the above code.
Can anybody help?

答:
If the list is empty and you get not exception, it's likely your credentials are correct (no exception), but your user doesn't have access to subscriptions (no permissions)

In the Azure portal, in the subscription panel you have a button "Access control (IAM)" to define what users are allowed to a given subscription.
https://learn.microsoft.com/azure/role-based-access-control/role-assignments-portal

https://learn.microsoft.com/azure/role-based-access-control/rbac-and-directory-admin-roles

(I work at MS in the SDK team)

Body:
I'm trying to list the subscriptions in an Azure account using azure-python-sdk.

I have followed this link in documentation.

https://learn.microsoft.com/en-us/python/api/azure-mgmt-subscription/azure.mgmt.subscription.operations.subscriptionsoperations?view=azure-python#list-custom-headers-none--raw-false----operation-config-

from azure.mgmt.subscription import SubscriptionClient
from msrestazure.azure_active_directory import UserPassCredentials

credentials = UserPassCredentials(username='xxxx', password='xxxx')
sub_client = SubscriptionClient(credentials)
subs = [sub.as_dict() for sub in sub_client.subscriptions.list()]
print(subs)

It is supposed to return a list of subscriptions.
However, I see only empty list returned every time I try the above code.
Can anybody help?


问:
Flatten array of multiple nested arrays without recursion - javascript
Maybe it's stupid question but I cannot realize is that possible to flatten multidimensional array without recursion?

I have one solution written by me with recursion:

```<code>function transform (arr) {
   var result = [];
   arr.forEach(flatten)
   function flatten (el) {
     if (Array.isArray(el)) {
        return el.forEach(flatten);
     }
     return result.push(el);
   }
   return result;
}
</code>```

Example of an array to flatten:

```<code>[1, {a: [2, 3]}, 4, [5, [6]], [[7], 8, 9], 10]
</code>```

And execution:

```<code>var a = [1, {a: [2, 3]}, 4, [5, [6]], [[7], 8, 9], 10];
var r = transform(r);
console.log(r); // [1, {a: [2, 3]}, 4, 5, 6, 7, 8, 9, 10]
</code>```

Thanks!

答:
We can use JS Array flat() method for this, which is currently supported in most of the browsers except IE, as of May 2019.

Syntax

```<code>var newArray = arr.flat([depth]);
</code>```

depth: Optional

The depth level specifying how deep a nested array structure should be flattened. Defaults to 1.

Flattening nested arrays

One Level Depth:

const arr1 = [1, 2, [3, 4]]
const flattenArr = arr1.flat()
console.log(flattenArr)
// [1, 2, 3, 4]```
</div>
</div>
</p>
<hr />
<h2>Two Level Depth:</h2>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const arr2 = [1, 2, [3, 4, [5, 6]]];
const flattenArr = arr2.flat(2)   // <== using 2 here
console.log(flattenArr)
// [1, 2, 3, 4, [5, 6]]</code>```

Any Level Deep:

const arr3 = [1, {a: [2, 3]}, 4, [5, [6]], [[7], 8, 9], 10]

// Using `Infinity` here to flatten any depth level array
// For this use case we could have also used 3 here
const flattenArr = arr3.flat(Infinity)
console.log(flattenArr)
// [1, {a: [2, 3]}, 4, 5, 6, 7, 8, 9, 10]```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100%!important; }</code>```

Body:
Maybe it's stupid question but I cannot realize is that possible to flatten multidimensional array without recursion?

I have one solution written by me with recursion:

function transform (arr) {
   var result = [];
   arr.forEach(flatten)
   function flatten (el) {
     if (Array.isArray(el)) {
        return el.forEach(flatten);
     }
     return result.push(el);
   }
   return result;
}

Example of an array to flatten:

[1, {a: [2, 3]}, 4, [5, [6]], [[7], 8, 9], 10]

And execution:

var a = [1, {a: [2, 3]}, 4, [5, [6]], [[7], 8, 9], 10];
var r = transform(r);
console.log(r); // [1, {a: [2, 3]}, 4, 5, 6, 7, 8, 9, 10]

Thanks!

Body:
We can use JS Array flat() method for this, which is currently supported in most of the browsers except IE, as of May 2019.

Syntax

var newArray = arr.flat([depth]);

depth: Optional

The depth level specifying how deep a nested array structure should be flattened. Defaults to 1.

Flattening nested arrays

One Level Depth:

const arr1 = [1, 2, [3, 4]]
const flattenArr = arr1.flat()
console.log(flattenArr)
// [1, 2, 3, 4]

Two Level Depth:

const arr2 = [1, 2, [3, 4, [5, 6]]];
const flattenArr = arr2.flat(2)   // <== using 2 here
console.log(flattenArr)
// [1, 2, 3, 4, [5, 6]]

Any Level Deep:

const arr3 = [1, {a: [2, 3]}, 4, [5, [6]], [[7], 8, 9], 10]

// Using `Infinity` here to flatten any depth level array
// For this use case we could have also used 3 here
const flattenArr = arr3.flat(Infinity)
console.log(flattenArr)
// [1, {a: [2, 3]}, 4, 5, 6, 7, 8, 9, 10]

.as-console-wrapper { max-height: 100%!important; }


问:
Gnuplot: Plotting from *txt files from different directories by reading column header
My folder structure looks kind of like this

```<code>$ tree
.
├── Original_folder
│   └── cat.txt
├── folder1
│   └── cat.txt
├── folder2
│   └── cat.txt
├── folder3
│
└── cat.txt
</code>```

Each cat.txt file has 5 line before starting the column header.
Sample cat.txt file is like this

```<code>Version LRv1.10.0
Build date 2017-12-06
MOL-calc
PRESSURE
!
      Time[s]     InletT[K]   InletP[Pa]   O2_GasOut     C_GasOut
       100         0.000885   1000000       0.0007       0.2111
and so on....
</code>```

I want to plot first column along with the column which have column header with a keyword "_GasOut". (There are unknown number of header with this keywords, For each column I would like to have a separate graph). Additionally, the graphical results of Original_folder should be plotted in the same graph for all the plots from folder1, folder2, folder3...... and so on.

Corresponding graph should be saved in the corresponding folders.

N.B: folder numbers are not fixed.
I added one of the cat.txt file for reference. https://1drv.ms/t/s!Aoomvi55MLAQh1wMmpnPGnliFmgg

答:
This can be done entirely in gnuplot.

I do not understand exactly where the script is supposed to find the names to match against desired column headers, but here is a simple gnuplot script that works for a single known column header, followed by a slightly more complicated script that assumes you have collected the desired names into an array of strings.

```<code>set term pdf
set key autotitle columnheader   # not strictly necessary but ensures the program
                                 # interprets the first line of data as headers
HEADER = "_GasOut"
orig = "original_folder/cat.txt"
do for [f=1:10] {                # 10 folders
  in = sprintf("folder%d/cat.txt", f)
  out = sprintf("folder%d/plot.pdf")
  plot orig skip 5 using 1:(column(HEADER)), \
       in skip 5 using 1:(column(HEADER))
}
</code>```

Now let's do the same thing except we add a loop over multiple column headers.

```<code>set term pdf
set key autotitle columnheader

array HEADS = [ "C_GasOut", "SurfaceT_cell7[K]", "O2_intMassFlowOut[kg]", \
                  "H2O_Conv", "InletT[K]" ]
orig = "original_folder/cat.txt"

do for [h = 1 : |HEADS|] {
  HEADER = HEADS[h]
  do for [f=1:10] {
    in = sprintf("folder%d/cat.txt", f)
    out = sprintf("folder%d/plot.pdf")
    plot orig skip 5 using 1:(column(HEADER)), \
         in skip 5 using 1:(column(HEADER))
  }
}
</code>```

If the names or number of the subfolders are not known in advance you could substitute the loop [f=1:10] with one that iterates over a list of folder names.  For example:

```<code>folders = system("ls -1 fold*")
nfolders = words(folders)
do for [f = 1 : nfolders] {
    in = sprintf("%s/cat.txt", folders(word(folders,f)))
    ... etc
</code>```

Body:
My folder structure looks kind of like this

$ tree
.
├── Original_folder
│   └── cat.txt
├── folder1
│   └── cat.txt
├── folder2
│   └── cat.txt
├── folder3
│
└── cat.txt

Each cat.txt file has 5 line before starting the column header.
Sample cat.txt file is like this

Version LRv1.10.0
Build date 2017-12-06
MOL-calc
PRESSURE
!
      Time[s]     InletT[K]   InletP[Pa]   O2_GasOut     C_GasOut
       100         0.000885   1000000       0.0007       0.2111
and so on....

I want to plot first column along with the column which have column header with a keyword "_GasOut". (There are unknown number of header with this keywords, For each column I would like to have a separate graph). Additionally, the graphical results of Original_folder should be plotted in the same graph for all the plots from folder1, folder2, folder3...... and so on.

Corresponding graph should be saved in the corresponding folders.

N.B: folder numbers are not fixed.
I added one of the cat.txt file for reference. https://1drv.ms/t/s!Aoomvi55MLAQh1wMmpnPGnliFmgg

Body:
This can be done entirely in gnuplot.

I do not understand exactly where the script is supposed to find the names to match against desired column headers, but here is a simple gnuplot script that works for a single known column header, followed by a slightly more complicated script that assumes you have collected the desired names into an array of strings.

set term pdf
set key autotitle columnheader   # not strictly necessary but ensures the program
                                 # interprets the first line of data as headers
HEADER = "_GasOut"
orig = "original_folder/cat.txt"
do for [f=1:10] {                # 10 folders
  in = sprintf("folder%d/cat.txt", f)
  out = sprintf("folder%d/plot.pdf")
  plot orig skip 5 using 1:(column(HEADER)), \
       in skip 5 using 1:(column(HEADER))
}

Now let's do the same thing except we add a loop over multiple column headers.

set term pdf
set key autotitle columnheader

array HEADS = [ "C_GasOut", "SurfaceT_cell7[K]", "O2_intMassFlowOut[kg]", \
                  "H2O_Conv", "InletT[K]" ]
orig = "original_folder/cat.txt"

do for [h = 1 : |HEADS|] {
  HEADER = HEADS[h]
  do for [f=1:10] {
    in = sprintf("folder%d/cat.txt", f)
    out = sprintf("folder%d/plot.pdf")
    plot orig skip 5 using 1:(column(HEADER)), \
         in skip 5 using 1:(column(HEADER))
  }
}

If the names or number of the subfolders are not known in advance you could substitute the loop [f=1:10] with one that iterates over a list of folder names.  For example:

folders = system("ls -1 fold*")
nfolders = words(folders)
do for [f = 1 : nfolders] {
    in = sprintf("%s/cat.txt", folders(word(folders,f)))
    ... etc


问:
jQuery countdown pause and repeat
I'm trying to code some feature to page, but I'm not able to put together all pieces :-(

All I want is simple counter which counts to 0 and then show message (.confirmation). If You disrupt (move mouse or touch keyobaord) counter pauses and show different message (.warning) and after few seconds repeat counting from begining. Ufff...

I've element for monitoring user action and conter but I don't know how to add this together:

```<code>       //monitors user action
        $('.warning, .confirmation').hide();

        $(document).bind('mousemove keydown', function() {
            $('.warning').show().delay(2000).fadeOut(500);
        });

        //counts for example from 5 seconds (this value is in the <span></span> in html section)
        var sec = $('#box span').text()
        var timer = setInterval(function() {
           $('#box span').text(--sec);
           if (sec == 0) {
              $('.confirmation').show(function() {
                $(document).unbind();
              });
              clearInterval(timer);
           }
        }, 1000);
</code>```

答:
Try something like that:

```<code>        //countdown pause timer
        var countDownPauseTimer = 0;

        //monitors user action
        $('.warning, .confirmation').hide();

        $(document).bind('mousemove keydown', function() {
            countDownPauseTimer = 10; // Countdown will pause for 10 seconds
            $('.warning').show().delay(2000).fadeOut(500);
        });

        //counts for example from 5 seconds (this value is in the <span></span> in html section)
        var sec = $('#box span').text()
        var timer = setInterval(function() {
           if (countDownPauseTimer > 0)
                countDownPauseTimer--;
           else
                $('#box span').text(--sec);
           if (sec == 0) {
              $('.confirmation').show(function() {
                $(document).unbind();
              });
              clearInterval(timer);
           }
        }, 1000);
</code>```

What I did here is introduce another variable to indicate that we are pausing the countdown and to hold the number of seconds left for the pause.

In the interval tick I check if there is a pause and decide which value to decrement...

I didn't test it but it should work.

Update

Below is an updated code with the countdown restarting after pause ends:

```<code>        //countdown pause timer
        var countDownPauseTimer = -1;

        //monitors user action
        $('.warning, .confirmation').hide();

        $(document).bind('mousemove keydown', function() {
            countDownPauseTimer = 10; // Countdown will pause for 10 seconds
            $('.warning').show().delay(2000).fadeOut(500);
        });

        //counts for example from 5 seconds (this value is in the <span></span> in html section)
        var sec = $('#box span').text();
        var timer = setInterval(function() {
           if (countDownPauseTimer > 0)
                countDownPauseTimer--;
           else if (countDownPauseTimer == 0) {
                countDownPauseTimer--;
                sec = $('#box span').text();
           }
           else
                $('#box span').text(--sec);
           if (sec == 0) {
              $('.confirmation').show(function() {
                $(document).unbind();
              });
              clearInterval(timer);
           }
        }, 1000);
</code>```

Title: jQuery countdown pause and repeat

Body:
I'm trying to code some feature to page, but I'm not able to put together all pieces :-(

All I want is simple counter which counts to 0 and then show message (.confirmation). If You disrupt (move mouse or touch keyobaord) counter pauses and show different message (.warning) and after few seconds repeat counting from begining. Ufff...

I've element for monitoring user action and conter but I don't know how to add this together:

       //monitors user action
        $('.warning, .confirmation').hide();

        $(document).bind('mousemove keydown', function() {
            $('.warning').show().delay(2000).fadeOut(500);
        });

        //counts for example from 5 seconds (this value is in the  in html section)
        var sec = $('#box span').text()
        var timer = setInterval(function() {
           $('#box span').text(--sec);
           if (sec == 0) {
              $('.confirmation').show(function() {
                $(document).unbind();
              });
              clearInterval(timer);
           }
        }, 1000);

Body:
Try something like that:

        //countdown pause timer
        var countDownPauseTimer = 0;

        //monitors user action
        $('.warning, .confirmation').hide();

        $(document).bind('mousemove keydown', function() {
            countDownPauseTimer = 10; // Countdown will pause for 10 seconds
            $('.warning').show().delay(2000).fadeOut(500);
        });

        //counts for example from 5 seconds (this value is in the <span></span> in html section)
        var sec = $('#box span').text()
        var timer = setInterval(function() {
           if (countDownPauseTimer > 0)
                countDownPauseTimer--;
           else
                $('#box span').text(--sec);
           if (sec == 0) {
              $('.confirmation').show(function() {
                $(document).unbind();
              });
              clearInterval(timer);
           }
        }, 1000);

What I did here is introduce another variable to indicate that we are pausing the countdown and to hold the number of seconds left for the pause.

In the interval tick I check if there is a pause and decide which value to decrement...

I didn't test it but it should work.

Update

Below is an updated code with the countdown restarting after pause ends:

        //countdown pause timer
        var countDownPauseTimer = -1;

        //monitors user action
        $('.warning, .confirmation').hide();

        $(document).bind('mousemove keydown', function() {
            countDownPauseTimer = 10; // Countdown will pause for 10 seconds
            $('.warning').show().delay(2000).fadeOut(500);
        });

        //counts for example from 5 seconds (this value is in the <span></span> in html section)
        var sec = $('#box span').text();
        var timer = setInterval(function() {
           if (countDownPauseTimer > 0)
                countDownPauseTimer--;
           else if (countDownPauseTimer == 0) {
                countDownPauseTimer--;
                sec = $('#box span').text();
           }
           else
                $('#box span').text(--sec);
           if (sec == 0) {
              $('.confirmation').show(function() {
                $(document).unbind();
              });
              clearInterval(timer);
           }
        }, 1000);


问:
preg_match special characters
How can I use preg_match to see if special characters [^'£$%^&*()}{@:'#~?><>,;@|\-=-_+-¬`] exist in a string?

答:
For me, this works best:</p>

```<code>$string = 'Test String';

$blacklistChars = '"%\'*;<>?^`{|}~/\\#=&';

$pattern = preg_quote($blacklistChars, '/');
if (preg_match('/[' . $pattern . ']/', $string)) {
   // string contains one or more of the characters in var $blacklistChars
}
</code>```

Title: preg_match special characters

Body:
For me, this works best:

$string = 'Test String';

$blacklistChars = '"%\'*;<>?^`{|}~/\\#=&';

$pattern = preg_quote($blacklistChars, '/');
if (preg_match('/[' . $pattern . ']/', $string)) {
   // string contains one or more of the characters in var $blacklistChars
}


问:
WordPress permalinks do not work with non-Plain setting (e.g. Month and name)
TL;DR

mod_rewrite is loaded

.htaccess is writable

AllowOverride ALL is set

LogLevel debug is set

logs reveal a redirect loop (see below)

details

The WordPress blog is located in filesystem location /var/www/html/ (i.e. index.php is in there, as are all the wp-*.php files such as wp-settings.php).

The WordPress blog's General Settings for WordPress Address (URL) and Site Address (URL) are both set to https://example.com/blog.

When I set the Permalink Settings to Month and name (or anything other than Plain), the .htaccess file is automatically modified to contain the following mod_rewrite block, and the URL paths adjust accordingly, e.g. /blog/2019/03/hello-world/, yet the accessing the URLs results in an Internal Server Error.

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /blog/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /blog/index.php [L]
</IfModule>

# END WordPress
</code>```

The log reveals the following:

```<code>Request exceeded the limit of 10 internal redirects due to probable configuration error.
AH00121: r->uri = /blog/index.php, referer: https://staging.example.com/blog/
AH00122: redirected from r->uri = /blog/index.php, referer: https://staging.example.com/blog/
... the above line repeated ...
AH00122: redirected from r->uri = /2019/03/10/hello-world/, referer: https://staging.example.com/blog/
</code>```

a hint of success...

With the Permalink Settings set to Plain, the .htaccess file is essentially empty, and the links work, though they are of the undesirable form /?p=123:

```<code># BEGIN WordPress

# END WordPress
</code>```

When I set Custom Structure, to /index.php/%year%/%monthnum%/%postname%/, the blog links are updated to the format /blog/index.php/2019/03/hello-world/ and they work, but now the URL is ugly (the /index.php/).

So why doesn't it work with /%year%/%monthnum%/%postname%/ and the automatically set .htaccess directives?

gory details

It shouldn't matter, but for the record: this WordPress blog is hosted in a Virtual Machine instance (VM instance) of the Compute Engine of Google Cloud Platform.

答:
Remove /blog from the last rule (RewriteBase stays as before).

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /blog/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress
</code>```

Body:
TL;DR

mod_rewrite is loaded

.htaccess is writable

AllowOverride ALL is set

LogLevel debug is set

logs reveal a redirect loop (see below)

details

The WordPress blog is located in filesystem location /var/www/html/ (i.e. index.php is in there, as are all the wp-*.php files such as wp-settings.php).

The WordPress blog's General Settings for WordPress Address (URL) and Site Address (URL) are both set to https://example.com/blog.

When I set the Permalink Settings to Month and name (or anything other than Plain), the .htaccess file is automatically modified to contain the following mod_rewrite block, and the URL paths adjust accordingly, e.g. /blog/2019/03/hello-world/, yet the accessing the URLs results in an Internal Server Error.

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /blog/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /blog/index.php [L]
</IfModule>

# END WordPress

The log reveals the following:

Request exceeded the limit of 10 internal redirects due to probable configuration error.
AH00121: r->uri = /blog/index.php, referer: https://staging.example.com/blog/
AH00122: redirected from r->uri = /blog/index.php, referer: https://staging.example.com/blog/
... the above line repeated ...
AH00122: redirected from r->uri = /2019/03/10/hello-world/, referer: https://staging.example.com/blog/

a hint of success...

With the Permalink Settings set to Plain, the .htaccess file is essentially empty, and the links work, though they are of the undesirable form /?p=123:

# BEGIN WordPress

# END WordPress

When I set Custom Structure, to /index.php/%year%/%monthnum%/%postname%/, the blog links are updated to the format /blog/index.php/2019/03/hello-world/ and they work, but now the URL is ugly (the /index.php/).

So why doesn't it work with /%year%/%monthnum%/%postname%/ and the automatically set .htaccess directives?

gory details

It shouldn't matter, but for the record: this WordPress blog is hosted in a Virtual Machine instance (VM instance) of the Compute Engine of Google Cloud Platform.

Body:
Remove /blog from the last rule (RewriteBase stays as before).

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /blog/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress


答:
It would be much easier to understand OCaml syntax if we will stick to the grammar in which a top-level item could be only a definition1 which has the form

```<code>let <patt> = <expr>
</code>```

that has the following semantics -- compute expression <expr> and apply it to the pattern <patt>, if there is a match, then enrich the global context with the variables bound in the pattern <patt>.

Therefore, the conventional solution to your problem would be

```<code>let f x = x + 1
let g x = x + 2
let h x = x + 3

let () =
 Printf.printf "%d \n" (f (h (g 3)));
 ()
</code>```

Due to historic reasons, OCaml allows expression such as 1, "hello" or let x = 1 in x + x on the toplevel, provided that you separate them using ;;. Mostly this is due to the compatibility with the interactive top-level system, so that you can use OCaml as a calculator. I would advise against using ;; in real OCaml programs, that are written for the compiler consumption.

1) You call them declarations, though they are actually definitions, however for our case, it doesn't matter.

Title: Separating multiple `let` declarations followed by a single `let in`expression in OCaml

Body:
This question elaborates on OCaml syntax trap: multiple lets using separators.

In terms of programming imperative OCaml, how does one have multiple let statements that runs before a single let ... in without changing all declarations into expressions?

For example,

let f x = x + 1
let g x = x + 2
let h x = x + 3

compiles with no problem, but

let f x = x + 1
let g x = x + 2
let h x = x + 3 in (Printf.printf "%d \n" (f (h (g 3))) ; ())

doesn't work, because the first two are declarations whereas the last one is an expression. The same observation applies to variables. One way to correct this error is to nest change the first two lets into expressions and nest the let...in. However, this seems quite tedious and awkward:

let f x = x + 1 in
  let g x = x + 2 in
    let h x = x + 3 in (Printf.printf "%d \n" (f (h (g 3))) ; ())

Alternatively, one could envision a long OCaml source code file starting with multiple let declarations of global variables, and a single let...in expression in the middle. In that case, it seems like a ;; is necessary to terminate the declarations on top so that the let... in works, but using the ;; is advised against by the documentation.

Is there another way to write this (more elegantly)?

Body:
It would be much easier to understand OCaml syntax if we will stick to the grammar in which a top-level item could be only a definition1 which has the form

let <patt> = <expr>

that has the following semantics -- compute expression <expr> and apply it to the pattern <patt>, if there is a match, then enrich the global context with the variables bound in the pattern <patt>.

Therefore, the conventional solution to your problem would be

let f x = x + 1
let g x = x + 2
let h x = x + 3

let () =
 Printf.printf "%d \n" (f (h (g 3)));
 ()

Due to historic reasons, OCaml allows expression such as 1, "hello" or let x = 1 in x + x on the toplevel, provided that you separate them using ;;. Mostly this is due to the compatibility with the interactive top-level system, so that you can use OCaml as a calculator. I would advise against using ;; in real OCaml programs, that are written for the compiler consumption.

1) You call them declarations, though they are actually definitions, however for our case, it doesn't matter.


问:
Subset data by group within pandas dataframe
I need to subset a dataframe using groups and three conditional rules. If within a group all values in the Value column are none, I need to retain the first row for that group. If within a group all values in the Value column are not none, I need to retain all the values. If within a group some of the values in the Value column are none and others not none, I need to drop all rows where there is a none. Columns Region and ID together define a unique group within the dataframe.

My first approach was to separate the dataframe into two chunks. The first chunk is rows where for a group there are all nulls.  The second chunk is  everything else. For the chunk of data where rows for a group contained all nulls, I would create a rownumber using a cumulative count of rows by group and query rows where the cumulative count = 1. For the second chunk, I would drop all rows where Value is null. Then I would append the dataframes.

Sample source dataframe

```<code>dfInput = pd.DataFrame({
'Region':     [1, 1, 2, 2, 2, 2, 2],
'ID':     ['A', 'A', 'B', 'B', 'B', 'A', 'A'],
'Value':[0, 1, 1, None, 2, None, None],
})
</code>```

Desired output dataframe:

```<code>dfOutput = pd.DataFrame({
'Region':     [1, 1, 2, 2, 2],
'ID':     ['A', 'A', 'B', 'B', 'A'],
'Value':[0, 1, 1, 2, None],
})
</code>```

答:
Just follow your logic and using groupby

```<code>dfInput.groupby(['Region','ID']).Value.apply(lambda x : x.head(1) if x.isnull().all() else x.dropna()).\
        reset_index(level=[0,1]).sort_index()
Out[86]:
   Region ID  Value
0       1  A    0.0
1       1  A    1.0
2       2  B    1.0
4       2  B    2.0
5       2  A    NaN
</code>```

Body:
I need to subset a dataframe using groups and three conditional rules. If within a group all values in the Value column are none, I need to retain the first row for that group. If within a group all values in the Value column are not none, I need to retain all the values. If within a group some of the values in the Value column are none and others not none, I need to drop all rows where there is a none. Columns Region and ID together define a unique group within the dataframe.

My first approach was to separate the dataframe into two chunks. The first chunk is rows where for a group there are all nulls.  The second chunk is  everything else. For the chunk of data where rows for a group contained all nulls, I would create a rownumber using a cumulative count of rows by group and query rows where the cumulative count = 1. For the second chunk, I would drop all rows where Value is null. Then I would append the dataframes.

Sample source dataframe

dfInput = pd.DataFrame({
'Region':     [1, 1, 2, 2, 2, 2, 2],
'ID':     ['A', 'A', 'B', 'B', 'B', 'A', 'A'],
'Value':[0, 1, 1, None, 2, None, None],
})

Desired output dataframe:

dfOutput = pd.DataFrame({
'Region':     [1, 1, 2, 2, 2],
'ID':     ['A', 'A', 'B', 'B', 'A'],
'Value':[0, 1, 1, 2, None],
})

Body:
Just follow your logic and using groupby

dfInput.groupby(['Region','ID']).Value.apply(lambda x : x.head(1) if x.isnull().all() else x.dropna()).\
        reset_index(level=[0,1]).sort_index()
Out[86]:
   Region ID  Value
0       1  A    0.0
1       1  A    1.0
2       2  B    1.0
4       2  B    2.0
5       2  A    NaN


问:
Text in a flex container doesn't wrap in IE11
Consider the following snippet:

.parent {
  display: flex;
  flex-direction: column;
  width: 400px;
  border: 1px solid red;
  align-items: center;
}
.child {
  border: 1px solid blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="child">
    Lorem Ipsum is simply dummy text of the printing and typesetting industry
  </div>
  <div class="child">
    Lorem Ipsum is simply dummy text of the printing and typesetting industry
  </div>
</div></code>```

In Chrome, the text is wrapping as expected:

But, in IE11, the text is not wrapping:

Is this a known bug in IE? (if yes, a pointer will be appreciated)

Is there a known workaround?

This similar question doesn't have a definite answer and an official pointer.

答:
Somehow all these solutions didn't work for me. There is clearly an IE bug in flex-direction:column.

I only got it working after removing flex-direction:

```<code>flex-wrap: wrap;
align-items: center;
align-content: center;
</code>```

Body:
Consider the following snippet:

.parent {
  display: flex;
  flex-direction: column;
  width: 400px;
  border: 1px solid red;
  align-items: center;
}
.child {
  border: 1px solid blue;
}

    Lorem Ipsum is simply dummy text of the printing and typesetting industry

    Lorem Ipsum is simply dummy text of the printing and typesetting industry

In Chrome, the text is wrapping as expected:

But, in IE11, the text is not wrapping:

Is this a known bug in IE? (if yes, a pointer will be appreciated)

Is there a known workaround?

This similar question doesn't have a definite answer and an official pointer.

Body:
Somehow all these solutions didn't work for me. There is clearly an IE bug in flex-direction:column.

I only got it working after removing flex-direction:

flex-wrap: wrap;
align-items: center;
align-content: center;


问:
Sqlalchemy filter by calculated datetime hybrid_property
I have a model Prescription.

```<code>from datetime import timedelta
from sqlalchemy.ext.hybrid import hybrid_property

class Prescription(db.Model):
    """ docstring """
    ID = db.column(db.Integer, primary_key=True)
    date = db.Column(db.DateTime)
    duration = db.Column(db.SmallInteger)

    @hybrid_property
    def expiration_date(self):
        # return self.date + timedelta(days=self.duration)
        return self.date + timedelta(days=7)

    @classmethod
    def actual(cls ):
        """ docstring """
        today = datetime.today()

        return cls.query.filter(Prescription.expiration_date>=today)
</code>```

I want to get only actual prescriptions in my actual method, and when I specify

```<code>@hybrid_property
def expiration_date(self):
    return self.date + timedelta(days=7)
</code>```

everything works like a charm.

But every prescription has a different duration, and when I specify

```<code>@hybrid_property
def expiration_date(self):
     return self.date + timedelta(days=self.duration)
</code>```

I've got an error

```<code>TypeError: unsupported type for timedelta days component: InstrumentedAttribute
</code>```

I tried to make a little hack like this

```<code>@property
def days(self):
    return int(self.duration)
</code>```

but no luck.
Can anyone tell some workaround, or creating some lazy object for duration field or maybe another way get actual prescriptions, filtering by calculated expiration_date?

答:
In your @classmethod annotated actual() method, you are trying to access a non-static property(expiration_date) which is raising the error.
As per my understanding of what your code is doing, I have changed the code as follow:

```<code>from datetime import datetime,timedelta
from sqlalchemy.ext.hybrid import hybrid_property
from flask_sqlalchemy import SQLAlchemy
from flask import Flask

app = Flask(__name__)
db = SQLAlchemy(app)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['SQLALCHEMY_DATABASE_URI'] ='sqlite:///'

class Prescription(db.Model):
    """ docstring """
    def mydefault(context):
        return context.get_current_parameters()['date'] + timedelta(days=context.get_current_parameters()['duration'])

    ID = db.Column(db.Integer,primary_key= True)
    date = db.Column(db.Date)
    duration = db.Column(db.SmallInteger)
    expiration_date = db.Column(db.Date,default = mydefault)

    @classmethod
    def actual(cls ):
        """ docstring """
        today = datetime.today().date()
        return cls.query.filter(Prescription.expiration_date>=today).all()
    def __repr__(self):
      return "Id:{} , date:{}, duration:{}, expiration_date:{}".format(self.ID,self.date,self.duration,self.expiration_date)

db.create_all()
q=Prescription(ID=1,date=datetime(2019,5,26).date(),duration = 1) #Expired
r=Prescription(ID=2,date=datetime(2019,5,20).date(),duration = 3) #Expired
s=Prescription(ID=3,date=datetime(2019,5,27).date(),duration = 5) #Not Expired
t = Prescription(ID=4,date=datetime.now().date(),duration = 1) #Not Expired

db.session.add(q)
db.session.add(r)
db.session.add(s)
db.session.add(t)
db.session.commit()

list_obj = Prescription.query.all()
print("All Objects in DB:-")
for l in list_obj:
  print(l)
print()
print("Valid Prescription:")
print(Prescription.actual())
</code>```

Output:

One thing I can suggest to you is since the model does not need the time of expiration.
So you could change

```<code>date = db.Column(db.DateTime)
</code>```

to

```<code>date = db.Column(db.Date)
</code>```

and it will ease your task :)

Body:
I have a model Prescription.

from datetime import timedelta
from sqlalchemy.ext.hybrid import hybrid_property

class Prescription(db.Model):
    """ docstring """
    ID = db.column(db.Integer, primary_key=True)
    date = db.Column(db.DateTime)
    duration = db.Column(db.SmallInteger)

    @hybrid_property
    def expiration_date(self):
        # return self.date + timedelta(days=self.duration)
        return self.date + timedelta(days=7)

    @classmethod
    def actual(cls ):
        """ docstring """
        today = datetime.today()

        return cls.query.filter(Prescription.expiration_date>=today)

I want to get only actual prescriptions in my actual method, and when I specify

@hybrid_property
def expiration_date(self):
    return self.date + timedelta(days=7)

everything works like a charm.

But every prescription has a different duration, and when I specify

@hybrid_property
def expiration_date(self):
     return self.date + timedelta(days=self.duration)

I've got an error

TypeError: unsupported type for timedelta days component: InstrumentedAttribute

I tried to make a little hack like this

@property
def days(self):
    return int(self.duration)

but no luck.
Can anyone tell some workaround, or creating some lazy object for duration field or maybe another way get actual prescriptions, filtering by calculated expiration_date?

Body:
In your @classmethod annotated actual() method, you are trying to access a non-static property(expiration_date) which is raising the error.
As per my understanding of what your code is doing, I have changed the code as follow:

from datetime import datetime,timedelta
from sqlalchemy.ext.hybrid import hybrid_property
from flask_sqlalchemy import SQLAlchemy
from flask import Flask

app = Flask(__name__)
db = SQLAlchemy(app)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['SQLALCHEMY_DATABASE_URI'] ='sqlite:///'

class Prescription(db.Model):
    """ docstring """
    def mydefault(context):
        return context.get_current_parameters()['date'] + timedelta(days=context.get_current_parameters()['duration'])

    ID = db.Column(db.Integer,primary_key= True)
    date = db.Column(db.Date)
    duration = db.Column(db.SmallInteger)
    expiration_date = db.Column(db.Date,default = mydefault)

    @classmethod
    def actual(cls ):
        """ docstring """
        today = datetime.today().date()
        return cls.query.filter(Prescription.expiration_date>=today).all()
    def __repr__(self):
      return "Id:{} , date:{}, duration:{}, expiration_date:{}".format(self.ID,self.date,self.duration,self.expiration_date)

db.create_all()
q=Prescription(ID=1,date=datetime(2019,5,26).date(),duration = 1) #Expired
r=Prescription(ID=2,date=datetime(2019,5,20).date(),duration = 3) #Expired
s=Prescription(ID=3,date=datetime(2019,5,27).date(),duration = 5) #Not Expired
t = Prescription(ID=4,date=datetime.now().date(),duration = 1) #Not Expired

db.session.add(q)
db.session.add(r)
db.session.add(s)
db.session.add(t)
db.session.commit()

list_obj = Prescription.query.all()
print("All Objects in DB:-")
for l in list_obj:
  print(l)
print()
print("Valid Prescription:")
print(Prescription.actual())

Output:

One thing I can suggest to you is since the model does not need the time of expiration.
So you could change

date = db.Column(db.DateTime)

to

date = db.Column(db.Date)

and it will ease your task :)


问:
EF 4.1 Code First - OnModelCreating call time
When I debug my application this method seems not to be executing in constructor context of DbContext. So when it is called then?</p>

答: OnModelCreating triggers when EF4 is creating the database. Usually this event is used to configure the way EF4 generates the database, so if you executed your application before and your model remains the same, the database is already there and EF4 does not try to generate a new one (although this behaviour also depends on some configuration parameters). </p>