问:
I am trying to run yargs command, and it is not working
I am running:

```<code>node app.js add
</code>```

And my code is:

```<code>const yargs = require('yargs');
yargs.command({
    command:'add',
    describe:'Adding command',
    handler:function(){
        console.log('Adding notes');
    },
})
</code>```

But nothing printed on the console.

答:
As @jonrsharpe mentioned in the comment above.

You need to either call parse function or access argv property

Try:

```<code>const yargs = require('yargs');

yargs
    .command({
        command:'add',
        describe:'Adding command',
        handler: argv => {
            console.log('Adding notes');
        }
    })
    .parse();
</code>```

Or

```<code>const yargs = require('yargs');

const argv = yargs
    .command({
        command: 'add',
        describe: 'Adding command',
        handler: argv => {
            console.log('Adding notes');
        }
    })
    .argv;
</code>```

node index.js add

Body:
I am running:

node app.js add

And my code is:

const yargs = require('yargs');
yargs.command({
    command:'add',
    describe:'Adding command',
    handler:function(){
        console.log('Adding notes');
    },
})

But nothing printed on the console.

Body:
As @jonrsharpe mentioned in the comment above.

You need to either call parse function or access argv property

Try:

const yargs = require('yargs');

yargs
    .command({
        command:'add',
        describe:'Adding command',
        handler: argv => {
            console.log('Adding notes');
        }
    })
    .parse();

Or

const yargs = require('yargs');

const argv = yargs
    .command({
        command: 'add',
        describe: 'Adding command',
        handler: argv => {
            console.log('Adding notes');
        }
    })
    .argv;

node index.js add


来源: stackexchange

问:
Scale issues on chart
I have a graph below made in plotly(python). I have set graph y-axis in log scale. but I don't know why there are intermediate values between 1000 and 10k like (2,3,4,5,6...). What they are representing? and how they are removed? I must want to remove.
]1

The properties of axis are given below

```<code>trace1 = {
  "x": [1, 2, 3, 4, 5],
  "y": [500, 900, 1100, 10000, 300],
  "marker": {
    "color": 'rgb(255,140,0)',

  },
data = Data([trace1])
layout = {
  "autosize": False,
  "bargap": 0.0,
  "height": 480,
  "hovermode": "closest",
  "margin": {
    "r": 63,
    "t": 57,
    "b": 52,
    "l": 80,
    "pad": 0
  },
  "showlegend": False,
  "titlefont": {
    "color": "#000000",
    "size": 12.0
  },
  "width": 640,
  "xaxis": {
    "anchor": "y",
    "domain": [0.0, 1.0],
    "mirror": "ticks",
    "nticks": 9,
    "range": [0.5, 10.5],
    "showgrid": False,
    "showline": True,
    "side": "bottom",
    "tickfont": {"size": 20.0},
    "ticks": "inside",
    "title": "x-axes",
    "titlefont": {
      "color": "black",
      "size": 22.0
    },
    "type": "linear",
    "zeroline": False
  },
  "yaxis": {
    "tickmode":'auto',
    "ticks":'outside',
    "tick0":0,
    "dtick":100,
    "ticklen":8,
    "tickwidth":4,
    "anchor": "x",
    "mirror": "ticks",
    "domain": [0.0, 1.0],
    "nticks": 6,
    "showgrid": False,
    "showline": True,
    "side": "left",
    "tickfont": {"size": 20.0},
    "ticks": "inside",
    "title": "y-axis",
    "titlefont": {
      "color": "black",
      "size": 22.0
    },
    "type": "log",
    "zeroline": False,
  }
}
fig = dict(data=data, layout=layout)
py.plot(fig, filename='"log-no-log"')
</code>```

答:
The numbers represent the intermediate multiples until you get to the next order of magnitude. The first 3,4,5 etc. represent multiples of 100 until you reach the tick 1000. Then it will be the markers for multiples of 1000 until you reach 10k. Because of the logarithmic scale, they are not drawn equidistand.

So they might be useful if you want to read from the graph what your value at e.g. x=2 is.

ContentLicense: CC BY-SA 4.0

Title: Scale issues on chart

Body:
I have a graph below made in plotly(python). I have set graph y-axis in log scale. but I don't know why there are intermediate values between 1000 and 10k like (2,3,4,5,6...). What they are representing? and how they are removed? I must want to remove.
]1

The properties of axis are given below

trace1 = {
  "x": [1, 2, 3, 4, 5],
  "y": [500, 900, 1100, 10000, 300],
  "marker": {
    "color": 'rgb(255,140,0)',

  },
data = Data([trace1])
layout = {
  "autosize": False,
  "bargap": 0.0,
  "height": 480,
  "hovermode": "closest",
  "margin": {
    "r": 63,
    "t": 57,
    "b": 52,
    "l": 80,
    "pad": 0
  },
  "showlegend": False,
  "titlefont": {
    "color": "#000000",
    "size": 12.0
  },
  "width": 640,
  "xaxis": {
    "anchor": "y",
    "domain": [0.0, 1.0],
    "mirror": "ticks",
    "nticks": 9,
    "range": [0.5, 10.5],
    "showgrid": False,
    "showline": True,
    "side": "bottom",
    "tickfont": {"size": 20.0},
    "ticks": "inside",
    "title": "x-axes",
    "titlefont": {
      "color": "black",
      "size": 22.0
    },
    "type": "linear",
    "zeroline": False
  },
  "yaxis": {
    "tickmode":'auto',
    "ticks":'outside',
    "tick0":0,
    "dtick":100,
    "ticklen":8,
    "tickwidth":4,
    "anchor": "x",
    "mirror": "ticks",
    "domain": [0.0, 1.0],
    "nticks": 6,
    "showgrid": False,
    "showline": True,
    "side": "left",
    "tickfont": {"size": 20.0},
    "ticks": "inside",
    "title": "y-axis",
    "titlefont": {
      "color": "black",
      "size": 22.0
    },
    "type": "log",
    "zeroline": False,
  }
}
fig = dict(data=data, layout=layout)
py.plot(fig, filename='"log-no-log"')


问:
Confusion about install count of app on Google Play
In analytics section of Google Play developer's console, the analytics are clear to me. I am not clear regarding the public downloads count that's displayed on Google Play website and Android app. How does Google Play calculate and show that public download count? Is it by user or by device? For example if a single user installs an app on 4 devices, will the download count be incremented as 1 or 4?

Here is the screenshot for further clarification:

答: I think Google Play calculates downloads per device, if we looked at Google Play Services it add downloads over devices for example One User downloaded YouTube over four devices from same Google Account it will count four downloads but if you downloaded YouTube four times from same device then it will count only one download, i wish this may help you at your research :)


问:
concerns about required A records for setting up Firebase Dynamic Links with a custom subdomain
In setting up our own subdomain to handle Firebase Dynamic Links using these docs, the wizard says to put the A records at example.com in our DNS.  I'm getting pushback from our network administrators who are wary of creating an A record at the root of our domain, which is a large e-commerce web site.

A couple of concerns/questions about this:

The IP addresses required (151.101.1.195 and 151.101.65.195) point to non-Google servers (looks like Fastly), which is a bit alarming - it seems strange that Google would outsource their deep link hosting.

We don't want all of our e-commerce traffic (coming through example.com) to be subject to these A records.  Is it possible to put the A records at link.example.com instead?

答:
The Firebase documentation on using a custom domain for dynamic links has this note:

To use a custom domain for Dynamic Links, the domain must point to Firebase Hosting. If you have a domain you want to use with Dynamic Links and the domain points to a different host, you can either move to Firebase Hosting or create a subdomain hosted by Firebase, which you can use for Dynamic Links.

So you can indeed use a subdomain for the dynamic links. In that case, just set up the subdomain in Firebase hosting. You'll need the same TXT record as normal, to prove that you have access to the domain, but then just map the subdomain (e.g. links) for the A record.


问:
Decomposing a number into powers of 2
Hi I need to decompose a number into powers of 2 in swift 5 for an iOS app I'm writing fro a click and collect system.

The backend of this system is written in c# and uses the following to save a multi-pick list of options as a single number in the database eg:

choosing salads for a filled roll on an order system works thus:

```<code>lettuce = 1
cucumber = 2
tomato = 4
sweetcorn = 8
onion = 16
</code>```

by using this method it saves the options into the database for the choice made as (lettuce + tomato + onion) = 21 (1+4+16)

at the other end I use a c# function to do this thus:

```<code>for(int j = 0; j < 32; j++)
    {
    int mask = 1 << j;
    }
</code>```

I need to convert this function into a swift 5 format to integrate the decoder into my iOS app

any help would be greatly appreciated

答:
Hi I figured it out this is my final solution:

```<code>    var salads = "" as String
    let value = 127
    var j=0
    while j < 256 {

        let mask=1 << j
        if((value & mask) != 0) {
            salads.append(String(mask) + ",")
        }
        j += 1
    }
    salads = String(salads.dropLast()) // removes the final ","
    print(salads)
</code>```

This now feeds nicely into the in clause in my SQL query, thanks you all for your help! :)

Title: Decomposing a number into powers of 2

Body:
Hi I need to decompose a number into powers of 2 in swift 5 for an iOS app I'm writing fro a click and collect system.

The backend of this system is written in c# and uses the following to save a multi-pick list of options as a single number in the database eg:

choosing salads for a filled roll on an order system works thus:

lettuce = 1
cucumber = 2
tomato = 4
sweetcorn = 8
onion = 16

by using this method it saves the options into the database for the choice made as (lettuce + tomato + onion) = 21 (1+4+16)

at the other end I use a c# function to do this thus:

for(int j = 0; j < 32; j++)
    {
    int mask = 1 << j;
    }

I need to convert this function into a swift 5 format to integrate the decoder into my iOS app

any help would be greatly appreciated

Body:
Hi I figured it out this is my final solution:

    var salads = "" as String
    let value = 127
    var j=0
    while j < 256 {

        let mask=1 << j
        if((value & mask) != 0) {
            salads.append(String(mask) + ",")
        }
        j += 1
    }
    salads = String(salads.dropLast()) // removes the final ","
    print(salads)

This now feeds nicely into the in clause in my SQL query, thanks you all for your help! :)


问:
Location of MySQL configuration file (ie: my.cnf) not specified
Location of MySQL configuration file (ie: my.cnf) not specified

How can I fixed this thing?
I been trying to reinstall mysqlserver 5.5 / 5.7 and workbench countless of time. But I still not able to fix this issue.

答:
For maria-db users

back up the original /etc/mysql/my.cnf

