问:
CSS for rows of logos
I'm trying to code a row of logos in the footer of website https://www.andromedi.com/

The desktop version works fine but the mobile needs to looks like this

I checked online and the way to go apparently is using flexbox (I still need to better understand the difference between css-grid and flexbox)

The css code:

.footer-asociaciones-wrapper {
  width: 100%;
  margin: auto;
  padding: 1.5rem 5rem;
}

.footer-asociaciones-row {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  width: 100%;
}

.footer-asociaciones-column {
  display: flex;
  flex-direction: column;
  flex-basis: 100%;
  flex: 1;
}

.footer-asociaciones-column img {
    height:100px;
}

.footer-asociaciones-column a {
    margin: auto;
}

p.footer-asociaciones-title {
  padding: 1.5rem 1rem;
  color: white;
  font-family: 'DIN1451EngschriftRegular';
  font-size: large;
}
```

I tried using width: 33%; but then the logos overlap

Any help is appreciated. Thanks!

答:
So thanks to @BugsArePeopleToo I came up with the solution:

.footer-asociaciones-column {
    display: flex;
  flex-direction: column;
  flex-basis: 33%;
}

@media screen and (min-width: 481px) {

    .footer-asociaciones-column {
        flex-basis: 100%;
        flex: 1;
    }

}

.footer-asociaciones-column img {
  max-width: 100%;
  max-height: 100px;
  height: auto;
  width: auto;
}
```

Title: CSS for rows of logos

Body:
I'm trying to code a row of logos in the footer of website https://www.andromedi.com/

The desktop version works fine but the mobile needs to looks like this

I checked online and the way to go apparently is using flexbox (I still need to better understand the difference between css-grid and flexbox)

The css code:

.footer-asociaciones-wrapper {
  width: 100%;
  margin: auto;
  padding: 1.5rem 5rem;
}

.footer-asociaciones-row {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  width: 100%;
}

.footer-asociaciones-column {
  display: flex;
  flex-direction: column;
  flex-basis: 100%;
  flex: 1;
}

.footer-asociaciones-column img {
    height:100px;
}

.footer-asociaciones-column a {
    margin: auto;
}

p.footer-asociaciones-title {
  padding: 1.5rem 1rem;
  color: white;
  font-family: 'DIN1451EngschriftRegular';
  font-size: large;
}

I tried using width: 33%; but then the logos overlap

Any help is appreciated. Thanks!


来源: stackexchange

问:
Angular routing not working when deployed to tomcat 9 (Ubuntu 18.04)
I coded an angular project on my own PC, everything worked fine when I ran it locally with the command ng serve. Now I want to deploy it on tomcat on a VM (provided by my school) because my project needs to be public.

I created a git repository and downloaded the angular project on the VM. Followed a tutorial to deploy the app in tomcat, which simply consisted of 2 steps:

Run ng build --base-href=/angular/ to generate some files

Copy the generated files to tomcat's /webapps subfolder

But it does not work as intended. To me it seems like there's an issue with routing.

Here's my routing module:

```<code>const appRoutes: Routes = [
  {path: 'coachPortal', component: CoachPortalComponent},
  {path: 'userPortal', component: UserPortalComponent},
  {path: 'users', component: UsersComponent},
  {path: 'userDetails/:id', component: UserDetailsComponent},
  {path: 'mySessions', component: MySessionsComponent},
  {path: '', redirectTo: '/coachPortal', pathMatch: 'full'},
  {path: '**', component: CoachPortalComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(appRoutes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
</code>```

To navigate between routes, I use this old simple code: window.location.href = '/users';

This worked like a charm when I ran it locally on my pc.

But I'm guessing the reason why it's not working anymore after deploying on tomcat is because tomcat adds the prefix angular/.

When running locally on my pc the urls were localhost:4200/{componenturl}.

But on the VM it's x.x.x.x:8080/angular/{componenturl}

But because of the routing redirects I am getting 404 errors. When I first visit the root url x.x.x.x:8080/angular, it matches with the rule {path: '', redirectTo: '/coachPortal', pathMatch: 'full'}. and loads the coachPortal component and even changes the url to angular/coachPortal. But refreshing the page or manually entering angular/coachPortal gives a 404 error. And all other links don't work either.

Also on the coachPortal I have an image with src ../../../assets/logo.png and it obviously doesn't load because of how the generated files in webapps folder have different folder structure... How can I fix this? The image is directly under assets folder.

答:
My understanding is that when you try to navigate to a virtual sub directory that is usually resolved via Angular Routing, when it is deployed your webserver is looking for an actual directory of 'coachportal', which doesn't exist so returns a 404. If the route had been navigated to through your app (by navigation buttons etc.) Angular Router would resolve it and bring up the virtual sub-directory. Your webserver is stopping the route from getting to Angular Router to resolve it. Your webserver checks to see if there is an actual folder or file and then redirects to your root to handle the routing if there is no file or folder with that name. For web projects I have deployed on IIS I include a web.config file with the following code:

```<code><configuration>
    <system.webServer>
      <rewrite>
        <rules>
          <rule name="Angular" stopProcessing="true">
            <match url=".*" />
            <conditions logicalGrouping="MatchAll">
              <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
              <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
            </conditions>
            <action type="Rewrite" url="/" />
          </rule>
        </rules>
      </rewrite>
    </system.webServer>
</configuration>
</code>```

from this post: Routing in Angular 7 running in subfolder not working correctly I'm not sure if it will work with your deployment setup, but should at least give you insight into what may be going on.

For your assets folder remove the ../s for a relative directory and just leave it as assets/logo.png it should handle this correctly. you can test it locally.

EDIT: changed some things for clarity

ContentLicense: CC BY-SA 4.0

Body:
I coded an angular project on my own PC, everything worked fine when I ran it locally with the command ng serve. Now I want to deploy it on tomcat on a VM (provided by my school) because my project needs to be public.

I created a git repository and downloaded the angular project on the VM. Followed a tutorial to deploy the app in tomcat, which simply consisted of 2 steps:

Run ng build --base-href=/angular/ to generate some files

Copy the generated files to tomcat's /webapps subfolder

But it does not work as intended. To me it seems like there's an issue with routing.

Here's my routing module:

