问:
Synchronizing access to MPI3 shared memory : is this code guaranteed to work by MPI standards?
The MPI-3 standard introduces shared-memory, that can be read and written by all processes sharing this memory without using calls to the MPI library.
While there are examples of one-sided communications using shared or non-shared memory, I did not find much information about how to use shared memory correctly with direct access.

I ended up doing something like this, which works well, but I was wondering if the MPI standard guarantees that it will always work?

```<code>// initialization:
MPI_Comm comm_shared;
MPI_Comm_split_type(MPI_COMM_WORLD, MPI_COMM_TYPE_SHARED, i_mpi, MPI_INFO_NULL, &comm_shared);

// allocation
const int N_WIN=10;
const int mem_size = 1000*1000;
double* mem[10];
MPI_Win win[N_WIN];
for (int i=0; i<N_WIN; i++) {   // I need several buffers.
    MPI_Win_allocate_shared( mem_size, sizeof(double), MPI_INFO_NULL, comm_shared, &mem[i], &win[i] );
    MPI_Win_lock_all(0, win);
}

while(1) {
    MPI_Barrier(comm_shared);
    ... // write anywhere on shared memory
    MPI_Barrier(comm_shared);
    ... // read on shared memory written by other processes
}

// deallocation
for (int i=0; i<N_WIN; i++) {
    MPI_Win_unlock_all(win[i]);
    MPI_Win_free(&win[i]);
}
</code>```

Here, I ensure synchronization by using MPI_Barrier() and assume the hardware makes the memory view consistent.
Furthermore, because I have several shared windows, a single call to MPI_Barrier seems more efficient than calling MPI_Win_fence() on every shared memory window.

It seems to work well an my x86 laptops and servers.
But is this programm a valid/correct MPI program?
Is there a more efficient method of achieving the same thing?

答:
I would be tempted to say this MPI program is not valid.

To explain what I base my opinion on

In the description of MPI_Win_allocate_shared:

The consistency of load/store accesses from/to the shared memory as observed by the user program depends on the architecture.  A consistent view can be created in the unified memory model  (see  Section  11.4)  by utilizing the window synchronization functions  (see Section 11.5) or explicitly completing outstanding store accesses (e.g.,  by calling MPI_WIN_FLUSH). MPI does not define semantics for accessing shared memory windows in the separate memory model.

Section 11.4, about the memory models, which states:

In the RMA unified model, public and private copies are identical and updates via put or accumulate calls are eventually observed by load operations without additional RMA calls. A store access to a window is eventually visible to remote get or accumulate calls without additional RMA calls.  These stronger semantics of the RMA unified model allow the user to omit some synchronization calls and potentially improve performance.

In the advice to users that follows only indicates:

If accesses in the RMA unified model are not synchronized (with locks or flushes, see Section 11.5.3), load and store operations might observe changes to the memory while they are in progress.

Section 11.7, semantic and correctness says:

MPI_BARRIER provides process synchronization,  but not memory synchronization.

The different examples in 11.8 explain well how to use flush and sync operations.

The only synchronization ever addressed is always and only one-sided ones, i.e. in your case, MPI_Win_flush{,_all}, or MPI_Win_unlock{,_all} (except the mutual exclusion of active and passive concurrent synchronization that has to be enforced by the user, or the usage of MPI_MODE_NOCHECK assert flag).

So either you access directly memory with store, and you need to call MPI_Win_sync() on each of your windows before calling MPI_Barrier (as explained in example 11.10) to ensure synchronization, or you are doing RMA accesses and then you would have to call at least MPI_Win_flush_all before the second barrier to ensure the operations have been propagated. If you try to read using load operation, you may have to synchronize after the second barrier as well before doing so.

Another solution would be to unlock and re-lock between barriers, or to use  Compiler and hardware specific notations could ensure the load occurs after the data is updated.

Body:
The MPI-3 standard introduces shared-memory, that can be read and written by all processes sharing this memory without using calls to the MPI library.
While there are examples of one-sided communications using shared or non-shared memory, I did not find much information about how to use shared memory correctly with direct access.

I ended up doing something like this, which works well, but I was wondering if the MPI standard guarantees that it will always work?

// initialization:
MPI_Comm comm_shared;
MPI_Comm_split_type(MPI_COMM_WORLD, MPI_COMM_TYPE_SHARED, i_mpi, MPI_INFO_NULL, &comm_shared);

// allocation
const int N_WIN=10;
const int mem_size = 1000*1000;
double* mem[10];
MPI_Win win[N_WIN];
for (int i=0; i<N_WIN; i++) {   // I need several buffers.
    MPI_Win_allocate_shared( mem_size, sizeof(double), MPI_INFO_NULL, comm_shared, &mem[i], &win[i] );
    MPI_Win_lock_all(0, win);
}

while(1) {
    MPI_Barrier(comm_shared);
    ... // write anywhere on shared memory
    MPI_Barrier(comm_shared);
    ... // read on shared memory written by other processes
}

// deallocation
for (int i=0; i<N_WIN; i++) {
    MPI_Win_unlock_all(win[i]);
    MPI_Win_free(&win[i]);
}

Here, I ensure synchronization by using MPI_Barrier() and assume the hardware makes the memory view consistent.
Furthermore, because I have several shared windows, a single call to MPI_Barrier seems more efficient than calling MPI_Win_fence() on every shared memory window.

It seems to work well an my x86 laptops and servers.
But is this programm a valid/correct MPI program?
Is there a more efficient method of achieving the same thing?


来源: stackexchange

问:
Can I make a function that accepts both ram and rom pointers in Microchip C18?
When I declare a function that accepts const char* and I pass a string literal, I get a

Warning: [2066] type qualifier mismatch in assignment

because string literals are rom const char*. It's the same the other way around.

Though the PIC is Harvard architecture, the memory is mapped into one contiguous address space, so theoretically it should be possible to support both ram and rom pointers the same way. Probably I have to use rom pointers because they are 24 bit while ram pointers are 16 bit.

However, just casting a const char* to a const rom char* does not work.

答:
Unfortunately, this is an inherent limitation of the Microchip C18 compiler. A pointer in C18 can point to either ROM or RAM, but not both.

This is why you will find duplicated functions for ROM and RAM operations in e.g. the Microchip Application Libraries:

```<code>BYTE* TCPPutString(TCP_SOCKET hTCP, BYTE* Data);
ROM BYTE* TCPPutROMString(TCP_SOCKET hTCP, ROM BYTE* Data);
</code>```

The Hi-Tech PICC-18 compiler has the appropriate address space determined at runtime, which allows for more flexible pointer usage. This is one of the reasons I ditched C18 in favour of PICC-18.

See the answers to this question and John Temples' Comparison of Hi-Tech PICC-18 and MPLAB C18 for more insight.

ContentLicense: CC BY-SA 3.0

Body:
Unfortunately, this is an inherent limitation of the Microchip C18 compiler. A pointer in C18 can point to either ROM or RAM, but not both.

This is why you will find duplicated functions for ROM and RAM operations in e.g. the Microchip Application Libraries:

BYTE* TCPPutString(TCP_SOCKET hTCP, BYTE* Data);
ROM BYTE* TCPPutROMString(TCP_SOCKET hTCP, ROM BYTE* Data);

The Hi-Tech PICC-18 compiler has the appropriate address space determined at runtime, which allows for more flexible pointer usage. This is one of the reasons I ditched C18 in favour of PICC-18.

See the answers to this question and John Temples' Comparison of Hi-Tech PICC-18 and MPLAB C18 for more insight.


问:
Filename is not changing while sharing pdf files in Android
I am using react-native-share library to share a pdf file.  I am sharing by converting it to base64 string but I am unable to change filename.

```<code>  shareProfile = async(data) => {
    Share.open({url: `data:application/pdf;base64, ${data}`, filename: 'test'})
  }
</code>```

I found property in documents but still it is not working. It is frustrating.
Thank you in advance.

答:
I'm running into this same issue. There appears to be a fix for this which was merged into their master branch, a few short weeks ago. However when react-native-share is installed via npm / yarn for some reason it doesn't include the fix.

Here's the fix commit:
https://github.com/react-native-community/react-native-share/pull/689/commits

And if you look at the source code -- you can see that it has been successfully merged.

I tried copying/pasting his fix into my local repo and it works (file names on android share worked), unfortunately we need to be able to get the fix from the source code.

ContentLicense: CC BY-SA 4.0

Body:
I am using react-native-share library to share a pdf file.  I am sharing by converting it to base64 string but I am unable to change filename.

  shareProfile = async(data) => {
    Share.open({url: `data:application/pdf;base64, ${data}`, filename: 'test'})
  }

I found property in documents but still it is not working. It is frustrating.
Thank you in advance.


问:
How do you pass variables to other JS modules with Fetch API?
A JavaScript app uses Web Audio API to create sounds from JSON data. I am fetching weather data, going through the JSON data and setting their properties to variables then using those variables to manipulate my application and create sounds. Each function in it's own JavaScript module script file. The main.js not shown here is the entry point to app.

A sample JSON that will get replaced with real weather data.

dummy-data.json

```<code>{
    "weather": {
        "temp": 4,
        "rain": 1,
        "wind": 1.2
    }
}
</code>```

The fetch API logic.

fetchWeather.js

```<code>import { manageData} from './manageScript.js';

const DUMMY = '../dummy-data.json';

const fetchWeather = () => {
    fetch(DUMMY)
        .then((res) => {
            return res.json();
        })
        .then((data) => {
            manageData(data); // attaches JSON weather properties to variables
        })
        .catch((error) => {
            console.log(error);
        });
};

export { fetchWeather };
</code>```

Attaches the JSON data to variables.

manageScript.js

```<code>function manageData(data) {
    let rain = data.weather.rain;
    //let wind = data.weather.wind;

    let rainProbability;

    if (rain == 1) {
        rainProbability = 1;
    }
    else {
        rainProbability = 0;
    }

    return rainProbability; // not sure how to return the data....?
};

export { manageData };
</code>```