copy and rename /etc/mysql/mariadb.conf.d/50-server.cnf to /etc/mysql/my.cnf.

This would fix the problem.

Remember to revert changes after finish.

ContentLicense: CC BY-SA 3.0


问:
How to fix 'ibatis binding exception' when testing mybatis functionality in Springboot?
I'm trying to make a unit test for Mybatis in SpringBoot. I keep getting ibatis.binding.bindingException whenever I try to execute a query defined in the mapper.xml.

My test code is stored in src/test/java/service with name UserServiceImplTest.

```<code>@SpringBootTest
@RunWith(SpringRunner.class)
public class UserServiceImplTest {

    @Autowired
    UserDao userDao;

    @Test
    public void getUserByIdAndEmail() throws SQLException {
        User user = userDao.getUserByIdAndEmail("admin", "admin@sample.com");
        assertThat(user.getUser_email()).isEqualTo("admin@sample.com");
    }
}
</code>```

```<code>@Repository
public class UserDao implements UserDaoMapper{
    @Autowired
    private SqlSessionTemplate sqlSession;

    public User getUserByIdAndEmail(String user_id, String user_email) {
        UserDaoMapper mapper = sqlSession.getMapper(UserDaoMapper.class);
        return mapper.getUserByIdAndEmail(user_id, user_email);
    }
}
</code>```

SqlSessionTemplate, SqlSessionFactory and Datasource beans are defined in a java file where there is @SpringBootApplication.

From

```<code>User user = userDao.getUserByIdAndEmail("admin", "admin@sample.com");
</code>```

I was hoping at least to get null User, but when executing the method itself the error pops out. Below is the error log.

```<code>org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.sampleProject.dao.UserDaoMapper.getUserByIdAndEmail

    at org.apache.ibatis.binding.MapperMethod$SqlCommand.<init>(MapperMethod.java:227)
    at org.apache.ibatis.binding.MapperMethod.<init>(MapperMethod.java:49)
    at org.apache.ibatis.binding.MapperProxy.cachedMapperMethod(MapperProxy.java:65)
    at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:58)
    at com.sun.proxy.$Proxy99.getUserByIdAndEmail(Unknown Source)
    at com.sampleProject.dao.UserDao.getUserByIdAndEmail(UserDao.java:25)
    at com.sampleProject.dao.UserDao$$FastClassBySpringCGLIB$$a267b137.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:749)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688)
    at com.sampleProject.dao.UserDao$$EnhancerBySpringCGLIB$$b41323d1.getUserByIdAndEmail(<generated>)
    at com.sampleProject.service.UserServiceImplTest.getUserByIdAndEmail(UserServiceImplTest.java:75)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
</code>```

答: For some reason, after creating a 'resources' directory under test and moving *mapper.xml files under the resources directly solved the problem. I guess the test class was not able to find mapper.xml files, causing a binding exception as a result.</p>

Body:
I'm trying to make a unit test for Mybatis in SpringBoot. I keep getting ibatis.binding.bindingException whenever I try to execute a query defined in the mapper.xml.

My test code is stored in src/test/java/service with name UserServiceImplTest.

@SpringBootTest
@RunWith(SpringRunner.class)
public class UserServiceImplTest {

    @Autowired
    UserDao userDao;

    @Test
    public void getUserByIdAndEmail() throws SQLException {
        User user = userDao.getUserByIdAndEmail("admin", "admin@sample.com");
        assertThat(user.getUser_email()).isEqualTo("admin@sample.com");
    }
}

@Repository
public class UserDao implements UserDaoMapper{
    @Autowired
    private SqlSessionTemplate sqlSession;

    public User getUserByIdAndEmail(String user_id, String user_email) {
        UserDaoMapper mapper = sqlSession.getMapper(UserDaoMapper.class);
        return mapper.getUserByIdAndEmail(user_id, user_email);
    }
}

SqlSessionTemplate, SqlSessionFactory and Datasource beans are defined in a java file where there is @SpringBootApplication.

From

User user = userDao.getUserByIdAndEmail("admin", "admin@sample.com");

I was hoping at least to get null User, but when executing the method itself the error pops out. Below is the error log.

org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.sampleProject.dao.UserDaoMapper.getUserByIdAndEmail

    at org.apache.ibatis.binding.MapperMethod$SqlCommand.<init>(MapperMethod.java:227)
    at org.apache.ibatis.binding.MapperMethod.<init>(MapperMethod.java:49)
    at org.apache.ibatis.binding.MapperProxy.cachedMapperMethod(MapperProxy.java:65)
    at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:58)
    at com.sun.proxy.$Proxy99.getUserByIdAndEmail(Unknown Source)
    at com.sampleProject.dao.UserDao.getUserByIdAndEmail(UserDao.java:25)
    at com.sampleProject.dao.UserDao$$FastClassBySpringCGLIB$$a267b137.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:749)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688)
    at com.sampleProject.dao.UserDao$$EnhancerBySpringCGLIB$$b41323d1.getUserByIdAndEmail(<generated>)
    at com.sampleProject.service.UserServiceImplTest.getUserByIdAndEmail(UserServiceImplTest.java:75)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)


问:
image in an Expanded TableViewCell is lost after scrolling
I am creating an application in which i have many table cells(>300). I have successfully implemented expanding and collapsing tableview cells. On expansion an image is displayed which is fetched from a webservice, on clicking the expanded cell, the cell collapses again, if another cell is clicked the previous cell collapsed and current cell expands. Now the problem is if the user scrolls the tableview with the cell expanded table works fine but when he returns
to it the image gets lost, and there is a bit of problem with the functionality as well( the table takes that cell to be collapsed).

Moreover if the user keeps on scrolling the table down he can encounter that image in a collapased cell(which looks very bad), i think its because dequeueReusableCellWithIdentifier is fetching the already expanded cell.

PS: Every image is different based on the cell value but it is fetched in  a different call(not al together ie to fetch 300 images i make 300 independent calls).

答:
```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UIImageView * imageView;
    UILabel     * nameLabel;

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                       reuseIdentifier:CellIdentifier] autorelease];

        nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(45.0, 5.0, 245.0, 34.0)];
        nameLabel.font = [UIFont fontWithName:CELL_FONT size:CELL_FONT_SIZE];
        nameLabel.tag = 2;
        nameLabel.backgroundColor = [UIColor clearColor];
        [cell.contentView addSubview:nameLabel];
        [nameLabel release];

        imageView = [[UIImageView alloc] initWithFrame:CGRectMake(5.0, 5.0, 30.0, 30.0)];
        imageView.tag = 1;
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        [cell.contentView addSubview:imageView];
        [imageView release];
    }
    else {
        imageView = (id)[cell.contentView viewWithTag:1];
        nameLabel = (id)[cell.contentView viewWithTag:2];
    }

    return cell;
}
</code>```

ContentLicense: CC BY-SA 2.5


问:
Introspection of token using offline_access scope in identityserver4
I managed to introspect the access token when using the scope define by myself. I just need to post to the endpoint with basic authorization with username is my scope name and password is my scope api secret. But offline_access is a default scope define by the IdentityServer, how do i introspect it? Is there any way i can customize the offline_access scope with a api secret? I need to use offline_access because only this scope able to provide me refresh token.</p>

答:
I found a way to introspect the offline_access scope token. I hope this may help someone who stuck like me. Let said my code

```<code>    public static IEnumerable<ApiResource> GetApis()
    {
        return new List<ApiResource>
        {
            new ApiResource("api1", "My API")
            {
                ApiSecrets = { new Secret("secret".Sha256()) }
            }
        };
    }
</code>```

and my client code is

```<code>    public static IEnumerable<Client> GetClients()
    {
        return new List<Client>
        {
            // resource owner password grant client
            new Client
            {
                ClientId = "ro.client",
                AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,

                ClientSecrets =
                {
                    new Secret("secret".Sha256())
                },
                AllowedScopes = new List<string>
                {
                    "api1",
                   IdentityServerConstants.StandardScopes.OfflineAccess,
                },
                AllowOfflineAccess = true,
                AccessTokenType = AccessTokenType.Reference, // revocation endpoint work with reference access token only
            }
        };
    }
</code>```

When requesting for an access token , include both api1 and offline_access together,

When requesting for an refresh token,

When doing introspection,take note that the username api1 and password secret will be use during basic authorization

When doing revocation of reference token or refresh token,take note that the username ro.client and password secret will be use during basic authorization,

Body:
I found a way to introspect the offline_access scope token. I hope this may help someone who stuck like me. Let said my code

    public static IEnumerable<ApiResource> GetApis()
    {
        return new List<ApiResource>
        {
            new ApiResource("api1", "My API")
            {
                ApiSecrets = { new Secret("secret".Sha256()) }
            }
        };
    }

and my client code is

    public static IEnumerable<Client> GetClients()
    {
        return new List<Client>
        {
            // resource owner password grant client
            new Client
            {
                ClientId = "ro.client",
                AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,

                ClientSecrets =
                {
                    new Secret("secret".Sha256())
                },
                AllowedScopes = new List<string>
                {
                    "api1",
                   IdentityServerConstants.StandardScopes.OfflineAccess,
                },
                AllowOfflineAccess = true,
                AccessTokenType = AccessTokenType.Reference, // revocation endpoint work with reference access token only
            }
        };
    }

When requesting for an access token , include both api1 and offline_access together,

When requesting for an refresh token,

When doing introspection,take note that the username api1 and password secret will be use during basic authorization

When doing revocation of reference token or refresh token,take note that the username ro.client and password secret will be use during basic authorization,


问:
React Native Webview push new page on  clicked
I'm trying to create a hybrid react native app to host my website's content in webviews. Something like this: Supreme App

One thing I want to achieve is: when a href> link is clicked on my website, instead of webview just show the new link's content, I want the app to push a new page and show the new link content in the new page, so that I can maintain a good page backstack and it feels more like native app (for each navigation, there's a new page for it).

I'm wondering how I can detect link click, push a new page instead of let the webview do default link navigation. Thanks!

答:
You can use WebView prop onNavigationStateChange to detect the change in url.

On clicking  the webview will redirect, the onNavigationStateChange will fire. You can use this callback to push a new screen in the app.

Eg.

```<code>       <WebView
             ref={r => this.webview = r}
             style = {{marginTop : 0}}
             onNavigationStateChange={this._onNavigationStateChange}
             source = {{uri: 'https://www.your-url.com' }}
       />

      _onNavigationStateChange=(webViewState)=>{
          let newUrl = webViewState.url
          /*Your navigation logic*/
       }
</code>```

Reference

Title: React Native Webview push new page on <a> clicked