const appRoutes: Routes = [
  {path: 'coachPortal', component: CoachPortalComponent},
  {path: 'userPortal', component: UserPortalComponent},
  {path: 'users', component: UsersComponent},
  {path: 'userDetails/:id', component: UserDetailsComponent},
  {path: 'mySessions', component: MySessionsComponent},
  {path: '', redirectTo: '/coachPortal', pathMatch: 'full'},
  {path: '**', component: CoachPortalComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(appRoutes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

To navigate between routes, I use this old simple code: window.location.href = '/users';

This worked like a charm when I ran it locally on my pc.

But I'm guessing the reason why it's not working anymore after deploying on tomcat is because tomcat adds the prefix angular/.

When running locally on my pc the urls were localhost:4200/{componenturl}.

But on the VM it's x.x.x.x:8080/angular/{componenturl}

But because of the routing redirects I am getting 404 errors. When I first visit the root url x.x.x.x:8080/angular, it matches with the rule {path: '', redirectTo: '/coachPortal', pathMatch: 'full'}. and loads the coachPortal component and even changes the url to angular/coachPortal. But refreshing the page or manually entering angular/coachPortal gives a 404 error. And all other links don't work either.

Also on the coachPortal I have an image with src ../../../assets/logo.png and it obviously doesn't load because of how the generated files in webapps folder have different folder structure... How can I fix this? The image is directly under assets folder.

Body:
My understanding is that when you try to navigate to a virtual sub directory that is usually resolved via Angular Routing, when it is deployed your webserver is looking for an actual directory of 'coachportal', which doesn't exist so returns a 404. If the route had been navigated to through your app (by navigation buttons etc.) Angular Router would resolve it and bring up the virtual sub-directory. Your webserver is stopping the route from getting to Angular Router to resolve it. Your webserver checks to see if there is an actual folder or file and then redirects to your root to handle the routing if there is no file or folder with that name. For web projects I have deployed on IIS I include a web.config file with the following code:

<configuration>
    <system.webServer>
      <rewrite>
        <rules>
          <rule name="Angular" stopProcessing="true">
            <match url=".*" />
            <conditions logicalGrouping="MatchAll">
              <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
              <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
            </conditions>
            <action type="Rewrite" url="/" />
          </rule>
        </rules>
      </rewrite>
    </system.webServer>
</configuration>

from this post: Routing in Angular 7 running in subfolder not working correctly I'm not sure if it will work with your deployment setup, but should at least give you insight into what may be going on.

For your assets folder remove the ../s for a relative directory and just leave it as assets/logo.png it should handle this correctly. you can test it locally.

EDIT: changed some things for clarity


问:
Delete previous month, before appending new data
I'm setting up a new data table in SpotFire. Since the newest update SpotFire X, the Automation Service Job Builder is available for us. Therefore I want to create job schedule which will automatically append (new) data into my existing data table. I am pretty new with scripting and programming so any help would be so appreciated. I have a SAP BW Query which is connected with my Spotfire dashboards. This query only contains the latest month of data. Since the Automation Service Job Builder only have a weekly interval, I want to implement some intelligence before letting the scheduler adding data. The query will not refresh every week/day but every month. That's why I want the script to delete (if possible) the data first before appending the data to the data table, otherwise I will get duplicates in the data table.

I tried to search for scripts, but couldn't find anything usefull. I do have found this script.

```<code>dtTarget=usertable*
selection = IndexSet(dtTarget.RowCount,True)
for r in selection:
selection[r] = (r>=(dtTarget.RowCount-10))
dtTarget.RemoveRows(RowSelection(selection))
</code>```

答:
For my example code below, I've used a Spotfire file with the following:

Spotfire Datatable name = Store

Name of data column holding the date = [Date]

The data was loaded from the Spotfire demodata database.

If you just want to clear the table before loading, you can use this.

```<code>from Spotfire.Dxp.Data import RowSelection, IndexSet
table = Document.Data.Tables["Store"]
table.RemoveRows(RowSelection(IndexSet(table.RowCount, True)))
</code>```

If you want to delete everything older than last month, but keep everything newer, this will do it. Passing None into the last_month function will cause it to get last month as of today.

```<code>from datetime import date, timedelta
from Spotfire.Dxp.Data import RowSelection

def last_month(from_date):
    if from_date is None:
        from_date = date.today()
    end_date = from_date.replace(day=1) - timedelta(days=1)
    start_date = date(end_date.year, end_date.month, 1)
    return (start_date, end_date)

table = Document.Data.Tables["Store"]
(start,end) = last_month(date(1994,12,6))
rows_to_delete = table.Select("[Date] <= Date('{}')".format(end.strftime("%x")))
table.RemoveRows(rows_to_delete)
</code>```

You can set the actual table as an input parameter to the ironpython script instead of naming it directly in the script as I've done. You can do the same with the date column name.

Body:
I'm setting up a new data table in SpotFire. Since the newest update SpotFire X, the Automation Service Job Builder is available for us. Therefore I want to create job schedule which will automatically append (new) data into my existing data table. I am pretty new with scripting and programming so any help would be so appreciated. I have a SAP BW Query which is connected with my Spotfire dashboards. This query only contains the latest month of data. Since the Automation Service Job Builder only have a weekly interval, I want to implement some intelligence before letting the scheduler adding data. The query will not refresh every week/day but every month. That's why I want the script to delete (if possible) the data first before appending the data to the data table, otherwise I will get duplicates in the data table.

I tried to search for scripts, but couldn't find anything usefull. I do have found this script.

dtTarget=usertable*
selection = IndexSet(dtTarget.RowCount,True)
for r in selection:
selection[r] = (r>=(dtTarget.RowCount-10))
dtTarget.RemoveRows(RowSelection(selection))

Body:
For my example code below, I've used a Spotfire file with the following:

Spotfire Datatable name = Store

Name of data column holding the date = [Date]

The data was loaded from the Spotfire demodata database.

If you just want to clear the table before loading, you can use this.

from Spotfire.Dxp.Data import RowSelection, IndexSet
table = Document.Data.Tables["Store"]
table.RemoveRows(RowSelection(IndexSet(table.RowCount, True)))

If you want to delete everything older than last month, but keep everything newer, this will do it. Passing None into the last_month function will cause it to get last month as of today.

from datetime import date, timedelta
from Spotfire.Dxp.Data import RowSelection

def last_month(from_date):
    if from_date is None:
        from_date = date.today()
    end_date = from_date.replace(day=1) - timedelta(days=1)
    start_date = date(end_date.year, end_date.month, 1)
    return (start_date, end_date)

table = Document.Data.Tables["Store"]
(start,end) = last_month(date(1994,12,6))
rows_to_delete = table.Select("[Date] <= Date('{}')".format(end.strftime("%x")))
table.RemoveRows(rows_to_delete)

You can set the actual table as an input parameter to the ironpython script instead of naming it directly in the script as I've done. You can do the same with the date column name.


问:
Plus sign in the select clause of an SQL
I am working on an old SQL written for Oracle. There is a part of the select clause that I do not understand, even after googling and checking the questions related to the + sign with the key words Oracle and SQL.

I have checked the answer for a similar question for the where clause here and I found an Oracle docs for the join as well, but it does not make sense for the select clause.

Given an SQL below what is the purpose of the plus sign.

```<code>select '01,'||
lpad(
   (select nvl(count(*), 0) from table1)
   +
   (select nvl(count(*), 0) from table2)
   +
   (select nvl(count(*), 0) from table3)
,9,'0')
from DUAL
</code>```

The sample output

```<code>01,000011111
</code>```

From a sample sql output, it seems that it is for concatenating a result, but I want to be sure.

答:
The + is not for string concatenation.  It is for addition.  Plus, count() does not return NULL values so nvl() is not needed.

This should be equivalent:

```<code>select ('01,' ||
        lpad( ((select count(*) from table1) +
               (select count(*) from table2) +
               (select count(*) from table3)
              ), 9, '0'
            )
        )
from DUAL
</code>```

Body:
I am working on an old SQL written for Oracle. There is a part of the select clause that I do not understand, even after googling and checking the questions related to the + sign with the key words Oracle and SQL.

I have checked the answer for a similar question for the where clause here and I found an Oracle docs for the join as well, but it does not make sense for the select clause.

Given an SQL below what is the purpose of the plus sign.

select '01,'||
lpad(
   (select nvl(count(*), 0) from table1)
   +
   (select nvl(count(*), 0) from table2)
   +
   (select nvl(count(*), 0) from table3)
,9,'0')
from DUAL

The sample output

01,000011111

From a sample sql output, it seems that it is for concatenating a result, but I want to be sure.

Body:
The + is not for string concatenation.  It is for addition.  Plus, count() does not return NULL values so nvl() is not needed.

This should be equivalent:

select ('01,' ||
        lpad( ((select count(*) from table1) +
               (select count(*) from table2) +
               (select count(*) from table3)
              ), 9, '0'
            )
        )
from DUAL


问:
nohup and enter will stop the process: why?
My script needs root privileges and I want to run it on a remote machine and then be able to turn off my local computer.

So I did:
$ nohup sudo ./myScript arg1 &

... which I always do, but on a different machine where I'm always root, so without sudo. For some reason now it's not working:

```<code>nohup sudo ./myScript.sh 1 &  //then I press enter twice
[8] 24264
me@my-laptop:~/myFolder$ nohup: ignoring input and appending output to `nohup.out'

[8]+  Stopped                 nohup sudo ./myScript.sh 1
</code>```

What am I doing wrong here?

答:
As mentioned in other answers, if a background process started with nohup tries to read from or write to the terminal, it is put into the "Stopped" state. The sudo process that you're executing tries to read your password from the terminal, so the process is stopped (for some reason, the reading seems to be triggered when Enter is pressed).

So, to avoid this, you ned to make sure to enter your password and become root before nohup is executed. For example, like this:

sudo bash -c 'nohup ./myScript.sh arg1 &'
```

ContentLicense: CC BY-SA 3.0

Body:
My script needs root privileges and I want to run it on a remote machine and then be able to turn off my local computer.

So I did:
$ nohup sudo ./myScript arg1 &

... which I always do, but on a different machine where I'm always root, so without sudo. For some reason now it's not working:

nohup sudo ./myScript.sh 1 &  //then I press enter twice
[8] 24264
me@my-laptop:~/myFolder$ nohup: ignoring input and appending output to `nohup.out'

[8]+  Stopped                 nohup sudo ./myScript.sh 1

What am I doing wrong here?


问:
How encrypt SQLite database with FireDAC?
I'm create SQLite databse with DB Browser for SQLite (non encrypted) and open with FireDAC in delphi.(Can retrive data Eg. Select * from abc).

How encrypt this SQLite database with FireDAC? When enter username, password and encrypt get message  "Cipher DB is not encrypdet"

Note:

When create SQLite database from Delphi FireDac I can use encryption!

答:
From the Documentation

SQLite Encrypted Database

Approach

One of the distinctive SQLite
features is the high-speed strong database encryption. It allows you
to make database file content confidential and enforce integrity
control on the database file.  The encrypted database format is not
compatible with other similar SQLite encryption extensions. This means
that you cannot use an encrypted database, encrypted with non-FireDAC
libraries. If you need to do this, then you have to decrypt a database
with an original tool and encrypt it with FireDAC.


问:
How to post object and List using postman
I am using postman packaged app to send a post request.

I want to request the following controller.

How to send a post requestbody using postman object(with values) and a list using the raw format?

```<code>    @RequestMapping(value = "register", method = RequestMethod.POST)
    @ResponseBody
    public ResponseMessage save(@RequestBody Freelancer freelancer, @RequestBody List<Integer> skills) {
</code>```

I have tried like this :

```<code>{
  "address": "colombo",
  "username": "hesh",
  "password": "123",
  "registetedDate": "2015-4-3",
  "firstname": "hesh",
  "contactNo": "07762",
  "accountNo": "16161",
  "lastName": "jay"
}
{
    "array[0]" :1436517454492,
    "array[1]" :1436517476993
}
</code>```

答:
If you use the following format in your request section while making sure the request url is of http://localhost:XXXX/OperationName/V#. </p>

```<code>      {
      "address": "colombo",
      "username": "hesh",
      "password": "123",
      "registetedDate": "2015-4-3",
      "firstname": "hesh",
      "contactNo": "07762",
      "accountNo": "16161",
      "lastName": "jay",
      "listName":[
       {
        "elementOne":"valueOne"
       },
       {
        "elementTwo":"valueTwo"
       },
       ...]
     }
</code>```

Body:
I am using postman packaged app to send a post request.

I want to request the following controller.

How to send a post requestbody using postman object(with values) and a list using the raw format?

    @RequestMapping(value = "register", method = RequestMethod.POST)
    @ResponseBody
    public ResponseMessage save(@RequestBody Freelancer freelancer, @RequestBody List<Integer> skills) {

I have tried like this :

{
  "address": "colombo",
  "username": "hesh",
  "password": "123",
  "registetedDate": "2015-4-3",
  "firstname": "hesh",
  "contactNo": "07762",
  "accountNo": "16161",
  "lastName": "jay"
}
{
    "array[0]" :1436517454492,
    "array[1]" :1436517476993
}

Body:
If you use the following format in your request section while making sure the request url is of http://localhost:XXXX/OperationName/V#.

      {
      "address": "colombo",
      "username": "hesh",
      "password": "123",
      "registetedDate": "2015-4-3",
      "firstname": "hesh",
      "contactNo": "07762",
      "accountNo": "16161",
      "lastName": "jay",
      "listName":[
       {
        "elementOne":"valueOne"
       },
       {
        "elementTwo":"valueTwo"
       },
       ...]
     }


问:
How to Access Linux Files in a WSL distro from Windows 10?
Recently I updated my Windows 10 Pro with May Update (version 1903, build 18362.116). Then for my existing distros: OpenSuse Leap 15 and Ubuntu (installed from MS Store), I wanted to open a linux directory by using Explorer and I'm getting this message:

```<code>[susedis@mypc ~]$ explorer.exe .
If 'explorer.exe' is not a typo you can use command-not-found to lookup the package that contains it, like this:
    cnf explorer.exe
</code>```

This problem happens also with VSC (code) and VSC-Insiders (code-insiders).

I've read this article and ...

OPTION 1: my current problem

OPTION 2: icon LINUX does not exist in tree view

OPTION 3: it works

Supposedly options 1 and 2 should exist and work, even more with the latest update. What's wrong? Thanks in advance.

PS1: I've found these articles Run Visual Studio Code for Linux from WSL and Using Visual Studio Code with Windows Subsystem for Linux, they talk about installing xserver and more stuff on side linux. But many other articles and videos don't talk about it, it's like it was a built-in feature of Windows. This is so dark.

答:
I just found what is the root of my problem: the distro.

explorer, code, code-insiders commands ONLY work through UBUNTU and I was using OpenSuse.

This warning is lacking in every article on Web I read, including on VSC site (example: Developing in WSL). This is a disadvantage for other distros. Very bad.

PS1: The solution can be found here.

Body:
Recently I updated my Windows 10 Pro with May Update (version 1903, build 18362.116). Then for my existing distros: OpenSuse Leap 15 and Ubuntu (installed from MS Store), I wanted to open a linux directory by using Explorer and I'm getting this message:

[susedis@mypc ~]$ explorer.exe .
If 'explorer.exe' is not a typo you can use command-not-found to lookup the package that contains it, like this:
    cnf explorer.exe

This problem happens also with VSC (code) and VSC-Insiders (code-insiders).

I've read this article and ...

OPTION 1: my current problem

OPTION 2: icon LINUX does not exist in tree view

OPTION 3: it works

Supposedly options 1 and 2 should exist and work, even more with the latest update. What's wrong? Thanks in advance.

PS1: I've found these articles Run Visual Studio Code for Linux from WSL and Using Visual Studio Code with Windows Subsystem for Linux, they talk about installing xserver and more stuff on side linux. But many other articles and videos don't talk about it, it's like it was a built-in feature of Windows. This is so dark.


问:
java collection without null object
Is there any collection in java that won't add null object? Given a list of item, query DB for those items, when the result returned from DB, i'll add the item to result list if it does exist in DB, if it doesn't DB return null, then I'll discard it.

I have following code does this:

```<code>reqIds.forEach(
        reqId -> {
          columnValueMap.clear();
          columnValueMap.put("request_id", reqId);
          EventAudit auditRecord =
              pollDatabaseFindByIdAndKey(
                  EventAudit.class, columnValueMap);

          if (auditRecord != null) {
            auditMap.put(auditRecord.getRequestId(), auditRecord);
          }
        });
</code>```

i know i can use Java stream filter to filter out null but just wonder if there is any smart collection that will reject null object automatically so i don't need to do extra Null checking

答:
You can use apache commons collection to do this,

```<code>import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.PredicateUtils;
import com.google.common.collect.Lists;

public class Test {
    public static void main(String[] args) {
        List<Integer> l = Lists.newArrayList(1, 2, 3, null, 7, null, 8, null);
        CollectionUtils.filter(l, PredicateUtils.notNullPredicate());
        System.out.println(l);
    }
}
</code>```

above code will print output as like,

```<code>[1, 2, 3, 7, 8]
</code>```

Title: java collection without null object

Body:
Is there any collection in java that won't add null object? Given a list of item, query DB for those items, when the result returned from DB, i'll add the item to result list if it does exist in DB, if it doesn't DB return null, then I'll discard it.

I have following code does this:

reqIds.forEach(
        reqId -> {
          columnValueMap.clear();
          columnValueMap.put("request_id", reqId);
          EventAudit auditRecord =
              pollDatabaseFindByIdAndKey(
                  EventAudit.class, columnValueMap);

          if (auditRecord != null) {
            auditMap.put(auditRecord.getRequestId(), auditRecord);
          }
        });

i know i can use Java stream filter to filter out null but just wonder if there is any smart collection that will reject null object automatically so i don't need to do extra Null checking

Body:
You can use apache commons collection to do this,

import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.PredicateUtils;
import com.google.common.collect.Lists;

public class Test {
    public static void main(String[] args) {
        List<Integer> l = Lists.newArrayList(1, 2, 3, null, 7, null, 8, null);
        CollectionUtils.filter(l, PredicateUtils.notNullPredicate());
        System.out.println(l);
    }
}

above code will print output as like,

[1, 2, 3, 7, 8]


问:
Is there a modern community to share knowledge and best-practicies of those who work with SuiteScript 2.0?
I'm fairly new to NetSuite and SuiteScript 2.0 in particular. I have already developed several applications and what I found out is that there is almost nothing I can find on the internet about SuiteScript. I mean if you use React or Vue or other popular frameworks, you can easily google for issues you have and most likely you will find several answers, which is definitely cool.

There is NetSuite Help Center - some sort of API documentation which I use all the time. There is a Suite Answers, where you can find help from NetSuite Support. But those are just internal resources with its pros and cons. As I've mentioned earlier, I did try to find additional resources on the web where people share their experience (best practicies etc.), but unfortunately didn't found anything. Even here, on stackoverflow, not so many people are into SuiteScript.

Those who worked with NetSuite for a while, please share some info where to find on-demand help.

答: Check out the NetSuite Professionals Slack group. It is free, and there are over 4000 members. https://www.netsuiteprofessionals.com </p>


问:
Difference Between ASCIIEncoding and Encoding
I understand that Encoding can be used to initialize object to perform any type of Encoding, ASCII, Unicode, UTF-8 etc.
It appears to me that all these are sufficient for performing any kind of encoding, then what is the need for ASCIIEncoding?</p>

答:
The Encoding class, in addition to being the base class of all encoders, provides static property accessors to the named subclasses.

Encoding.ASCII returns an instance of ASCIIEncoding which, in turn, subclasses Encoding and passes the codepage 0x4e9f (US-ASCII) to the base constructor.


问:
How to handle/wait for the element which is getting displayed only after some operation on the page
I have a requirement where i have to wait for the element for appear after certain operation like clicking on a dropdown. I am automating using protractor and js. Is there any way i can wait or put some condition for the element to be displayed and enabled before performing some operation.

I wrote the below code , but still its giving the error as element not interactable. Sleep however does help in this case. Is there any way i can wait dynamically.?

```<code>element(by.className("btn-group tropos-sandbox-filters-container")).isPresent().then(function(){
            element(by.className("btn-group tropos-sandbox-filters-container")).click();
            console.log("The dropdown element is present");
        })
</code>```

答:
Maybe try:

```<code>// dropDownEl: ElementFinder = $('selector');
browser.wait(EC.visibilityOf(dropDownEL), waitingTime, 'errorMsg');
</code>```

as in:

```<code>const dropDownEl: ElementFinder = element(by.className("btn-group tropos-sandbox-filters-container"));
browser.wait(EC.visibilityOf(dropDownEL), waitingTime, 'errorMsg');
dropDownEl.click();
console.log("The dropdown element is present");
</code>```

Body:
I have a requirement where i have to wait for the element for appear after certain operation like clicking on a dropdown. I am automating using protractor and js. Is there any way i can wait or put some condition for the element to be displayed and enabled before performing some operation.

I wrote the below code , but still its giving the error as element not interactable. Sleep however does help in this case. Is there any way i can wait dynamically.?

element(by.className("btn-group tropos-sandbox-filters-container")).isPresent().then(function(){
            element(by.className("btn-group tropos-sandbox-filters-container")).click();
            console.log("The dropdown element is present");
        })

Body:
Maybe try:

// dropDownEl: ElementFinder = $('selector');
browser.wait(EC.visibilityOf(dropDownEL), waitingTime, 'errorMsg');

as in:

const dropDownEl: ElementFinder = element(by.className("btn-group tropos-sandbox-filters-container"));
browser.wait(EC.visibilityOf(dropDownEL), waitingTime, 'errorMsg');
dropDownEl.click();
console.log("The dropdown element is present");


问:
Extracting Raw XML via lxml etree
I'm trying to extract raw XML from an XML file.

So if my data is:

```<code>        <xml>
            ... Lots of XML ...

            <getThese>
                <clonedKey>1</clonedKey>
                <clonedKey>2</clonedKey>
                <clonedKey>3</clonedKey>
                <randomStuff>this is a sentence</randomStuff>
            </getThese>
            <getThese>
                <clonedKey>6</clonedKey>
                <clonedKey>8</clonedKey>
                <clonedKey>3</clonedKey>
                <randomStuff>more words</randomStuff>
            </getThese>

            ... Lots of XML ...

        </xml>
</code>```

I can get the keys I want easily using etree:

```<code>from lxml import etree
search_me = etree.fromstring(xml_str)
search_me.findall('./xml/getThis')
</code>```

But how do I get the actual content as raw XML? All the stuff I can see in the docs is for getting elements/text/attributes rather than the raw XML.

My desired output would be a list with two elements:

```<code>["<getThese>
                <clonedKey>1</clonedKey>
                <clonedKey>2</clonedKey>
                <clonedKey>3</clonedKey>
                <randomStuff>this is a sentence</randomStuff>
            </getThese>",
"<getThese>
                <clonedKey>6</clonedKey>
                <clonedKey>8</clonedKey>
                <clonedKey>3</clonedKey>
                <randomStuff>more words</randomStuff>
            </getThese>"]
</code>```

答:
You should be able to use tostring() to serialize the XML.

Example...

```<code>from lxml import etree

xml = """
<xml>
    <getThese>
        <clonedKey>1</clonedKey>
        <clonedKey>2</clonedKey>
        <clonedKey>3</clonedKey>
        <randomStuff>this is a sentence</randomStuff>
    </getThese>
    <getThese>
        <clonedKey>6</clonedKey>
        <clonedKey>8</clonedKey>
        <clonedKey>3</clonedKey>
        <randomStuff>more words</randomStuff>
    </getThese>
</xml>
"""

parser = etree.XMLParser(remove_blank_text=True)

tree = etree.fromstring(xml, parser=parser)

elems = []

for elem in tree.xpath("getThese"):
    elems.append(etree.tostring(elem).decode())

print(elems)
</code>```

Printed output...

```<code>['<getThese><clonedKey>1</clonedKey><clonedKey>2</clonedKey><clonedKey>3</clonedKey><randomStuff>this is a sentence</randomStuff></getThese>', '<getThese><clonedKey>6</clonedKey><clonedKey>8</clonedKey><clonedKey>3</clonedKey><randomStuff>more words</randomStuff></getThese>']
</code>```

Title: Extracting Raw XML via lxml etree

Body:
I'm trying to extract raw XML from an XML file.

So if my data is:

        <xml>
            ... Lots of XML ...

            <getThese>
                <clonedKey>1</clonedKey>
                <clonedKey>2</clonedKey>
                <clonedKey>3</clonedKey>
                <randomStuff>this is a sentence</randomStuff>
            </getThese>
            <getThese>
                <clonedKey>6</clonedKey>
                <clonedKey>8</clonedKey>
                <clonedKey>3</clonedKey>
                <randomStuff>more words</randomStuff>
            </getThese>

            ... Lots of XML ...

        </xml>

I can get the keys I want easily using etree:

from lxml import etree
search_me = etree.fromstring(xml_str)
search_me.findall('./xml/getThis')

But how do I get the actual content as raw XML? All the stuff I can see in the docs is for getting elements/text/attributes rather than the raw XML.

My desired output would be a list with two elements:

["<getThese>
                <clonedKey>1</clonedKey>
                <clonedKey>2</clonedKey>
                <clonedKey>3</clonedKey>
                <randomStuff>this is a sentence</randomStuff>
            </getThese>",
"<getThese>
                <clonedKey>6</clonedKey>
                <clonedKey>8</clonedKey>
                <clonedKey>3</clonedKey>
                <randomStuff>more words</randomStuff>
            </getThese>"]

Body:
You should be able to use tostring() to serialize the XML.

Example...

from lxml import etree

xml = """
<xml>
    <getThese>
        <clonedKey>1</clonedKey>
        <clonedKey>2</clonedKey>
        <clonedKey>3</clonedKey>
        <randomStuff>this is a sentence</randomStuff>
    </getThese>
    <getThese>
        <clonedKey>6</clonedKey>
        <clonedKey>8</clonedKey>
        <clonedKey>3</clonedKey>
        <randomStuff>more words</randomStuff>
    </getThese>
</xml>
"""

parser = etree.XMLParser(remove_blank_text=True)

tree = etree.fromstring(xml, parser=parser)

elems = []

for elem in tree.xpath("getThese"):
    elems.append(etree.tostring(elem).decode())

print(elems)

Printed output...

['<getThese><clonedKey>1</clonedKey><clonedKey>2</clonedKey><clonedKey>3</clonedKey><randomStuff>this is a sentence</randomStuff></getThese>', '<getThese><clonedKey>6</clonedKey><clonedKey>8</clonedKey><clonedKey>3</clonedKey><randomStuff>more words</randomStuff></getThese>']


问:
measuring real running time of an algorithm
Approximately, how many physical instructions of MIPS does an abstract algorithm operation amortize to? As for an abstract algorithm operation, I means a basic operation, such as add, divide, etc.

I see this is not a strict measuring technique :-)

Kejia

答:
Donald Knuth addressed this very problem in writing Volume 1 of "The Art of Computer Programming".
In the preface he gives a lengthy justification for presenting algorithms in the assembly code for an imaginary machine -

... To avoid this dilemma, I have
  attempted to design an "ideal"
  computer called "MIX," with very
  simple rules of operation ...

That way, one can talk sensibly about how many "cycles" an algorithm would take, without having to care about differences between machines, caching, latency, pipelines, or any of the other ways computers have been optimized to save time, at the expense of knowing how long they will take.

ContentLicense: CC BY-SA 2.5


问:
how to get json object in laravel controller
I'm performing and API that receive json object, but cannot read it. Actually I don't know if it should be received as Request, or how...

First I try to get the json and decode it to an array. After that, I return the same array to json in the response. But it's returned as empty ({})

That's my route

```<code>Route::post('enviar_encuestas', 'EncuestaUsuarioController@store');
</code>```

And in my controller, for that method I perform the following

```<code>public function store(Request $request){
    $users = json_decode($request);
    return response()->json($users);
}
</code>```

In Postman I send perform the following
HTTP POST Request to

```<code>https://encuestasapi.informixsys.com.ar/public/enviar_encuestas
</code>```

I select Body and raw, after that I select JSON(application/json)
and write the following

```<code>{
        "id_encuesta" : 1,
        "email" : "asd@hotmail.com",
        "razon_social" : "asd",
        "nro_ref_autopack" : 1
}
</code>```

答:
You could retrieve the posted json data and return it back as json through:</p>

```<code>public function store(Request $request){
    $users = json_decode($request->json()->all());
    return response()->json($users);
}
</code>```

Body:
I'm performing and API that receive json object, but cannot read it. Actually I don't know if it should be received as Request, or how...

First I try to get the json and decode it to an array. After that, I return the same array to json in the response. But it's returned as empty ({})

That's my route

Route::post('enviar_encuestas', 'EncuestaUsuarioController@store');

And in my controller, for that method I perform the following

public function store(Request $request){
    $users = json_decode($request);
    return response()->json($users);
}

In Postman I send perform the following
HTTP POST Request to

https://encuestasapi.informixsys.com.ar/public/enviar_encuestas

I select Body and raw, after that I select JSON(application/json)
and write the following

{
        "id_encuesta" : 1,
        "email" : "asd@hotmail.com",
        "razon_social" : "asd",
        "nro_ref_autopack" : 1
}

Body:
You could retrieve the posted json data and return it back as json through:

public function store(Request $request){
    $users = json_decode($request->json()->all());
    return response()->json($users);
}


问:
Why does `precise` qualifier not take effect?
I'm trying to improve Henry Thasler's GLSL implementation of double-single arithmetic (from his GLSL Mandelbrot demo) to work reliably on NVIDIA graphics on Linux. I've recently learned that since OpenGL 4.0 (§4.7 The Precise Qualifier in the spec) or with GL_ARB_gpu_shader5 extension (spec) we can use precise qualifier to make the calculations follow exact sequence of arithmetic operations specified in the GLSL source.

But the following attempt appears to not give any improvement:

#version 330
#extension GL_ARB_gpu_shader5 : require

vec2 ds_add(vec2 dsa, vec2 dsb)
{
    precise float t1 = dsa.x + dsb.x;
    precise float e = t1 - dsa.x;
    precise float t2 = ((dsb.x - e) + (dsa.x - (t1 - e))) + dsa.y + dsb.y;

    precise vec2 dsc;
    dsc.x = t1 + t2;
    dsc.y = t2 - (dsc.x - t1);
    return dsc;
}
```

<p>The result is the same as if there were no <code>precise</code> added. I've checked that the algorithm itself is correct: it works as is (even without <code>precise</code>) on Intel Core i7-4765T built-in graphics, and if I hide some variables to inhibit optimizations, then NVidia also gives the correct results. Here's how I inhibit the optimizations:</p>

<pre class="lang-c prettyprint-override"><code>#version 330

#define hide(x) ((x)*one)
uniform float one=1;

vec2 ds_add(vec2 dsa, vec2 dsb)
{
    float t1 = dsa.x + dsb.x;
    float e = hide(t1) - dsa.x;
    float t2 = ((dsb.x - e) + (dsa.x - (t1 - e))) + dsa.y + dsb.y;

    vec2 dsc;
    dsc.x = t1 + t2;
    dsc.y = t2 - (hide(dsc.x) - t1);
    return dsc;
}
</code>```

So, apparently, I'm using the precise qualifier incorrectly. But what exactly is wrong here?

For reference, I'm using NVidia GeForce GTX 750Ti with binary nvidia driver 390.116. Here's the full C++ test:

#include <cmath>
#include <vector>
#include <string>
#include <limits>
#include <iomanip>
#include <iostream>
// glad.h is generated by the following command:
// glad --out-path=. --generator=c --omit-khrplatform --api="gl=3.3" --profile=core --extensions=
#include "glad/glad.h"
#include <GL/freeglut.h>
#include <glm/glm.hpp>
using glm::vec4;

GLuint vao, vbo;
GLuint texFBO;
GLuint program;
GLuint fbo;
int width=1, height=2;

void printShaderOutput(int texW, int texH)
{
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, texFBO);

    std::vector<vec4> data(texW*texH);
    glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_FLOAT, data.data());
    std::cout << "a,b,sum,relError(sum),note\n";
    for(int i=0;i<width;++i)
    {
        const auto a=double(data[i+width*0].x)+double(data[i+width*0].y);
        const auto b=double(data[i+width*0].z)+double(data[i+width*0].w);
        const auto sum=double(data[i+width*1].x)+double(data[i+width*1].y);
        const auto trueSum=a+b;
        const auto sumErr=(sum-trueSum)/trueSum;
        std::cout << std::setprecision(std::numeric_limits<double>::max_digits10)
                  << a << ',' << b << ','
                  << sum << ','
                  << std::setprecision(3)
                  << sumErr << ','
                  << (std::abs(sumErr)>1e-14 ? "WARN" : "OK")
                  << '\n';
    }
    std::cout.flush();
}

GLuint makeShader(GLenum type, std::string const& srcStr)
{
    const auto shader=glCreateShader(type);
    const GLint srcLen=srcStr.size();
    const GLchar*const src=srcStr.c_str();
    glShaderSource(shader, 1, &src, &srcLen);
    glCompileShader(shader);
    GLint status=-1;
    glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
    assert(glGetError()==GL_NO_ERROR);
    assert(status);
    return shader;
}

void loadShaders()
{
    program=glCreateProgram();

    const auto vertexShader=makeShader(GL_VERTEX_SHADER, 1+R"(
#version 330
in vec4 vertex;
void main() { gl_Position=vertex; }
)");
    glAttachShader(program, vertexShader);

    const auto fragmentShader=makeShader(GL_FRAGMENT_SHADER, 1+R"(
#version 330
#extension GL_ARB_gpu_shader5 : require

vec2 ds_add(vec2 dsa, vec2 dsb)
{
    precise float t1 = dsa.x + dsb.x;
    precise float e = t1 - dsa.x;
    precise float t2 = ((dsb.x - e) + (dsa.x - (t1 - e))) + dsa.y + dsb.y;

    precise vec2 dsc;
    dsc.x = t1 + t2;
    dsc.y = t2 - (dsc.x - t1);
    return dsc;
}

uniform vec2 a, b;
out vec4 color;

void main()
{
    if(gl_FragCoord.y<1)   // first row
        color=vec4(a,b);
    else if(gl_FragCoord.y<2)   // second row
        color=vec4(ds_add(a,b),0,0);
}

)");
    glAttachShader(program, fragmentShader);

    glLinkProgram(program);
    GLint status=0;
    glGetProgramiv(program, GL_LINK_STATUS, &status);
    assert(glGetError()==GL_NO_ERROR);
    assert(status);

    glDetachShader(program, fragmentShader);
    glDeleteShader(fragmentShader);

    glDetachShader(program, vertexShader);
    glDeleteShader(vertexShader);
}

void setupBuffers()
{
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);
    glGenBuffers(1, &vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    const GLfloat vertices[]=
    {
        -1, -1,
         1, -1,
        -1,  1,
         1,  1,
    };
    glBufferData(GL_ARRAY_BUFFER, sizeof vertices, vertices, GL_STATIC_DRAW);
    constexpr GLuint attribIndex=0;
    constexpr int coordsPerVertex=2;
    glVertexAttribPointer(attribIndex, coordsPerVertex, GL_FLOAT, false, 0, 0);
    glEnableVertexAttribArray(attribIndex);
    glBindVertexArray(0);
}

bool init()
{
    if(!gladLoadGL())
    {
        std::cerr << "Failed to initialize GLAD\n";
        return false;
    }
    if(!GLAD_GL_VERSION_3_3)
    {
        std::cerr << "OpenGL 3.3 not supported\n";
        return false;
    }

    glGenTextures(1, &texFBO);
    glGenFramebuffers(1,&fbo);

    loadShaders();
    setupBuffers();

    glViewport(0,0,width,height);

    glBindTexture(GL_TEXTURE_2D,texFBO);
    glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA32F,width,height,0,GL_RGBA,GL_UNSIGNED_BYTE,nullptr);
    glBindTexture(GL_TEXTURE_2D,0);
    glBindFramebuffer(GL_FRAMEBUFFER,fbo);
    glFramebufferTexture2D(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0,GL_TEXTURE_2D,texFBO,0);
    const auto status=glCheckFramebufferStatus(GL_FRAMEBUFFER);
    assert(status==GL_FRAMEBUFFER_COMPLETE);
    glBindFramebuffer(GL_FRAMEBUFFER,0);

    return true;
}

void display()
{
    const static bool inited=init();
    if(!inited) std::exit(1);

    glBindFramebuffer(GL_FRAMEBUFFER,fbo);

    glUseProgram(program);
#define SPLIT_DOUBLE_TO_FLOATS(x) GLfloat(x),GLfloat(x-GLfloat(x))
    glUniform2f(glGetUniformLocation(program,"a"),SPLIT_DOUBLE_TO_FLOATS(3.1415926535897932));
    glUniform2f(glGetUniformLocation(program,"b"),SPLIT_DOUBLE_TO_FLOATS(2.7182818284590452));
    glUniform1f(glGetUniformLocation(program,"rtWidth"),width);

    glBindVertexArray(vao);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    glBindVertexArray(0);

    printShaderOutput(width, height);
    std::exit(0);

    glFinish();
}

int main(int argc, char** argv)
{
    glutInitContextVersion(3,3);
    glutInitContextProfile(GLUT_CORE_PROFILE);
    glutInit(&argc, argv);

    glutInitDisplayMode(GLUT_RGB);

    glutInitWindowSize(width, height);
    glutCreateWindow("Test");
    glutDisplayFunc(display);

    glutMainLoop();
}
```

<p>I've been able to extract the NVfp5.0 assembly from the GLSL program binaries in the different cases:</p>

<ul>
<li>Naïve case without <code>hide</code> and without <code>precise</code>:</li>
</ul>

```!!NVfp5.0
OPTION NV_internal;
OPTION NV_bindless_texture;
PARAM c[2] = { program.local[0..1] };
TEMP R0;
TEMP T;
TEMP RC, HC;
OUTPUT result_color0 = result.color;
SLT.F R0.x, fragment.position.y, {1, 0, 0, 0};
TRUNC.U.CC HC.x, R0;
IF NE.x;
MOV.F result_color0.xy, c[0];
MOV.F result_color0.zw, c[1].xyxy;
ELSE;
SLT.F R0.x, fragment.position.y, {2, 0, 0, 0};
TRUNC.U.CC HC.x, R0;
IF NE.x;
ADD.F R0.y, -c[0].x, c[0].x;
ADD.F R0.x, -c[1], c[1];
ADD.F R0.x, R0, R0.y;
ADD.F R0.x, R0, c[0].y;
ADD.F R0.y, R0.x, c[1];
ADD.F R0.x, c[0], c[1];
ADD.F result_color0.x, R0, R0.y;
ADD.F result_color0.y, R0, -R0;
MOV.F result_color0.zw, {0, 0, 0, 0}.x;
ENDIF;
ENDIF;
END
```

<ul>
<li>The case with <code>precise</code> (notice that nothing changes except <code>.PREC</code> suffix in the "instructions"):</li>
</ul>

```!!NVfp5.0
OPTION NV_internal;
OPTION NV_bindless_texture;
PARAM c[2] = { program.local[0..1] };
TEMP R0;
TEMP T;
TEMP RC, HC;
OUTPUT result_color0 = result.color;
SLT.F R0.x, fragment.position.y, {1, 0, 0, 0};
TRUNC.U.CC HC.x, R0;
IF NE.x;
MOV.F result_color0.xy, c[0];
MOV.F result_color0.zw, c[1].xyxy;
ELSE;
SLT.F R0.x, fragment.position.y, {2, 0, 0, 0};
TRUNC.U.CC HC.x, R0;
IF NE.x;
ADD.F.PREC R0.y, -c[0].x, c[0].x;
ADD.F.PREC R0.x, -c[1], c[1];
ADD.F.PREC R0.x, R0, R0.y;
ADD.F.PREC R0.x, R0, c[0].y;
ADD.F.PREC R0.y, R0.x, c[1];
ADD.F.PREC R0.x, c[0], c[1];
ADD.F.PREC result_color0.x, R0, R0.y;
ADD.F.PREC result_color0.y, R0, -R0;
MOV.F result_color0.zw, {0, 0, 0, 0}.x;
ENDIF;
ENDIF;
END
```

<ul>
<li>The case with <code>hide</code>, which does work, and obviously has a different sequence of arithmetic operations:</li>
</ul>

```!!NVfp5.0
OPTION NV_internal;
OPTION NV_bindless_texture;
PARAM c[3] = { program.local[0..2] };
TEMP R0, R1;
TEMP T;
TEMP RC, HC;
OUTPUT result_color0 = result.color;
SLT.F R0.x, fragment.position.y, {1, 0, 0, 0};
TRUNC.U.CC HC.x, R0;
IF NE.x;
MOV.F result_color0.xy, c[1];
MOV.F result_color0.zw, c[2].xyxy;
ELSE;
SLT.F R0.x, fragment.position.y, {2, 0, 0, 0};
TRUNC.U.CC HC.x, R0;
IF NE.x;
ADD.F R0.x, c[1], c[2];
MAD.F R0.y, R0.x, c[0].x, -c[1].x;
ADD.F R0.z, R0.x, -R0.y;
ADD.F R0.z, -R0, c[1].x;
ADD.F R0.y, -R0, c[2].x;
ADD.F R0.y, R0, R0.z;
ADD.F R0.y, R0, c[1];
ADD.F R0.y, R0, c[2];
ADD.F R1.x, R0, R0.y;
MAD.F R0.x, R1, c[0], -R0;
MOV.F R1.zw, {0, 0, 0, 0}.x;
ADD.F R1.y, R0, -R0.x;
MOV.F result_color0, R1;
ENDIF;
ENDIF;
END
```

答:
Nothing wrong with your shader. The ds_add() code just haven't any operation that could be merged at the compilation time. Usually add and multiply/divide merge. But your code have add operations only.

Update:

In the case all your variables are stored in GPU registers during calculation process. Order of operations for registers doesn't depend on code or compiler. It doesn't even depend on just hardware. It depends on currently running operations in the GPU.

Precision of floating point operations between registers isn't strictly 32 bit. It usually higher then. The actual precision for GPUs is a commercial secret. The actual precision for x86 FPU is 80 bit or 128 bit, despite the variables are stored in 32 bit memory.

However GPUs are not designed for very precise calculation. The algorithm's author knows it and implements double thought pairs of 32-bit floats. If you need to advance precision, then you have to use long double with quads of 32-bit floats. Simple 'precise' doesn't help.

Body:
I'm trying to improve Henry Thasler's GLSL implementation of double-single arithmetic (from his GLSL Mandelbrot demo) to work reliably on NVIDIA graphics on Linux. I've recently learned that since OpenGL 4.0 (§4.7 The Precise Qualifier in the spec) or with GL_ARB_gpu_shader5 extension (spec) we can use precise qualifier to make the calculations follow exact sequence of arithmetic operations specified in the GLSL source.

But the following attempt appears to not give any improvement:

#version 330
#extension GL_ARB_gpu_shader5 : require

vec2 ds_add(vec2 dsa, vec2 dsb)
{
    precise float t1 = dsa.x + dsb.x;
    precise float e = t1 - dsa.x;
    precise float t2 = ((dsb.x - e) + (dsa.x - (t1 - e))) + dsa.y + dsb.y;

    precise vec2 dsc;
    dsc.x = t1 + t2;
    dsc.y = t2 - (dsc.x - t1);
    return dsc;
}

The result is the same as if there were no precise added. I've checked that the algorithm itself is correct: it works as is (even without precise) on Intel Core i7-4765T built-in graphics, and if I hide some variables to inhibit optimizations, then NVidia also gives the correct results. Here's how I inhibit the optimizations:

#version 330

#define hide(x) ((x)*one)
uniform float one=1;

vec2 ds_add(vec2 dsa, vec2 dsb)
{
    float t1 = dsa.x + dsb.x;
    float e = hide(t1) - dsa.x;
    float t2 = ((dsb.x - e) + (dsa.x - (t1 - e))) + dsa.y + dsb.y;

    vec2 dsc;
    dsc.x = t1 + t2;
    dsc.y = t2 - (hide(dsc.x) - t1);
    return dsc;
}

So, apparently, I'm using the precise qualifier incorrectly. But what exactly is wrong here?

For reference, I'm using NVidia GeForce GTX 750Ti with binary nvidia driver 390.116. Here's the full C++ test:

#include <cmath>
#include <vector>
#include <string>
#include <limits>
#include <iomanip>
#include <iostream>
// glad.h is generated by the following command:
// glad --out-path=. --generator=c --omit-khrplatform --api="gl=3.3" --profile=core --extensions=
#include "glad/glad.h"
#include <GL/freeglut.h>
#include <glm/glm.hpp>
using glm::vec4;

GLuint vao, vbo;
GLuint texFBO;
GLuint program;
GLuint fbo;
int width=1, height=2;

void printShaderOutput(int texW, int texH)
{
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, texFBO);

    std::vector<vec4> data(texW*texH);
    glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_FLOAT, data.data());
    std::cout << "a,b,sum,relError(sum),note\n";
    for(int i=0;i<width;++i)
    {
        const auto a=double(data[i+width*0].x)+double(data[i+width*0].y);
        const auto b=double(data[i+width*0].z)+double(data[i+width*0].w);
        const auto sum=double(data[i+width*1].x)+double(data[i+width*1].y);
        const auto trueSum=a+b;
        const auto sumErr=(sum-trueSum)/trueSum;
        std::cout << std::setprecision(std::numeric_limits<double>::max_digits10)
                  << a << ',' << b << ','
                  << sum << ','
                  << std::setprecision(3)
                  << sumErr << ','
                  << (std::abs(sumErr)>1e-14 ? "WARN" : "OK")
                  << '\n';
    }
    std::cout.flush();
}

GLuint makeShader(GLenum type, std::string const& srcStr)
{
    const auto shader=glCreateShader(type);
    const GLint srcLen=srcStr.size();
    const GLchar*const src=srcStr.c_str();
    glShaderSource(shader, 1, &src, &srcLen);
    glCompileShader(shader);
    GLint status=-1;
    glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
    assert(glGetError()==GL_NO_ERROR);
    assert(status);
    return shader;
}

void loadShaders()
{
    program=glCreateProgram();

    const auto vertexShader=makeShader(GL_VERTEX_SHADER, 1+R"(
#version 330
in vec4 vertex;
void main() { gl_Position=vertex; }
)");
    glAttachShader(program, vertexShader);

    const auto fragmentShader=makeShader(GL_FRAGMENT_SHADER, 1+R"(
#version 330
#extension GL_ARB_gpu_shader5 : require

vec2 ds_add(vec2 dsa, vec2 dsb)
{
    precise float t1 = dsa.x + dsb.x;
    precise float e = t1 - dsa.x;
    precise float t2 = ((dsb.x - e) + (dsa.x - (t1 - e))) + dsa.y + dsb.y;

    precise vec2 dsc;
    dsc.x = t1 + t2;
    dsc.y = t2 - (dsc.x - t1);
    return dsc;
}

uniform vec2 a, b;
out vec4 color;

void main()
{
    if(gl_FragCoord.y<1)   // first row
        color=vec4(a,b);
    else if(gl_FragCoord.y<2)   // second row
        color=vec4(ds_add(a,b),0,0);
}

)");
    glAttachShader(program, fragmentShader);

    glLinkProgram(program);
    GLint status=0;
    glGetProgramiv(program, GL_LINK_STATUS, &status);
    assert(glGetError()==GL_NO_ERROR);
    assert(status);

    glDetachShader(program, fragmentShader);
    glDeleteShader(fragmentShader);

    glDetachShader(program, vertexShader);
    glDeleteShader(vertexShader);
}

void setupBuffers()
{
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);
    glGenBuffers(1, &vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    const GLfloat vertices[]=
    {
        -1, -1,
         1, -1,
        -1,  1,
         1,  1,
    };
    glBufferData(GL_ARRAY_BUFFER, sizeof vertices, vertices, GL_STATIC_DRAW);
    constexpr GLuint attribIndex=0;
    constexpr int coordsPerVertex=2;
    glVertexAttribPointer(attribIndex, coordsPerVertex, GL_FLOAT, false, 0, 0);
    glEnableVertexAttribArray(attribIndex);
    glBindVertexArray(0);
}

bool init()
{
    if(!gladLoadGL())
    {
        std::cerr << "Failed to initialize GLAD\n";
        return false;
    }
    if(!GLAD_GL_VERSION_3_3)
    {
        std::cerr << "OpenGL 3.3 not supported\n";
        return false;
    }

    glGenTextures(1, &texFBO);
    glGenFramebuffers(1,&fbo);

    loadShaders();
    setupBuffers();

    glViewport(0,0,width,height);

    glBindTexture(GL_TEXTURE_2D,texFBO);
    glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA32F,width,height,0,GL_RGBA,GL_UNSIGNED_BYTE,nullptr);
    glBindTexture(GL_TEXTURE_2D,0);
    glBindFramebuffer(GL_FRAMEBUFFER,fbo);
    glFramebufferTexture2D(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0,GL_TEXTURE_2D,texFBO,0);
    const auto status=glCheckFramebufferStatus(GL_FRAMEBUFFER);
    assert(status==GL_FRAMEBUFFER_COMPLETE);
    glBindFramebuffer(GL_FRAMEBUFFER,0);

    return true;
}

void display()
{
    const static bool inited=init();
    if(!inited) std::exit(1);

    glBindFramebuffer(GL_FRAMEBUFFER,fbo);

    glUseProgram(program);
#define SPLIT_DOUBLE_TO_FLOATS(x) GLfloat(x),GLfloat(x-GLfloat(x))
    glUniform2f(glGetUniformLocation(program,"a"),SPLIT_DOUBLE_TO_FLOATS(3.1415926535897932));
    glUniform2f(glGetUniformLocation(program,"b"),SPLIT_DOUBLE_TO_FLOATS(2.7182818284590452));
    glUniform1f(glGetUniformLocation(program,"rtWidth"),width);

    glBindVertexArray(vao);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    glBindVertexArray(0);

    printShaderOutput(width, height);
    std::exit(0);

    glFinish();
}

int main(int argc, char** argv)
{
    glutInitContextVersion(3,3);
    glutInitContextProfile(GLUT_CORE_PROFILE);
    glutInit(&argc, argv);

    glutInitDisplayMode(GLUT_RGB);

    glutInitWindowSize(width, height);
    glutCreateWindow("Test");
    glutDisplayFunc(display);

    glutMainLoop();
}

I've been able to extract the NVfp5.0 assembly from the GLSL program binaries in the different cases:

Naïve case without hide and without precise:

!!NVfp5.0
OPTION NV_internal;
OPTION NV_bindless_texture;
PARAM c[2] = { program.local[0..1] };
TEMP R0;
TEMP T;
TEMP RC, HC;
OUTPUT result_color0 = result.color;
SLT.F R0.x, fragment.position.y, {1, 0, 0, 0};
TRUNC.U.CC HC.x, R0;
IF NE.x;
MOV.F result_color0.xy, c[0];
MOV.F result_color0.zw, c[1].xyxy;
ELSE;
SLT.F R0.x, fragment.position.y, {2, 0, 0, 0};
TRUNC.U.CC HC.x, R0;
IF NE.x;
ADD.F R0.y, -c[0].x, c[0].x;
ADD.F R0.x, -c[1], c[1];
ADD.F R0.x, R0, R0.y;
ADD.F R0.x, R0, c[0].y;
ADD.F R0.y, R0.x, c[1];
ADD.F R0.x, c[0], c[1];
ADD.F result_color0.x, R0, R0.y;
ADD.F result_color0.y, R0, -R0;
MOV.F result_color0.zw, {0, 0, 0, 0}.x;
ENDIF;
ENDIF;
END

The case with precise (notice that nothing changes except .PREC suffix in the "instructions"):

!!NVfp5.0
OPTION NV_internal;
OPTION NV_bindless_texture;
PARAM c[2] = { program.local[0..1] };
TEMP R0;
TEMP T;
TEMP RC, HC;
OUTPUT result_color0 = result.color;
SLT.F R0.x, fragment.position.y, {1, 0, 0, 0};
TRUNC.U.CC HC.x, R0;
IF NE.x;
MOV.F result_color0.xy, c[0];
MOV.F result_color0.zw, c[1].xyxy;
ELSE;
SLT.F R0.x, fragment.position.y, {2, 0, 0, 0};
TRUNC.U.CC HC.x, R0;
IF NE.x;
ADD.F.PREC R0.y, -c[0].x, c[0].x;
ADD.F.PREC R0.x, -c[1], c[1];
ADD.F.PREC R0.x, R0, R0.y;
ADD.F.PREC R0.x, R0, c[0].y;
ADD.F.PREC R0.y, R0.x, c[1];
ADD.F.PREC R0.x, c[0], c[1];
ADD.F.PREC result_color0.x, R0, R0.y;
ADD.F.PREC result_color0.y, R0, -R0;
MOV.F result_color0.zw, {0, 0, 0, 0}.x;
ENDIF;
ENDIF;
END

The case with hide, which does work, and obviously has a different sequence of arithmetic operations:

!!NVfp5.0
OPTION NV_internal;
OPTION NV_bindless_texture;
PARAM c[3] = { program.local[0..2] };
TEMP R0, R1;
TEMP T;
TEMP RC, HC;
OUTPUT result_color0 = result.color;
SLT.F R0.x, fragment.position.y, {1, 0, 0, 0};
TRUNC.U.CC HC.x, R0;
IF NE.x;
MOV.F result_color0.xy, c[1];
MOV.F result_color0.zw, c[2].xyxy;
ELSE;
SLT.F R0.x, fragment.position.y, {2, 0, 0, 0};
TRUNC.U.CC HC.x, R0;
IF NE.x;
ADD.F R0.x, c[1], c[2];
MAD.F R0.y, R0.x, c[0].x, -c[1].x;
ADD.F R0.z, R0.x, -R0.y;
ADD.F R0.z, -R0, c[1].x;
ADD.F R0.y, -R0, c[2].x;
ADD.F R0.y, R0, R0.z;
ADD.F R0.y, R0, c[1];
ADD.F R0.y, R0, c[2];
ADD.F R1.x, R0, R0.y;
MAD.F R0.x, R1, c[0], -R0;
MOV.F R1.zw, {0, 0, 0, 0}.x;
ADD.F R1.y, R0, -R0.x;
MOV.F result_color0, R1;
ENDIF;
ENDIF;
END


问:
Examine two columns and delete lowest number of the id of column named contentid
Data comes from:

```<code>SELECT
    CONTENTID, t1.TITLE, t1.PAGEID, COUNT, SPACENAME, CREATIONDATE, LASTMODDATE, VERSION
FROM
    (SELECT
         SPACEID, TITLE, PAGEID, COUNT(*) AS COUNT
     FROM
         CONTENT
     WHERE
         CONTENTTYPE = 'ATTACHMENT'
     GROUP BY
         TITLE, PAGEID, SPACEID
     HAVING
         COUNT(TITLE) > 1 AND COUNT(PAGEID) > 1) t1
JOIN
    (SELECT
         CONTENTID, CREATIONDATE, LASTMODDATE, VERSION, TITLE, PAGEID
     FROM
         CONTENT
     WHERE
         VERSION = 1) t4 ON t4.PAGEID = t1.PAGEID
JOIN
    (SELECT
         SPACEID, SPACENAME
     FROM
         SPACES) t2 ON t1.SPACEID = t2.SPACEID
ORDER BY
    t1.PAGEID,t1.TITLE, CREATIONDATE, LASTMODDATE
</code>```

Output (removed some of the columns because it is just the first two needed to make the decision on what to remove and it is easier to display here):

```<code>CONTENTID   TITLE
--------------------------------------------
26902677    Time Logging Guidelines V5.docx
46170401    Time Logging Guidelines V5.docx
157909073   Time Logging Guidelines V5.docx
157909072   Time Logging Guidelines V5.docx
355860497   Time Logging Guidelines V5.docx
535953771   Time Logging Guidelines V5.docx
540117589   Time Logging Guidelines V5.docx
554729950   Time Logging Guidelines V5.docx
1246646     Induction Plan Template.docx
472350756   Induction Plan Template.docx
535953845   Induction Plan Template.docx
544508546   Induction Plan Template.docx
544508547   Induction Plan Template.docx
</code>```

I need to delete all but the highest contentid for each title.  There are actually about 66k of rows of this type of fix

The end result for the output above:

```<code>554729950   Time Logging Guidelines V5.docx
544508547   Induction Plan Template.docx
</code>```

答:
One way would be to use ROW_NUMBER() to generate a number for every row of data, and PARTITION it by the TITLE column descending. This would give you a number of 1 for the highest CONTENTID for every TITLE. You can then delete everything that does not have a row number of 1.

Here's an example.

```<code>-- create a temp table to store the test data
IF OBJECT_ID('tempdb..#test_data') IS NOT NULL DROP TABLE #test_data
CREATE TABLE #test_data (
    content_id INT NOT NULL,
    title VARCHAR(100) NOT NULL
)

-- add the test data
INSERT INTO #test_data
SELECT 26902677    , 'Time Logging Guidelines V5.docx'
UNION SELECT 46170401    , 'Time Logging Guidelines V5.docx'
UNION SELECT 157909073  , 'Time Logging Guidelines V5.docx'
UNION SELECT 157909072  , 'Time Logging Guidelines V5.docx'
UNION SELECT 355860497  , 'Time Logging Guidelines V5.docx'
UNION SELECT 535953771  , 'Time Logging Guidelines V5.docx'
UNION SELECT 540117589  , 'Time Logging Guidelines V5.docx'
UNION SELECT 554729950  , 'Time Logging Guidelines V5.docx'
UNION SELECT 1246646      , 'Induction Plan Template.docx'
UNION SELECT 472350756  , 'Induction Plan Template.docx'
UNION SELECT 535953845  , 'Induction Plan Template.docx'
UNION SELECT 544508546  , 'Induction Plan Template.docx'
UNION SELECT 544508547  , 'Induction Plan Template.docx';

-- generate an row number for each row of the data
WITH ordered AS (
    SELECT
        content_id,
        title,
        ROW_NUMBER() OVER (PARTITION BY title ORDER BY content_id DESC) AS row_num
    FROM
        #test_data
        )

-- delete all the rows that are not equal to 1
DELETE d
FROM #test_data d
INNER JOIN ordered o ON d.content_id = o.content_id AND o.row_num > 1

-- check the results
SELECT * FROM #test_data
</code>```

Body:
Data comes from:

SELECT
    CONTENTID, t1.TITLE, t1.PAGEID, COUNT, SPACENAME, CREATIONDATE, LASTMODDATE, VERSION
FROM
    (SELECT
         SPACEID, TITLE, PAGEID, COUNT(*) AS COUNT
     FROM
         CONTENT
     WHERE
         CONTENTTYPE = 'ATTACHMENT'
     GROUP BY
         TITLE, PAGEID, SPACEID
     HAVING
         COUNT(TITLE) > 1 AND COUNT(PAGEID) > 1) t1
JOIN
    (SELECT
         CONTENTID, CREATIONDATE, LASTMODDATE, VERSION, TITLE, PAGEID
     FROM
         CONTENT
     WHERE
         VERSION = 1) t4 ON t4.PAGEID = t1.PAGEID
JOIN
    (SELECT
         SPACEID, SPACENAME
     FROM
         SPACES) t2 ON t1.SPACEID = t2.SPACEID
ORDER BY
    t1.PAGEID,t1.TITLE, CREATIONDATE, LASTMODDATE

Output (removed some of the columns because it is just the first two needed to make the decision on what to remove and it is easier to display here):

CONTENTID   TITLE
--------------------------------------------
26902677    Time Logging Guidelines V5.docx
46170401    Time Logging Guidelines V5.docx
157909073   Time Logging Guidelines V5.docx
157909072   Time Logging Guidelines V5.docx
355860497   Time Logging Guidelines V5.docx
535953771   Time Logging Guidelines V5.docx
540117589   Time Logging Guidelines V5.docx
554729950   Time Logging Guidelines V5.docx
1246646     Induction Plan Template.docx
472350756   Induction Plan Template.docx
535953845   Induction Plan Template.docx
544508546   Induction Plan Template.docx
544508547   Induction Plan Template.docx

I need to delete all but the highest contentid for each title.  There are actually about 66k of rows of this type of fix

The end result for the output above:

554729950   Time Logging Guidelines V5.docx
544508547   Induction Plan Template.docx

Body:
One way would be to use ROW_NUMBER() to generate a number for every row of data, and PARTITION it by the TITLE column descending. This would give you a number of 1 for the highest CONTENTID for every TITLE. You can then delete everything that does not have a row number of 1.

Here's an example.

-- create a temp table to store the test data
IF OBJECT_ID('tempdb..#test_data') IS NOT NULL DROP TABLE #test_data
CREATE TABLE #test_data (
    content_id INT NOT NULL,
    title VARCHAR(100) NOT NULL
)

-- add the test data
INSERT INTO #test_data
SELECT 26902677    , 'Time Logging Guidelines V5.docx'
UNION SELECT 46170401    , 'Time Logging Guidelines V5.docx'
UNION SELECT 157909073  , 'Time Logging Guidelines V5.docx'
UNION SELECT 157909072  , 'Time Logging Guidelines V5.docx'
UNION SELECT 355860497  , 'Time Logging Guidelines V5.docx'
UNION SELECT 535953771  , 'Time Logging Guidelines V5.docx'
UNION SELECT 540117589  , 'Time Logging Guidelines V5.docx'
UNION SELECT 554729950  , 'Time Logging Guidelines V5.docx'
UNION SELECT 1246646      , 'Induction Plan Template.docx'
UNION SELECT 472350756  , 'Induction Plan Template.docx'
UNION SELECT 535953845  , 'Induction Plan Template.docx'
UNION SELECT 544508546  , 'Induction Plan Template.docx'
UNION SELECT 544508547  , 'Induction Plan Template.docx';

-- generate an row number for each row of the data
WITH ordered AS (
    SELECT
        content_id,
        title,
        ROW_NUMBER() OVER (PARTITION BY title ORDER BY content_id DESC) AS row_num
    FROM
        #test_data
        )

-- delete all the rows that are not equal to 1
DELETE d
FROM #test_data d
INNER JOIN ordered o ON d.content_id = o.content_id AND o.row_num > 1

-- check the results
SELECT * FROM #test_data


问:
cannot read property 'apply' of undefined gulp
I am trying to use the ng-factory generator to scaffold a new project to build an angularjs component. After the project has been created with the yo ng-factory command, I tried to run it using the gulp serve task but found the following error:

```<code>c:\projects\bywebclient>gulp serve
[11:20:51] Loading C:\projects\bywebclient\gulp_tasks\browsersync.js
[11:20:52] Loading C:\projects\bywebclient\gulp_tasks\karma.js
[11:20:57] Loading C:\projects\bywebclient\gulp_tasks\misc.js
[11:20:57] Loading C:\projects\bywebclient\gulp_tasks\webpack.js
[11:21:07] Using gulpfile c:\projects\bywebclient\gulpfile.js
C:\Users\ATUL KALE\AppData\Roaming\npm\node_modules\gulp\bin\gulp.js:129
gulpInst.start.apply(gulpInst, toRun);
</code>```

^

TypeError: Cannot read property 'apply' of undefined

  at C:\Users\ATUL KALE\AppData\Roaming\npm\node_modules\gulp\bin\gulp.js:129:
  19

  at _combinedTickCallback (internal/process/next_tick.js:67:7)

  at process._tickCallback (internal/process/next_tick.js:98:9)

  at Module.runMain (module.js:577:11)

  at run (bootstrap_node.js:352:7)

  at startup (bootstrap_node.js:144:9)

  at bootstrap_node.js:467:3

Am I missing something? I already tried to run again the npm install

Thanks,
Atul Kale

答:
```<code>npm install -g gulp-cli
</code>```

And important: after running that command, open a new terminal so it'll take effect.

Body:
I am trying to use the ng-factory generator to scaffold a new project to build an angularjs component. After the project has been created with the yo ng-factory command, I tried to run it using the gulp serve task but found the following error:

c:\projects\bywebclient>gulp serve
[11:20:51] Loading C:\projects\bywebclient\gulp_tasks\browsersync.js
[11:20:52] Loading C:\projects\bywebclient\gulp_tasks\karma.js
[11:20:57] Loading C:\projects\bywebclient\gulp_tasks\misc.js
[11:20:57] Loading C:\projects\bywebclient\gulp_tasks\webpack.js
[11:21:07] Using gulpfile c:\projects\bywebclient\gulpfile.js
C:\Users\ATUL KALE\AppData\Roaming\npm\node_modules\gulp\bin\gulp.js:129
gulpInst.start.apply(gulpInst, toRun);

^

TypeError: Cannot read property 'apply' of undefined

  at C:\Users\ATUL KALE\AppData\Roaming\npm\node_modules\gulp\bin\gulp.js:129:
  19

  at _combinedTickCallback (internal/process/next_tick.js:67:7)

  at process._tickCallback (internal/process/next_tick.js:98:9)

  at Module.runMain (module.js:577:11)

  at run (bootstrap_node.js:352:7)

  at startup (bootstrap_node.js:144:9)

  at bootstrap_node.js:467:3

Am I missing something? I already tried to run again the npm install

Thanks,
Atul Kale

Body:
npm install -g gulp-cli

And important: after running that command, open a new terminal so it'll take effect.


问:
Question on how to draw back-to-back plot using R and ggplot2
I aiming  to draw a pyramid plot, like the one attached.

I found several example using  ggplot, but I am still struggling with the adoption of my example to my data (or the data that I want to plot).

```<code>structure(list(serial = c(40051004, 16160610, 16090310), DMSex = structure(c(2,
2, 2), label = "Gender from household grid", labels = c(`No answer/refused` = -9,
`Don't know` = -8, `Interview not achieved` = -7, `Schedule not applicable` = -2,
`Item not applicable` = -1, Male = 1, Female = 2), class = "haven_labelled"),
    dtotac = structure(c(-9, -9, -8), label = "DV: Total actual hours in all jobs and businesses", labels = c(`No answer/refused` = -9,
    `Don't know` = -8, `Interview not achieved` = -7, `Item not applicable` = -1
    ), class = "haven_labelled")), row.names = c(NA, -3L), class = c("tbl_df",
"tbl", "data.frame"))
</code>```

How can I convert my data and to draw the back-to-back plot? Or how to define the Gender and dtotac variables without subseting?

The code that I am using

```<code>library(ggplot2)
library(plyr)
library(gridExtra)