I want the variables from manageData function above to work here

makeSynth.js

```<code>import { manageData } from './manageScript.js';

const createSynth = () => {
    //Web Audio API stuff goes here to create sounds from the variables.

    //How do I get the variables to work here. Code below does not work!
    let soundOfRain = manageData().rainProbability;
    console.log(soundOfRain);
};
</code>```

答:
You can achieve this by refactoring your promises into a async/await pattern then returning the result (a different method of dealing with promises). Also - your createSynth function should be calling fetchWeather, not manageScript

dummy-data.json

```<code>{
    "weather": {
        "temp": 4,
        "rain": 1,
        "wind": 1.2
    }
}
</code>```

manageScript.js

```<code>function manageData(data) {
    let rain = data.weather.rain;
    //let wind = data.weather.wind;

    let rainProbability;

    if (rain == 1) {
        rainProbability = 1;
    } else {
        rainProbability = 0;
    }

    return rainProbability;
}

export { manageData };
</code>```

fetchWeather.js

```<code>import { manageData } from "./manageScript.js";

const DUMMY = "../dummy-data.json";

// Use async/await to be able to return a variable out from the promise
const fetchWeather = async () => {
    const raw = await fetch(DUMMY);
    const json_data = await raw.json();
    const rain = manageData(json_data);
    // Now you should be able to return the variable back out of the function
    return rain;
};

export { fetchWeather };
</code>```

makeSynth.js

```<code>import { fetchWeather } from "./fetchWeather.js";

const createSynth = async () => {
    //Web Audio API stuff goes here to create sounds from the variables.

    //Need to call fetchWeather (which in turn will call manageData)
    let soundOfRain = await fetchWeather();
    console.log(soundOfRain);
};

createSynth();
</code>```

Body:
A JavaScript app uses Web Audio API to create sounds from JSON data. I am fetching weather data, going through the JSON data and setting their properties to variables then using those variables to manipulate my application and create sounds. Each function in it's own JavaScript module script file. The main.js not shown here is the entry point to app.

A sample JSON that will get replaced with real weather data.

dummy-data.json

{
    "weather": {
        "temp": 4,
        "rain": 1,
        "wind": 1.2
    }
}

The fetch API logic.

fetchWeather.js

import { manageData} from './manageScript.js';

const DUMMY = '../dummy-data.json';

const fetchWeather = () => {
    fetch(DUMMY)
        .then((res) => {
            return res.json();
        })
        .then((data) => {
            manageData(data); // attaches JSON weather properties to variables
        })
        .catch((error) => {
            console.log(error);
        });
};

export { fetchWeather };

Attaches the JSON data to variables.

manageScript.js

function manageData(data) {
    let rain = data.weather.rain;
    //let wind = data.weather.wind;

    let rainProbability;

    if (rain == 1) {
        rainProbability = 1;
    }
    else {
        rainProbability = 0;
    }

    return rainProbability; // not sure how to return the data....?
};

export { manageData };

I want the variables from manageData function above to work here

makeSynth.js

import { manageData } from './manageScript.js';

const createSynth = () => {
    //Web Audio API stuff goes here to create sounds from the variables.

    //How do I get the variables to work here. Code below does not work!
    let soundOfRain = manageData().rainProbability;
    console.log(soundOfRain);
};

Body:
You can achieve this by refactoring your promises into a async/await pattern then returning the result (a different method of dealing with promises). Also - your createSynth function should be calling fetchWeather, not manageScript

dummy-data.json

{
    "weather": {
        "temp": 4,
        "rain": 1,
        "wind": 1.2
    }
}

manageScript.js

function manageData(data) {
    let rain = data.weather.rain;
    //let wind = data.weather.wind;

    let rainProbability;

    if (rain == 1) {
        rainProbability = 1;
    } else {
        rainProbability = 0;
    }

    return rainProbability;
}

export { manageData };

fetchWeather.js

import { manageData } from "./manageScript.js";

const DUMMY = "../dummy-data.json";

// Use async/await to be able to return a variable out from the promise
const fetchWeather = async () => {
    const raw = await fetch(DUMMY);
    const json_data = await raw.json();
    const rain = manageData(json_data);
    // Now you should be able to return the variable back out of the function
    return rain;
};

export { fetchWeather };

makeSynth.js

import { fetchWeather } from "./fetchWeather.js";

const createSynth = async () => {
    //Web Audio API stuff goes here to create sounds from the variables.

    //Need to call fetchWeather (which in turn will call manageData)
    let soundOfRain = await fetchWeather();
    console.log(soundOfRain);
};

createSynth();


问:
How to call such a function?
Could somebody show me an example how to execute a query with pgQuery from this postgresql-query library? I created a function like this:

doIt :: (HasPostgres m, MonadLogger m) => Text -> m Bool
doIt name = do
  (val::[Only Int]) <- pgQuery [sqlExp|select setting from pg_settings where name=#{name}|]
  return ...
```

<p>but I cannot understand how to run it. It has a signature:</p>

<pre class="lang-hs prettyprint-override"><code>pgQuery :: (HasPostgres m, MonadLogger m, ToSqlBuilder q, FromRow r) => q -> m [r]
</code>```

I can execute it with runSqlBuilder (to get a Query and to execute it with standard query/query_) but how to execute it with pgQuery in IO monad?

答:
It looks as if you're supposed to use a PgMonadT transformer (effectively a ReaderT for a Connection) to manage your database connection, plus a LoggerT for logging.  So, the following type-checks:

```<code>main :: IO ()
main = do
  c <- connect defaultConnectInfo { connectHost = "..." }
  x <- runStderrLoggingT . runPgMonadT c $ doIt "whatever"
  print x
</code>```

In practice, you probably want to run most of your program in a custom monad, so something like:

```<code>{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}

import Control.Monad.IO.Class
import Control.Monad.Logger
import Database.PostgreSQL.Query
import Data.Text (Text)

type M = PgMonadT (LoggingT IO)

runM :: M a -> IO a
runM act = do
  c <- connect defaultConnectInfo { connectHost = "..." }
  runStderrLoggingT . runPgMonadT c $ act

doIt :: Text -> M Bool
doIt name = do
  (val::[Only Int]) <- pgQuery [sqlExp|select setting from pg_settings where name=#{name}|]
  return False

main :: IO ()
main = runM $ do
  x <- doIt "whatever"
  liftIO $ print x
</code>```

Title: How to call such a function?

Body:
Could somebody show me an example how to execute a query with pgQuery from this postgresql-query library? I created a function like this:

doIt :: (HasPostgres m, MonadLogger m) => Text -> m Bool
doIt name = do
  (val::[Only Int]) <- pgQuery [sqlExp|select setting from pg_settings where name=#{name}|]
  return ...

but I cannot understand how to run it. It has a signature:

pgQuery :: (HasPostgres m, MonadLogger m, ToSqlBuilder q, FromRow r) => q -> m [r]

I can execute it with runSqlBuilder (to get a Query and to execute it with standard query/query_) but how to execute it with pgQuery in IO monad?

Body:
It looks as if you're supposed to use a PgMonadT transformer (effectively a ReaderT for a Connection) to manage your database connection, plus a LoggerT for logging.  So, the following type-checks:

main :: IO ()
main = do
  c <- connect defaultConnectInfo { connectHost = "..." }
  x <- runStderrLoggingT . runPgMonadT c $ doIt "whatever"
  print x

In practice, you probably want to run most of your program in a custom monad, so something like:

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}

import Control.Monad.IO.Class
import Control.Monad.Logger
import Database.PostgreSQL.Query
import Data.Text (Text)

type M = PgMonadT (LoggingT IO)

runM :: M a -> IO a
runM act = do
  c <- connect defaultConnectInfo { connectHost = "..." }
  runStderrLoggingT . runPgMonadT c $ act

doIt :: Text -> M Bool
doIt name = do
  (val::[Only Int]) <- pgQuery [sqlExp|select setting from pg_settings where name=#{name}|]
  return False

main :: IO ()
main = runM $ do
  x <- doIt "whatever"
  liftIO $ print x


问:
MVVM binding viewmodel property child to viewmodel property
not sure if my title explains well the issue im having.

In my application i make a service calls to
-retrieve a list of customers.
-retrieve a list of organisations.

Then i bind this list of customers to a listbox on my view.

In my viewmodel i have the following properties:

```<code>IEnumerable<Organisation> Organisations
ObservableCollection<Customer> Customers
</code>```

Organisation properties: OrganisationId, OrganisationName

Customer properties: CustomerId, OrganisationId, CustomerFirstName, CustomerLastName

Inside the Listbox on my view i want to show the organisationname for each customer in the list.

how can i go about binding this in my view? I just want a textblock to show the organisationname for the customer.

答:
Bind the Listbox to a Linq query exposed from your ViewModel.

```<code>Public IEnumerable ItemsView
{
get {
return
    {
    from customer in this.Customers
    from org in this.Organisations
    where customer.OrganisationId=org.OrganisationId
    select new { FirstName=customer.FirstName, LastName=customer.LastName, OrganisationName=org.OrganisationName}

};
}
</code>```

Then just bind the listbox in Ritch's answer to this.

PS. I'm writing this on my phone so the code may not be perfect.

Body:
not sure if my title explains well the issue im having.

In my application i make a service calls to
-retrieve a list of customers.
-retrieve a list of organisations.

Then i bind this list of customers to a listbox on my view.

In my viewmodel i have the following properties:

IEnumerable<Organisation> Organisations
ObservableCollection<Customer> Customers

Organisation properties: OrganisationId, OrganisationName

Customer properties: CustomerId, OrganisationId, CustomerFirstName, CustomerLastName

Inside the Listbox on my view i want to show the organisationname for each customer in the list.

how can i go about binding this in my view? I just want a textblock to show the organisationname for the customer.

Body:
Bind the Listbox to a Linq query exposed from your ViewModel.

Public IEnumerable ItemsView
{
get {
return
    {
    from customer in this.Customers
    from org in this.Organisations
    where customer.OrganisationId=org.OrganisationId
    select new { FirstName=customer.FirstName, LastName=customer.LastName, OrganisationName=org.OrganisationName}

};
}

Then just bind the listbox in Ritch's answer to this.

PS. I'm writing this on my phone so the code may not be perfect.


问:
How to make selenium open https page, which displayed manually and not displayed while automated run?
Browsing with chrome to web site with htpps connection manually is available and display the site.
Browsing same site by selenium automated test, doesn't display the page, display empty page.
If i load chrome user profile, automation do open the required page.
Other https site (QA) does displayed through automated connection, the problem is with production sites.
Is there any setting can be added to selenium to open the page?</p>

答:
```<code> try this if works
            HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
            chromePrefs.put("profile.default_content_settings.popups", 0);
            chromePrefs.put("download.default_directory", downloadFilepath);
            ChromeOptions options = new ChromeOptions();
            options.setExperimentalOption("prefs", chromePrefs);
            options.addArguments("--start-maximized");
            options.setExperimentalOption("useAutomationExtension", false);
            options.addArguments("disable-infobars");
            DesiredCapabilities cap = DesiredCapabilities.chrome();
            cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
            cap.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR,
            UnexpectedAlertBehaviour.ACCEPT);
            cap.setCapability(ChromeOptions.CAPABILITY, options);
            driver.set(new ChromeDriver(cap));
</code>```


问:
Get Max of len(string) in nested dictionary if string can be None
I'm trying to get the max length of a string from a nested dictionary. The field can be a string or None.

When doing this with a list from a nested dictionary, the following works:

max_value = max(dict, key=lambda d: len(dict[d]["list_key"]))

When I run this on the string field, code is:

max_value = max(dict, key=lambda d: len(dict[d]["string_key"]))

because the string can be None, I receive the following error:

TypeError: object of type 'NoneType' has no len()

How can I incorporate is not None into the second function?

答:
please do not use python built-in class/type to name your variables, instead of using dict you can use my_dict:

```<code>max_value = max(my_dict, key=lambda k: len(my_dict[k]["string_key"] or ''))
</code>```

Body:
please do not use python built-in class/type to name your variables, instead of using dict you can use my_dict:

max_value = max(my_dict, key=lambda k: len(my_dict[k]["string_key"] or ''))


问:
Why does Dplyr group_by not respect .drop=FALSE
I have a very simple data count problem where I am grouping by two fields (MktDate,Indexname) which are date and chr types respectively. I have a few indexes with no data on certain dates and all I'm looking for my code to do is to include a 0 on those dates. I have tried a number of different solutions following dplyr's group_by documentation but I can not get this short piece of code to return a value of 0 when no data is present. Here is my code</p>

```<code>IdxStats <- IdxData %>%
  group_by(MktDate,IndexName,.drop=FALSE) %>%
  summarize(CountSecurity = length(MktDate)) %>%
  ungroup
</code>```

答:
The .drop is correct, but when you use length, the data.frame doesn't exist at all, so length is it, will be weird. Try this below:

```<code>set.seed(100)
IdxData = data.frame(MktDate=sample(1:3,10,replace=TRUE),
                     IndexName=sample(LETTERS[1:3],10,replace=TRUE))

IdxData %>% count(MktDate,IndexName,.drop=FALSE)
# A tibble: 9 x 3
  MktDate IndexName     n
    <int> <fct>     <int>
1       1 A             0
2       1 B             0
3       1 C             1
4       2 A             1
5       2 B             1
6       2 C             4
7       3 A             0
8       3 B             2
9       3 C             1
</code>```

Or if you need the name "CountSecurity" (thanks to @arg0naut91 ) :

```<code>IdxData %>%
count(MktDate,IndexName,.drop=FALSE,name="CountSecurity")
</code>```

Body:
I have a very simple data count problem where I am grouping by two fields (MktDate,Indexname) which are date and chr types respectively. I have a few indexes with no data on certain dates and all I'm looking for my code to do is to include a 0 on those dates. I have tried a number of different solutions following dplyr's group_by documentation but I can not get this short piece of code to return a value of 0 when no data is present. Here is my code

IdxStats <- IdxData %>%
  group_by(MktDate,IndexName,.drop=FALSE) %>%
  summarize(CountSecurity = length(MktDate)) %>%
  ungroup

Body:
The .drop is correct, but when you use length, the data.frame doesn't exist at all, so length is it, will be weird. Try this below:

set.seed(100)
IdxData = data.frame(MktDate=sample(1:3,10,replace=TRUE),
                     IndexName=sample(LETTERS[1:3],10,replace=TRUE))

IdxData %>% count(MktDate,IndexName,.drop=FALSE)
# A tibble: 9 x 3
  MktDate IndexName     n
    <int> <fct>     <int>
1       1 A             0
2       1 B             0
3       1 C             1
4       2 A             1
5       2 B             1
6       2 C             4
7       3 A             0
8       3 B             2
9       3 C             1

Or if you need the name "CountSecurity" (thanks to @arg0naut91 ) :

IdxData %>%
count(MktDate,IndexName,.drop=FALSE,name="CountSecurity")


问:
Django Form: Only show manytomany objects from logged in user
The current problem is that my form shows the logged in user all Portfolios ever created. The form should only show portfolios that the logged-in user created.

Something like this:

```<code>associated_portfolios manytomany field = ...objects.filter(user=user_id)
</code>```

I'm not sure if this should be implemented in the forms.py or views.py and if so how. I've been going through the django documentation and found 'formfield_for_manytomany' but not sure if this is only meant for admin.

Models.py

```<code>class Portfolio(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=20)
    description = models.CharField(max_length=250, blank=True, null=True)

class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=50)
    body = RichTextUploadingField(blank=True, null=True)
    associated_portfolios = models.ManyToManyField(Portfolio, blank=True)
    created_on = models.DateField(auto_now_add=True, editable=False)
</code>```

Views.py

```<code>class PostCreate(CreateView):
    model = Post
    form_class = PostCreateForm

    def formfield_for_manytomany(self, db_field, request, **kwargs):
        self.fields['associated_portfolios'] = Portfolio.objects.filter(user=self.request.user)
        return super().formfield_for_manytomany(db_field, request, using=self.using, **kwargs)
</code>```

forms.py

```<code>class PortfolioCreateForm(ModelForm):
    class Meta:
        model = Portfolio
        fields = ['user', 'name', 'description']

class PostCreateForm(ModelForm):
    class Meta:
        model = Post
        fields = ['user', 'title', 'body', 'category', 'associated_portfolios']
</code>```

答:
Since you're using a ModelForm, the associated_protfolios field will be a ModelMultipleChoiceField [docs]. This field has a queryset attribute [docs]. We want to modify that attribute.

Django's CreateView has a method get_form, which in this case will grab your PostCreateForm. This is a good spot to filter the field's queryset, since we have access to the user:

class PostCreate(CreateView):
    model = Post
    form_class = PostCreateForm

    def get_form(self, *args, **kwargs):
        form = super().get_form(*args, **kwargs)  # Get the form as usual
        user = self.request.user
        form.fileds['associated_portfolios'].queryset = Portfolio.objects.filter(user=user)
        return form
```

Body:
The current problem is that my form shows the logged in user all Portfolios ever created. The form should only show portfolios that the logged-in user created.

Something like this:

associated_portfolios manytomany field = ...objects.filter(user=user_id)

I'm not sure if this should be implemented in the forms.py or views.py and if so how. I've been going through the django documentation and found 'formfield_for_manytomany' but not sure if this is only meant for admin.

Models.py

class Portfolio(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=20)
    description = models.CharField(max_length=250, blank=True, null=True)

class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=50)
    body = RichTextUploadingField(blank=True, null=True)
    associated_portfolios = models.ManyToManyField(Portfolio, blank=True)
    created_on = models.DateField(auto_now_add=True, editable=False)

Views.py

class PostCreate(CreateView):
    model = Post
    form_class = PostCreateForm

    def formfield_for_manytomany(self, db_field, request, **kwargs):
        self.fields['associated_portfolios'] = Portfolio.objects.filter(user=self.request.user)
        return super().formfield_for_manytomany(db_field, request, using=self.using, **kwargs)

forms.py

class PortfolioCreateForm(ModelForm):
    class Meta:
        model = Portfolio
        fields = ['user', 'name', 'description']

class PostCreateForm(ModelForm):
    class Meta:
        model = Post
        fields = ['user', 'title', 'body', 'category', 'associated_portfolios']


问:
"is not a function" jQuery
I have a little problem with jQuery. I just want to remove and add class on my "li" but it said to me "is not a function". Here my code :

```<code>$(document).ready(function (){
    var title = $('title')
    var nav = $('.nav-a')

    for ($i = 0 ; $i<nav.length ; $i++)
    {
       if (title[0].text === nav[$i].text){
        var newTitle = title[0].text
        var newNav = nav[$i].text
        var navI = nav[$i].parentElement
        console.log(newTitle)
        console.log(newNav)
        console.log(navI)

        nav.parent().removeClass('menu-active')
        navI.addClass('menu-active')
       }
    }
  })
</code>```

In console I have : Uncaught TypeError: navI.addClass is not a function

答:
The issue is because you're calling native Element object methods on jQuery objects and vice versa.

To fix this stick with one or the other. As such, here's a simplified jQuery example, which uses filter() to match elements by their text instead of an explicit loop.

jQuery(function($) {
  var title = $('title').text();
  var nav = $('.nav-a').filter(function() {
    return $(this).text().trim() === title;
  }).parent().addClass('menu-active');
})
```

Title: "is not a function" jQuery

Body:
I have a little problem with jQuery. I just want to remove and add class on my "li" but it said to me "is not a function". Here my code :

$(document).ready(function (){
    var title = $('title')
    var nav = $('.nav-a')

    for ($i = 0 ; $i<nav.length ; $i++)
    {
       if (title[0].text === nav[$i].text){
        var newTitle = title[0].text
        var newNav = nav[$i].text
        var navI = nav[$i].parentElement
        console.log(newTitle)
        console.log(newNav)
        console.log(navI)

        nav.parent().removeClass('menu-active')
        navI.addClass('menu-active')
       }
    }
  })

In console I have : Uncaught TypeError: navI.addClass is not a function


问:
Serilog Timestamp @t is not in UTC time
I'm coding in C# and I have a log file generated with Serilog, written to a file and formatted in Json with CompactJsonFormatter.
The problem is that the time is not set to the correct timezone, it is in UTC+0.
Is there a method to set the correct timezone for the timestamp? P.S. TimeWrap is deprecated

Example row generated in the log file:

```<code>{"@t":"2020-02-19T13:34:55.6398202Z","@mt":"Stringa random {stringToLog}","stringToLog":"this"}
</code>```

This is the method i'm using to generate the log:

答:
At the moment it is not possible to change how the timestamp is converted to string using the existing CompactJsonFormatter... It's hard-coded to always get the UtcDateTime and then convert it to string.

If you want to change this, you'll have to implement your own version of the CompactJsonFormatter by creating your own class that implements ITextFormatter and tell Serilog to use that instead.

You can copy the code of the CompactJsonFormatter to your codebase and modify it to suit your needs.

Then you just switch to your custom formatter instead of using the default one:

```<code>var logger = new LoggerConfiguration()
    .WriteTo.File(new YourCompactJsonFormatter(), "App.log")
    .CreateLogger();
</code>```

Title: Serilog Timestamp @t is not in UTC time

Body:
I'm coding in C# and I have a log file generated with Serilog, written to a file and formatted in Json with CompactJsonFormatter.
The problem is that the time is not set to the correct timezone, it is in UTC+0.
Is there a method to set the correct timezone for the timestamp? P.S. TimeWrap is deprecated

Example row generated in the log file:

{"@t":"2020-02-19T13:34:55.6398202Z","@mt":"Stringa random {stringToLog}","stringToLog":"this"}

This is the method i'm using to generate the log:

Body:
At the moment it is not possible to change how the timestamp is converted to string using the existing CompactJsonFormatter... It's hard-coded to always get the UtcDateTime and then convert it to string.

If you want to change this, you'll have to implement your own version of the CompactJsonFormatter by creating your own class that implements ITextFormatter and tell Serilog to use that instead.

You can copy the code of the CompactJsonFormatter to your codebase and modify it to suit your needs.

Then you just switch to your custom formatter instead of using the default one:

var logger = new LoggerConfiguration()
    .WriteTo.File(new YourCompactJsonFormatter(), "App.log")
    .CreateLogger();


问:
Indexing View on Aggregate Field
I am just wondering if there is any way to create index on agregate field?

```<code>CREATE TABLE test2 (
id INTEGER,
name VARCHAR(10),
family VARCHAR(10),
amount INTEGER)

CREATE VIEW dbo.test2_v WITH SCHEMABINDING
AS
SELECT id, SUM(amount) as amount, COUNT_BIG(*) as tmp
FROM dbo.test2
GROUP BY id

CREATE UNIQUE CLUSTERED INDEX vIdx ON test2_v(amount)
</code>```

I have next error message with this code:

Cannot create the clustered index
  "vIdx" on view "test.dbo.test2_v"
  because the index key includes columns
  that are not in the GROUP BY clause.
  Consider eliminating columns that are
  not in the GROUP BY clause from the
  index key.

答:
Your index needs to include ID most likely. Amount won't be unique enough either

As per the error message

...the index key includes columns that are not in the GROUP BY clause....

Title: Indexing View on Aggregate Field

Body:
I am just wondering if there is any way to create index on agregate field?

CREATE TABLE test2 (
id INTEGER,
name VARCHAR(10),
family VARCHAR(10),
amount INTEGER)

CREATE VIEW dbo.test2_v WITH SCHEMABINDING
AS
SELECT id, SUM(amount) as amount, COUNT_BIG(*) as tmp
FROM dbo.test2
GROUP BY id

CREATE UNIQUE CLUSTERED INDEX vIdx ON test2_v(amount)

I have next error message with this code:

Cannot create the clustered index
  "vIdx" on view "test.dbo.test2_v"
  because the index key includes columns
  that are not in the GROUP BY clause.
  Consider eliminating columns that are
  not in the GROUP BY clause from the
  index key.


问:
Referencing Text Content Controls
I am trying to reference and paste a specified string into a specific Text Content Controls and have been unable to do this properly.

Basically I have gone through and tried a few different things,  first being this;

```<code>Private Sub Document_ContentControlOnExit(ByVal ContentControl As ContentControl, Cancel As Boolean)

Dim ccs As ContentControls, cc As ContentControl
Set ccs = ActiveDocument.ContentControls
For Each cc In ccs
  If cc.Title = "ComboBox1" And cc.Range.Text = "Choose an item." Then
  SelectContentControlsByTitle("TextBox1").Add.SetPlaceholderText , , "Please make a drop down selection or manually fill out if not applicable"
</code>```

The above does not work, as every time I exit my content controller combo box it actually recreates the "placeholdertext" multiple times. I need this to only fill the "TextBox1" Content control.

I have also tried doing something like this,

```<code>Dim ccs As ContentControls, cc As ContentControl
Set ccs = ActiveDocument.ContentControls
Set CB1 = SelectContentControlsByTitle("TextBox1")
For Each cc In ccs
  If cc.Title = "ComboBox1" And cc.Range.Text = "Choose an item." Then
  CB1.Value = "Please make a drop down selection or manually fill out if not applicable"
</code>```

Due to the type, value is not able to be used like this. This does not work either.

Below is the original way I was doing what I wanted with the Active-X TextBox which does work;

```<code>Private Sub Document_ContentControlOnExit(ByVal ContentControl As ContentControl, Cancel As Boolean)

Dim ccs As ContentControls, cc As ContentControl
Set ccs = ActiveDocument.ContentControls
For Each cc In ccs
  If cc.Title = "ComboBox2" And cc.Range.Text = "Choose an item." Then
  TextBox2.Value = "Please make a drop down selection or manually fill out if not applicable"

  ElseIf cc.Title = "ComboBox2" And cc.Range.Text = "TMS backup" Then
  TextBox2.Value = "The TMS installation directory, settings directory and the database was backed up before the update was performed"

  ElseIf cc.Title = "ComboBox2" And cc.Range.Text = "TMS installation" Then
  TextBox2.Value = "Installation of version 1.17.X.19XXX performed"

  ElseIf cc.Title = "ComboBox2" And cc.Range.Text = "TMS update" Then
  TextBox2.Value = "Update from version 1.16.X.XXXXX to version 1.17.X.19XXX performed"

  ElseIf cc.Title = "ComboBox2" And cc.Range.Text = "Tool presetter update" Then
  TextBox2.Value = "Update from version 1.16.X.XXXXX to version 1.17.X.19XXX performed"

  ElseIf cc.Title = "ComboBox2" And cc.Range.Text = "Database generated" Then
  TextBox2.Value = "Database structure created with version 1.17.0"
</code>```

How can I do the above, while using the Text Content Controls?

答:
Try this for setting the text box text:</p>

```<code>Sub SetContentcontrolText()
    Dim oRange As Range
    Dim cc As ContentControl
    For Each cc In ActiveDocument.ContentControls
        If cc.Title = "ComboBox1" And cc.Range.Text = "Choose an item." Then
            Set oRange = ActiveDocument.SelectContentControlsByTitle("TextBox1")(1).Range
            oRange.Text = "Please make a drop down selection or manually fill out if not applicable"
        End If
    Next
End Sub
</code>```

Title: Referencing Text Content Controls

Body:
I am trying to reference and paste a specified string into a specific Text Content Controls and have been unable to do this properly.

Basically I have gone through and tried a few different things,  first being this;

Private Sub Document_ContentControlOnExit(ByVal ContentControl As ContentControl, Cancel As Boolean)

Dim ccs As ContentControls, cc As ContentControl
Set ccs = ActiveDocument.ContentControls
For Each cc In ccs
  If cc.Title = "ComboBox1" And cc.Range.Text = "Choose an item." Then
  SelectContentControlsByTitle("TextBox1").Add.SetPlaceholderText , , "Please make a drop down selection or manually fill out if not applicable"

The above does not work, as every time I exit my content controller combo box it actually recreates the "placeholdertext" multiple times. I need this to only fill the "TextBox1" Content control.

I have also tried doing something like this,

Dim ccs As ContentControls, cc As ContentControl
Set ccs = ActiveDocument.ContentControls
Set CB1 = SelectContentControlsByTitle("TextBox1")
For Each cc In ccs
  If cc.Title = "ComboBox1" And cc.Range.Text = "Choose an item." Then
  CB1.Value = "Please make a drop down selection or manually fill out if not applicable"

Due to the type, value is not able to be used like this. This does not work either.

Below is the original way I was doing what I wanted with the Active-X TextBox which does work;

Private Sub Document_ContentControlOnExit(ByVal ContentControl As ContentControl, Cancel As Boolean)

Dim ccs As ContentControls, cc As ContentControl
Set ccs = ActiveDocument.ContentControls
For Each cc In ccs
  If cc.Title = "ComboBox2" And cc.Range.Text = "Choose an item." Then
  TextBox2.Value = "Please make a drop down selection or manually fill out if not applicable"

  ElseIf cc.Title = "ComboBox2" And cc.Range.Text = "TMS backup" Then
  TextBox2.Value = "The TMS installation directory, settings directory and the database was backed up before the update was performed"

  ElseIf cc.Title = "ComboBox2" And cc.Range.Text = "TMS installation" Then
  TextBox2.Value = "Installation of version 1.17.X.19XXX performed"

  ElseIf cc.Title = "ComboBox2" And cc.Range.Text = "TMS update" Then
  TextBox2.Value = "Update from version 1.16.X.XXXXX to version 1.17.X.19XXX performed"

  ElseIf cc.Title = "ComboBox2" And cc.Range.Text = "Tool presetter update" Then
  TextBox2.Value = "Update from version 1.16.X.XXXXX to version 1.17.X.19XXX performed"

  ElseIf cc.Title = "ComboBox2" And cc.Range.Text = "Database generated" Then
  TextBox2.Value = "Database structure created with version 1.17.0"

How can I do the above, while using the Text Content Controls?

Body:
Try this for setting the text box text:

Sub SetContentcontrolText()
    Dim oRange As Range
    Dim cc As ContentControl
    For Each cc In ActiveDocument.ContentControls
        If cc.Title = "ComboBox1" And cc.Range.Text = "Choose an item." Then
            Set oRange = ActiveDocument.SelectContentControlsByTitle("TextBox1")(1).Range
            oRange.Text = "Please make a drop down selection or manually fill out if not applicable"
        End If
    Next
End Sub


问:
ForEach Loop Iterates Twice Instead Of Once - Powershell
Once again I have broken a foreach loop and cannot figure out why. It appears to iterate twice instead of once for some of the accounts. I think I have my {} in the correct format but apparently not.  Can anyone help me find what I'm missing?

Relevant Code:

```<code>foreach ($OU in $OUs) {

    # Search for User and/or Computer Objects inactive for XX days.  Disable object if not in DoNotDisable Security Groups
    $days = $days + "D"
    $accounts = Search-ADAccount -SearchBase $OU.DistinguishedName -AccountInactive -TimeSpan ([timespan]7D) @scope
    foreach($account in $accounts){
        If ($noDisable -notcontains $account.Name) {
            Write-Host $account
    #        #Disable-ADAccount -Identity $account.DistinguishedName -Verbose $whatIf | Export-Csv $logFile
       }
    }
}
</code>```

Output:  Each computer account is listed twice except the last 2.

答:
If your directory tree looks like this:

```<code>NC root
 |- TopLevelOU
     |- SubOU
     |   |- Computer1
     |   |- Computer2
     |- Computer3
     |- Computer4
</code>```

... and you start by querying for all OUs, and then search (recursively) through each one, you're going to get every object under SubOU twice - once from searching through the TopLevelOU, and once more from searching directly against SubOU.

Add -SearchScope OneLevel to your Search-ADAccount invocation if you want to contain each search to the immediate children of the target OU:

```<code>$accounts = Search-ADAccount -SearchBase $OU.DistinguishedName -SearchScope OneLevel -AccountInactive -TimeSpan ([timespan]7D) @scope
</code>```

Body:
Once again I have broken a foreach loop and cannot figure out why. It appears to iterate twice instead of once for some of the accounts. I think I have my {} in the correct format but apparently not.  Can anyone help me find what I'm missing?

Relevant Code:

foreach ($OU in $OUs) {

    # Search for User and/or Computer Objects inactive for XX days.  Disable object if not in DoNotDisable Security Groups
    $days = $days + "D"
    $accounts = Search-ADAccount -SearchBase $OU.DistinguishedName -AccountInactive -TimeSpan ([timespan]7D) @scope
    foreach($account in $accounts){
        If ($noDisable -notcontains $account.Name) {
            Write-Host $account
    #        #Disable-ADAccount -Identity $account.DistinguishedName -Verbose $whatIf | Export-Csv $logFile
       }
    }
}

Output:  Each computer account is listed twice except the last 2.

Body:
If your directory tree looks like this:

NC root
 |- TopLevelOU
     |- SubOU
     |   |- Computer1
     |   |- Computer2
     |- Computer3
     |- Computer4

... and you start by querying for all OUs, and then search (recursively) through each one, you're going to get every object under SubOU twice - once from searching through the TopLevelOU, and once more from searching directly against SubOU.

Add -SearchScope OneLevel to your Search-ADAccount invocation if you want to contain each search to the immediate children of the target OU:

$accounts = Search-ADAccount -SearchBase $OU.DistinguishedName -SearchScope OneLevel -AccountInactive -TimeSpan ([timespan]7D) @scope


问:
How do you programmatically change limit data expression in Spotfire JS Viz
I have the code below, which takes a string from a text area and adds it to the limit data expression of a Spotfire visualisation.  However when I try and run the code against a JS visualisation, I get the following error:

AttributeError: 'NoneType' object has no attribute 'Data'

When running the same code on a Spotfire (native) visualization, it works fine with no issues. What do I need to change in the code to have the equivalent of limit data by expression box for a js viz?

```<code>from Spotfire.Dxp.Application.Visuals import *
from Spotfire.Dxp.Data import *

for vis in Document.ActivePageReference.Visuals:
    if vis.Title == 'Chart wizard area':
        ta= vis.As[HtmlTextArea]().HtmlContent

print ta

for vis1 in Application.Document.ActivePageReference.Visuals:
    if vis1.Title == 'chart viz': #if statement for testing
        print 'hello'
        visual = vis.As[Visualization]()
        visual.Data.WhereClauseExpression = ta
</code>```

答:
This is not possible

With IronPython you can only edit Spotfire objects. Js viz is a javascript object and thus it is unaccessible from IronPython.

Body:
I have the code below, which takes a string from a text area and adds it to the limit data expression of a Spotfire visualisation.  However when I try and run the code against a JS visualisation, I get the following error:

AttributeError: 'NoneType' object has no attribute 'Data'

When running the same code on a Spotfire (native) visualization, it works fine with no issues. What do I need to change in the code to have the equivalent of limit data by expression box for a js viz?

from Spotfire.Dxp.Application.Visuals import *
from Spotfire.Dxp.Data import *

for vis in Document.ActivePageReference.Visuals:
    if vis.Title == 'Chart wizard area':
        ta= vis.As[HtmlTextArea]().HtmlContent

print ta

for vis1 in Application.Document.ActivePageReference.Visuals:
    if vis1.Title == 'chart viz': #if statement for testing
        print 'hello'
        visual = vis.As[Visualization]()
        visual.Data.WhereClauseExpression = ta


问:
Is there any tool to profile each layer of a DNN in Pytorch and Tensorflow?
I want to know the execution time of each layer of a DNN.
Is there any tool can profile each layer?
I know I can insert some print in a model, but I am not sure it will be accurate.</p>

答:
To check the size and parameters of each layer you can use the torch summary.

To compute time the execution time of each layer, you can use the torchprof.

I don't know any project that merges both libs. Maybe it's your opportunity (lol)


问:
Storage/File delete methods don't delete the file from storage
I am uploading images to storage/uploads and have a queue job that uploads those images to AWS. Here is the code of the job:

```<code>$path = storage_path() . '/uploads/' . $this->fileId;
$fileName = $this->fileId . '.png';

if (Storage::disk('s3images')->put('profile/' . $fileName, fopen($path, 'r+'))) {
   File::delete($path);
}
</code>```

Once the image has been uploaded to AWS the job is supposed to delete the image from storage/uploads but it's not doing that. The images are successfully uploaded to AWS. I tried to delete specific files directly without the if-statement but nothing seems to work. I even tried with Storage::delete but that didn't work either. Could someone point me in the right direction please?

答:
You may use

```<code>Storage::delete('upload/profile/' . $fileName);
</code>```

See Documentation

Body:
I am uploading images to storage/uploads and have a queue job that uploads those images to AWS. Here is the code of the job:

$path = storage_path() . '/uploads/' . $this->fileId;
$fileName = $this->fileId . '.png';

if (Storage::disk('s3images')->put('profile/' . $fileName, fopen($path, 'r+'))) {
   File::delete($path);
}

Once the image has been uploaded to AWS the job is supposed to delete the image from storage/uploads but it's not doing that. The images are successfully uploaded to AWS. I tried to delete specific files directly without the if-statement but nothing seems to work. I even tried with Storage::delete but that didn't work either. Could someone point me in the right direction please?

Body:
You may use

Storage::delete('upload/profile/' . $fileName);

See Documentation


问:
Using duplicate parameters in a URL
We are building an API in-house and often are passing a parameter with multiple values.

They use: mysite.com?id=1&id=2&id=3

Instead of: mysite.com?id=1,2,3

I favor the second approach but I was curious if it was actually incorrect to do the first?

答:
I guess it depends on technology you use, how it becomes convenient. I am currently standing in front of the same question using currency=USD,CHF or currency=USD&currency=CHF

I am using Thymeleaf and using the second option makes it easy to work, I can then request something like: ${param.currency.contains(currency.value)}. When I try to use the first option it seems it takes the "array" like a string, so I need to split first and then do contain, what leads me to a more mess code.

Just my 50 cents :-)

Title: Using duplicate parameters in a URL


问:
Send a mail using Javascript without going through Outlook
Is it possible to Send a mail using Javascript without going through Outlook</p>

答: Impossible. You can't send a mail using JavaScript without user intervertion.</p>


问:
Including default substitutions inside other `substitutions`
From here... https://cloud.google.com/cloud-build/docs/configuring-builds/substitute-variable-values

I am trying to use substitutions inside my cloudbuild.yaml file but almost all my substitutions depend on the project ID of the project I am deploying to.

I have my yaml file like this...

```<code>steps:
- name: 'gcr.io/cloud-builders/gcloud'
  args: ['functions', 'deploy', 'functionName', ...other args... , '--service-account', '${_SERVICE_ACCOUNT}', '--source', '${_SOURCE_REPO}']
substitutions:
  _SOURCE_REPO: 'https://source.developers.google.com/projects/$PROJECT_ID/repos/my-repo-id/moveable-aliases/master/paths/functions/src'
  _SERVICE_ACCOUNT: 'blah@${PROJECT_ID}.iam.gserviceaccount.com'
</code>```

And whatever I try with the substitutions (I have tried both formats $_FOO and ${_FOO}) and what I end up with is blah@${PROJECT_ID}.iam.gserviceaccount.com with the ${PROJECT_ID} text still in there rather than it having the actual project ID.

If I move the text into the step and just use it instead of the substitution then it works. But ideally I'd like to use this method as these values will be used a lot so would like to save repetition.

EDIT

Well, I've tried a few different options including some of the suggestions that @ralemos mentioned but nothing seems to be working.

If I use this format...

```<code>steps:
  - name: 'gcr.io/cloud-builders/gcloud'
    args: ['functions', 'deploy', 'functionName', ...other args... , '--service-account', '${SERVICE_ACCOUNT}', '--source', '${SOURCE_REPO}']
options:
  env:
    SOURCE_REPO: 'https://source.developers.google.com/projects/${PROJECT_ID}/repos/my-repo-id/moveable-aliases/master/paths/functions/src'
    SERVICE_ACCOUNT: 'blah@${PROJECT_ID}.iam.gserviceaccount.com
</code>```

It complains that the env lines are invalid.

If I use this format...

```<code>steps:
  - name: 'gcr.io/cloud-builders/gcloud'
    args: ['functions', 'deploy', 'functionName', ...other args... , '--service-account', '${SERVICE_ACCOUNT}', '--source', '${SOURCE_REPO}']
options:
  env:
    'SOURCE_REPO=https://source.developers.google.com/projects/${PROJECT_ID}/repos/my-repo-id/moveable-aliases/master/paths/functions/src'
    'SERVICE_ACCOUNT=blah@${PROJECT_ID}.iam.gserviceaccount.com
</code>```

It complains that SERVICE_ACCOUNT and SOURCE_REPO are not valid built-in substitutions.

If I use $$SOURCE_REPO as the syntax it just replaces it with $SOURCE_REPO rather than using the substitution.

It seems for now that what I'm trying just isn't possible.

答:
You could use env variables instead of substitutions, as you can see on the answer of this community post.

The result would be something like this:

```<code>steps:
  - name: 'gcr.io/cloud-builders/gcloud'
    args: ['functions', 'deploy', 'functionName', ...other args... , '--service-account', '${SERVICE_ACCOUNT}', '--source', '${SOURCE_REPO}']
options:
  env:
    SOURCE_REPO: 'https://source.developers.google.com/projects/${PROJECT_ID}/repos/my-repo-id/moveable-aliases/master/paths/functions/src'
    SERVICE_ACCOUNT: 'blah@${PROJECT_ID}.iam.gserviceaccount.com
</code>```

Body:
From here... https://cloud.google.com/cloud-build/docs/configuring-builds/substitute-variable-values

I am trying to use substitutions inside my cloudbuild.yaml file but almost all my substitutions depend on the project ID of the project I am deploying to.

I have my yaml file like this...

steps:
- name: 'gcr.io/cloud-builders/gcloud'
  args: ['functions', 'deploy', 'functionName', ...other args... , '--service-account', '${_SERVICE_ACCOUNT}', '--source', '${_SOURCE_REPO}']
substitutions:
  _SOURCE_REPO: 'https://source.developers.google.com/projects/$PROJECT_ID/repos/my-repo-id/moveable-aliases/master/paths/functions/src'
  _SERVICE_ACCOUNT: 'blah@${PROJECT_ID}.iam.gserviceaccount.com'

And whatever I try with the substitutions (I have tried both formats $_FOO and ${_FOO}) and what I end up with is blah@${PROJECT_ID}.iam.gserviceaccount.com with the ${PROJECT_ID} text still in there rather than it having the actual project ID.

If I move the text into the step and just use it instead of the substitution then it works. But ideally I'd like to use this method as these values will be used a lot so would like to save repetition.

EDIT

Well, I've tried a few different options including some of the suggestions that @ralemos mentioned but nothing seems to be working.

If I use this format...

steps:
  - name: 'gcr.io/cloud-builders/gcloud'
    args: ['functions', 'deploy', 'functionName', ...other args... , '--service-account', '${SERVICE_ACCOUNT}', '--source', '${SOURCE_REPO}']
options:
  env:
    SOURCE_REPO: 'https://source.developers.google.com/projects/${PROJECT_ID}/repos/my-repo-id/moveable-aliases/master/paths/functions/src'
    SERVICE_ACCOUNT: 'blah@${PROJECT_ID}.iam.gserviceaccount.com

It complains that the env lines are invalid.

If I use this format...

steps:
  - name: 'gcr.io/cloud-builders/gcloud'
    args: ['functions', 'deploy', 'functionName', ...other args... , '--service-account', '${SERVICE_ACCOUNT}', '--source', '${SOURCE_REPO}']
options:
  env:
    'SOURCE_REPO=https://source.developers.google.com/projects/${PROJECT_ID}/repos/my-repo-id/moveable-aliases/master/paths/functions/src'
    'SERVICE_ACCOUNT=blah@${PROJECT_ID}.iam.gserviceaccount.com

It complains that SERVICE_ACCOUNT and SOURCE_REPO are not valid built-in substitutions.

If I use $$SOURCE_REPO as the syntax it just replaces it with $SOURCE_REPO rather than using the substitution.

It seems for now that what I'm trying just isn't possible.

Body:
You could use env variables instead of substitutions, as you can see on the answer of this community post.

The result would be something like this:

steps:
  - name: 'gcr.io/cloud-builders/gcloud'
    args: ['functions', 'deploy', 'functionName', ...other args... , '--service-account', '${SERVICE_ACCOUNT}', '--source', '${SOURCE_REPO}']
options:
  env:
    SOURCE_REPO: 'https://source.developers.google.com/projects/${PROJECT_ID}/repos/my-repo-id/moveable-aliases/master/paths/functions/src'
    SERVICE_ACCOUNT: 'blah@${PROJECT_ID}.iam.gserviceaccount.com


问:
Find how many numbers that are perfect squares and the sqrt() is a prime number in a L, R range
First off all, feel free to improve the formatting of the question

This question is already solved by Goswin von Brederlow!

Hello, i'm praticing programming and this problem came across and i don't know how is the best way to solve this:

The question have T test cases that consists in:

Given a range L and R, find how many numbers meet the constraints:

i) Number is a perfect square;

ii) The sqrt(Number) is a prime number.