Body:
I'm trying to create a hybrid react native app to host my website's content in webviews. Something like this: Supreme App

One thing I want to achieve is: when a  link is clicked on my website, instead of webview just show the new link's content, I want the app to push a new page and show the new link content in the new page, so that I can maintain a good page backstack and it feels more like native app (for each navigation, there's a new page for it).

I'm wondering how I can detect link click, push a new page instead of let the webview do default link navigation. Thanks!

Body:
You can use WebView prop onNavigationStateChange to detect the change in url.

On clicking <a> the webview will redirect, the onNavigationStateChange will fire. You can use this callback to push a new screen in the app.

Eg.

       <WebView
             ref={r => this.webview = r}
             style = {{marginTop : 0}}
             onNavigationStateChange={this._onNavigationStateChange}
             source = {{uri: 'https://www.your-url.com' }}
       />

      _onNavigationStateChange=(webViewState)=>{
          let newUrl = webViewState.url
          /*Your navigation logic*/
       }

Reference


问:
Evaluate postfix using a stack in C++
```<code>#include <iostream>
#include <sstream>
#include <stack>
#include <limits>
#include <string>
using namespace std;

int main()
{
    string input;
    cout << "Enter a postfix expression: " << endl;
    getline(cin, input);

    int operand1, operand2, result,number;
    stack<char>operation;

    stringstream temp;

    int i=0;
    while (i < input.length())
    {
        if (isdigit(input[i]))
        {
            operation.push(input[i]);
        }
        else
        {
            operand2 = operation.top();
            temp << operation.top();
            operation.pop();

            operand1 = operation.top();
            temp << operation.top();
            operation.pop();

            switch(operand1,operand2)
            {
                case '+': result=operand1 + operand2;
                break;

                case '-': result=operand1 - operand2;
                break;

                case '*': result=operand1 * operand2;
                break;

                case '/': result=operand1 / operand2;
                break;
            }
            operation.push(result);
        }
        i++;
    }
    cout << "The result is: "<<temp.str()<<endl;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    return 0;
}
</code>```

I've changed the code and managed to obtain the "pop" value, but the operation didn't work.

答:
You probably meant

```<code>switch(input[i])
</code>```

instead

```<code>switch(operation.top())
</code>```

Title: Evaluate postfix using a stack in C++

Body:
#include <iostream>
#include <sstream>
#include <stack>
#include <limits>
#include <string>
using namespace std;

int main()
{
    string input;
    cout << "Enter a postfix expression: " << endl;
    getline(cin, input);

    int operand1, operand2, result,number;
    stack<char>operation;

    stringstream temp;

    int i=0;
    while (i < input.length())
    {
        if (isdigit(input[i]))
        {
            operation.push(input[i]);
        }
        else
        {
            operand2 = operation.top();
            temp << operation.top();
            operation.pop();

            operand1 = operation.top();
            temp << operation.top();
            operation.pop();

            switch(operand1,operand2)
            {
                case '+': result=operand1 + operand2;
                break;

                case '-': result=operand1 - operand2;
                break;

                case '*': result=operand1 * operand2;
                break;

                case '/': result=operand1 / operand2;
                break;
            }
            operation.push(result);
        }
        i++;
    }
    cout << "The result is: "<<temp.str()<<endl;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    return 0;
}

I've changed the code and managed to obtain the "pop" value, but the operation didn't work.

Body:
You probably meant

switch(input[i])

instead

switch(operation.top())


问:
Get script's url by handle (in wordpress)
Is it possible to get a script url from one of my working scripts, by handle?

So for example if i have a plugin's JS file registered with the handle wp-js-plugin and i want to get this JS file's url. how can i do that?

答:
Simple:

const scriptUrls = [...document.querySelectorAll('script')].map(e=>e.src)

This will list all the urls for each script.


问:
LINQ Concat nested queries sorting
I have the following code:

```<code>var comp = db.Companies.Select(x => new
        {

            topid = x.ID_comp,
            hill = ((from company in db.Companies
                    where x.ID_comp > company.ID_comp
                    orderby company.ID_comp
                    select new { h = company.ID_comp.ToString() })
                    .Concat((
                    from company in db.Companies
                    where x.ID_comp > company.ID_comp
                    orderby company.ID_comp descending
                    select new { h = company.ID_comp.ToString() })))
                    .Select(y => y.h)
        });
</code>```