SerialGenderWorkN <- data.frame(Type = sample(c('Male', 'Female', 'Female'),
                                              11421, replace=TRUE),
                                dtotac = sample (0:60, 11421, replace=TRUE))

WrkFactor <- ordered(cut(SerialGenderWork$dtotac,
                         breaks = c(0, seq(20, 60, 10)),
                         include.lowest = TRUE))

SerialGenderWorkN$dtotac <- WrkFactor

ggplotWrk <- ggplot(data =SerialGenderWorkN, aes(x=dtotac))

ggplotWrk.female <- ggplotWrk +
  geom_bar(data=subset(SerialGenderWorkN, Type == 'Female'),
           aes( y = ..count../sum(..count..), fill = dtotac)) +
  scale_y_continuous('', labels = scales::percent) +
  theme(legend.position = 'none',
        axis.title.y = element_blank(),
        plot.title = element_text(size = 11.5),
        plot.margin=unit(c(0.1,0.2,0.1,-.1),"cm"),
        axis.ticks.y = element_blank(),
        axis.text.y = theme_bw()$axis.text.y) +
  ggtitle("Female") +
  theme(plot.title = element_text(hjust = 0.5)) +
  coord_flip()

ggplotWrk.male <- ggplotWrk +
  geom_bar(data=subset(SerialGenderWorkN,Type == 'Male'),
           aes( y = ..count../sum(..count..), fill = dtotac)) +
  scale_y_continuous('', labels = scales::percent,
                     trans = 'reverse') +
  theme(legend.position = 'none',
        axis.text.y = element_blank(),
        axis.ticks.y = element_blank(),
        plot.title = element_text(size = 11.5),
        plot.margin=unit(c(0.1,0.2,0.1,-.1),"cm")) +
  ggtitle("Male") +
  theme(plot.title = element_text(hjust = 0.5)) +
  coord_flip() +
  xlab("Work Hours")