Limits:

1 <= T <= 1e4

1 <= L, R <= 1e12

Time limit: 1 second

So, i tried it with a simple idea of pre-processing with an unodered_map(lld, bool) all the answers with the sieve of eratosthenes for each sqrt(Number) given that Number is a perfect square

After, I pass in range pow(sqrt(l), 2) and increments it the next odd number... like: 4 9 16 25, the difference are odd numbers: 5 7 9...

My code:

```<code>long long int l, r; scanf("%lld %lld", &l, &r);
long long int odd = ceil(sqrt(l)), n = odd*odd;
odd = (2*odd) + 1;
long long int ans = 0;
while((n >= l && n <= r)){
    it = h.find(n);
    ans = ans + it->second;
    n = n + odd;
    odd = odd + 2;
}
</code>```

But a i still got TLE, i need some help guys, thank you!

答:
The only question I see I infer from  "i don't know how is the best way to solve this".

Your way seems to be pretty smart already. You have some bugs even in just the bit of code you pasted. You seem to compute the sum of the numbers instead of counting them.

One thing I could think of improving is the counting itself. Looks like you have a hash table of all the squares of primes and you simply test all auqares if they are in the table.

Why not make a balanced tree out of the primes? In each node you store the minimum and maximum number and the count for the subtree. The leaves would be (n, n, 1) where n is one of the squares of primes. Given L and R you can then go through the tree and sum up all subtrees that are in the interval and recurse into subtrees that are only partially inside. Ignore everything outside. That should add a logarithmic factor to your complexity.