The task is to build "pyramids" of ids for each company's id: 121 for 3, 12321 for 4 and so on (if there are companies with id's like 1, 2, 3 4). The idea of the given query is to take all ids that are less than current in 2 sets and then concatenate them, ordering the second set in descending order (the top of the pyramid duplicates, but I'll return to it later).

The problem is that the order by clause is not performed for each set separately, and at the end I get something like 1 2 3 1 2 3 for a company with id 4. How can I order the nested queries in different orders?

UPD1: The data I work with:

Table db.Companies

```<code>ID_comp | name
--------------------
   1    |Don_avia
   2    |Aeroflot
   3    |Dale_avia
   4    |air_France
   5    |British_AW
</code>```

Output:

```<code>1:
2: 1 1
3: 1 2 1 2
4: 1 2 3 1 2 3
5: 1 2 3 4 1 2 3 4
</code>```

UPD2: Resulting query:

```<code>SELECT
[Extent1].[ID_comp] AS [ID_comp],
[Project3].[C2] AS [C1],
[Project3].[C1] AS [C2]
FROM  [dbo].[Company] AS [Extent1]
OUTER APPLY  (SELECT
    [UnionAll1].[C1] AS [C1],
    1 AS [C2]
    FROM  (SELECT
         CAST( [Extent2].[ID_comp] AS nvarchar(max)) AS [C1]
        FROM [dbo].[Company] AS [Extent2]
        WHERE [Extent1].[ID_comp] > [Extent2].[ID_comp]
    UNION ALL
        SELECT
         CAST( [Extent3].[ID_comp] AS nvarchar(max)) AS [C1]
        FROM [dbo].[Company] AS [Extent3]
        WHERE [Extent1].[ID_comp] > [Extent3].[ID_comp]) AS [UnionAll1] ) AS [Project3]
ORDER BY [Extent1].[ID_comp] ASC, [Project3].[C2] ASC
</code>```

答:
Looks like you've hit EF6 query translation bug - ordering of .Concat (SQL UNION ALL) subqueries is ignored.

The workaround I've found is to append fake limiting operator like Take(int.MaxValue) to the subqueries, which is causing EF6 to consider the orderings:

```<code>hill =
    (from company in db.Companies
     where x.ID_comp > company.ID_comp
     orderby company.ID_comp
     select new { h = company.ID_comp.ToString() }
    ).Take(int.MaxValue)
    .Concat(
    (from company in db.Companies
     where x.ID_comp > company.ID_comp
     orderby company.ID_comp descending
     select new { h = company.ID_comp.ToString() }
    ).Take(int.MaxValue))
    .Select(y => y.h)
</code>```

Generated SQL:

SELECT
    [Extent1].[ID_comp] AS [ID_comp],
    [Project5].[C2] AS [C1],
    [Project5].[C1] AS [C2]
    FROM  [dbo].[Company] AS [Extent1]
    OUTER APPLY  (SELECT
        [UnionAll1].[C1] AS [C1],
        1 AS [C2]
        FROM  (SELECT TOP (2147483647)
            [Project1].[C1] AS [C1]
            FROM ( SELECT
                [Extent2].[ID_comp] AS [ID_comp],
                 CAST( [Extent2].[ID_comp] AS nvarchar(max)) AS [C1]
                FROM [dbo].[Company] AS [Extent2]
                WHERE [Extent1].[ID_comp] > [Extent2].[ID_comp]
            )  AS [Project1]
            ORDER BY [Project1].[ID_comp] ASC
        UNION ALL
            SELECT TOP (2147483647)
            [Project3].[C1] AS [C1]
            FROM ( SELECT
                [Extent3].[ID_comp] AS [ID_comp],
                 CAST( [Extent3].[ID_comp] AS nvarchar(max)) AS [C1]
                FROM [dbo].[Company] AS [Extent3]
                WHERE [Extent1].[ID_comp] > [Extent3].[ID_comp]
            )  AS [Project3]
            ORDER BY [Project3].[ID_comp] DESC) AS [UnionAll1] ) AS [Project5]
    ORDER BY [Extent1].[ID_comp] ASC, [Project5].[C2] ASC
```

Title: LINQ Concat nested queries sorting

Body:
I have the following code:

var comp = db.Companies.Select(x => new
        {

            topid = x.ID_comp,
            hill = ((from company in db.Companies
                    where x.ID_comp > company.ID_comp
                    orderby company.ID_comp
                    select new { h = company.ID_comp.ToString() })
                    .Concat((
                    from company in db.Companies
                    where x.ID_comp > company.ID_comp
                    orderby company.ID_comp descending
                    select new { h = company.ID_comp.ToString() })))
                    .Select(y => y.h)
        });

The task is to build "pyramids" of ids for each company's id: 121 for 3, 12321 for 4 and so on (if there are companies with id's like 1, 2, 3 4). The idea of the given query is to take all ids that are less than current in 2 sets and then concatenate them, ordering the second set in descending order (the top of the pyramid duplicates, but I'll return to it later).

The problem is that the order by clause is not performed for each set separately, and at the end I get something like 1 2 3 1 2 3 for a company with id 4. How can I order the nested queries in different orders?

UPD1: The data I work with:

Table db.Companies

ID_comp | name
--------------------
   1    |Don_avia
   2    |Aeroflot
   3    |Dale_avia
   4    |air_France
   5    |British_AW

Output:

1:
2: 1 1
3: 1 2 1 2
4: 1 2 3 1 2 3
5: 1 2 3 4 1 2 3 4

UPD2: Resulting query:

SELECT
[Extent1].[ID_comp] AS [ID_comp],
[Project3].[C2] AS [C1],
[Project3].[C1] AS [C2]
FROM  [dbo].[Company] AS [Extent1]
OUTER APPLY  (SELECT
    [UnionAll1].[C1] AS [C1],
    1 AS [C2]
    FROM  (SELECT
         CAST( [Extent2].[ID_comp] AS nvarchar(max)) AS [C1]
        FROM [dbo].[Company] AS [Extent2]
        WHERE [Extent1].[ID_comp] > [Extent2].[ID_comp]
    UNION ALL
        SELECT
         CAST( [Extent3].[ID_comp] AS nvarchar(max)) AS [C1]
        FROM [dbo].[Company] AS [Extent3]
        WHERE [Extent1].[ID_comp] > [Extent3].[ID_comp]) AS [UnionAll1] ) AS [Project3]
ORDER BY [Extent1].[ID_comp] ASC, [Project3].[C2] ASC

Body:
Looks like you've hit EF6 query translation bug - ordering of .Concat (SQL UNION ALL) subqueries is ignored.

The workaround I've found is to append fake limiting operator like Take(int.MaxValue) to the subqueries, which is causing EF6 to consider the orderings:

hill =
    (from company in db.Companies
     where x.ID_comp > company.ID_comp
     orderby company.ID_comp
     select new { h = company.ID_comp.ToString() }
    ).Take(int.MaxValue)
    .Concat(
    (from company in db.Companies
     where x.ID_comp > company.ID_comp
     orderby company.ID_comp descending
     select new { h = company.ID_comp.ToString() }
    ).Take(int.MaxValue))
    .Select(y => y.h)

Generated SQL:

SELECT
    [Extent1].[ID_comp] AS [ID_comp],
    [Project5].[C2] AS [C1],
    [Project5].[C1] AS [C2]
    FROM  [dbo].[Company] AS [Extent1]
    OUTER APPLY  (SELECT
        [UnionAll1].[C1] AS [C1],
        1 AS [C2]
        FROM  (SELECT TOP (2147483647)
            [Project1].[C1] AS [C1]
            FROM ( SELECT
                [Extent2].[ID_comp] AS [ID_comp],
                 CAST( [Extent2].[ID_comp] AS nvarchar(max)) AS [C1]
                FROM [dbo].[Company] AS [Extent2]
                WHERE [Extent1].[ID_comp] > [Extent2].[ID_comp]
            )  AS [Project1]
            ORDER BY [Project1].[ID_comp] ASC
        UNION ALL
            SELECT TOP (2147483647)
            [Project3].[C1] AS [C1]
            FROM ( SELECT
                [Extent3].[ID_comp] AS [ID_comp],
                 CAST( [Extent3].[ID_comp] AS nvarchar(max)) AS [C1]
                FROM [dbo].[Company] AS [Extent3]
                WHERE [Extent1].[ID_comp] > [Extent3].[ID_comp]
            )  AS [Project3]
            ORDER BY [Project3].[ID_comp] DESC) AS [UnionAll1] ) AS [Project5]
    ORDER BY [Extent1].[ID_comp] ASC, [Project5].[C2] ASC


问:
neo4j - Return single instance of node - querying by property?
I am building a social network that has a specialized audience.

Users are related to each other by three primary relationship types.

```<code>[:FRIENDS]->(:USER),
[:WORKS_AT]->(:COMPANY),
[:WORKED_AT]->(:COMPANY),
[:FOLLOWS].
</code>```

When working through a search scenario (a user wants to find another user), I've given each relationship a "priority" (so to speak).

For example, if a user wants to find another user named "Bart Simpson" - first, we will check co-worker relationships ([:WORKS_AT],[:WORKED_AT]). I've assigned those relationships a priority of 1. That way, "Bart Simpson" who works with me will appear in the search results before "Bart Simpson" - who lives hundreds of miles away in Springfield.

The second priority is [:FRIENDS]->(:USER). Do any of my friends have a friend named "Bart Simpson?" Priority #2.

The last priority is a global search. I don't have any co-workers named "Bart Simpson", my friends don't have any friends named "Bart Simpson" - but I met Bart at a conference, and I want to "friend" him. So, I've added a "Global" search. Find any users named "Bart Simpson".

So far, this is my Cypher:

```<code>optional match (u:USER {id:'1'})-[:WORKS_AT|:WORKED_AT]-(w:COMPANY)-[r]-(f:USER)
with collect(f{.*, priority:1,relationship:r.title,type:type(r)}) as user
optional match (u:USER {id: '1'})-[:FRIENDS]-(:USER)-[r:FRIENDS]-(f:USER)
with user + collect(f{.*, priority:2,relationship:r.title,type:type(r)}) as user
optional match (f:USER)
where f.id <> '1'
with user + collect(f{.*, priority:3,relationship:'',type:''}) as user
unwind user as users
with users as user
where toLower(user.last_name) STARTS WITH toLower('Sc') OR toLower(user.first_name) STARTS WITH toLower('Sc')
return distinct user
</code>```

This is fantastic - however, a user could work at the same company, as well as
be friends, as well as appear in the global search. So - we have the potential for three (or more) "copies" of the same user - with different relationship attributes. The relationship attributes are important because in the app, they provide important context to the search. "Bart Simpson - Works at XYZ Company."

So what I'm really looking for is the ability to either return the user record with the highest priority - and do that based on the "ID" field. If that doesn't work, I could see a situation where we try to update the property of a node. So, when the query hits the priority 2 search, if there is already a user in the collection with the same "ID", it just appends the P2 relationship type to the record.  Either is fine with me.

I'm open to suggestions and listening!

答:
So, I've made some progress!

```<code>MATCH
    (subject:USER {id:'1'})
MATCH
    (subject)-[:WORKS_AT|:WORKED_AT]-(w:COMPANY)-[r]-(f1:USER)
WHERE
    toLower(f1.last_name) STARTS WITH toLower('Sc') or
    toLower(f1.first_name) STARTS WITH toLower('Sc')
WITH
    COLLECT(f1.id) AS userIds,
    COLLECT(f1{.*,priority:1,rType:type(r), title:r.title, detail:w.name}) AS users
OPTIONAL MATCH
    (subject)-[:FRIEND]-(fw:USER)-[r:FRIEND]-(f2:USER)
WHERE
    NOT(f2.id in userIds) AND
    (
        toLower(f2.last_name) STARTS WITH toLower('Sc') or
        toLower(f2.first_name) STARTS WITH toLower('Sc')
    )
WITH
    users + COLLECT(f2{.*,priority:2,rType:"FRIEND", title:"Friends with " + fw.first_name + " " + fw.last_name, detail:''}) AS users,
    userIds + collect(f2.id) AS userIds
OPTIONAL MATCH
    (f3:USER)
WHERE
    NOT(f3.id in userIds) AND
    (
        toLower(f3.last_name) starts with toLower('Sc') OR
        toLower(f3.first_name) starts with toLower('Sc')
    )
WITH
    users + COLLECT(f3{.*,priority:3,rType:"GLOBAL", title:"", detail:''}) AS users
RETURN
    users
</code>```

The query has evolved a bit. Essentially, at the first stage, we collect the userIds of the items that were returned. At each subsequent stage, the results returned are compared against the running list of ids. If the id of the result is already in the list of ids, it is filtered out - thus ensuring a unique id in the set.

This is working - and for now, I'm going to run with it. Is this the most efficient query, or is there a better way to deal with this scenario?

Body:
I am building a social network that has a specialized audience.

Users are related to each other by three primary relationship types.

[:FRIENDS]->(:USER),
[:WORKS_AT]->(:COMPANY),
[:WORKED_AT]->(:COMPANY),
[:FOLLOWS].

When working through a search scenario (a user wants to find another user), I've given each relationship a "priority" (so to speak).

For example, if a user wants to find another user named "Bart Simpson" - first, we will check co-worker relationships ([:WORKS_AT],[:WORKED_AT]). I've assigned those relationships a priority of 1. That way, "Bart Simpson" who works with me will appear in the search results before "Bart Simpson" - who lives hundreds of miles away in Springfield.

The second priority is [:FRIENDS]->(:USER). Do any of my friends have a friend named "Bart Simpson?" Priority #2.

The last priority is a global search. I don't have any co-workers named "Bart Simpson", my friends don't have any friends named "Bart Simpson" - but I met Bart at a conference, and I want to "friend" him. So, I've added a "Global" search. Find any users named "Bart Simpson".

So far, this is my Cypher:

optional match (u:USER {id:'1'})-[:WORKS_AT|:WORKED_AT]-(w:COMPANY)-[r]-(f:USER)
with collect(f{.*, priority:1,relationship:r.title,type:type(r)}) as user
optional match (u:USER {id: '1'})-[:FRIENDS]-(:USER)-[r:FRIENDS]-(f:USER)
with user + collect(f{.*, priority:2,relationship:r.title,type:type(r)}) as user
optional match (f:USER)
where f.id <> '1'
with user + collect(f{.*, priority:3,relationship:'',type:''}) as user
unwind user as users
with users as user
where toLower(user.last_name) STARTS WITH toLower('Sc') OR toLower(user.first_name) STARTS WITH toLower('Sc')
return distinct user

This is fantastic - however, a user could work at the same company, as well as
be friends, as well as appear in the global search. So - we have the potential for three (or more) "copies" of the same user - with different relationship attributes. The relationship attributes are important because in the app, they provide important context to the search. "Bart Simpson - Works at XYZ Company."

So what I'm really looking for is the ability to either return the user record with the highest priority - and do that based on the "ID" field. If that doesn't work, I could see a situation where we try to update the property of a node. So, when the query hits the priority 2 search, if there is already a user in the collection with the same "ID", it just appends the P2 relationship type to the record.  Either is fine with me.

I'm open to suggestions and listening!

Body:
So, I've made some progress!

MATCH
    (subject:USER {id:'1'})
MATCH
    (subject)-[:WORKS_AT|:WORKED_AT]-(w:COMPANY)-[r]-(f1:USER)
WHERE
    toLower(f1.last_name) STARTS WITH toLower('Sc') or
    toLower(f1.first_name) STARTS WITH toLower('Sc')
WITH
    COLLECT(f1.id) AS userIds,
    COLLECT(f1{.*,priority:1,rType:type(r), title:r.title, detail:w.name}) AS users
OPTIONAL MATCH
    (subject)-[:FRIEND]-(fw:USER)-[r:FRIEND]-(f2:USER)
WHERE
    NOT(f2.id in userIds) AND
    (
        toLower(f2.last_name) STARTS WITH toLower('Sc') or
        toLower(f2.first_name) STARTS WITH toLower('Sc')
    )
WITH
    users + COLLECT(f2{.*,priority:2,rType:"FRIEND", title:"Friends with " + fw.first_name + " " + fw.last_name, detail:''}) AS users,
    userIds + collect(f2.id) AS userIds
OPTIONAL MATCH
    (f3:USER)
WHERE
    NOT(f3.id in userIds) AND
    (
        toLower(f3.last_name) starts with toLower('Sc') OR
        toLower(f3.first_name) starts with toLower('Sc')
    )
WITH
    users + COLLECT(f3{.*,priority:3,rType:"GLOBAL", title:"", detail:''}) AS users
RETURN
    users

The query has evolved a bit. Essentially, at the first stage, we collect the userIds of the items that were returned. At each subsequent stage, the results returned are compared against the running list of ids. If the id of the result is already in the list of ids, it is filtered out - thus ensuring a unique id in the set.

This is working - and for now, I'm going to run with it. Is this the most efficient query, or is there a better way to deal with this scenario?


问:
After `npm install` an error about a syntax error in python appears?
I am trying to install the necessary dependencies for Exokit, but I am getting an error relating to a Python syntax error.

This is for a something new I wanted to try involving VR in the browser. I've recloned the repository from their github and downloaded straight from their website. I followed the instructions given to a T (there was only 4 of them lol).

I have not yet touched the code and this is the error that I am getting.

```<code>Austin@DESKTOP-UD2R1O4 MINGW64 ~/exokit (master)
$ npm install

> raw-buffer@0.0.19 install C:\Users\Austin\exokit\node_modules\raw-buffer
> node-gyp rebuild

C:\Users\Austin\exokit\node_modules\raw-buffer>if not defined
npm_config_node_gyp (node "C:\Program
Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-
bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild )  else (node
"C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js" rebuild )
gyp ERR! configure error
gyp ERR! stack Error: Command failed: C:\Users\Austin\Anaconda3\python.EXE -c import sys; print "%s.%s.%s" % sys.version_info[:3];
gyp ERR! stack   File "<string>", line 1
gyp ERR! stack     import sys; print "%s.%s.%s" % sys.version_info[:3];
gyp ERR! stack                                ^
gyp ERR! stack SyntaxError: invalid syntax
gyp ERR! stack
gyp ERR! stack     at ChildProcess.exithandler (child_process.js:276:12)
gyp ERR! stack     at emitTwo (events.js:126:13)
gyp ERR! stack     at ChildProcess.emit (events.js:214:7)
gyp ERR! stack     at maybeClose (internal/child_process.js:915:16)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:209:5)
gyp ERR! System Windows_NT 10.0.17134
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Users\Austin\exokit\node_modules\raw-buffer
gyp ERR! node -v v8.12.0
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! raw-buffer@0.0.19 install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the raw-buffer@0.0.19 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Austin\AppData\Roaming\npm-cache\_logs\2019-01-06T06_55_37_752Z-debug.log
</code>```

答:
In case the answer(s) provided doesn't work for you, here are some tips you can follow in order to mitigate related problems for windows OS.

NOTE: If you already tried installing the build tools via npm command with no success, it is probably a good idea to delete everything before applying any of the tips below.

You can find the build tools here and just delete the folders (but I don't know if they are installed somewhere else):

C:\Users\'yourUser'\.windows-build-tools\

C:\Users\'yourUser'\AppData\Roaming\npm\node_modules\windows-build-tools

After ensuring that the folders specified above are deleted, then you can try applying any of the following tips.

First Tip:

Run CMD or PowerShell as Administrator

Install node-gyp using the following command: npm install -g node-gyp

Download and install windows build tools manually from this link: Windows_Build_tools

Download and install Python 2.7

Register Microsoft Visual Studio version to npm using the following command: npm config set msvs_version <your msvs_version e.g. 2017>

Register the path of python executable file to npm using the following command: npm config set python <the path to python executable file>

Second Tip (RECOMMENDED)

Run CMD or PowerShell as Administrator

Install windows-build-tools with the python-path directly using the following command: npm --add-python-to-path='true' install --global --production windows-build-tools

You can run the following command: npm config set python <the path to python executable file>, in order to be sure that npm is pointing to the correct path of python executable file.
 In order to use this command, you can find the python path here (i.e. after running the command in the previous step): C:\Users\<your_user_name>\.windows-build-tools\python27

More information or description about node-gyp can be found here: node-gyp

More information about possible windows build tools issues can be found in the following links:
https://github.com/felixrieseberg/windows-build-tools/issues/47

https://github.com/felixrieseberg/windows-build-tools/issues/56

Additional Note: Some people tend to have spaces in their project path names whereas, some tools don't handle spaces in path names well. You can get more info here: https://github.com/nodejs/node-gyp/issues/809

Hope this solves your problem.

Body:
I am trying to install the necessary dependencies for Exokit, but I am getting an error relating to a Python syntax error.

This is for a something new I wanted to try involving VR in the browser. I've recloned the repository from their github and downloaded straight from their website. I followed the instructions given to a T (there was only 4 of them lol).

I have not yet touched the code and this is the error that I am getting.

Austin@DESKTOP-UD2R1O4 MINGW64 ~/exokit (master)
$ npm install

> raw-buffer@0.0.19 install C:\Users\Austin\exokit\node_modules\raw-buffer
> node-gyp rebuild

C:\Users\Austin\exokit\node_modules\raw-buffer>if not defined
npm_config_node_gyp (node "C:\Program
Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-
bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild )  else (node
"C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js" rebuild )
gyp ERR! configure error
gyp ERR! stack Error: Command failed: C:\Users\Austin\Anaconda3\python.EXE -c import sys; print "%s.%s.%s" % sys.version_info[:3];
gyp ERR! stack   File "<string>", line 1
gyp ERR! stack     import sys; print "%s.%s.%s" % sys.version_info[:3];
gyp ERR! stack                                ^
gyp ERR! stack SyntaxError: invalid syntax
gyp ERR! stack
gyp ERR! stack     at ChildProcess.exithandler (child_process.js:276:12)
gyp ERR! stack     at emitTwo (events.js:126:13)
gyp ERR! stack     at ChildProcess.emit (events.js:214:7)
gyp ERR! stack     at maybeClose (internal/child_process.js:915:16)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:209:5)
gyp ERR! System Windows_NT 10.0.17134
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Users\Austin\exokit\node_modules\raw-buffer
gyp ERR! node -v v8.12.0
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! raw-buffer@0.0.19 install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the raw-buffer@0.0.19 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Austin\AppData\Roaming\npm-cache\_logs\2019-01-06T06_55_37_752Z-debug.log


问:
How to sign data with encrypted RSA private key (AES-256-CBC) in python
Partial example of private_key (this variable is a string):

```<code>-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-256-CBC,hidden_text..