## Plutting it together
grid.arrange(ggplotWrk.male, ggplotWrk.female,
             widths=c(0.4, 0.4), ncol=2)
</code>```

And this is the output

How can I move the "Work hours" to show between the "Male" and "Female" plots?

答:
You can use the top argument and bring it down using vjust.

grid.arrange(ggplotWrk.male, ggplotWrk.female,
             widths=c(0.4, 0.4), ncol=2,
             top = textGrob("Work Hours",gp=gpar(fontsize=11,font=1), vjust=2))
```

Body:
I aiming  to draw a pyramid plot, like the one attached.

I found several example using  ggplot, but I am still struggling with the adoption of my example to my data (or the data that I want to plot).

structure(list(serial = c(40051004, 16160610, 16090310), DMSex = structure(c(2,
2, 2), label = "Gender from household grid", labels = c(`No answer/refused` = -9,
`Don't know` = -8, `Interview not achieved` = -7, `Schedule not applicable` = -2,
`Item not applicable` = -1, Male = 1, Female = 2), class = "haven_labelled"),
    dtotac = structure(c(-9, -9, -8), label = "DV: Total actual hours in all jobs and businesses", labels = c(`No answer/refused` = -9,
    `Don't know` = -8, `Interview not achieved` = -7, `Item not applicable` = -1
    ), class = "haven_labelled")), row.names = c(NA, -3L), class = c("tbl_df",
"tbl", "data.frame"))