Body:
First off all, feel free to improve the formatting of the question

This question is already solved by Goswin von Brederlow!

Hello, i'm praticing programming and this problem came across and i don't know how is the best way to solve this:

The question have T test cases that consists in:

Given a range L and R, find how many numbers meet the constraints:

i) Number is a perfect square;

ii) The sqrt(Number) is a prime number.

Limits:

1 <= T <= 1e4

1 <= L, R <= 1e12

Time limit: 1 second

So, i tried it with a simple idea of pre-processing with an unodered_map(lld, bool) all the answers with the sieve of eratosthenes for each sqrt(Number) given that Number is a perfect square

After, I pass in range pow(sqrt(l), 2) and increments it the next odd number... like: 4 9 16 25, the difference are odd numbers: 5 7 9...

My code:

long long int l, r; scanf("%lld %lld", &l, &r);
long long int odd = ceil(sqrt(l)), n = odd*odd;
odd = (2*odd) + 1;
long long int ans = 0;
while((n >= l && n <= r)){
    it = h.find(n);
    ans = ans + it->second;
    n = n + odd;
    odd = odd + 2;
}

But a i still got TLE, i need some help guys, thank you!


问:
How can I find the mistake in ASP.net SQL insert query?
hello iam making insert in a table using asp.net this my code below  ,i got this error System.Data.SqlClient.SqlException: 'Incorrect syntax near ','.'  can any body help me to figure out the problem                                                                                </p>