lots_of_hidden_text..

-----END RSA PRIVATE KEY-----
</code>```

When I try to do the following:

```<code>from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
rsakey = RSA.importKey(private_key, passphrase=privkey_secret_string)
signer = PKCS1_v1_5.new(rsakey)
signature = signer.sign(data)
</code>```

I'm getting value error on the importKey:

```<code>Error: ValueError: Unsupport PEM encryption algorithm.
</code>```

I can see that RSA.importKey doesn't support AES-256-CBC, but i can't find any way to import this private key.

The only solution i've seen in order to create an AES signer is:

```<code>signer = AES.new(privkey_secret_string, AES.MODE_CBC, IV=iv)
</code>```

But this doesn't use the private key

答:
You can either switch to PyCryptodome or decrypt the key with a system call to openssl prior to importing the key:

echo PASSPHRASE | openssl rsa -in key.pem

Body:
Partial example of private_key (this variable is a string):

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-256-CBC,hidden_text..

lots_of_hidden_text..

-----END RSA PRIVATE KEY-----

When I try to do the following:

from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
rsakey = RSA.importKey(private_key, passphrase=privkey_secret_string)
signer = PKCS1_v1_5.new(rsakey)
signature = signer.sign(data)

I'm getting value error on the importKey:

Error: ValueError: Unsupport PEM encryption algorithm.

I can see that RSA.importKey doesn't support AES-256-CBC, but i can't find any way to import this private key.

The only solution i've seen in order to create an AES signer is:

signer = AES.new(privkey_secret_string, AES.MODE_CBC, IV=iv)

But this doesn't use the private key


问:
Current offset behavior when set by kafka-consumer-groups to earliest?
I have a kafka topic with 25 partitions and the cluster has been running for 5 months.

As per my understanding for each partition for a given topic, the offset starts from 0,1,2... (un-bounded)

I see log-end-offset at a very high value (right now -> 1230628032)

I created a new consumer group with offset being set to earliest; so i expected the offset from which a client for that consumer group will start from offset 0.

The command which I used to create a new consumer group with offset to earliest:

```<code>kafka-consumer-groups  --bootstrap-server <IP_address>:9092 --reset-offsets --to-earliest --topic some-topic --group to-earliest-cons --execute
</code>```

I see the consumer group being created. I expected the current-offset being to 0; however when I described the consumer group the current offset was very high , at the moment --> 1143755193.

The record retention period set is for 7 days (standard value).

My question is why didn't we see the first offset from which a consumer from this consumer group will read 0? Has it to do something with data-retention?

Can anyone help understand this?

答:
It is exactly data retention. It is highly probable that Kafka already removed old messages with offset 0 from your partitions, so it doesn't make sense to start from 0. Instead, Kafka will set offset to the earliest available message on your partition. You can check those offsets using:

```<code>./kafka-run-class.sh kafka.tools.GetOffsetShell --broker-list <IP_address>:9092 --topic some-topic --time -2
</code>```

You will probably see values really close to what you're seeing as new consumer offset.

You can also try and set offset explicitly to 0:

```<code>./kafka-consumer-groups.sh  --bootstrap-server <IP_address>:9092 --reset-offsets --to-offset 0 --topic some-topic --group to-earliest-cons --execute
</code>```

However, you will see warning that offset 0 does not exist and it will use higher value (aforementioned earliest message available)

```<code>New offset (0) is lower than earliest offset for topic partition some-topic. Value will be set to 1143755193
</code>```

Body:
I have a kafka topic with 25 partitions and the cluster has been running for 5 months.

As per my understanding for each partition for a given topic, the offset starts from 0,1,2... (un-bounded)

I see log-end-offset at a very high value (right now -> 1230628032)

I created a new consumer group with offset being set to earliest; so i expected the offset from which a client for that consumer group will start from offset 0.

The command which I used to create a new consumer group with offset to earliest:

kafka-consumer-groups  --bootstrap-server <IP_address>:9092 --reset-offsets --to-earliest --topic some-topic --group to-earliest-cons --execute

I see the consumer group being created. I expected the current-offset being to 0; however when I described the consumer group the current offset was very high , at the moment --> 1143755193.

The record retention period set is for 7 days (standard value).

My question is why didn't we see the first offset from which a consumer from this consumer group will read 0? Has it to do something with data-retention?

Can anyone help understand this?

Body:
It is exactly data retention. It is highly probable that Kafka already removed old messages with offset 0 from your partitions, so it doesn't make sense to start from 0. Instead, Kafka will set offset to the earliest available message on your partition. You can check those offsets using:

./kafka-run-class.sh kafka.tools.GetOffsetShell --broker-list <IP_address>:9092 --topic some-topic --time -2

You will probably see values really close to what you're seeing as new consumer offset.

You can also try and set offset explicitly to 0:

./kafka-consumer-groups.sh  --bootstrap-server <IP_address>:9092 --reset-offsets --to-offset 0 --topic some-topic --group to-earliest-cons --execute

However, you will see warning that offset 0 does not exist and it will use higher value (aforementioned earliest message available)

New offset (0) is lower than earliest offset for topic partition some-topic. Value will be set to 1143755193


问:
Getting X-Mailer attribute in php imap
how I can get X-Mailer attribute in php imap lib ?

I can't find any fetch function for attribute  http://php.net/manual/en/function.imap-fetchheader.php

```<code> $inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());

  $header =  imap_fetchheader($inbox, 1);
  var_dump($header);