How can I convert my data and to draw the back-to-back plot? Or how to define the Gender and dtotac variables without subseting?

The code that I am using

library(ggplot2)
library(plyr)
library(gridExtra)

SerialGenderWorkN <- data.frame(Type = sample(c('Male', 'Female', 'Female'),
                                              11421, replace=TRUE),
                                dtotac = sample (0:60, 11421, replace=TRUE))

WrkFactor <- ordered(cut(SerialGenderWork$dtotac,
                         breaks = c(0, seq(20, 60, 10)),
                         include.lowest = TRUE))

SerialGenderWorkN$dtotac <- WrkFactor

ggplotWrk <- ggplot(data =SerialGenderWorkN, aes(x=dtotac))

ggplotWrk.female <- ggplotWrk +
  geom_bar(data=subset(SerialGenderWorkN, Type == 'Female'),
           aes( y = ..count../sum(..count..), fill = dtotac)) +
  scale_y_continuous('', labels = scales::percent) +
  theme(legend.position = 'none',
        axis.title.y = element_blank(),
        plot.title = element_text(size = 11.5),
        plot.margin=unit(c(0.1,0.2,0.1,-.1),"cm"),
        axis.ticks.y = element_blank(),
        axis.text.y = theme_bw()$axis.text.y) +
  ggtitle("Female") +
  theme(plot.title = element_text(hjust = 0.5)) +
  coord_flip()