```<code>protected void ButtonSave_Click(object sender, EventArgs e)
       {

           SqlConnection con = new SqlConnection("Data Source=LAPTOP-U11A4VS6;Initial Catalog=Task;Integrated Security=True");
           con.Open();
           //SqlCommand cmd = new SqlCommand("Invoice_Product", con);
           //cmd.CommandType = CommandType.StoredProcedure;

           SqlCommand cmd = new SqlCommand("insert into [Invoice_Product] (" + Convert.ToInt32(TextBoxInvoice.Text)
             + "','"+Convert.ToInt32(TextBoxInvoice.Text)+"','"+"'"+TextBoxDate.Text+"'"
             + "','"+"'"+DropDownList1.SelectedItem.Text+"'"
             +"','"+"'"+DropDownList2.SelectedItem.Text+"'"+"','"+Convert.ToDouble(LabelPrice1.Text)
             + "','"+Convert.ToInt32(TextBoxQty.Text)+"','"+Convert.ToDouble(LabelTot1.Text)
             + "','"+Convert.ToDouble(LabelDiscount1.Text)+"','"+Convert.ToDouble(LabelNet1.Text)
             + "','"+"'"+DropDownListStores.SelectedItem.Text+"'"+"','"+Convert.ToDouble(TextBoxFinalTot.Text)
             + "','"+Convert.ToDouble(TextBoxTaxes.Text)+ "','"+Convert.ToDouble(TextBoxFinalNet.Text)+")",con);

           int k = cmd.ExecuteNonQuery();
            if (k > 0)
           {
                Response.Write("<script> alert ('User Added')</Script>)");

           }
           else Response.Write("<script> alert ('Error')</Script>)");

           //con.Close();
       }
</code>```