/* close the connection */
imap_close($inbox);
</code>```

output I am getting is

```<code> string(405) "MIME-Version: 1.0
Received: by 10.42.228.195; Wed, 16 Feb 2011 21:18:06 -0800 (PST)
Date: Wed, 16 Feb 2011 21:18:06 -0800
Message-ID: <AANLkTikj8NgGgkG=Of=V6VvNSt2QZ3WLNKUVZxpcs4tk@mail.gmail.com>
Subject: Get Gmail on your mobile phone
From: Gmail Team <mail-noreply@google.com>
To: test case2 <email@gmail.com>
Content-Type: multipart/alternative; boundary=20cf302234f1c34163049c73853c

"
</code>```

答:
Method:

Fetch headers with imap_fetchheader()

Extract X-Mailer field from headers

Extract value from field

Example:

```<code>$inbox = imap_open($hostname,$username,$password);
if (!$inbox) {
    echo('Cannot connect to Gmail: ' . imap_last_error());
    exit;
}
$header_string =  imap_fetchheader($inbox, 1);
preg_match_all('/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)\r\n/m',
        $header_string, $matches);
$headers = array_combine($matches[1], $matches[2]);
$xmailer = $headers['X-Mailer'];
imap_close($inbox);
</code>```

Title: Getting X-Mailer attribute in php imap

Body:
how I can get X-Mailer attribute in php imap lib ?

I can't find any fetch function for attribute  http://php.net/manual/en/function.imap-fetchheader.php

 $inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());

  $header =  imap_fetchheader($inbox, 1);
  var_dump($header);

/* close the connection */
imap_close($inbox);

output I am getting is

 string(405) "MIME-Version: 1.0
Received: by 10.42.228.195; Wed, 16 Feb 2011 21:18:06 -0800 (PST)
Date: Wed, 16 Feb 2011 21:18:06 -0800
Message-ID: <AANLkTikj8NgGgkG=Of=V6VvNSt2QZ3WLNKUVZxpcs4tk@mail.gmail.com>
Subject: Get Gmail on your mobile phone
From: Gmail Team <mail-noreply@google.com>
To: test case2 <email@gmail.com>
Content-Type: multipart/alternative; boundary=20cf302234f1c34163049c73853c

"

Body:
Method:

Fetch headers with imap_fetchheader()

Extract X-Mailer field from headers

Extract value from field

Example:

$inbox = imap_open($hostname,$username,$password);
if (!$inbox) {
    echo('Cannot connect to Gmail: ' . imap_last_error());
    exit;
}
$header_string =  imap_fetchheader($inbox, 1);
preg_match_all('/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)\r\n/m',
        $header_string, $matches);
$headers = array_combine($matches[1], $matches[2]);
$xmailer = $headers['X-Mailer'];
imap_close($inbox);


问:
Generating 3-tuples from a set of 2-tuples
In an earlier question:

Generating maximum number of 3-tuples from a list of 2-tuples

I got an answer from @AChampion that seems to work if the number of 2-tuples is divisible by 3. However, the solution fails if we, for example, have 10 2-tuples. After fumbling with it for a while I'm under the impression that it is impossible to find a perfect solution for say:

```<code>(1,2)(1,3),(1,4),(2,3),(2,4),(3,4)
</code>```

So I'm interested in finding one solution that minimizes the number of remainder tuples. In the example above the result could be:

```<code>(1,2,3)           # derived from (1,2), (1,3), (2,3)
(1,4),(2,4),(3,4) # remainder tuples
</code>```

The rule for generating 3-tuple from 3 2-tuple is:

```<code>(a,b), (b,c), (c,a) -> (a, b, c)
</code>```

i.e. the 2-tuples is a cycle with length 3. The order of the elements in a 3-tuple is not important, i.e:

```<code>(a,b,c) == (c,a,b)
</code>```

I'm actually interested in the case where we have a number n:

```<code>for x in range(1,n+1):
    for y in range(1,n+1):
        if x!=y:
            a.append((x,y))

# a = [ (1,2),...,(1,n), (2,1),(2,3),...,(2,n),...(n,1),...,(n,n-1) ]
</code>```

From a, minimize the number of 2-tuples that is left when producing 3-tuples. Each 2-tuple can only be used once.

I wrapped my brain around this for several hours but I can't seem to come up with an elegant solution (well, neither have I found an ugly one:-) for the general case. Any thoughts?

答:
For this you need to create number of combinations that will use for replacement. Then loop over you data for 3 item that contains any of above combinations and replace them.
I have done thi in several steps.

```<code>from itertools import combinations

# create replacements elements
number_combinations_raw = list(combinations(range(1, 5), 3))

# create proper number combinations
number_combinations = []
for item in number_combinations_raw:
    if (item[0] + 1 == item[1]) and (item[1] + 1 == item[2]):
        number_combinations.append(item)

# create test data
data = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4)]

# reduce data
reduce_data = []
for number_set in number_combinations:
    count = 0
    merged_data = []
    for item in data:
        if (number_set[0] in item and number_set[1] in item) or (number_set[1] in item and number_set[2] in item) \
            or (number_set[0] in item and number_set[2] in item):
            merged_data.append(item)
            count += 1
    if count == 3:
        reduce_data.append((number_set, merged_data))

# delete merged elements from data list and add replacement
for item in data:
    for reduce_item in reduce_data:
        for element in reduce_item[1]:
            if element in data:
                data.remove(element)

        data = [reduce_item[0]] + data