ggplotWrk.male <- ggplotWrk +
  geom_bar(data=subset(SerialGenderWorkN,Type == 'Male'),
           aes( y = ..count../sum(..count..), fill = dtotac)) +
  scale_y_continuous('', labels = scales::percent,
                     trans = 'reverse') +
  theme(legend.position = 'none',
        axis.text.y = element_blank(),
        axis.ticks.y = element_blank(),
        plot.title = element_text(size = 11.5),
        plot.margin=unit(c(0.1,0.2,0.1,-.1),"cm")) +
  ggtitle("Male") +
  theme(plot.title = element_text(hjust = 0.5)) +
  coord_flip() +
  xlab("Work Hours")

## Plutting it together
grid.arrange(ggplotWrk.male, ggplotWrk.female,
             widths=c(0.4, 0.4), ncol=2)

And this is the output

How can I move the "Work hours" to show between the "Male" and "Female" plots?


问:
How to process gyroscope values to find orientation using python in real time?
I need to find in which direction the head is moving in real time using python. The device placed on head returns 9 values (Gyroscope, Acceleration and Magnetometer) in degrees per second unit. Now how do I process these values in real time to get head orientation. I wish to know in which direction the user is moving his/her head like left-right or up-down. How to do it in python? </p>

答: In JavaScript, it should be simple. Just take the start value zaxis and calculate decrease or increase degrees of z value. So you get the moving direction of your head if your phone is horizontal. Have a look here