答:
You have things like this in your code:

```<code>"','"+"'"
</code>```

which will output:

```<code>',''
</code>```

so you're doubling up your quote marks in some places.

I'd pay attention to the above comment though, this really isn't a good way to build queries.

Body:
hello iam making insert in a table using asp.net this my code below  ,i got this error System.Data.SqlClient.SqlException: 'Incorrect syntax near ','.'  can any body help me to figure out the problem

protected void ButtonSave_Click(object sender, EventArgs e)
       {

           SqlConnection con = new SqlConnection("Data Source=LAPTOP-U11A4VS6;Initial Catalog=Task;Integrated Security=True");
           con.Open();
           //SqlCommand cmd = new SqlCommand("Invoice_Product", con);
           //cmd.CommandType = CommandType.StoredProcedure;

           SqlCommand cmd = new SqlCommand("insert into [Invoice_Product] (" + Convert.ToInt32(TextBoxInvoice.Text)
             + "','"+Convert.ToInt32(TextBoxInvoice.Text)+"','"+"'"+TextBoxDate.Text+"'"
             + "','"+"'"+DropDownList1.SelectedItem.Text+"'"
             +"','"+"'"+DropDownList2.SelectedItem.Text+"'"+"','"+Convert.ToDouble(LabelPrice1.Text)
             + "','"+Convert.ToInt32(TextBoxQty.Text)+"','"+Convert.ToDouble(LabelTot1.Text)
             + "','"+Convert.ToDouble(LabelDiscount1.Text)+"','"+Convert.ToDouble(LabelNet1.Text)
             + "','"+"'"+DropDownListStores.SelectedItem.Text+"'"+"','"+Convert.ToDouble(TextBoxFinalTot.Text)
             + "','"+Convert.ToDouble(TextBoxTaxes.Text)+ "','"+Convert.ToDouble(TextBoxFinalNet.Text)+")",con);

           int k = cmd.ExecuteNonQuery();
            if (k > 0)
           {
                Response.Write(")");

           }
           else Response.Write(")");

           //con.Close();
       }

Body:
You have things like this in your code:

"','"+"'"

which will output:

',''

so you're doubling up your quote marks in some places.

I'd pay attention to the above comment though, this really isn't a good way to build queries.


问:
How to decode a JSON string?
On the server side do I have 2 hashes I encode into JSON strings like so

```<code>my $j = JSON->new;
$j = $j->utf8;

my $data;
$data->{users}  = $j->encode(\%user_result);
$data->{owners} = $j->encode(\%owner_result);
$json_string    = to_json($data);

print $cgi->header(-type => "application/json", -charset => "utf-8");
print $json_string;
</code>```

On the client side I have

```<code>$(document).ready(function(){

    $('form').live('submit', function(){

    $.ajax({
        type: "GET",
        url: "/cgi-bin/ajax_confirm.pl",
        contentType: "application/json; charset=utf-8",
        dataType: "json",

        data: $(this).serialize(),

        error: function(XMLHttpRequest, textStatus, errorThrown) {
        $('div#create_result').text("responseText: " + XMLHttpRequest.responseText +
                        ", textStatus: " + textStatus +
                        ", errorThrown: " + errorThrown);
        $('div#create_result').addClass("error");
        },

        success: function(result){
        if (result.error) {
            $('div#create_result').text("result.error: " + result.error);
            $('div#create_result').addClass("error");
        } else { // perl script says everything is okay

            var users  = result.users;
            var owners = result.owners;
...
</code>```

users contains

```<code>{"ss":"Sandra Schlichting","fn":"Full name"}
</code>```

but it is not an array. When I use $.each() it takes on character at a time.

Problem

How do I turn it into an array, so I can use

```<code>function makeTable(users) {
    var result = '<table>\n<tr><td>Initials</td><td>Full Name</td></tr>\n';
    $.each(users, function(index, value) {
        result += '<tr><td>' + index + '</td><td>' + value + '</td></tr>\n';
    });
    result += '</table>';
    return (result);
}
</code>```

which should produce

```<code>Initials    Full Name
ss  Sandra Schlichting
fn  Full name
</code>```

答:
you can use for in statement</p>

```<code>var index = 0;
for(user in users){
  result += '<tr><td>' + index + '</td><td>' + user['fn'] + '</td></tr>\n';
index++;
}
</code>```

Title: How to decode a JSON string?

Body:
On the server side do I have 2 hashes I encode into JSON strings like so

my $j = JSON->new;
$j = $j->utf8;

my $data;
$data->{users}  = $j->encode(\%user_result);
$data->{owners} = $j->encode(\%owner_result);
$json_string    = to_json($data);

print $cgi->header(-type => "application/json", -charset => "utf-8");
print $json_string;

On the client side I have