# remove duplicated replaced elements
final_list = list(dict.fromkeys(data))
</code>```

Output:

```<code>[(1, 2, 3), (1, 4), (2, 4)]
</code>```

Body:
In an earlier question:

Generating maximum number of 3-tuples from a list of 2-tuples

I got an answer from @AChampion that seems to work if the number of 2-tuples is divisible by 3. However, the solution fails if we, for example, have 10 2-tuples. After fumbling with it for a while I'm under the impression that it is impossible to find a perfect solution for say:

(1,2)(1,3),(1,4),(2,3),(2,4),(3,4)

So I'm interested in finding one solution that minimizes the number of remainder tuples. In the example above the result could be:

(1,2,3)           # derived from (1,2), (1,3), (2,3)
(1,4),(2,4),(3,4) # remainder tuples

The rule for generating 3-tuple from 3 2-tuple is:

(a,b), (b,c), (c,a) -> (a, b, c)

i.e. the 2-tuples is a cycle with length 3. The order of the elements in a 3-tuple is not important, i.e:

(a,b,c) == (c,a,b)

I'm actually interested in the case where we have a number n:

for x in range(1,n+1):
    for y in range(1,n+1):
        if x!=y:
            a.append((x,y))

# a = [ (1,2),...,(1,n), (2,1),(2,3),...,(2,n),...(n,1),...,(n,n-1) ]

From a, minimize the number of 2-tuples that is left when producing 3-tuples. Each 2-tuple can only be used once.

I wrapped my brain around this for several hours but I can't seem to come up with an elegant solution (well, neither have I found an ugly one:-) for the general case. Any thoughts?

Body:
For this you need to create number of combinations that will use for replacement. Then loop over you data for 3 item that contains any of above combinations and replace them.
I have done thi in several steps.

from itertools import combinations

# create replacements elements
number_combinations_raw = list(combinations(range(1, 5), 3))

# create proper number combinations
number_combinations = []
for item in number_combinations_raw:
    if (item[0] + 1 == item[1]) and (item[1] + 1 == item[2]):
        number_combinations.append(item)

# create test data
data = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4)]

# reduce data
reduce_data = []
for number_set in number_combinations:
    count = 0
    merged_data = []
    for item in data:
        if (number_set[0] in item and number_set[1] in item) or (number_set[1] in item and number_set[2] in item) \
            or (number_set[0] in item and number_set[2] in item):
            merged_data.append(item)
            count += 1
    if count == 3:
        reduce_data.append((number_set, merged_data))

# delete merged elements from data list and add replacement
for item in data:
    for reduce_item in reduce_data:
        for element in reduce_item[1]:
            if element in data:
                data.remove(element)

        data = [reduce_item[0]] + data

# remove duplicated replaced elements
final_list = list(dict.fromkeys(data))

Output:

[(1, 2, 3), (1, 4), (2, 4)]


问:
Calculating three differents sum in three tables
I have these tables:

```<code>DROP TABLE IF EXISTS books;
CREATE TABLE `books` (
  `bookId` mediumint(8) UNSIGNED NOT NULL,
  `title` varchar(10) NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `books`
  ADD PRIMARY KEY (`bookId`),

DROP TABLE IF EXISTS movements;
CREATE TABLE `movements` (
  `movementId` mediumint(8) UNSIGNED NOT NULL,
  `movementTypeId` tinyint(3) UNSIGNED NOT NULL,
  `deletedFlag` tinyint(3) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `movements`
  ADD PRIMARY KEY (`movementId`),
  ADD KEY `movementId` (`movementTypeId`,`deletedFlag`) USING BTREE;

DROP TABLE IF EXISTS movements_types;
CREATE TABLE `movements_types` (
  `movementTypeId` mediumint(8) UNSIGNED NOT NULL,
  `title` varchar(200) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `movements_types`
  ADD PRIMARY KEY (`movementTypeId`);

DROP TABLE IF EXISTS movements_books;
CREATE TABLE `movements_books` (
  `movementId` mediumint(8) UNSIGNED NOT NULL,
  `bookId` mediumint(8) UNSIGNED NOT NULL,
  `bookSize` tinyint(3) UNSIGNED NOT NULL,
  `quantity` smallint(5) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `books` (`bookId`, `title`) VALUES
(1, 'Harry Potter'),
(2, 'Mysql Join'),
(3, 'Comedy');

INSERT INTO `movements` (`movementId`, `movementTypeId`, `deletedFlag`) VALUES
(7, 1, 0),
(8, 2, 0),
(9, 2, 0);

INSERT INTO `movements_types` (`movementTypeId`, `title`) VALUES
(1, "Bought"),
(2, "Sold");

INSERT INTO `movements_books` (`movementId`, `bookId`, `bookSize`, `quantity`) VALUES
(7, 1, 1, 3),
(7, 1, 2, 3),
(7, 2, 1, 3),
(7, 2, 2, 3),
(8, 1, 1, 2),
(8, 1, 1, 2),
(9, 2, 1, 3);
</code>```

bookSize is just an integer indicating the size of the book.

movements_books actually has 111824 records, movements has 4534.
deletedFlag is 1 for a deleted movement (I prefer to keep them flagged) and 0 otherwise.

I need help creating indexes and I need these results:

1) sizes sold/bought/available for each book (bookId, bookSize, booksSold, booksBought, booksBought minus booksSold)

2) books sold/bought/available for each book of all size (bookId, booksSold, booksBought, booksBought minus booksSold)

To get the one of the statistics I tried:

```<code>SELECT
   books.title
   movements_books_grouped.bookId,
   SUM(IF(movements.movementTypeId=1, movements_books_grouped.quantity, NULL)) AS booksBought,
   SUM(IF(movements.movementTypeId=2, movements_books_grouped.quantity, NULL)) AS booksSold,
   (
       SUM(IF(movements.movementTypeId=1, movements_books_grouped.quantity, 0))-
       SUM(IF(movements.movementTypeId=2, movements_books_grouped.quantity, 0))
   ) AS booksAvailability,
   FROM
   (
   SELECT bookId,quantity,movementId FROM movements_books GROUP BY bookId
   ) AS movements_books_grouped
   JOIN movements ON movements.movementId=movements_books_grouped.movementId
   JOIN books ON books.bookId=movements_books_grouped.bookId
   GROUP BY movements_books_grouped.bookId
   ORDER BY book.title
</code>```

but it's very slow.
Edit: I needed to add another table to the example because that's the one that makes really slow the last query. I need to join to this table because I need to order the result by title.

答:
Here's a query that can use indexes:

```<code>SELECT m.movementId
     , m.movementTypeId
     , m.deletedFlag
     , mb.bookId
     , mb.bookSize
     , t.title
  FROM movements m
  JOIN movements_types t
    ON t.movementTypeId = m.movementTypeId
  JOIN movements_books mb
    ON mb.movementid = m.movementid
 WHERE m.deletedFlag=0;
</code>```

An index on (m.movementTypeId, m.deletedFlag) may prove beneficial, but best to suck it and see.

Body:
I have these tables:

DROP TABLE IF EXISTS books;
CREATE TABLE `books` (
  `bookId` mediumint(8) UNSIGNED NOT NULL,
  `title` varchar(10) NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `books`
  ADD PRIMARY KEY (`bookId`),

DROP TABLE IF EXISTS movements;
CREATE TABLE `movements` (
  `movementId` mediumint(8) UNSIGNED NOT NULL,
  `movementTypeId` tinyint(3) UNSIGNED NOT NULL,
  `deletedFlag` tinyint(3) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `movements`
  ADD PRIMARY KEY (`movementId`),
  ADD KEY `movementId` (`movementTypeId`,`deletedFlag`) USING BTREE;

DROP TABLE IF EXISTS movements_types;
CREATE TABLE `movements_types` (
  `movementTypeId` mediumint(8) UNSIGNED NOT NULL,
  `title` varchar(200) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `movements_types`
  ADD PRIMARY KEY (`movementTypeId`);

DROP TABLE IF EXISTS movements_books;
CREATE TABLE `movements_books` (
  `movementId` mediumint(8) UNSIGNED NOT NULL,
  `bookId` mediumint(8) UNSIGNED NOT NULL,
  `bookSize` tinyint(3) UNSIGNED NOT NULL,
  `quantity` smallint(5) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `books` (`bookId`, `title`) VALUES
(1, 'Harry Potter'),
(2, 'Mysql Join'),
(3, 'Comedy');

INSERT INTO `movements` (`movementId`, `movementTypeId`, `deletedFlag`) VALUES
(7, 1, 0),
(8, 2, 0),
(9, 2, 0);

INSERT INTO `movements_types` (`movementTypeId`, `title`) VALUES
(1, "Bought"),
(2, "Sold");

INSERT INTO `movements_books` (`movementId`, `bookId`, `bookSize`, `quantity`) VALUES
(7, 1, 1, 3),
(7, 1, 2, 3),
(7, 2, 1, 3),
(7, 2, 2, 3),
(8, 1, 1, 2),
(8, 1, 1, 2),
(9, 2, 1, 3);

bookSize is just an integer indicating the size of the book.

movements_books actually has 111824 records, movements has 4534.
deletedFlag is 1 for a deleted movement (I prefer to keep them flagged) and 0 otherwise.

I need help creating indexes and I need these results:

1) sizes sold/bought/available for each book (bookId, bookSize, booksSold, booksBought, booksBought minus booksSold)

2) books sold/bought/available for each book of all size (bookId, booksSold, booksBought, booksBought minus booksSold)

To get the one of the statistics I tried:

SELECT
   books.title
   movements_books_grouped.bookId,
   SUM(IF(movements.movementTypeId=1, movements_books_grouped.quantity, NULL)) AS booksBought,
   SUM(IF(movements.movementTypeId=2, movements_books_grouped.quantity, NULL)) AS booksSold,
   (
       SUM(IF(movements.movementTypeId=1, movements_books_grouped.quantity, 0))-
       SUM(IF(movements.movementTypeId=2, movements_books_grouped.quantity, 0))
   ) AS booksAvailability,
   FROM
   (
   SELECT bookId,quantity,movementId FROM movements_books GROUP BY bookId
   ) AS movements_books_grouped
   JOIN movements ON movements.movementId=movements_books_grouped.movementId
   JOIN books ON books.bookId=movements_books_grouped.bookId
   GROUP BY movements_books_grouped.bookId
   ORDER BY book.title

but it's very slow.
Edit: I needed to add another table to the example because that's the one that makes really slow the last query. I need to join to this table because I need to order the result by title.

Body:
Here's a query that can use indexes:

SELECT m.movementId
     , m.movementTypeId
     , m.deletedFlag
     , mb.bookId
     , mb.bookSize
     , t.title
  FROM movements m
  JOIN movements_types t
    ON t.movementTypeId = m.movementTypeId
  JOIN movements_books mb
    ON mb.movementid = m.movementid
 WHERE m.deletedFlag=0;

An index on (m.movementTypeId, m.deletedFlag) may prove beneficial, but best to suck it and see.


问:
What are Keys in the Stateless widgets class?
In the flutter docs there's sample code for a stateless widget subclass as shown:

```<code>class GreenFrog extends StatelessWidget {
  const GreenFrog({ Key key }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return new Container(color: const Color(0xFF2DBD3A));
  }
}
</code>```

and this

```<code>class Frog extends StatelessWidget {
  const Frog({
    Key key,
    this.color: const Color(0xFF2DBD3A),
    this.child,
  }) : super(key: key);

  final Color color;

  final Widget child;

  @override
  Widget build(BuildContext context) {
    return new Container(color: color, child: child);
  }
}
</code>```

What is a key and when should this super constructor be used? It seems like if you have your own constructor you must have {Key key} why? I've seen other examples where the super keyword is not used so this is where my confusion is.

答:
The Key is an optional parameter needed to preserve state in your widget tree, you have to use them if you want to move a collection of elements in your tree and preserve the state of them.

The best explanation can be found in this video by Google When to Use Keys - Flutter Widgets 101 Ep. 4

Body:
In the flutter docs there's sample code for a stateless widget subclass as shown:

class GreenFrog extends StatelessWidget {
  const GreenFrog({ Key key }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return new Container(color: const Color(0xFF2DBD3A));
  }
}

and this

class Frog extends StatelessWidget {
  const Frog({
    Key key,
    this.color: const Color(0xFF2DBD3A),
    this.child,
  }) : super(key: key);

  final Color color;

  final Widget child;

  @override
  Widget build(BuildContext context) {
    return new Container(color: color, child: child);
  }
}

What is a key and when should this super constructor be used? It seems like if you have your own constructor you must have {Key key} why? I've seen other examples where the super keyword is not used so this is where my confusion is.


问:
How to get R function to return multiple values of parameters
I would like that my function would produce values for different values of one of my parameters (in this case CC), so that I can easily turn this into a dataframe.

Here is the code I am using:

```<code>ub_duration <- function(age, cc = c(12, 18, 24), cc_lag, dur,
                        extended) {
    dur = if (age < 30){
        if (cc < 15) return(150)
        if (cc >= 15 & cc < 24) return(210)
        if (cc >= 24) return(330)
    }
    dur = if (age >= 30 & age < 40){
        if (cc < 15) return(180)
        if (cc >= 15 & cc < 24) return(330)
        if (cc >= 24) return(420)
    }
    dur = if (age >= 50){
        if (cc < 15) return(270)
        if (cc >= 15 & cc < 24) return(480)
        if (cc >= 24) return(540)
    }
    return(dur)
}
</code>```

When I call the function, this is what  get

```<code>> ub_duration(25,c(12, 18, 24),0)
[1] 150
Warning message:
In if (cc < 15) return(150) :
the condition has length > 1 and only the first element will be used
</code>```

答:
I'm not 100% I understand, but I'm guessing you want to loop over each cc value. I use the apply function to do the looping.

```<code>ub_duration0 <- function(age, cc) {
dur = if (age < 30){
if (cc < 15) return(150)
if (cc >= 15 & cc < 24) return(210)
if (cc >= 24) return(330)
}
dur = if (age >= 30 & age < 40){
if (cc < 15) return(180)
if (cc >= 15 & cc < 24) return(330)
if (cc >= 24) return(420)
}
dur = if (age >= 50){
if (cc < 15) return(270)
if (cc >= 15 & cc < 24) return(480)
if (cc >= 24) return(540)
}
return(dur)
}
ub_duration <- function(age, cc = c(12, 18, 24)) {
  sapply(cc, function(x) ub_duration0(age,x))}

> ub_duration(25,c(12, 18, 24))
[1] 150 210 330
</code>```

Body:
I would like that my function would produce values for different values of one of my parameters (in this case CC), so that I can easily turn this into a dataframe.

Here is the code I am using:

ub_duration <- function(age, cc = c(12, 18, 24), cc_lag, dur,
                        extended) {
    dur = if (age < 30){
        if (cc < 15) return(150)
        if (cc >= 15 & cc < 24) return(210)
        if (cc >= 24) return(330)
    }
    dur = if (age >= 30 & age < 40){
        if (cc < 15) return(180)
        if (cc >= 15 & cc < 24) return(330)
        if (cc >= 24) return(420)
    }
    dur = if (age >= 50){
        if (cc < 15) return(270)
        if (cc >= 15 & cc < 24) return(480)
        if (cc >= 24) return(540)
    }
    return(dur)
}

When I call the function, this is what  get

> ub_duration(25,c(12, 18, 24),0)
[1] 150
Warning message:
In if (cc < 15) return(150) :
the condition has length > 1 and only the first element will be used

Body:
I'm not 100% I understand, but I'm guessing you want to loop over each cc value. I use the apply function to do the looping.

ub_duration0 <- function(age, cc) {
dur = if (age < 30){
if (cc < 15) return(150)
if (cc >= 15 & cc < 24) return(210)
if (cc >= 24) return(330)
}
dur = if (age >= 30 & age < 40){
if (cc < 15) return(180)
if (cc >= 15 & cc < 24) return(330)
if (cc >= 24) return(420)
}
dur = if (age >= 50){
if (cc < 15) return(270)
if (cc >= 15 & cc < 24) return(480)
if (cc >= 24) return(540)
}
return(dur)
}
ub_duration <- function(age, cc = c(12, 18, 24)) {
  sapply(cc, function(x) ub_duration0(age,x))}

> ub_duration(25,c(12, 18, 24))
[1] 150 210 330


问:
Incorrectly Displayed Fields in Customizer WordPress (created three but displayed one)
I created the Options panel in WordPress customizer.php:

```<code>// Add theme options panel.
    $wp_customize->add_panel(
     'anvitest-lite', array(
     'title'           => esc_html__( 'Theme Options', 'anvitest-lite' ),
     'priority' => 11,
        )
    );
</code>```

Than I added a section to it:

```<code>$wp_customize->add_section(
     'title_section', array(
     'title' => esc_html__( 'Main Screen Section', 'anvitest-lite' ),
     'panel' => 'anvitest-lite',
        )
    );
</code>```

Up to this point, everything works fine. But in the section, I need to display four fields with contacts (mail, address and phone number). I create the fields:

```<code>/**************************email_field****************************/
    $wp_customize->add_setting(
        'email_field', array(
            'default'           => ''
        )
    );
    $wp_customize->add_control(
        'title_section', array(
        'label'           => esc_html__( 'Enter E-mail', 'anvitest-lite' ),
        'section'         => 'title_section',
        'settings'        => 'email_field',
        'type'            => 'email',
        'description'     => esc_html__( 'Enter your mail in this field', 'anvitest-lite' ),
        )
    );
    /**************************phone_field****************************/
    $wp_customize->add_setting(
        'phone_field', array(
            'default'           => ''
        )
    );
    $wp_customize->add_control(
        'title_section', array(
        'label'           => esc_html__( 'Enter Phone', 'anvitest-lite' ),
        'section'         => 'title_section',
        'settings'        => 'phone_field',
        'type'            => 'text',
        'description'     => esc_html__( 'Enter your phone in this field', 'anvitest-lite' ),
        )
    );
    /**************************adress_field****************************/
    $wp_customize->add_setting(
        'adress_field', array(
            'default'           => ''
        )
    );
    $wp_customize->add_control(
        'title_section', array(
        'label'           => esc_html__( 'Enter Adress', 'anvitest-lite' ),
        'section'         => 'title_section',
        'settings'        => 'adress_field',
        'type'            => 'text',
        'description'     => esc_html__( 'Enter your adress in this field', 'anvitest-lite' ),
        )
    );
</code>```

But from this only a field for entering an email address is displayed in this customizer. see screen: http://prntscr.com/nt891d . Please tell me what I'm doing wrong. Thank!

答:
I've found the solution. Here is the code:</p>

```<code> $wp_customize->add_panel(
        'anvitest-lite',[
            'title'           => esc_html__( 'Theme Options', 'anvitest-lite' ),
            'priority' => 11,
        ]
    );

    $wp_customize->add_section(
        'title_section', [
            'title' => esc_html__( 'Main Screen Section', 'anvitest-lite' ),
            'panel' => 'anvitest-lite',
            'priority'  => 200,
        ]
    );

    $wp_customize->add_setting(
        'email_field', array(
            'default'           => ''
        )
    );
    $wp_customize->add_control(
        'email_field', array(
            'section'         => 'title_section',
            'type'            => 'email',
            'description'     => esc_html__( 'Enter your mail in this field', 'anvitest-lite' ),
        )
    );
    /**************************phone_field****************************/
    $wp_customize->add_setting(
        'phone_field', array(
            'default'           => ''
        )
    );
    $wp_customize->add_control(
        'phone_field', array(
            'label'           => esc_html__( 'Enter Phone', 'anvitest-lite' ),
            'section'         => 'title_section',
            'type'            => 'text',
            'description'     => esc_html__( 'Enter your phone in this field', 'anvitest-lite' ),
        )
    );
    /**************************adress_field****************************/
    $wp_customize->add_setting(
        'adress_field', array(
            'default'           => ''
        )
    );
    $wp_customize->add_control(
        'adress_field', array(
            'label'           => esc_html__( 'Enter Adress', 'anvitest-lite' ),
            'section'         => 'title_section',
            'type'            => 'text',
            'description'     => esc_html__( 'Enter your adress in this field', 'anvitest-lite' ),
        )
    );
</code>```

Body:
I created the Options panel in WordPress customizer.php:

// Add theme options panel.
    $wp_customize->add_panel(
     'anvitest-lite', array(
     'title'           => esc_html__( 'Theme Options', 'anvitest-lite' ),
     'priority' => 11,
        )
    );

Than I added a section to it:

$wp_customize->add_section(
     'title_section', array(
     'title' => esc_html__( 'Main Screen Section', 'anvitest-lite' ),
     'panel' => 'anvitest-lite',
        )
    );

Up to this point, everything works fine. But in the section, I need to display four fields with contacts (mail, address and phone number). I create the fields:

/**************************email_field****************************/
    $wp_customize->add_setting(
        'email_field', array(
            'default'           => ''
        )
    );
    $wp_customize->add_control(
        'title_section', array(
        'label'           => esc_html__( 'Enter E-mail', 'anvitest-lite' ),
        'section'         => 'title_section',
        'settings'        => 'email_field',
        'type'            => 'email',
        'description'     => esc_html__( 'Enter your mail in this field', 'anvitest-lite' ),
        )
    );
    /**************************phone_field****************************/
    $wp_customize->add_setting(
        'phone_field', array(
            'default'           => ''
        )
    );
    $wp_customize->add_control(
        'title_section', array(
        'label'           => esc_html__( 'Enter Phone', 'anvitest-lite' ),
        'section'         => 'title_section',
        'settings'        => 'phone_field',
        'type'            => 'text',
        'description'     => esc_html__( 'Enter your phone in this field', 'anvitest-lite' ),
        )
    );
    /**************************adress_field****************************/
    $wp_customize->add_setting(
        'adress_field', array(
            'default'           => ''
        )
    );
    $wp_customize->add_control(
        'title_section', array(
        'label'           => esc_html__( 'Enter Adress', 'anvitest-lite' ),
        'section'         => 'title_section',
        'settings'        => 'adress_field',
        'type'            => 'text',
        'description'     => esc_html__( 'Enter your adress in this field', 'anvitest-lite' ),
        )
    );

But from this only a field for entering an email address is displayed in this customizer. see screen: http://prntscr.com/nt891d . Please tell me what I'm doing wrong. Thank!

Body:
I've found the solution. Here is the code:

 $wp_customize->add_panel(
        'anvitest-lite',[
            'title'           => esc_html__( 'Theme Options', 'anvitest-lite' ),
            'priority' => 11,
        ]
    );

    $wp_customize->add_section(
        'title_section', [
            'title' => esc_html__( 'Main Screen Section', 'anvitest-lite' ),
            'panel' => 'anvitest-lite',
            'priority'  => 200,
        ]
    );

    $wp_customize->add_setting(
        'email_field', array(
            'default'           => ''
        )
    );
    $wp_customize->add_control(
        'email_field', array(
            'section'         => 'title_section',
            'type'            => 'email',
            'description'     => esc_html__( 'Enter your mail in this field', 'anvitest-lite' ),
        )
    );
    /**************************phone_field****************************/
    $wp_customize->add_setting(
        'phone_field', array(
            'default'           => ''
        )
    );
    $wp_customize->add_control(
        'phone_field', array(
            'label'           => esc_html__( 'Enter Phone', 'anvitest-lite' ),
            'section'         => 'title_section',
            'type'            => 'text',
            'description'     => esc_html__( 'Enter your phone in this field', 'anvitest-lite' ),
        )
    );
    /**************************adress_field****************************/
    $wp_customize->add_setting(
        'adress_field', array(
            'default'           => ''
        )
    );
    $wp_customize->add_control(
        'adress_field', array(
            'label'           => esc_html__( 'Enter Adress', 'anvitest-lite' ),
            'section'         => 'title_section',
            'type'            => 'text',
            'description'     => esc_html__( 'Enter your adress in this field', 'anvitest-lite' ),
        )
    );


问:
How much memory to multiply int by a double?
How much memory does multiplying 16 bit unsigned integer by a double and assigning it to another unsigned 16 bit integer take in C?  Would it temporarily load the double result in a register before assigning it to int?  I'm doing some programming for embedded systems that's why I'm asking.</p>

```<code>u16int_t a = 3;
u16int_t b = a * .4;
</code>```

答:
Run 2*sizeof(double) to find out. The code needs a temporary to store (double)a as an implicit cast and another to store .4. Typically there will be two free register available and the actual cost is zero, but there might not be.

Note that this memory is allocated on the stack, so the effective cost of the memory is probably zero. The compiler is really good at reusing temporary memory slots, and this is unlikely to be where your deepest stack depth is.

If u16int_t a = 3 really is a constant piece of code and not an artifact of reduction, the compiler will optimize the whole thing away to u16int_t b = floating point constant and again allocates zero bytes for the multiply.

Body:
How much memory does multiplying 16 bit unsigned integer by a double and assigning it to another unsigned 16 bit integer take in C?  Would it temporarily load the double result in a register before assigning it to int?  I'm doing some programming for embedded systems that's why I'm asking.

u16int_t a = 3;
u16int_t b = a * .4;