问:
implement custom workflow in azure functions with time trigger in dynamics 365 at specified time
I have a custom workflow that copies the attachments from an email and places the copy in the notes.At the moment, this process is ran manually.
I want to enable this process to be ran automatically everyday at a specified time of day.
However i am unsure how to do this.

```<code>public class Email_Attachments_to_Regarding_Document_Store : CodeActivity
{
    protected override void Execute(CodeActivityContext executionContext)
    {
        ITracingService tracer = executionContext.GetExtension<ITracingService>();
        IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
        IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
        IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

        try
        {
            //Retrieve Email the workflow is running against from Dynamics
            Email email = service.Retrieve(context.PrimaryEntityName, context.PrimaryEntityId, new ColumnSet(true)).ToEntity<Email>();

            //Retrieve the attachment mimes related to the email
            DataCollection<Entity> mimes = service.RetrieveMultiple(new QueryExpression
            {
                EntityName = ActivityMimeAttachment.EntityLogicalName,
                ColumnSet = new ColumnSet(true),
                Criteria =
                {
                    Conditions =
                    {
                        //Filter by related Email, 'objectid' is the related email.
                        new ConditionExpression("objectid", ConditionOperator.Equal, email.Id)
                    }
                }
            }).Entities;

            foreach(ActivityMimeAttachment mime in mimes)
            {
                Annotation note = new Annotation
                {
                    AnnotationId = Guid.NewGuid(),
                    DocumentBody = mime.Body,
                    IsDocument = true,
                    FileName = mime.FileName,
                    MimeType = mime.MimeType,
                    ObjectTypeCode = email.RegardingObjectId.LogicalName,
                    ObjectId = email.RegardingObjectId
                };
                note.IsDocument = true;
                service.Create(note);

            }
        }
        catch (Exception e)
        {
            throw new InvalidPluginExecutionException(e.Message);
        }

    }
</code>```

This code copies the email attachments into notes. However i am unable to run this code at a specified time of day.
The code below is an azure function that connects to dynamics

```<code> public static class Function1
{
    [FunctionName("Function1")]
    public static void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, TraceWriter log)
    {
        log.Info($"C# Timer trigger function executed at: {DateTime.Now}");

        IServiceManagement<IOrganizationService> orgServiceManagement =
            ServiceConfigurationFactory.CreateManagement<IOrganizationService>(new Uri("https://disco.crm11.dynamics.com/XRMServices/2011/Discovery.svc"));

        AuthenticationCredentials authCredentials = new AuthenticationCredentials();
        authCredentials.ClientCredentials.UserName.UserName = "xxx@s.co.uk";
        authCredentials.ClientCredentials.UserName.Password = "xxxxx";
        AuthenticationCredentials tokenCredentials = orgServiceManagement.Authenticate(authCredentials);

        //Retreive the service

        IOrganizationService service = new OrganizationServiceProxy(orgServiceManagement, tokenCredentials.SecurityTokenResponse);

    }
}
</code>```

i want the azure function to implement/run the custom workflow but i am not sure how

答:
Hopefully this isnt too late. When I've needed to do something similar, I create an Action in Dynamics. The action will call the Workflow Activity.

I then call the action from my Azure Function App Code like this.

 OrganizationRequest req = new OrganizationRequest([insert action name here]);

 //execute the request
 OrganizationResponse response = organizationService.Execute(req);
```

Also I'd avoid putting credentials in your Azure Code. Ideally use Azure Key Vault for this. You can refer this post for ways to do this. Azure Function Authentication To Dynamics CRM Using Azure Key Vault

Body:
I have a custom workflow that copies the attachments from an email and places the copy in the notes.At the moment, this process is ran manually.
I want to enable this process to be ran automatically everyday at a specified time of day.
However i am unsure how to do this.

public class Email_Attachments_to_Regarding_Document_Store : CodeActivity
{
    protected override void Execute(CodeActivityContext executionContext)
    {
        ITracingService tracer = executionContext.GetExtension<ITracingService>();
        IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
        IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
        IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

        try
        {
            //Retrieve Email the workflow is running against from Dynamics
            Email email = service.Retrieve(context.PrimaryEntityName, context.PrimaryEntityId, new ColumnSet(true)).ToEntity<Email>();

            //Retrieve the attachment mimes related to the email
            DataCollection<Entity> mimes = service.RetrieveMultiple(new QueryExpression
            {
                EntityName = ActivityMimeAttachment.EntityLogicalName,
                ColumnSet = new ColumnSet(true),
                Criteria =
                {
                    Conditions =
                    {
                        //Filter by related Email, 'objectid' is the related email.
                        new ConditionExpression("objectid", ConditionOperator.Equal, email.Id)
                    }
                }
            }).Entities;

            foreach(ActivityMimeAttachment mime in mimes)
            {
                Annotation note = new Annotation
                {
                    AnnotationId = Guid.NewGuid(),
                    DocumentBody = mime.Body,
                    IsDocument = true,
                    FileName = mime.FileName,
                    MimeType = mime.MimeType,
                    ObjectTypeCode = email.RegardingObjectId.LogicalName,
                    ObjectId = email.RegardingObjectId
                };
                note.IsDocument = true;
                service.Create(note);

            }
        }
        catch (Exception e)
        {
            throw new InvalidPluginExecutionException(e.Message);
        }

    }

This code copies the email attachments into notes. However i am unable to run this code at a specified time of day.
The code below is an azure function that connects to dynamics

 public static class Function1
{
    [FunctionName("Function1")]
    public static void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, TraceWriter log)
    {
        log.Info($"C# Timer trigger function executed at: {DateTime.Now}");

        IServiceManagement<IOrganizationService> orgServiceManagement =
            ServiceConfigurationFactory.CreateManagement<IOrganizationService>(new Uri("https://disco.crm11.dynamics.com/XRMServices/2011/Discovery.svc"));

        AuthenticationCredentials authCredentials = new AuthenticationCredentials();
        authCredentials.ClientCredentials.UserName.UserName = "xxx@s.co.uk";
        authCredentials.ClientCredentials.UserName.Password = "xxxxx";
        AuthenticationCredentials tokenCredentials = orgServiceManagement.Authenticate(authCredentials);

        //Retreive the service

        IOrganizationService service = new OrganizationServiceProxy(orgServiceManagement, tokenCredentials.SecurityTokenResponse);

    }
}

i want the azure function to implement/run the custom workflow but i am not sure how

Body:
Hopefully this isnt too late. When I've needed to do something similar, I create an Action in Dynamics. The action will call the Workflow Activity.

I then call the action from my Azure Function App Code like this.

 OrganizationRequest req = new OrganizationRequest([insert action name here]);

 //execute the request
 OrganizationResponse response = organizationService.Execute(req);

Also I'd avoid putting credentials in your Azure Code. Ideally use Azure Key Vault for this. You can refer this post for ways to do this. Azure Function Authentication To Dynamics CRM Using Azure Key Vault


问:
How can I list all files in a directory on Windows without using dirent.h in C?
I can't find any way to list all files without using dirent.h. Does anyone have an idea or suggestions?
I can't work with dirent.h because my compiler doesn't work with it, so this is why I am searching for another option

I run and write the program on Windows 10.

答:
You want to use FindFirstFile, FindNextFile, and FindClose. Microsoft provides an example on MSDN:

Listing the Files in a Directory

```<code>#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <strsafe.h>
#pragma comment(lib, "User32.lib")

void DisplayErrorBox(LPTSTR lpszFunction);