$(document).ready(function(){

    $('form').live('submit', function(){

    $.ajax({
        type: "GET",
        url: "/cgi-bin/ajax_confirm.pl",
        contentType: "application/json; charset=utf-8",
        dataType: "json",

        data: $(this).serialize(),

        error: function(XMLHttpRequest, textStatus, errorThrown) {
        $('div#create_result').text("responseText: " + XMLHttpRequest.responseText +
                        ", textStatus: " + textStatus +
                        ", errorThrown: " + errorThrown);
        $('div#create_result').addClass("error");
        },

        success: function(result){
        if (result.error) {
            $('div#create_result').text("result.error: " + result.error);
            $('div#create_result').addClass("error");
        } else { // perl script says everything is okay

            var users  = result.users;
            var owners = result.owners;
...

users contains

{"ss":"Sandra Schlichting","fn":"Full name"}

but it is not an array. When I use $.each() it takes on character at a time.

Problem

How do I turn it into an array, so I can use

function makeTable(users) {
    var result = '
\n
Initials	Full Name
\n';
    $.each(users, function(index, value) {
        result += '
' + index + '	' + value + '
\n';
    });
    result += '
';
    return (result);
}

which should produce

Initials    Full Name
ss  Sandra Schlichting
fn  Full name

Body:
you can use for in statement

var index = 0;
for(user in users){
  result += '<tr><td>' + index + '</td><td>' + user['fn'] + '</td></tr>\n';
index++;
}


问:
How to calculate the 99th percentile of a dataset
I have a dataset of the mean of weights of two sample sizes, I have 100,000 tests and I am trying to find out the 99th percentile but I do not understand how to do so, I have found out the median quartile by doing the following;

```<code>summary(Lifts)
 Large           Small
 Min.   : 62.5   Min.   : 54.2
 1st Qu.: 99.1   1st Qu.: 96.0
 Median :106.0   Median :106.0
 Mean   :106.0   Mean   :106.0
 3rd Qu.:112.9   3rd Qu.:116.0
 Max.   :147.5   Max.   :156.8
</code>```

I need to find the 99th percentile of both the large and the small, I have tried using the quartile command;

```<code>quantile(Lifts, probs = c(0, 0.25, 0.50, 0.99))
Error in `[.data.frame`(x, order(x, na.last = na.last, decreasing = decreasing)) :
  undefined columns selected
</code>```

But I receive that error

any help would be appreciated

Body:
I have a dataset of the mean of weights of two sample sizes, I have 100,000 tests and I am trying to find out the 99th percentile but I do not understand how to do so, I have found out the median quartile by doing the following;

summary(Lifts)
 Large           Small
 Min.   : 62.5   Min.   : 54.2
 1st Qu.: 99.1   1st Qu.: 96.0
 Median :106.0   Median :106.0
 Mean   :106.0   Mean   :106.0
 3rd Qu.:112.9   3rd Qu.:116.0
 Max.   :147.5   Max.   :156.8

I need to find the 99th percentile of both the large and the small, I have tried using the quartile command;

quantile(Lifts, probs = c(0, 0.25, 0.50, 0.99))
Error in `[.data.frame`(x, order(x, na.last = na.last, decreasing = decreasing)) :
  undefined columns selected

But I receive that error

any help would be appreciated

Body:
Generally, to apply a function on all columns of a data frame, we can use lapply, which also works with quantile.

lapply(lifts, quantile, probs=c(0, 0.25, 0.50, 0.99))
# $large
#       0%     25%     50%     99%
#   14.400 161.675 488.450 950.506
#
# $small
#      0%    25%    50%    99%
#   0.900 30.800 43.650 97.744

We also may use sapply which does the same but yields as output a matrix.

sapply(lifts, quantile, probs=c(0, 0.25, 0.50, 0.99))
#       large  small
# 0%   14.400  0.900
# 25% 161.675 30.800
# 50% 488.450 43.650
# 99% 950.506 97.744

Data

lifts <- structure(list(large = c(489.9, 734.5, 905.6, 41.9, 950.2, 73.9,
444.7, 950.8, 303.9, 539, 399.4, 429.5, 670.2, 39.1, 324.6, 829.6,
97.9, 216.6, 500.1, 364.4, 762.6, 205.7, 191.6, 128.6, 749.2,
185, 736.9, 46.9, 114.2, 774.4, 626.5, 42.5, 52.5, 724.3, 518.3,
932.7, 602.5, 14.4, 794.9, 149.7, 621.6, 674.2, 685.1, 153.9,
42.3, 487, 787.5, 351.6, 689.3, 862.3), small = c(56.5, 63.6,
49.5, 76.7, 78, 25.8, 57.8, 19.2, 27.7, 38.3, 36.4, 4.4, 89.2,
68.8, 36.1, 71.8, 69.1, 35.8, 38.2, 26.9, 95.5, 30.7, 43.2, 58.8,
44.1, 35.4, 91.2, 37.1, 99.9, 94.5, 52, 38.2, 40.1, 50.9, 81.7,
7.5, 77.5, 71.9, 70.6, 8.2, 90.1, 31.1, 3.4, 52, 0.9, 30.5, 12.7,
45.6, 34.2, 13.4)), class = "data.frame", row.names = c(NA, -50L
))


问:
How can I subset into dataframes based on unique variable using a for loop?
want to subset a dataset into 4 categories (based on the 4 unique categories) using a for loop. I've tried some subsetting and haven't been successful.

```<code>ID Region Other
1  North    x
2  South    y
3  West     z
4  East     l
</code>```

I want to subset into 4 dataframes subset by "region"

I've tried the following but am not quite getting it! Any help would be greatly appreciated.

```<code>for region in test.region.unique():
    reg = test[test == region]
</code>```

答:
You could iterate groupby object:</p>

```<code>for group_name, group in df.groupby('column_name'):
    print(group_name)
    print(group)
</code>```

Body:
want to subset a dataset into 4 categories (based on the 4 unique categories) using a for loop. I've tried some subsetting and haven't been successful.

ID Region Other
1  North    x
2  South    y
3  West     z
4  East     l

I want to subset into 4 dataframes subset by "region"

I've tried the following but am not quite getting it! Any help would be greatly appreciated.

for region in test.region.unique():
    reg = test[test == region]

Body:
You could iterate groupby object:

for group_name, group in df.groupby('column_name'):
    print(group_name)
    print(group)


问:
What happens when QFuture goes out of scope?
I have following code which works (but it should not work)

```<code>void myfunction(){

  auto future = function_which_return_future();
  auto *watcher = new QFutureWatcher<VariantTable>;

  QObject::connect(watcher,&QFutureWatcher<VariantTable>::finished,this,[=](){
       VariantTable table = future.result();
       // do some stuff
       delete watcher;
   });

   watcher->setFuture(future);
}
</code>```

In this code, future goes out of scope but code inside watched's slot still get executed.

Is this because things are happening too fast and will my code may fail if things slowdown ? or its just that I don't need future after calling QFutureWatcher::setFuture ?

答:
About the usage of the future in your slot:

Your lambda slot copies the future and the watcher pointer by values. Therefore when the slot is called, it does not care about the original future that went out of scope.

About the usage of the future inside the QFutureWatcher<VariantTable> object:

If we take a look at the QFutureWatcher<T>::setFuture() implementation in the source code of QFutureWatcher, we can see:

```<code>template <typename T>
Q_INLINE_TEMPLATE void QFutureWatcher<T>::setFuture(const QFuture<T> &_future)
{
   if (_future == m_future)
       return;

   disconnectOutputInterface(true);
   m_future = _future;
   connectOutputInterface();
}
</code>```

The private member m_future is defined as QFuture<T> m_future;.

Apparently, the QFutureWatcher owns its own copy of the given future.

Consequently, the original future is not used anymore after your instruction: watcher->setFuture(future);

To answer your question:

I have following code which works (but it should not work)

Actually, with what's previously mentioned, it should work :)

Note: It may not work as intended since the copied future in your slot and the copied future in your watcher object are two distinct instances.

Body:
I have following code which works (but it should not work)

void myfunction(){

  auto future = function_which_return_future();
  auto *watcher = new QFutureWatcher<VariantTable>;

  QObject::connect(watcher,&QFutureWatcher<VariantTable>::finished,this,[=](){
       VariantTable table = future.result();
       // do some stuff
       delete watcher;
   });

   watcher->setFuture(future);
}

In this code, future goes out of scope but code inside watched's slot still get executed.

Is this because things are happening too fast and will my code may fail if things slowdown ? or its just that I don't need future after calling QFutureWatcher::setFuture ?

Body:
About the usage of the future in your slot:

Your lambda slot copies the future and the watcher pointer by values. Therefore when the slot is called, it does not care about the original future that went out of scope.

About the usage of the future inside the QFutureWatcher<VariantTable> object:

If we take a look at the QFutureWatcher<T>::setFuture() implementation in the source code of QFutureWatcher, we can see:

template <typename T>
Q_INLINE_TEMPLATE void QFutureWatcher<T>::setFuture(const QFuture<T> &_future)
{
   if (_future == m_future)
       return;

   disconnectOutputInterface(true);
   m_future = _future;
   connectOutputInterface();
}

The private member m_future is defined as QFuture<T> m_future;.

Apparently, the QFutureWatcher owns its own copy of the given future.

Consequently, the original future is not used anymore after your instruction: watcher->setFuture(future);

To answer your question:

I have following code which works (but it should not work)

Actually, with what's previously mentioned, it should work :)

Note: It may not work as intended since the copied future in your slot and the copied future in your watcher object are two distinct instances.


问:
How can I limit the number of objects that the user can drag and drop to a specific layout?
I developed a card sort app that the user can drag and drop cards on the screen according to the code here-
drag and drop code

how can I limit the number of objects that can be dragged to a specific layout?
(i would like to limit the number of objects to only one for each layout)

答:
It appears as though it is in the DragEvent.ACTION_DROP where the view is added to the new parent. So when that happens you can simply check if the view your adding it to already has a certain number of children:

Change this:

```<code>case DragEvent.ACTION_DROP:

    ...

    View v = (View) event.getLocalState();
    ViewGroup owner = (ViewGroup) v.getParent();
    owner.removeView(v);//remove the dragged view
    LinearLayout container = (LinearLayout) view;
    container.addView(v);
    v.setVisibility(View.VISIBLE);
</code>```

to this:

```<code>case DragEvent.ACTION_DROP:

    ...

    LinearLayout container = (LinearLayout) view;
    if (container.getChildCount() < 1) { // only move the view if the container has no kids
        View v = (View) event.getLocalState();
        ViewGroup owner = (ViewGroup) v.getParent();
        owner.removeView(v);
        container.addView(v);
    }
    v.setVisibility(View.VISIBLE);
</code>```

Body:
It appears as though it is in the DragEvent.ACTION_DROP where the view is added to the new parent. So when that happens you can simply check if the view your adding it to already has a certain number of children:

Change this:

case DragEvent.ACTION_DROP:

    ...

    View v = (View) event.getLocalState();
    ViewGroup owner = (ViewGroup) v.getParent();
    owner.removeView(v);//remove the dragged view
    LinearLayout container = (LinearLayout) view;
    container.addView(v);
    v.setVisibility(View.VISIBLE);

to this:

case DragEvent.ACTION_DROP:

    ...

    LinearLayout container = (LinearLayout) view;
    if (container.getChildCount() < 1) { // only move the view if the container has no kids
        View v = (View) event.getLocalState();
        ViewGroup owner = (ViewGroup) v.getParent();
        owner.removeView(v);
        container.addView(v);
    }
    v.setVisibility(View.VISIBLE);


问:
How to get ISO week numbers from date
I would like to get the ISO week number from a given date in string format, where Monday is the first day of the week, and the week that contains the first Thursday of the year is considered to be the first week.

From other answers, I think strftime("2017-11-18", format = "%V") suits my purpose the best.
However it doesn't work on Windows.

Any suggestions for alternatives with only the base package in R?

答:
The Python datetime library has a native function for getting ISO year, week number and week day: https://docs.python.org/3/library/datetime.html#datetime.date.isocalendar. It returns a tuple with all three values, so just select the second element if you want to have the week number only.

Example:

```<code>from datetime import datetime

// Create a datetime object from your string
my_date = datetime.strptime('2017-11-18', '%Y-%m-%d')
// Get the tuple of ISO date values from your datetime object
my_iso_tuple = my_date.isocalendar()
// Get the ISO week number
my_iso_week_number = my_iso_tuple[1]
</code>```

Title: How to get ISO week numbers from date

Body:
The Python datetime library has a native function for getting ISO year, week number and week day: https://docs.python.org/3/library/datetime.html#datetime.date.isocalendar. It returns a tuple with all three values, so just select the second element if you want to have the week number only.

Example:

from datetime import datetime

// Create a datetime object from your string
my_date = datetime.strptime('2017-11-18', '%Y-%m-%d')
// Get the tuple of ISO date values from your datetime object
my_iso_tuple = my_date.isocalendar()
// Get the ISO week number
my_iso_week_number = my_iso_tuple[1]


问:
return code of console application

Possible Duplicate:

  How do I get the application exit code from a Windows command line?

I have a console application. It will be executed from command prompt. It will return either 0 or 1 from main method. How can I know that what value is returned by the application?

答:
If you run the command line app with the Process class in C#:

if you look for the exitcode: process.ExitCode

if you need to read what the app has written to the console: process.StandardError.ReadToEnd() or process.StandardOutput.ReadToEnd()

If you need this in C++ since you gave that TAG too, I cannot help you much.

You should choose one of those tags, or have you put unrelated tags into the question?

Title: return code of console application