int _tmain(int argc, TCHAR *argv[])
{
   WIN32_FIND_DATA ffd;
   LARGE_INTEGER filesize;
   TCHAR szDir[MAX_PATH];
   size_t length_of_arg;
   HANDLE hFind = INVALID_HANDLE_VALUE;
   DWORD dwError=0;

   // If the directory is not specified as a command-line argument,
   // print usage.

   if(argc != 2)
   {
      _tprintf(TEXT("\nUsage: %s <directory name>\n"), argv[0]);
      return (-1);
   }

   // Check that the input path plus 3 is not longer than MAX_PATH.
   // Three characters are for the "\*" plus NULL appended below.

   StringCchLength(argv[1], MAX_PATH, &length_of_arg);

   if (length_of_arg > (MAX_PATH - 3))
   {
      _tprintf(TEXT("\nDirectory path is too long.\n"));
      return (-1);
   }

   _tprintf(TEXT("\nTarget directory is %s\n\n"), argv[1]);

   // Prepare string for use with FindFile functions.  First, copy the
   // string to a buffer, then append '\*' to the directory name.

   StringCchCopy(szDir, MAX_PATH, argv[1]);
   StringCchCat(szDir, MAX_PATH, TEXT("\\*"));

   // Find the first file in the directory.

   hFind = FindFirstFile(szDir, &ffd);

   if (INVALID_HANDLE_VALUE == hFind)
   {
      DisplayErrorBox(TEXT("FindFirstFile"));
      return dwError;
   }

   // List all the files in the directory with some info about them.

   do
   {
      if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
      {
         _tprintf(TEXT("  %s   <DIR>\n"), ffd.cFileName);
      }
      else
      {
         filesize.LowPart = ffd.nFileSizeLow;
         filesize.HighPart = ffd.nFileSizeHigh;
         _tprintf(TEXT("  %s   %ld bytes\n"), ffd.cFileName, filesize.QuadPart);
      }
   }
   while (FindNextFile(hFind, &ffd) != 0);

   dwError = GetLastError();
   if (dwError != ERROR_NO_MORE_FILES)
   {
      DisplayErrorBox(TEXT("FindFirstFile"));
   }

   FindClose(hFind);
   return dwError;
}

void DisplayErrorBox(LPTSTR lpszFunction)
{
    // Retrieve the system error message for the last-error code

    LPVOID lpMsgBuf;
    LPVOID lpDisplayBuf;
    DWORD dw = GetLastError();

    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        dw,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR) &lpMsgBuf,
        0, NULL );

    // Display the error message and clean up

    lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
        (lstrlen((LPCTSTR)lpMsgBuf)+lstrlen((LPCTSTR)lpszFunction)+40)*sizeof(TCHAR));
    StringCchPrintf((LPTSTR)lpDisplayBuf,
        LocalSize(lpDisplayBuf) / sizeof(TCHAR),
        TEXT("%s failed with error %d: %s"),
        lpszFunction, dw, lpMsgBuf);
    MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK);

    LocalFree(lpMsgBuf);
    LocalFree(lpDisplayBuf);
}
</code>```

Body:
You want to use FindFirstFile, FindNextFile, and FindClose. Microsoft provides an example on MSDN:

Listing the Files in a Directory

#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <strsafe.h>
#pragma comment(lib, "User32.lib")

void DisplayErrorBox(LPTSTR lpszFunction);

int _tmain(int argc, TCHAR *argv[])
{
   WIN32_FIND_DATA ffd;
   LARGE_INTEGER filesize;
   TCHAR szDir[MAX_PATH];
   size_t length_of_arg;
   HANDLE hFind = INVALID_HANDLE_VALUE;
   DWORD dwError=0;

   // If the directory is not specified as a command-line argument,
   // print usage.

   if(argc != 2)
   {
      _tprintf(TEXT("\nUsage: %s <directory name>\n"), argv[0]);
      return (-1);
   }

   // Check that the input path plus 3 is not longer than MAX_PATH.
   // Three characters are for the "\*" plus NULL appended below.

   StringCchLength(argv[1], MAX_PATH, &length_of_arg);

   if (length_of_arg > (MAX_PATH - 3))
   {
      _tprintf(TEXT("\nDirectory path is too long.\n"));
      return (-1);
   }

   _tprintf(TEXT("\nTarget directory is %s\n\n"), argv[1]);

   // Prepare string for use with FindFile functions.  First, copy the
   // string to a buffer, then append '\*' to the directory name.

   StringCchCopy(szDir, MAX_PATH, argv[1]);
   StringCchCat(szDir, MAX_PATH, TEXT("\\*"));

   // Find the first file in the directory.

   hFind = FindFirstFile(szDir, &ffd);

   if (INVALID_HANDLE_VALUE == hFind)
   {
      DisplayErrorBox(TEXT("FindFirstFile"));
      return dwError;
   }

   // List all the files in the directory with some info about them.

   do
   {
      if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
      {
         _tprintf(TEXT("  %s   <DIR>\n"), ffd.cFileName);
      }
      else
      {
         filesize.LowPart = ffd.nFileSizeLow;
         filesize.HighPart = ffd.nFileSizeHigh;
         _tprintf(TEXT("  %s   %ld bytes\n"), ffd.cFileName, filesize.QuadPart);
      }
   }
   while (FindNextFile(hFind, &ffd) != 0);

   dwError = GetLastError();
   if (dwError != ERROR_NO_MORE_FILES)
   {
      DisplayErrorBox(TEXT("FindFirstFile"));
   }

   FindClose(hFind);
   return dwError;
}

void DisplayErrorBox(LPTSTR lpszFunction)
{
    // Retrieve the system error message for the last-error code

    LPVOID lpMsgBuf;
    LPVOID lpDisplayBuf;
    DWORD dw = GetLastError();

    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        dw,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR) &lpMsgBuf,
        0, NULL );

    // Display the error message and clean up

    lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
        (lstrlen((LPCTSTR)lpMsgBuf)+lstrlen((LPCTSTR)lpszFunction)+40)*sizeof(TCHAR));
    StringCchPrintf((LPTSTR)lpDisplayBuf,
        LocalSize(lpDisplayBuf) / sizeof(TCHAR),
        TEXT("%s failed with error %d: %s"),
        lpszFunction, dw, lpMsgBuf);
    MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK);

    LocalFree(lpMsgBuf);
    LocalFree(lpDisplayBuf);
}


问:
best way to replace redis set value
I want to store a key-values type data into redis, values is a set type which means no duplicate value. I opereate in redis like this:

```<code>127.0.0.1:6379> sadd a 1 2 3
(integer) 3
127.0.0.1:6379> smembers a
1) "1"
2) "2"
3) "3"
127.0.0.1:6379> sadd a 4 5 6
(integer) 3
127.0.0.1:6379> smembers a
1) "3"
2) "2"
3) "4"
4) "5,"
5) "1"
6) "6"
</code>```

I want user set(4,5,6) replace set(1,2,3).

答:
Your question is ambiguous.

If your intention is to replace all members:

```<code># Setup "a" with 3 members
127.0.0.1:6379> del a
(integer) 1
127.0.0.1:6379> sadd a 1 2 3
(integer) 3

# Actions - delete entire set and add 3 new members in one go
127.0.0.1:6379> multi
OK
127.0.0.1:6379> del a
QUEUED
127.0.0.1:6379> sadd a 4 5 6
QUEUED
127.0.0.1:6379> exec
1) (integer) 1
2) (integer) 3
127.0.0.1:6379> smembers a
1) "4"
2) "5"
3) "6"
</code>```

If your intention is to replace only specific members:

```<code># Setup "a" with 4 members
127.0.0.1:6379> del a
(integer) 1
127.0.0.1:6379> sadd a 0 1 2 3
(integer) 4

# Actions - delete 3 specific members and add 3 more, leaving others unaffected
127.0.0.1:6379> multi
OK
127.0.0.1:6379> srem a 1 2 3
QUEUED
127.0.0.1:6379> sadd a 4 5 6
QUEUED
127.0.0.1:6379> exec
1) (integer) 3
2) (integer) 3
127.0.0.1:6379> smembers a
1) "0"
2) "4"
3) "5"
4) "6"
127.0.0.1:6379>
</code>```

Title: best way to replace redis set value

Body:
I want to store a key-values type data into redis, values is a set type which means no duplicate value. I opereate in redis like this:

127.0.0.1:6379> sadd a 1 2 3
(integer) 3
127.0.0.1:6379> smembers a
1) "1"
2) "2"
3) "3"
127.0.0.1:6379> sadd a 4 5 6
(integer) 3
127.0.0.1:6379> smembers a
1) "3"
2) "2"
3) "4"
4) "5,"
5) "1"
6) "6"

I want user set(4,5,6) replace set(1,2,3).

Body:
Your question is ambiguous.

If your intention is to replace all members:

# Setup "a" with 3 members
127.0.0.1:6379> del a
(integer) 1
127.0.0.1:6379> sadd a 1 2 3
(integer) 3

# Actions - delete entire set and add 3 new members in one go
127.0.0.1:6379> multi
OK
127.0.0.1:6379> del a
QUEUED
127.0.0.1:6379> sadd a 4 5 6
QUEUED
127.0.0.1:6379> exec
1) (integer) 1
2) (integer) 3
127.0.0.1:6379> smembers a
1) "4"
2) "5"
3) "6"

If your intention is to replace only specific members:

# Setup "a" with 4 members
127.0.0.1:6379> del a
(integer) 1
127.0.0.1:6379> sadd a 0 1 2 3
(integer) 4

# Actions - delete 3 specific members and add 3 more, leaving others unaffected
127.0.0.1:6379> multi
OK
127.0.0.1:6379> srem a 1 2 3
QUEUED
127.0.0.1:6379> sadd a 4 5 6
QUEUED
127.0.0.1:6379> exec
1) (integer) 3
2) (integer) 3
127.0.0.1:6379> smembers a
1) "0"
2) "4"
3) "5"
4) "6"
127.0.0.1:6379>


问:
ReSharper Code Cleanup/Reformat Code feature vs Versioning Control Systems
ReSharper Code cleanup feature (with "reorder members" and "reformat code" enabled) is really great. You define a layout template using XML, then a simple key combination reorganizes your whole source file (or folder/project/solution) according to the rules you set in the template.

Anyway, do you think that could be a problem regarding VCS like subversion, cvs, git, etc. ? Is there a chance that it causes many undesired conflicts ?

Thank you.

答:
I Agree with the previous answers that state that conflicts are possible and even likely.

If you are planning to reformat code then at least make sure that you don't mix reformat checkins with those that change the function of the actual code. This way people can skip past check-ins that are simple reformattings. It's also a good idea to make sure that everyone knows a reformat is coming up so that they can object if they have ongoing work in that area.

OwnerDisplayName: Romain Verdier

OwnerDisplayName: Simon


问:
ASP.net page without a code behind
I have an ASP.Net page with a C# code behind.

However, I've been asked to not use a code behind - so that it will be easier to deploy in SharePoint.

Is there a way to include the C# code in the ASP.Net page, without using a separate code behind file?

答:
I thought you could deploy just your .aspx page without the .aspx.cs so long as the DLL was in your bin. Part of the issue here is how visual studio .net works with .aspx pages.

Check it out here:
Working with Single-File Web Forms Pages in Visual Studio .NET

I know for sure that VS2008 with asp.net MVC RC you don't have code-behind files for your views.

OwnerDisplayName: Sophia

Title: ASP.net page without a code behind

OwnerDisplayName: NTulip


问:
Map hasn`t been displayed
please i have a problem with Map displaying, although, in the simulator it`s displayed well, on the iPhone i see this (the left one is with Hybrid mode and the right is with standard mode):

here is some of my code :

```<code>- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{

    location = newLocation.coordinate;

    MKCoordinateSpan span;
    if (shouldAdjustZoom) {
        //use the manually defined span
        span.latitudeDelta=.005;
        span.longitudeDelta=.005;
        mapRegion.span = span;
    }
    else {
        mapRegion=mapView.region;
        mapRegion.center=newLocation.coordinate;
        mapView.region=mapRegion;
    }

    // Apply new coordinates
    [mapView setRegion:mapRegion animated:TRUE];

}
</code>```

答: The blue color actually makes me think you are in the middle of the ocean. Have you checked your center point?</p>

Title: Map hasn`t been displayed

Body:
please i have a problem with Map displaying, although, in the simulator it`s displayed well, on the iPhone i see this (the left one is with Hybrid mode and the right is with standard mode):

here is some of my code :

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{

    location = newLocation.coordinate;

    MKCoordinateSpan span;
    if (shouldAdjustZoom) {
        //use the manually defined span
        span.latitudeDelta=.005;
        span.longitudeDelta=.005;
        mapRegion.span = span;
    }
    else {
        mapRegion=mapView.region;
        mapRegion.center=newLocation.coordinate;
        mapView.region=mapRegion;
    }

    // Apply new coordinates
    [mapView setRegion:mapRegion animated:TRUE];

}