问:
Visual studio in stuck Generating code
When I build a c++ project with Visual Studio the process get in stuck while Generating Code:

```<code>1>------ Rebuild All started: Project: myWrapper, Configuration: Release Win32 ------
1>  funzioni_ausiliarie.cpp
1>  myWrapperFunction.cpp
1>  NLP_eta_tre_spline.cpp
1>  Generating Code...
</code>```

MSVS is still responding and seems to being working, but I waited more than 10 minutes and it didn't finished. Finally I canceled the process.
Instead, building in debug mode it finisces in 20 seconds.

I also tried to disable "Whole Program Optimization" and "Multi-processor compilation" in C++ compile options and I left empty the parameter "Link Time Code Generation" in linker options (obviously for release configuration) but the problem still occurs.

Any help would be greately appreciated.

答:
With VS2017 (15.5.0), I ran into a problem where building a third-party library for Release hung the compiler at "Generating Code" for tens of minutes, and I gave up waiting. I had been using Whole Program Optimization, but turning that off didn't help.

I also had been using Optimization set to Maximum Speed (/O2). I changed it to Custom and turned on /Ob2, /Oi, /Os, and /Oy. The build completed in a few seconds. For the library I was using, that was good enough.

Title: Visual studio in stuck Generating code

Body:
When I build a c++ project with Visual Studio the process get in stuck while Generating Code:

1>------ Rebuild All started: Project: myWrapper, Configuration: Release Win32 ------
1>  funzioni_ausiliarie.cpp
1>  myWrapperFunction.cpp
1>  NLP_eta_tre_spline.cpp
1>  Generating Code...

MSVS is still responding and seems to being working, but I waited more than 10 minutes and it didn't finished. Finally I canceled the process.
Instead, building in debug mode it finisces in 20 seconds.

I also tried to disable "Whole Program Optimization" and "Multi-processor compilation" in C++ compile options and I left empty the parameter "Link Time Code Generation" in linker options (obviously for release configuration) but the problem still occurs.

Any help would be greately appreciated.


来源: stackexchange

问:
How to change size of UIButton
I'm trying to resize a UIButton in my iPhone app.  I have a UIButton synthesized and when I call the following code, it moves on the screen, but the width & height of the button never change.

```<code>button.frame.size = CGRectMake(104, 68, 158, 70);
</code>```

For example, when I change the height (70) to 40, the height of the button does not change.  If I change the x or y, however, it will move on the screen.

Any ideas?

答:
Shouldn't this be:

```<code>button.frame = CGRectMake(104, 68, 158, 70);
</code>```

i.e. you're creating the rect correctly, but you're assigning it to the size element of the CGRect called frame, not to the whole CGRect.  From CGGeometry.h:

```<code>struct CGPoint {
   CGFloat x;
   CGFloat y;
};
struct CGSize {
   CGFloat width;
   CGFloat height;
};
struct CGRect {
   CGPoint origin;
   CGSize size;
};
</code>```

Or more explicitely, you could write:

```<code>button.frame.size.width=158;
button.frame.size.height=70;
button.frame.origin.x=104;
button.frame.origin.y=68;
</code>```

ContentLicense: CC BY-SA 2.5

Title: How to change size of UIButton

Body:
I'm trying to resize a UIButton in my iPhone app.  I have a UIButton synthesized and when I call the following code, it moves on the screen, but the width & height of the button never change.

button.frame.size = CGRectMake(104, 68, 158, 70);

For example, when I change the height (70) to 40, the height of the button does not change.  If I change the x or y, however, it will move on the screen.

Any ideas?

Body:
Shouldn't this be:

button.frame = CGRectMake(104, 68, 158, 70);

i.e. you're creating the rect correctly, but you're assigning it to the size element of the CGRect called frame, not to the whole CGRect.  From CGGeometry.h:

struct CGPoint {
   CGFloat x;
   CGFloat y;
};
struct CGSize {
   CGFloat width;
   CGFloat height;
};
struct CGRect {
   CGPoint origin;
   CGSize size;
};

Or more explicitely, you could write:

button.frame.size.width=158;
button.frame.size.height=70;
button.frame.origin.x=104;
button.frame.origin.y=68;


问:
How do I append a Python object attribute (list)
I would like to write a function to append an attribute of a Python object, the attribute is a list.

Here is my code, which sets the attribute to a given value. Is there a simpler/cleaner way to this..

```<code>class Obj(object):
    def __init__(self):
        self.a = 2
        self.b = []
        self.c = []

    def append_att(self, att):
        at = getattr(self, att)
        at.append(self.a)
        setattr(self,att, at)
obj = Obj()
obj.append_att('b')
obj.append_att('b')
print obj.b
</code>```

答:
You can use self.__dict__ to append to the list with the same string variable name as the value to be added to the list:

```<code>class Obj(object):
   def __init__(self):
      self.a = 2
      self.b = []
      self.c = []
   def append_att(self, att):
      self.__dict__[att].append(self.a)

o = Obj()
o.append_att('b')
o.append_att('b')
o.append_att('c')
print(o.b)
print(o.c)
</code>```

Output:

```<code>[2, 2]
[2]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I would like to write a function to append an attribute of a Python object, the attribute is a list.

Here is my code, which sets the attribute to a given value. Is there a simpler/cleaner way to this..

class Obj(object):
    def __init__(self):
        self.a = 2
        self.b = []
        self.c = []

    def append_att(self, att):
        at = getattr(self, att)
        at.append(self.a)
        setattr(self,att, at)
obj = Obj()
obj.append_att('b')
obj.append_att('b')
print obj.b

Body:
You can use self.__dict__ to append to the list with the same string variable name as the value to be added to the list:

class Obj(object):
   def __init__(self):
      self.a = 2
      self.b = []
      self.c = []
   def append_att(self, att):
      self.__dict__[att].append(self.a)

o = Obj()
o.append_att('b')
o.append_att('b')
o.append_att('c')
print(o.b)
print(o.c)

Output:

[2, 2]
[2]


问:
Find the closest distance between every galaxy in the data and create pairs based on closest distance between them
My task is to pair up galaxies that are closest together from a large list of galaxies. I have the RA, DEC and Z of each, and a formula to work out the distance between each one from the data given. However, I can't work out an efficient method of iterating over the whole list to find the distance between EACH galaxy and EVERY other galaxy in the list, with the intention of then matching each galaxy with its nearest neighbour.

The data has been imported in the following way:

```<code>    hdulist = fits.open("documents/RADECMASSmatch.fits")
    CATAID = data['CATAID_1']
    Xpos_DEIMOS_1 = data['Xpos_DEIMOS_1']
    z = data['Z_1']
    RA = data['RA']
    DEC = data['DEC']
</code>```

I have tried something like:

```<code>    radiff = []
    for i in range(0,n):
        for j in range(i+1,n):
            radiff.append(abs(RA[i]-RA[j]))
</code>```

to initially work out difference in RA and DEC between every galaxy, which does actually work but I feel like there must be a better way.

A friend suggested something along the lines of:

```<code>    galaxy_coords = (data['RA'],data['DEC'],data['Z])
    separation_matrix = np.zeros((len(galaxy_coords),len(galaxy_coords))

    done = []
    for i, coords1 in enumerate(galaxy_coords):
          for j, coords2 in enumerate(galaxy_coords):
                if (j,i) in done:
                    separation_matrix[i,j] += separation matrix[j,i]
                    continue
                    separation = your_formula(coords1, coords2)
                    separation_matrix[i,j] += separation
                    done.append((i,j))
</code>```

But I don't really understand this so can't readily apply it. I've tried but it yields nothing useful.

Any help with this would be much appreciated, thanks

答:
Your friend's code seems to be generating a 2D array of the distances between each pair, and taking advantage of the symmetry (distance(x,y) = distance(y,x)). It would be slightly better if it used itertools to generate combinations, and assigned your_formula(coords1, coords2) to  separation_matrix[i,j] and separation_matrix[j,i] within the same iteration, rather than having separate iterations for both i,j and j,i.

Even better would probably be this package that uses a tree-based algorithm: https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.spatial.KDTree.html . It seems to be focused on rectilinear coordinates, but that should be addressable in linear time.

Body:
My task is to pair up galaxies that are closest together from a large list of galaxies. I have the RA, DEC and Z of each, and a formula to work out the distance between each one from the data given. However, I can't work out an efficient method of iterating over the whole list to find the distance between EACH galaxy and EVERY other galaxy in the list, with the intention of then matching each galaxy with its nearest neighbour.

The data has been imported in the following way:

    hdulist = fits.open("documents/RADECMASSmatch.fits")
    CATAID = data['CATAID_1']
    Xpos_DEIMOS_1 = data['Xpos_DEIMOS_1']
    z = data['Z_1']
    RA = data['RA']
    DEC = data['DEC']

I have tried something like:

    radiff = []
    for i in range(0,n):
        for j in range(i+1,n):
            radiff.append(abs(RA[i]-RA[j]))

to initially work out difference in RA and DEC between every galaxy, which does actually work but I feel like there must be a better way.

A friend suggested something along the lines of:

    galaxy_coords = (data['RA'],data['DEC'],data['Z])
    separation_matrix = np.zeros((len(galaxy_coords),len(galaxy_coords))

    done = []
    for i, coords1 in enumerate(galaxy_coords):
          for j, coords2 in enumerate(galaxy_coords):
                if (j,i) in done:
                    separation_matrix[i,j] += separation matrix[j,i]
                    continue
                    separation = your_formula(coords1, coords2)
                    separation_matrix[i,j] += separation
                    done.append((i,j))

But I don't really understand this so can't readily apply it. I've tried but it yields nothing useful.

Any help with this would be much appreciated, thanks


问:
React Native Android App with 64k+ methods
I have problem with running RN Android app using react-native run-android

It throws exception at the build stage and can't figure out the issue.

```<code>Execution failed for task ':react-native-firebase:transformClassesWithDexForDebugAndroidTest'.
> com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536
</code>```

I've tried various solutions on the web and it was all in vein.
Tried solutions were enabling multiDex and increase the javaMaxHeapSize in dexOptions.

This error can be seen as a library or component dependent, but it happens for any kind of apps which exceeds 64k limits.

One more thing:
It compiles without any problem in Android Studio

答:
You have too many methods by the look of it. This a common DEX issue. As mentioned here:

DexIndexOverflowException issue after updating to latest appcompat and support library

Add this to your build.gradle:

```<code>android {

  defaultConfig {
    ...

    // Enabling multidex support.
    multiDexEnabled true
  }
  ...
}

dependencies {
  compile 'com.android.support:multidex:1.0.1'
}
</code>```

Then in your Android Manifest add this:

```<code><?xml version="1.0" encoding="utf-8"?>
  <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.multidex.myapplication">
    <application
      ...
      android:name="android.support.multidex.MultiDexApplication">
      ...
    </application>
</manifest>
</code>```

Let me know if this helps! I have come across this issue before myself.

Body:
I have problem with running RN Android app using react-native run-android

It throws exception at the build stage and can't figure out the issue.

Execution failed for task ':react-native-firebase:transformClassesWithDexForDebugAndroidTest'.
> com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536

I've tried various solutions on the web and it was all in vein.
Tried solutions were enabling multiDex and increase the javaMaxHeapSize in dexOptions.

This error can be seen as a library or component dependent, but it happens for any kind of apps which exceeds 64k limits.

One more thing:
It compiles without any problem in Android Studio

Body:
You have too many methods by the look of it. This a common DEX issue. As mentioned here:

DexIndexOverflowException issue after updating to latest appcompat and support library

Add this to your build.gradle:

android {

  defaultConfig {
    ...

    // Enabling multidex support.
    multiDexEnabled true
  }
  ...
}

dependencies {
  compile 'com.android.support:multidex:1.0.1'
}

Then in your Android Manifest add this:

<?xml version="1.0" encoding="utf-8"?>
  <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.multidex.myapplication">
    <application
      ...
      android:name="android.support.multidex.MultiDexApplication">
      ...
    </application>
</manifest>

Let me know if this helps! I have come across this issue before myself.


问:
CSS flex box - how to make items center vertically with a full height background
I'm trying to align some text within a box vertically centered, whilst ensuring the background colour stretches full height.

HTML:

```<code><div class="feature-content">
<div class="feature-visual">
    <div class="embed-container">
        <iframe src="https://player.vimeo.com/video/214852366?controls=0&hd=1&autohide=1" title="Factory Pattern & REHAU" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen="" width="640" height="312" frameborder="0"></iframe>
    </div>
</div>
<div class="quote">
    <div class="words">Improved our conversion rates to a level that far surpassed expectation.
    </div>
</div>
</code>```

CSS:

```<code>article section.case-study .feature-content {
    align-items: stretch;
    align-content: stretch;
    display: flex;
    padding-top: .35em;
}
article section.case-study .feature-content .feature-visual {
    flex-grow: 1;
    flex-basis: 65%;
}
article section.case-study .feature-content .quote {
    align-self: stretch;
    background: #db6f72;
    color: #FFF;
    flex-basis: 35%;
    flex-grow: 1;
    position: relative;
}
article section.case-study .feature-content .quote .words {
    font-family: "Georgia", serif;
    font-size: 2em;
    font-style: italic;
    line-height: 1.5;
    padding-top: 4.5em;
    width: 80%;
}
</code>```

Current live version here https://factorypattern.co.uk/case-study/rehau-interactive-touchscreen/

Image here of what I want it to look like:
enter image description here

Any assistance greatly appreciated :)

答:
There is a CSS rule for the right block (the one containing the text quote) where you can add this in order to center its content vertically (it makes that item itself a flex container):

```<code>article section.case-study .feature-content .quote {
    [ ... original settings remin unchanged ... ]
    display: flex;
    flex-direction: column;
    justify-content: center;
}
</code>```

In addition you have to erase the padding-top from this rule to avoid a vertical offset from the center:

```<code>article section.case-study .feature-content .quote .words {
    font-family: "Georgia",serif;
    font-size: 1.85em;
    font-style: italic;
    line-height: 1.3;
    /* padding-top: 1.25em; */ --> erase / set to zero
    width: 80%;
}
</code>```

Body:
I'm trying to align some text within a box vertically centered, whilst ensuring the background colour stretches full height.

HTML:

Improved our conversion rates to a level that far surpassed expectation.

CSS:

article section.case-study .feature-content {
    align-items: stretch;
    align-content: stretch;
    display: flex;
    padding-top: .35em;
}
article section.case-study .feature-content .feature-visual {
    flex-grow: 1;
    flex-basis: 65%;
}
article section.case-study .feature-content .quote {
    align-self: stretch;
    background: #db6f72;
    color: #FFF;
    flex-basis: 35%;
    flex-grow: 1;
    position: relative;
}
article section.case-study .feature-content .quote .words {
    font-family: "Georgia", serif;
    font-size: 2em;
    font-style: italic;
    line-height: 1.5;
    padding-top: 4.5em;
    width: 80%;
}

Current live version here https://factorypattern.co.uk/case-study/rehau-interactive-touchscreen/

Image here of what I want it to look like:
enter image description here

Any assistance greatly appreciated :)

Body:
There is a CSS rule for the right block (the one containing the text quote) where you can add this in order to center its content vertically (it makes that item itself a flex container):

article section.case-study .feature-content .quote {
    [ ... original settings remin unchanged ... ]
    display: flex;
    flex-direction: column;
    justify-content: center;
}

In addition you have to erase the padding-top from this rule to avoid a vertical offset from the center:

article section.case-study .feature-content .quote .words {
    font-family: "Georgia",serif;
    font-size: 1.85em;
    font-style: italic;
    line-height: 1.3;
    /* padding-top: 1.25em; */ --> erase / set to zero
    width: 80%;
}


问:
How to programmatically deploy a C# storm topology to HDInsight
Is the only way to programmatically submit a storm topology to HDInsight for the package to be a jar file?  It mentions deploying a C# file in the link below but only through a manual process.

If not, how do I deploy a C# topology to an HDInsight cluster programmatically, I.E. without using the UI to submit in Visual Studio.

I've been able to test and work out my storm topology using C# with the submit button but I need this cluster to start every night and stop every morning.

https://learn.microsoft.com/en-us/azure/hdinsight/storm/apache-storm-deploy-monitor-topology-linux

Am I reading storm jar /usr/hdp/current/storm-client/contrib/storm-starter/storm-starter-topologies-*.jar org.apache.storm.starter.WordCountTopology WordCount such that org.apache.storm.starter.WordCountTopology has to be a jar file?

答:
Note: The HDInsight tools should be used to submit C# or hybrid topologies to your Storm cluster.

I you want to programmatically deploy a topology, you may refer "Programmatically deploy a topology to Apache Storm on HDInsight".


问:
Get EarthEngine Image from URL to geoTIFF
I haven't been able to ascertain if there is a way to load a geoTIFF into an ee.Image. I am quite certain that it is possible to do that in some way using a combination of AppEngine and EarthEngine going this route:  load geoTIFF -> ee.Array + metadata -> ee.Image.
Or is it a matter of choosing some 3rd party python lib that allows this, pull the data with urllib, interpret that using the lib and create an ee.Array from that?

(by ee.Array I more or less mean an array in an earth-engine context. Not a concrete data type)

答:
You can't directly load a GeoTIFF from a URL through a script, but you can upload a GeoTIFF using the earthengine command line tool.

https://developers.google.com/earth-engine/command_line

The only other option might be to go through an ee.Blob(), however there's no way to convert that directly into an Array or an Image, and no way to decode a GeoTIFF there.


问:
Semi-transparent color layer over background-image?
I have a DIV and I would like to put a pattern as background. This pattern is gray. So to make it a little more nice, I would like to put a light transparent color "layer" over. Below is what I tried but which did not work. Is there a way to put the colored layer over the background image?

Here's my CSS:

```<code>background: url('../img/bg/diagonalnoise.png');
background-color: rgba(248, 247, 216, 0.7);
</code>```

答:
You can use a semitransparent pixel, which you can generate for example here, even in base64
 Here is an example with white 50%:

```<code>background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8Xw8AAoMBgDTD2qgAAAAASUVORK5CYII=),
url(../img/leftpanel/intro1.png);
background-size: cover, cover;
</code>```

without uploading

without extra html

i guess the loading should be quicker than box-shadow or linear gradient

ContentLicense: CC BY-SA 4.0

Body:
I have a DIV and I would like to put a pattern as background. This pattern is gray. So to make it a little more nice, I would like to put a light transparent color "layer" over. Below is what I tried but which did not work. Is there a way to put the colored layer over the background image?

Here's my CSS:

background: url('../img/bg/diagonalnoise.png');
background-color: rgba(248, 247, 216, 0.7);

Body:
You can use a semitransparent pixel, which you can generate for example here, even in base64
 Here is an example with white 50%:

background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8Xw8AAoMBgDTD2qgAAAAASUVORK5CYII=),
url(../img/leftpanel/intro1.png);
background-size: cover, cover;

without uploading

without extra html

i guess the loading should be quicker than box-shadow or linear gradient


问:
Asynchronous DataClass running post Exit Sub
I have a custom class in VBA that pulls historical data from Bloomberg. The class, and the Bloomberg objects it uses, are asynchronous and based on the RTD platform.

The issue I'm having is that I run Subs that call this custom class, but the event handling code in the custom class only runs once my Sub is finished.

```<code>Dim bbHist As New HistDataControl

Sub PullDataAndDoStuff()
     bbHist.MakeHistRequest StockTicker, "MOV_AVG_50D", startDate, Date
     Call DoStuffWithTheData
End Sub

Private Sub DoStuffWithTheData()
 ..... 'None of this works, because MakeHistRequest / bbHist class hasn't run
End Sub
</code>```

Is there a way to force Excel to wait until the bbHist has run?

答:
The problem is that the bbg handler waits.
So the solution is to make your sub wait for the bbg query to end, and then call your processing data sub.
There are plenty of solutions for that on stackoverflow so I'll let you look for that.</p>

Body:
I have a custom class in VBA that pulls historical data from Bloomberg. The class, and the Bloomberg objects it uses, are asynchronous and based on the RTD platform.

The issue I'm having is that I run Subs that call this custom class, but the event handling code in the custom class only runs once my Sub is finished.

Dim bbHist As New HistDataControl

Sub PullDataAndDoStuff()
     bbHist.MakeHistRequest StockTicker, "MOV_AVG_50D", startDate, Date
     Call DoStuffWithTheData
End Sub

Private Sub DoStuffWithTheData()
 ..... 'None of this works, because MakeHistRequest / bbHist class hasn't run
End Sub

Is there a way to force Excel to wait until the bbHist has run?


问:
Django ORM Get users not assigned to the Team
models.py

```<code>from django.db import models

class UserGroup(models.Model):
    members = models.ManyToManyField(User, related_name='members', through='UserGroupMember')

class UserGroupMember(models.Model):
    user = models.ForeignKey(User)
    usergroup = models.ForeignKey(UserGroup)

class Cohort(models.Model):
    user_groups = models.ManyToManyField(UserGroup)

class Team(models.Model):
    cohort = models.ForeignKey(Cohort)
    members = models.ManyToManyField(User, related_name='team_members', through='TeamMembers', blank=True)

class TeamMembers(models.Model):
    team = models.ForeignKey(Team)
    user = models.ForeignKey(User)
</code>```

Single user can be part of only one team within a cohort.

Query #1

I need to write the query to get the users for a given cohort that are not assigned to any team.

I tried this:

```<code>User.objects.filter(
    members__cohort=cohort
).filter(
    team_members__isnull=True
)
</code>```

but that does not give me the user if he is part of the team in another cohort.

Query #2

I want to annotate the new field (boolean) which tells you is the user assigned to some team in the cohort, something like:

```<code>User.objects.filter(
    members__cohort=cohort
).annotate(
    is_team_member=...
)
</code>```

I am using Python 2.7.13 and Django 1.9.8. Thanks.

答:
Try constructing the queryset by excluding all the members that are assigned to a team in the cohort:

```<code>User.objects.filter(
    members_cohort=cohort,
).exclude(
    team_members__cohort=cohort,
)
</code>```

Body:
models.py

from django.db import models

class UserGroup(models.Model):
    members = models.ManyToManyField(User, related_name='members', through='UserGroupMember')

class UserGroupMember(models.Model):
    user = models.ForeignKey(User)
    usergroup = models.ForeignKey(UserGroup)

class Cohort(models.Model):
    user_groups = models.ManyToManyField(UserGroup)

class Team(models.Model):
    cohort = models.ForeignKey(Cohort)
    members = models.ManyToManyField(User, related_name='team_members', through='TeamMembers', blank=True)

class TeamMembers(models.Model):
    team = models.ForeignKey(Team)
    user = models.ForeignKey(User)

Single user can be part of only one team within a cohort.

Query #1

I need to write the query to get the users for a given cohort that are not assigned to any team.

I tried this:

User.objects.filter(
    members__cohort=cohort
).filter(
    team_members__isnull=True
)

but that does not give me the user if he is part of the team in another cohort.

Query #2

I want to annotate the new field (boolean) which tells you is the user assigned to some team in the cohort, something like:

User.objects.filter(
    members__cohort=cohort
).annotate(
    is_team_member=...
)

I am using Python 2.7.13 and Django 1.9.8. Thanks.

Body:
Try constructing the queryset by excluding all the members that are assigned to a team in the cohort:

User.objects.filter(
    members_cohort=cohort,
).exclude(
    team_members__cohort=cohort,
)


问:
Is there an Open File dialog for Access 2010 64bit?
How do I get an Open File dialog for Access 2010 64bit?  Normally I would use the common dialog control but that is 32bit and cannot be used with Access 2010 64 bit.</p>

答:
I missed the 64-bit Access detail. It's very unlikely that you should be running it, but if you are, here is an article for your consideration that explains how you have to alter your API call to work -- you have to use the new long pointer data type:

Compatibility Between the 32-bit and 64-bit Versions of Office 2010

If you alter the API code accordingly, it should work fine on 64-bit Access.

But you should really ask why you're using 64-bit Access. It's really not at all recommended by MS that anyone use 64-bit Office unless they have specific reasons why they need it (such as needing to use the extra memory it provides, particularly for things like complex Excel spreadsheet models). Access is definitely not one of the apps that benefits much from the conversion to 64-bit.

Detailed discussion of the subject:

Office 2010 - about the 64-bit version - Office Watch

Installing Office 2010 64-bit - Office Watch

Office 32-bit or 64-bit - which version is installed? - Office Watch

Office 32 and 64 bit on the same machine - Office Watch

Preparing for Office 2010 64-bit - Office Watch

64-bit Office - is it worth the trouble? - Office Watch

In short, most people shouldn't be running 64-bit Office, precisely for the reason you encountered -- it causes legacy code with outside dependencies on 32-bit components and APIs to fail.


问:
Pandas: display groupby aggregate statistic with data
Data Snippet

I am trying to add a new column to my data frame that displays the average purchase amount per user. The data frame is called trainDf and the below line of code produces the average by user. I'm trying to learn how to add it as a column to display similar  to the above image.

AveragePurchaseAmountUser = trainDf.groupby(by='User_ID')['Purchase_Amount'].mean()
```

Thank you in advance!

答:
You can try:</p>

```<code>trainDf['AveragePurchaseAmountUser'] = trainDf.groupby(['User_ID'])['Purchase_Amount'].mean()
</code>```

Body:
Data Snippet

I am trying to add a new column to my data frame that displays the average purchase amount per user. The data frame is called trainDf and the below line of code produces the average by user. I'm trying to learn how to add it as a column to display similar  to the above image.

AveragePurchaseAmountUser = trainDf.groupby(by='User_ID')['Purchase_Amount'].mean()

Thank you in advance!

Body:
You can try:

trainDf['AveragePurchaseAmountUser'] = trainDf.groupby(['User_ID'])['Purchase_Amount'].mean()


问:
Excel formula to get number of days between two dates in months with precision
what's the formula to get number of days between two dates in months with days precision.

For example: the number of days between 01-01-2017 & 14-02-2017 these two dates is 45 days. (31 days + 14 days - including both) So I'm expecting 1 month 14 days as output. So the format should be 1.14 (1 month 14 days)

Edit:
There is no assumption of 30 days in a month. I'm expecting exact calendar difference.

答:
If I understand you correctly, I've been using this method to do exactly that.
Assume the following:

D17 is the Start Date

E17 is the End Date

If you used the following formula:

=DATEDIF(D17,E17,"y") & "years, " & DATEDIF(D17,E17),"ym") & "months, " & E17-DATE(YEAR(E17),MONTH(E17),1) & "days"

To get the exact format you want, you might want to edit the formula to look something like this:

=DATEDIF(D17,E17),"ym") & "." & E17-DATE(YEAR(E17),MONTH(E17),1)

Hope this works as well for you as it does me.


问:
Why is the code body not giving the same result?
This code as follows displays the least commonly repeated number in the list and works correctly and gives me the answer 3...

```<code>    theList = [1,3,1,2,2]
listCheck, least = len(theList), 0
for theLeast in theList:
    if theList.count(theLeast) <= listCheck :
        listCheck = theList.count(theLeast)
        least = theLeast
print (least)
</code>```

However when I define & change the list to a sequence of integers, the code says that 1 is the least common??

```<code> def The_uncommon(integers):
    theList = integers
    listCheck, least = len(theList), 0
    for theLeast in theList:
        if theList.count(theLeast) <= listCheck :
            listCheck = theList.count(theLeast)
            least = theLeast
            return (least)
print(The_uncommon([1,3,1,2,2]))
</code>```

Any advice is welcome

答:
Classical indentation problem with python.   </p>

```<code>   def The_uncommon(integers):
        theList = integers
        listCheck, least = len(theList), 0
        for theLeast in theList:
            if theList.count(theLeast) <= listCheck :
                listCheck = theList.count(theLeast)
                least = theLeast
        return (least)
    print(The_uncommon([1,3,1,2,2]))
</code>```

Body:
This code as follows displays the least commonly repeated number in the list and works correctly and gives me the answer 3...

    theList = [1,3,1,2,2]
listCheck, least = len(theList), 0
for theLeast in theList:
    if theList.count(theLeast) <= listCheck :
        listCheck = theList.count(theLeast)
        least = theLeast
print (least)

However when I define & change the list to a sequence of integers, the code says that 1 is the least common??

 def The_uncommon(integers):
    theList = integers
    listCheck, least = len(theList), 0
    for theLeast in theList:
        if theList.count(theLeast) <= listCheck :
            listCheck = theList.count(theLeast)
            least = theLeast
            return (least)
print(The_uncommon([1,3,1,2,2]))

Any advice is welcome

Body:
Classical indentation problem with python.

   def The_uncommon(integers):
        theList = integers
        listCheck, least = len(theList), 0
        for theLeast in theList:
            if theList.count(theLeast) <= listCheck :
                listCheck = theList.count(theLeast)
                least = theLeast
        return (least)
    print(The_uncommon([1,3,1,2,2]))


问:
Adding and accessing a searchView in the actionbar

This is my first question in Stack Overflow, so please don't mind if I there are any mistakes...
I want to add a SearchView to an activity's Actionbar, so that when the user types a name in the SearchView, the RecyclerView would be filtered to give the relevant names.
This is the code that I have for the activity's onCreateOptionsMenu method:

```<code>@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);

    getMenuInflater().inflate(R.menu.search, menu);

    searchViewInstructors = (SearchView) menu.findItem(R.id.searchViewInstructors).getActionView();

    searchViewInstructors.setActivated(true);
    searchViewInstructors.setQueryHint("Search by name");
    searchViewInstructors.onActionViewExpanded();
    searchViewInstructors.setIconified(true);
    searchViewInstructors.clearFocus();
    searchViewInstructors.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            adapter.getFilter().filter(newText);
            return false;
        }
    });

    return true;
}
</code>```

And this is the code for res/menu/search.xml, where the SearchView is an item:

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".TrainersActivity">

<item
    android:id="@+id/searchViewInstructors"
    android:icon="@android:drawable/ic_menu_search"
    android:title="Search by name"
    app:showAsAction="always"
    android:actionViewClass="android.widget.SearchView"/>
</menu>
</code>```

The problem I'm facing, and the reason I've asked the question even with the many answers I found on Stack Overflow for the exact same or similar questions, is that no matter what I did, I get a nullPointerException:

```<code>12-05 18:58:33.559 19381-19381/worldontheotherside.wordpress.com.drvingapp E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: worldontheotherside.wordpress.com.drvingapp, PID: 19381
                                                                                java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setActivated(boolean)' on a null object reference
                                                                                at worldontheotherside.wordpress.com.drvingapp.TrainersActivity.onCreateOptionsMenu(TrainersActivity.java:78)
                                                                                at android.app.Activity.onCreatePanelMenu(Activity.java:3307)
                                                                                at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:320)
                                                                                at android.support.v7.view.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:95)
                                                                                at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.onCreatePanelMenu(AppCompatDelegateImplBase.java:333)
                                                                                at android.support.v7.app.AppCompatDelegateImplV9.preparePanel(AppCompatDelegateImplV9.java:1372)
                                                                                at android.support.v7.app.AppCompatDelegateImplV9.doInvalidatePanelMenu(AppCompatDelegateImplV9.java:1652)
                                                                                at android.support.v7.app.AppCompatDelegateImplV9$1.run(AppCompatDelegateImplV9.java:137)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6692)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
</code>```

I appreciate it if someone would tell me exactly what I'm doing wrong, and how to solve it. Thanks.

答:
Use

```<code>app:actionViewClass="android.widget.SearchView"
</code>```

instead of

```<code>android:actionViewClass="android.widget.SearchView"
</code>```

Body:
This is my first question in Stack Overflow, so please don't mind if I there are any mistakes...
I want to add a SearchView to an activity's Actionbar, so that when the user types a name in the SearchView, the RecyclerView would be filtered to give the relevant names.
This is the code that I have for the activity's onCreateOptionsMenu method:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);

    getMenuInflater().inflate(R.menu.search, menu);

    searchViewInstructors = (SearchView) menu.findItem(R.id.searchViewInstructors).getActionView();

    searchViewInstructors.setActivated(true);
    searchViewInstructors.setQueryHint("Search by name");
    searchViewInstructors.onActionViewExpanded();
    searchViewInstructors.setIconified(true);
    searchViewInstructors.clearFocus();
    searchViewInstructors.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            adapter.getFilter().filter(newText);
            return false;
        }
    });

    return true;
}

And this is the code for res/menu/search.xml, where the SearchView is an item:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".TrainersActivity">

<item
    android:id="@+id/searchViewInstructors"
    android:icon="@android:drawable/ic_menu_search"
    android:title="Search by name"
    app:showAsAction="always"
    android:actionViewClass="android.widget.SearchView"/>
</menu>

The problem I'm facing, and the reason I've asked the question even with the many answers I found on Stack Overflow for the exact same or similar questions, is that no matter what I did, I get a nullPointerException:

12-05 18:58:33.559 19381-19381/worldontheotherside.wordpress.com.drvingapp E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: worldontheotherside.wordpress.com.drvingapp, PID: 19381
                                                                                java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setActivated(boolean)' on a null object reference
                                                                                at worldontheotherside.wordpress.com.drvingapp.TrainersActivity.onCreateOptionsMenu(TrainersActivity.java:78)
                                                                                at android.app.Activity.onCreatePanelMenu(Activity.java:3307)
                                                                                at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:320)
                                                                                at android.support.v7.view.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:95)
                                                                                at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.onCreatePanelMenu(AppCompatDelegateImplBase.java:333)
                                                                                at android.support.v7.app.AppCompatDelegateImplV9.preparePanel(AppCompatDelegateImplV9.java:1372)
                                                                                at android.support.v7.app.AppCompatDelegateImplV9.doInvalidatePanelMenu(AppCompatDelegateImplV9.java:1652)
                                                                                at android.support.v7.app.AppCompatDelegateImplV9$1.run(AppCompatDelegateImplV9.java:137)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6692)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)

I appreciate it if someone would tell me exactly what I'm doing wrong, and how to solve it. Thanks.

Body:
Use

app:actionViewClass="android.widget.SearchView"

instead of

android:actionViewClass="android.widget.SearchView"


问:
Cant get Firebase Storage security rules to refuse access to a file
I'm sure I'm missing something wrt Firebase Storage rules, but I've done the following:

STEP 1

Firstly I set the following Firebase Storage rule:

```<code>service firebase.storage {
  match /b/{bucket}/o {
    match /items/{dev_key}/{perm_id}/{file_name} {
      allow write: if request.auth.uid == dev_id;
      allow read: if request.auth.token.permId == perm_id;
    }
  }
}
</code>```

I expected only signed in users with a custom claim permId matching the relevant location to be able to download the file, allow read: if request.auth.token.permId == perm_id;.

So, I then set a custom claim in Cloud Functions on a user as follows:

STEP 2

```<code>    admin.auth().setCustomUserClaims(uid, {permId: '1'}).then(() => {
        // send off some triggers to let user know the download is coming
        admin.database().ref(`collection/${uid}/${itemId}`).update({
            downloadReady: true
        });
    });
</code>```

Then I signed the user out and signed back in again... which set the custom claims.
I checked that they were set in Cloud Functions as follows:

STEP 3

```<code>admin.auth().verifyIdToken(idToken).then((claims) => {
       console.log("--------------claims -------------");
       console.log(JSON.stringify(claims));
    });
</code>```

And I saw in the claims string... permID: "1"

On the client side I then requested a downloadURL (here is hopefully where I'm going wrong)... I expected this to not be the public download url but rather the download url that the Firebase Storage security rules will check:

STEP 4

```<code>var pathReference = storage.ref('items/<some-key>/1/Item-1');

pathReference.getDownloadURL()
.then((url)=>{
    console.log("url: ", url);
})
</code>```

The url I received from this call gave me this link
https://firebasestorage.googleapis.com/v0/b/emiru84-games.appspot.com/o/games%2FcfaoVuEdJqOWDi9oeaLLphXl0E82%2F1%2FGame-1?alt=media&token=45653143-924a-4a7e-b51d-00774d8986a0
(a tiny little image I use for testing)

So far so good, the user with the correct claim was able to view this image

I then repeated step 2, logout/login again, except this time with a permId of "0". I expected the url generated previously to no longer work since my user no longer had the correct custom claim... and the bucket location was still at the same location (bucket/dev_key/1/filename) but it still worked.

If I repeated step 4 I got a new url, which then gave the appropriate 403 error response. However the old url still worked (I guess as long as the token parameter is tacked on). Is this expected, if so, I'm not sure I understand how the Storage security rules make a difference if the download url is public anyway?

Any help clearing my foggy brain would be appreciated.

答:
The download URL in Cloud Storage for Firebase is always publicly readable. It is not affected by security rules.

If you don't want to allow public access to a file, you can revoke its download URL.

Body:
I'm sure I'm missing something wrt Firebase Storage rules, but I've done the following:

STEP 1

Firstly I set the following Firebase Storage rule:

service firebase.storage {
  match /b/{bucket}/o {
    match /items/{dev_key}/{perm_id}/{file_name} {
      allow write: if request.auth.uid == dev_id;
      allow read: if request.auth.token.permId == perm_id;
    }
  }
}

I expected only signed in users with a custom claim permId matching the relevant location to be able to download the file, allow read: if request.auth.token.permId == perm_id;.

So, I then set a custom claim in Cloud Functions on a user as follows:

STEP 2

    admin.auth().setCustomUserClaims(uid, {permId: '1'}).then(() => {
        // send off some triggers to let user know the download is coming
        admin.database().ref(`collection/${uid}/${itemId}`).update({
            downloadReady: true
        });
    });

Then I signed the user out and signed back in again... which set the custom claims.
I checked that they were set in Cloud Functions as follows:

STEP 3

admin.auth().verifyIdToken(idToken).then((claims) => {
       console.log("--------------claims -------------");
       console.log(JSON.stringify(claims));
    });

And I saw in the claims string... permID: "1"

On the client side I then requested a downloadURL (here is hopefully where I'm going wrong)... I expected this to not be the public download url but rather the download url that the Firebase Storage security rules will check:

STEP 4

var pathReference = storage.ref('items/<some-key>/1/Item-1');

pathReference.getDownloadURL()
.then((url)=>{
    console.log("url: ", url);
})

The url I received from this call gave me this link
https://firebasestorage.googleapis.com/v0/b/emiru84-games.appspot.com/o/games%2FcfaoVuEdJqOWDi9oeaLLphXl0E82%2F1%2FGame-1?alt=media&token=45653143-924a-4a7e-b51d-00774d8986a0
(a tiny little image I use for testing)

So far so good, the user with the correct claim was able to view this image

I then repeated step 2, logout/login again, except this time with a permId of "0". I expected the url generated previously to no longer work since my user no longer had the correct custom claim... and the bucket location was still at the same location (bucket/dev_key/1/filename) but it still worked.

If I repeated step 4 I got a new url, which then gave the appropriate 403 error response. However the old url still worked (I guess as long as the token parameter is tacked on). Is this expected, if so, I'm not sure I understand how the Storage security rules make a difference if the download url is public anyway?

Any help clearing my foggy brain would be appreciated.


问:
Cassandra, filter latest rows from an append only table
Currently I have a simple table as follows:

```<code>CREATE TABLE datatable (timestamp bigint, value bigint,  PRIMARY KEY (timestamp))
</code>```

This table is only growing and never being modified. The key is unique timestamp. All queries are range queries of the form:

```<code>SELECT * from datatable WHERE timestamp > 123456 ALLOW FILTERING
</code>```

Moreover, queries request only a small set of the latest rows inserted. The problem that I have right now is that performance of these queries negatively correlated with the table size. As table grows, it takes significantly longer to get response, even if query returns just a few rows.

Could you advise on how I should modify table schema to avoid performance degradation (e.g., create index or set clustering)?
Thanks!

答:
Add some time bucketing like

```<code>CREATE TABLE datatable (
  bucket timestamp,
  time timestamp,
  value bigint,
  PRIMARY KEY ((bucket), time)
) WITH CLUSTERING ORDER BY (time DESC);
</code>```

where bucket is the date truncated to the day or week or month (can figure out how many based on approx ingestion rate, a decent goal is about 64mb per partition but thats very flexible), that way you will collect all the rows for a period within a single partition very efficiently.

Having billions of partitions per node will cause slow down repairs and compactions significantly. Also partitioning order is random (murmur3 hash of the partition key order) so you cannot do things like have your above your query in order.

With the above you can then iterate from the bucket of your start time to the current bucket without ALLOW FILTERING (which you should never ever use outside of toy amounts of data or test environment kinda things) and the results will be in the order of the timestamps.

Body:
Currently I have a simple table as follows:

CREATE TABLE datatable (timestamp bigint, value bigint,  PRIMARY KEY (timestamp))

This table is only growing and never being modified. The key is unique timestamp. All queries are range queries of the form:

SELECT * from datatable WHERE timestamp > 123456 ALLOW FILTERING

Moreover, queries request only a small set of the latest rows inserted. The problem that I have right now is that performance of these queries negatively correlated with the table size. As table grows, it takes significantly longer to get response, even if query returns just a few rows.

Could you advise on how I should modify table schema to avoid performance degradation (e.g., create index or set clustering)?
Thanks!

Body:
Add some time bucketing like

CREATE TABLE datatable (
  bucket timestamp,
  time timestamp,
  value bigint,
  PRIMARY KEY ((bucket), time)
) WITH CLUSTERING ORDER BY (time DESC);

where bucket is the date truncated to the day or week or month (can figure out how many based on approx ingestion rate, a decent goal is about 64mb per partition but thats very flexible), that way you will collect all the rows for a period within a single partition very efficiently.

Having billions of partitions per node will cause slow down repairs and compactions significantly. Also partitioning order is random (murmur3 hash of the partition key order) so you cannot do things like have your above your query in order.

With the above you can then iterate from the bucket of your start time to the current bucket without ALLOW FILTERING (which you should never ever use outside of toy amounts of data or test environment kinda things) and the results will be in the order of the timestamps.


问:
HttpInterceptor change response body based on value from other observable
Some how i can't seem to change the response body based on the value from another observable which i can only get after i retrieved the response.

Changing the request is pretty simple, i don't know how to do it with the response.

```<code>@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {
  constructor(private _injector: Injector) {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).map((event: HttpEvent<any>) => {
      if (!(event instanceof HttpResponse)) return event;

      const translateService = this._injector.get(TranslateService);

      // retrieved the key from the reponse, now need to retrieve data from the translateservice
      translateService.get(`${event.body.key}`).subscribe((value: string) => {
        event.body.message = value;
      });

       // how to return new response ??
      return event.clone({ body: event.body });
    });
  }
}
</code>```

so basically i want to return a new reponse body with a new property 'message' on it.

答:
Since the intercept returns and observable you can switchMap it to the translate service's getEvent. Like So</p>

```<code>@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {
  constructor(private _injector: Injector) {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const translateService = this._injector.get(TranslateService);

    return next.handle(request)
        // filter out only events that HTTP event.
        .filter((event: HttpEvent<any>) =>(event instanceof HttpResponse))
        //then switch the observable to get the response of the translate service.
        .switchMap(event => translateService.get(`${event.body.key}`)
            .map(value=>event.body.message=value)));

    });
  }
}
</code>```

Body:
Some how i can't seem to change the response body based on the value from another observable which i can only get after i retrieved the response.

Changing the request is pretty simple, i don't know how to do it with the response.

@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {
  constructor(private _injector: Injector) {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).map((event: HttpEvent<any>) => {
      if (!(event instanceof HttpResponse)) return event;

      const translateService = this._injector.get(TranslateService);

      // retrieved the key from the reponse, now need to retrieve data from the translateservice
      translateService.get(`${event.body.key}`).subscribe((value: string) => {
        event.body.message = value;
      });

       // how to return new response ??
      return event.clone({ body: event.body });
    });
  }
}

so basically i want to return a new reponse body with a new property 'message' on it.

Body:
Since the intercept returns and observable you can switchMap it to the translate service's getEvent. Like So

@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {
  constructor(private _injector: Injector) {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const translateService = this._injector.get(TranslateService);

    return next.handle(request)
        // filter out only events that HTTP event.
        .filter((event: HttpEvent<any>) =>(event instanceof HttpResponse))
        //then switch the observable to get the response of the translate service.
        .switchMap(event => translateService.get(`${event.body.key}`)
            .map(value=>event.body.message=value)));

    });
  }
}


问:
How do I get a HWND from inside a DLL?
I have a DLL that I want to play sounds using Direct Sound.  In order to play sounds, I need the HWND of the executable.  I don't have a HWND of the executable that loads the DLL.  How do I get that in the DLL without passing it in from the executable?</p>

答:
You could use GetCurrentProcessId to get the current process Id.

You could then call EnumWindows, and check each window with GetWindowThreadProcessId to find a window associated with your process.

However, an easier option might be to just generate your own Window.  You can create a 1x1 pixel window that is not visible, and use it with Direct Sound.

This has the advantage of working even if your calling process doesn't have a usable window (or deletes window handles regularly).

Title: How do I get a HWND from inside a DLL?


问:
Dynamically build child routes using JSON object
I have hardcoded my child routes like below. But i want to built it using a JSON object i.e. below should be dynamically added and its components should be automatically imported. JSON Object can be stored in a file also. Is there a way to achieve the requirement.

```<code>  [
    { path: 'step1', component: aComponent },
    { path: 'step2', component: bComponent },
    { path: 'step3', component: cComponent },
    { path: 'step4', component: dComponent },
    { path: 'step5', component: eComponent },
    { path: 'step6', component: fComponent }
  ]
</code>```

End result should be like below.

```<code> export const abcRoutes: Routes = [
      {
        path: '',
        component: abcLandingComponent,
        children: [
          { path: 'step1', component: aComponent },
          { path: 'step2', component: bComponent },
          { path: 'step3', component: cComponent },
          { path: 'step4', component: dComponent },
          { path: 'step5', component: eComponent },
          { path: 'step6', component: fComponent }
        ]
      }
</code>```

答:
Could you export them as this?

```<code>import { aComponent } from './aComponent.componet';
import { bComponent } from './bComponent.componet';
etc...

// or use a barrel file.

import { aComponent, bComponent, etc.. } from './components';

export const childRoutes = [
  { path: 'step1', component: aComponent },
  { path: 'step2', component: bComponent },
  { path: 'step3', component: cComponent },
  { path: 'step4', component: dComponent },
  { path: 'step5', component: eComponent },
  { path: 'step6', component: fComponent }
];
</code>```

And then just import them as?

```<code>import { childRoutes } from './routes';

export const abcRoutes: Routes = [
{
  path: '',
  component: abcLandingComponent,
  children: childRoutes
}];
</code>```

Body:
I have hardcoded my child routes like below. But i want to built it using a JSON object i.e. below should be dynamically added and its components should be automatically imported. JSON Object can be stored in a file also. Is there a way to achieve the requirement.

  [
    { path: 'step1', component: aComponent },
    { path: 'step2', component: bComponent },
    { path: 'step3', component: cComponent },
    { path: 'step4', component: dComponent },
    { path: 'step5', component: eComponent },
    { path: 'step6', component: fComponent }
  ]

End result should be like below.

 export const abcRoutes: Routes = [
      {
        path: '',
        component: abcLandingComponent,
        children: [
          { path: 'step1', component: aComponent },
          { path: 'step2', component: bComponent },
          { path: 'step3', component: cComponent },
          { path: 'step4', component: dComponent },
          { path: 'step5', component: eComponent },
          { path: 'step6', component: fComponent }
        ]
      }

Body:
Could you export them as this?

import { aComponent } from './aComponent.componet';
import { bComponent } from './bComponent.componet';
etc...

// or use a barrel file.

import { aComponent, bComponent, etc.. } from './components';

export const childRoutes = [
  { path: 'step1', component: aComponent },
  { path: 'step2', component: bComponent },
  { path: 'step3', component: cComponent },
  { path: 'step4', component: dComponent },
  { path: 'step5', component: eComponent },
  { path: 'step6', component: fComponent }
];

And then just import them as?

import { childRoutes } from './routes';

export const abcRoutes: Routes = [
{
  path: '',
  component: abcLandingComponent,
  children: childRoutes
}];


问:
SQL order by with join two tables Optimization
How can I improve the performance by joining two big tables and sort by 1st able unique index?

I need only 1st table data with sort by. without order query will performance so fast.

Here is the example of queries

```<code>select a.* from T1 a, T2 b where a.c1 = b.c2;
select a.* from T1 a, T2 b where a.c1 = b.c2 order by a.id;
</code>```

just FYI, T1 and T2 have the proper index.

T1 table count is "54483938"
T2 table count is "54483820"

I am more interest in T1 data with sort by which T1 Records exist on T2.

I tried using an in operator query, it took me into 300 sec.

答:
You can try the three forms of the query:

join (which you have)

in (which you claim to have run)

exists

The exists version is:

```<code>select a.*
from T1 a
where exists (select 1 from T2 b where a.c1 = b.c2)
order by a.id;
</code>```

For this query, I would recommend indexes on T1(id, c1) and T2(c2).

Body:
How can I improve the performance by joining two big tables and sort by 1st able unique index?

I need only 1st table data with sort by. without order query will performance so fast.

Here is the example of queries

select a.* from T1 a, T2 b where a.c1 = b.c2;
select a.* from T1 a, T2 b where a.c1 = b.c2 order by a.id;

just FYI, T1 and T2 have the proper index.

T1 table count is "54483938"
T2 table count is "54483820"

I am more interest in T1 data with sort by which T1 Records exist on T2.

I tried using an in operator query, it took me into 300 sec.

Body:
You can try the three forms of the query:

join (which you have)

in (which you claim to have run)

exists

The exists version is:

select a.*
from T1 a
where exists (select 1 from T2 b where a.c1 = b.c2)
order by a.id;

For this query, I would recommend indexes on T1(id, c1) and T2(c2).


问:
Project Builds and Runs, but does not Archive
I have a project which builds and runs fine on the simulator and device, but fails when archiving.

The project is very old, but I have created a separate component which I have added in the workspace.

The main project is written in Objective-C, the new project is written in Swift 4. The project also uses CocoaPods and also includes another subproject written in Swift 3.2

There are various errors which all boil down to the same thing, the sub project is not producing any output when it is compiled. OR it is just not compiled. I see no errors in the code itself, just when trying to reference it:

```<code>//1
error: /Users/<user>/Library/Developer/Xcode/DerivedData/<id>/Build/Intermediates.noindex/ArchiveIntermediates/<app name>/BuildProductsPath/Release-iphoneos/Framework.framework: No such file or directory`

//2
Signing Identity:     "iPhone Developer: <redacted>“

/Users/<user>/Library/Developer/Xcode/DerivedData/<id>/Build/Intermediates.noindex/ ArchiveIntermediates/<app name>/InstallationBuildProductsLocation/Applications/<app name>/Frameworks/<framework>.framework: No such file or directory
Command /usr/bin/codesign failed with exit code 1

//3
@import ModuleName;

Module ‘ModuleName’ not found
</code>```

Here’s what I’ve tried:

Clear derived data

Restart Mac

Add $(SRCROOT) to Main Target > Build Settings > Framework Search Paths > Release

Confirmed project is present in Embedded Binaries

Confirmed project is present in Linked Frameworks and Libraries

Removing and re-adding project to embedded binaries and frameworks and libraries

Removing the import declaration

I am opening the workspace and not the project

Skip install set to YES in Subproject build settings

Comparing build settings from the working sub project with the failing one (they are the same)

Running pod update

Changing Always Embed Standard Swift Libraries makes no difference either way

Other notes:

In /Users/<user>/Library/Developer/Xcode/DerivedData/<id>/Build/ Intermediates.noindex/ArchiveIntermediates/<app name>/  InstallationBuildProductsLocation/Applications/<app name>.app/Frameworks/ there is    a .framework file for the other sub project and all the pods, but not for this one

In podfile, use_frameworks! is present

Update:

After running an archive today I am only seeing the error:

```<code>Module 'ModuleName' not found
</code>```

The other errors are gone

答:
The issue was to do with the iOS Deployment Target setting:

The main project: iOS 10

Sub project: iOS 11

In Debug it is building only for the current architecture, in Release it builds for all. Obvious once you know.

Setting the sub project to build for iOS 10 fixed the issue.

The most frustrating part: I double checked the build log and it doesn't mention the version issue anywhere :(

Body:
I have a project which builds and runs fine on the simulator and device, but fails when archiving.

The project is very old, but I have created a separate component which I have added in the workspace.

The main project is written in Objective-C, the new project is written in Swift 4. The project also uses CocoaPods and also includes another subproject written in Swift 3.2

There are various errors which all boil down to the same thing, the sub project is not producing any output when it is compiled. OR it is just not compiled. I see no errors in the code itself, just when trying to reference it:

//1
error: /Users/<user>/Library/Developer/Xcode/DerivedData/<id>/Build/Intermediates.noindex/ArchiveIntermediates/<app name>/BuildProductsPath/Release-iphoneos/Framework.framework: No such file or directory`

//2
Signing Identity:     "iPhone Developer: <redacted>“

/Users/<user>/Library/Developer/Xcode/DerivedData/<id>/Build/Intermediates.noindex/ ArchiveIntermediates/<app name>/InstallationBuildProductsLocation/Applications/<app name>/Frameworks/<framework>.framework: No such file or directory
Command /usr/bin/codesign failed with exit code 1

//3
@import ModuleName;

Module ‘ModuleName’ not found

Here’s what I’ve tried:

Clear derived data

Restart Mac

Add $(SRCROOT) to Main Target > Build Settings > Framework Search Paths > Release

Confirmed project is present in Embedded Binaries

Confirmed project is present in Linked Frameworks and Libraries

Removing and re-adding project to embedded binaries and frameworks and libraries

Removing the import declaration

I am opening the workspace and not the project

Skip install set to YES in Subproject build settings

Comparing build settings from the working sub project with the failing one (they are the same)

Running pod update

Changing Always Embed Standard Swift Libraries makes no difference either way

Other notes:

In /Users/<user>/Library/Developer/Xcode/DerivedData/<id>/Build/ Intermediates.noindex/ArchiveIntermediates/<app name>/  InstallationBuildProductsLocation/Applications/<app name>.app/Frameworks/ there is    a .framework file for the other sub project and all the pods, but not for this one

In podfile, use_frameworks! is present

Update:

After running an archive today I am only seeing the error:

Module 'ModuleName' not found

The other errors are gone


问:
how to make this mysql sub query work
```<code>SELECT c.noreg AS noreg, count( * ) AS jumlah
FROM kamar a, reservasi b, register c, identitas_psn d, sub_unit_kamar e
WHERE a.idkamar = b.kamar
AND b.noreg = c.id_reg_lengkap
AND c.norm = d.norm
AND c.idunit = e.id_subunit
AND c.noreg NOT
IN (

SELECT noreg
FROM register_keluar
)
AND (
c.idunit LIKE '20%'
)
AND jumlah > 1
GROUP BY noreg
ORDER BY jumlah DESC
</code>```

<p>// error is : AND jumlah > 1</p>

答: When you are combining the selection of any column and an aggregate alias (in your example: COUNT(*) as jumlah) and then you intend to use this aggregate alias (jumlah) somewhere in your query, with a GROUP BY condition, you need to use a HAVING condition after that corresponding GROUP BY.

Title: how to make this mysql sub query work

Body:
SELECT c.noreg AS noreg, count( * ) AS jumlah
FROM kamar a, reservasi b, register c, identitas_psn d, sub_unit_kamar e
WHERE a.idkamar = b.kamar
AND b.noreg = c.id_reg_lengkap
AND c.norm = d.norm
AND c.idunit = e.id_subunit
AND c.noreg NOT
IN (

SELECT noreg
FROM register_keluar
)
AND (
c.idunit LIKE '20%'
)
AND jumlah > 1
GROUP BY noreg
ORDER BY jumlah DESC

// error is : AND jumlah > 1


问:
How to give data from laravel to vue.js?
When i start write application i used to laravel blade. But now i have to transfer all to vue js and i don't known how to give data from controllers to vue.js. Also i don't know how to transfer this code</p>

```<code>@if(Session::has('error_text'))
        <div class="col-md-6 col-md-offset-3 formMessage">
            <div class="iw">
                <div class="text-error">{{Session::get('error_text')}}</div>
                @if(Session::has('with_link'))
                    <div class="help-text"><a href="{{Session::get('with_link')}}">{{Session::get('link_text')}}</a></div>
                @endif

                @if(Session::has('unknown_symbols'))
                    <div class="help-text"><a href="#">Report a bug</a></div>
                @endif
            </div>
        </div>
    @endif
</code>```

答:
In the blade file if you want to access the vue data you should use @{{ item }}. With the @ sign before the interpolation you escape the blade templating.

To pass data from the laravel to vue itself, you should use JSON which you call from your Vue and assign it to a variabel.

Body:
When i start write application i used to laravel blade. But now i have to transfer all to vue js and i don't known how to give data from controllers to vue.js. Also i don't know how to transfer this code

@if(Session::has('error_text'))

{{Session::get('error_text')}}

                @if(Session::has('with_link'))

{{Session::get('link_text')}}

                @endif

                @if(Session::has('unknown_symbols'))

Report a bug

                @endif

    @endif


问:
transform javascript array combining child
i go this json array

```<code>var responseArr = {options :{ch:["Hi", "By",], en:["Peter", "John"]}}
</code>```

is it possible change into this form

```<code>var responseArrB = {"options": [{'ch':'Hi',en:'Peter'},{ch:'By',en:'John'}]}
</code>```

i tried

```<code>let responseArrB = responseArr.options.ch.map( item => Object.assign({ch:item.ch, en:item.en}))
console.log(vv)
</code>```

but responseArrB..show

```<code>{ch: undefined, en: undefined}
</code>```

i could either show ch or en but can't combine it

```<code>let arrThree = responseArr.options.ch.map( item => Object.assign({ch:item, en:item}))
</code>```

答:
You could iterate the keys and build a new array for each key.

var object = { options: { ch: ["Hi", "By",], en: ["Peter", "John"] } },
    result = {
        options: Object
            .keys(object.options)
            .reduce((r, k) => (
                object.options[k].forEach((a, i) => {
                    r[i] = r[i] || {};
                    r[i][k] = a;
                }), r), [])
    };

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
i go this json array

var responseArr = {options :{ch:["Hi", "By",], en:["Peter", "John"]}}

is it possible change into this form

var responseArrB = {"options": [{'ch':'Hi',en:'Peter'},{ch:'By',en:'John'}]}

i tried

let responseArrB = responseArr.options.ch.map( item => Object.assign({ch:item.ch, en:item.en}))
console.log(vv)

but responseArrB..show

{ch: undefined, en: undefined}

i could either show ch or en but can't combine it

let arrThree = responseArr.options.ch.map( item => Object.assign({ch:item, en:item}))

Body:
You could iterate the keys and build a new array for each key.

var object = { options: { ch: ["Hi", "By",], en: ["Peter", "John"] } },
    result = {
        options: Object
            .keys(object.options)
            .reduce((r, k) => (
                object.options[k].forEach((a, i) => {
                    r[i] = r[i] || {};
                    r[i][k] = a;
                }), r), [])
    };

console.log(result);

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


问:
Format string date into date object
I have a date in this format: December 5th 2017. How do I convert it to either a timestamp or a date object?

I tried the following but it return NaN:

let tDate = new Date('December 5th 2017')

答: use a library like moment.js (momentjs.com) to parse custom date formats into Dates. As of version 2.13 it apparently comes with typings out of the box and can therefore be used easily with TypeScript (aureliajsrocks.com/moment-js-now-typescript-compatbile)</p>

Title: Format string date into date object


问:
transform character to a number in R
I loaded a data big set with read_delim(), since there I have the possibility to skip the first 4 rows of the data set which is not important for me. The data set is separated by ";". My Problem is the following:
I have some numbers like

```<code>-0,000364929204806685

0,00367021351121366

-0,0184237491339445
</code>```

as you can see this numbers are seperated by commas. Therefore if i change the  type of it to "numeric", during the loading phase, i get a formatting error like -3.649292e+14 for the first number. Thus i have to load the data as characters.
But now I am not able to do numeric calculations. as.numeric() doesen't work.

Is there any possibility to change this characters to numeric?

Thanks
Matthias

答:
Thanks everybody for help, it can be solved by using gsub(). In the upper example:

```<code>as.numeric(gsub(",", ".", Dat[1,12]))
</code>```

provides:

```<code>-0.0003649292
</code>```

Title: transform character to a number in R

Body:
I loaded a data big set with read_delim(), since there I have the possibility to skip the first 4 rows of the data set which is not important for me. The data set is separated by ";". My Problem is the following:
I have some numbers like

-0,000364929204806685

0,00367021351121366

-0,0184237491339445

as you can see this numbers are seperated by commas. Therefore if i change the  type of it to "numeric", during the loading phase, i get a formatting error like -3.649292e+14 for the first number. Thus i have to load the data as characters.
But now I am not able to do numeric calculations. as.numeric() doesen't work.

Is there any possibility to change this characters to numeric?

Thanks
Matthias

Body:
Thanks everybody for help, it can be solved by using gsub(). In the upper example:

as.numeric(gsub(",", ".", Dat[1,12]))

provides:

-0.0003649292


问:
How to edit this text file as merged information with same headers
I have a huge text file with data like this:-

```<code>EAST DUBBO - Unknown
EAST MAITLAND - 1892
EAST MAITLAND - 1902
EAST MAITLAND - 1920
EAST MAITLAND - 1937
EAST MAITLAND - 1940
EAST MAITLAND - 1956
EBOR - 1905
EBOR - 1911
EDEN - Unknown
ELLENBOROUGH - 1905
ELONG ELONG - 1920
ELONG ELONG - 1955
</code>```

and I need it to be in this format:-

```<code>EAST DUBBO - Unknown
EAST MAITLAND - 1892, 1902, 1920, 1937, 1940, 1956
EBOR - 1905, 1911
EDEN - Unknown
ELLENBOROUGH - 1905
ELONG ELONG - 1920, 1955
</code>```

It will take days to do by hand so i'm wondering if it can be solved programmatically or if there is an online tool?

答:
Assuming that the input lines are in sorted order (or otherwise grouped), this can be done with sed:</p>

```<code>#!/bin/sed -f

:loop

# If we've reached the end, print it and exit
# (Not required for GNU sed, whose N command continues)
$q
# read another line of input
N
# if the two lines have the same beginning, join them and repeat
/^\(.*\) - .*\n\1 - /s/\n.* - /,/
tloop

# otherwise, print the first line and eliminate it
P
s/.*\n//
bloop
</code>```

Body:
I have a huge text file with data like this:-

EAST DUBBO - Unknown
EAST MAITLAND - 1892
EAST MAITLAND - 1902
EAST MAITLAND - 1920
EAST MAITLAND - 1937
EAST MAITLAND - 1940
EAST MAITLAND - 1956
EBOR - 1905
EBOR - 1911
EDEN - Unknown
ELLENBOROUGH - 1905
ELONG ELONG - 1920
ELONG ELONG - 1955

and I need it to be in this format:-

EAST DUBBO - Unknown
EAST MAITLAND - 1892, 1902, 1920, 1937, 1940, 1956
EBOR - 1905, 1911
EDEN - Unknown
ELLENBOROUGH - 1905
ELONG ELONG - 1920, 1955

It will take days to do by hand so i'm wondering if it can be solved programmatically or if there is an online tool?

Body:
Assuming that the input lines are in sorted order (or otherwise grouped), this can be done with sed:

#!/bin/sed -f

:loop

# If we've reached the end, print it and exit
# (Not required for GNU sed, whose N command continues)
$q
# read another line of input
N
# if the two lines have the same beginning, join them and repeat
/^\(.*\) - .*\n\1 - /s/\n.* - /,/
tloop

# otherwise, print the first line and eliminate it
P
s/.*\n//
bloop


问:
How to find the second minimum number without using arrays or loops
I tried to write a program that receive from the user 5 integers and print the second minimum number.

Here is a sample of what I've tried:

```<code>#include <iostream>
using namespace std;
int main () {
int a,b,c,d,e;
cin>>a>>b>>c>>d>>e;
if (a>b && a<c && a<d && a<e)
    cout<<a<<endl;
if (b>a && b<c && b<d && b<e)
    cout<<b<<endl;
if (c>a && c<b && c<d && c<e)
    cout<<c<<endl;
if (d>a && d<b && d<c && d<e)
    cout <<d<<endl;
if (e>a && e<b && e<c && e<d)
cout <<e<<endl;
return 0;

}
</code>```

When I enter 1 2 3 4 5 it prints the second minimum, but when I enter

5 4 3 2 1 Nothing will print on the screen. What am I doing wrong with this? Is there any other way to write my program?

答:
What about a recursive and more generic approach?
No arrays, no loops and not limited to just 5 integers.

The following function get_2nd_min() keeps track of the two lowest integers read from std::cin a total of count times:

```<code>#include <climits>
#include <cstddef>
#include <iostream>

int get_2nd_min(size_t count, int min = INT_MAX, int second_min = INT_MAX)
{
   if (!count)
      return second_min; // end of recursion

   // read next value from cin
   int value;
   std::cin >> value;

   // Does second_min need to be updated?
   if (value < second_min) {

     // Does min also need to be updated?
     if (value < min) {
        // new min found
        second_min = min; // move the so far min to second_min
        min = value; // update the new min
     } else {
        // value is lower than second_min but higher than min
        second_min = value; // new second_min found, update it
     }
   }
   // perform recursion
   return get_2nd_min(count - 1, min, second_min);
}
</code>```

In order to read 5 integers and obtain the 2nd lowest:

```<code>int second_min = get_2nd_min(5);
</code>```

Body:
I tried to write a program that receive from the user 5 integers and print the second minimum number.

Here is a sample of what I've tried:

#include <iostream>
using namespace std;
int main () {
int a,b,c,d,e;
cin>>a>>b>>c>>d>>e;
if (a>b && a<c && a<d && a<e)
    cout<<a<<endl;
if (b>a && b<c && b<d && b<e)
    cout<<b<<endl;
if (c>a && c<b && c<d && c<e)
    cout<<c<<endl;
if (d>a && d<b && d<c && d<e)
    cout <<d<<endl;
if (e>a && e<b && e<c && e<d)
cout <<e<<endl;
return 0;

}

When I enter 1 2 3 4 5 it prints the second minimum, but when I enter

5 4 3 2 1 Nothing will print on the screen. What am I doing wrong with this? Is there any other way to write my program?

Body:
What about a recursive and more generic approach?
No arrays, no loops and not limited to just 5 integers.

The following function get_2nd_min() keeps track of the two lowest integers read from std::cin a total of count times:

#include <climits>
#include <cstddef>
#include <iostream>

int get_2nd_min(size_t count, int min = INT_MAX, int second_min = INT_MAX)
{
   if (!count)
      return second_min; // end of recursion

   // read next value from cin
   int value;
   std::cin >> value;

   // Does second_min need to be updated?
   if (value < second_min) {

     // Does min also need to be updated?
     if (value < min) {
        // new min found
        second_min = min; // move the so far min to second_min
        min = value; // update the new min
     } else {
        // value is lower than second_min but higher than min
        second_min = value; // new second_min found, update it
     }
   }
   // perform recursion
   return get_2nd_min(count - 1, min, second_min);
}

In order to read 5 integers and obtain the 2nd lowest:

int second_min = get_2nd_min(5);


问:
Aggregate class extending base class - Violation of LSP?
The Liskov Substitution Principle (LSP) on Wikipedia

Say I have a Alien class with an numFingers attribute*.  Occasionally, I need to pull the sum of the numFingers from the database, grouped by other field values.  In these cases, I have no need to manipulate each record individually, but I do need access to a lot of their functionality -- be able to get attributes, perform some basic logic on them, etc.  This may include data summed from thousands of records, so it makes little sense to instantiate thousands of Alien objects when the database query can do the work of summing for me.

I would like to make an extension class called AlienAggregate, whose attributes are set from the grouped & summed query.  This class would allow me to call any of Alien's methods.  The only difference between functionality of the two classes, is GetID().  The aggregate class has no ID, since its data has been derived from any number of records.  Because of this, calling GetID() on AlienAggregate throws an exception.

Is this a violation of the Liskov Substitution Principle?  Is there a better way to handle a call to GetID()?  Is there a better way to design the relationship between the Alien and AlienAggregate classes?

*Actual names may have been changed just because I can.

答:
I don't think you're violating LSP since the principle only applies when Alien is a subtype of AlienAggregate (or the other way around).  There is no is a relationship here (more of an aggregation of Alien's as you've appropriately named them).

Instead, it sounds like both Alien, and AlienAggregate probably implement a LooksAlien Interface.  The Alien class just has an additional method, GetID().

...just beware of the nefarious BeginInvasion method on AlienAggregate.


问:
How can I get a side-by-side diff when I do "git diff"?
When I type git diff, I'd like to see a side-by-side diff, like with diff -y, or like to display the diff in an interactive diff tool like kdiff3. How can this be done?

答:
Open Intellij IDEA, select a single or multiple commits in the "Version Control" tool window, browse changed files, and double click them to inspect changes side by side for each file.

With the bundled command-line launcher you can bring IDEA up anywhere with a simple idea some/path


问:
MVC ASP.NET MVC3 AllowHtml Attribute Not Working?
The question is very simple:

Say you have a model called Person

```<code>public class Person
{

       public int PersonID {get; set;}

       public string Name {get; set;}

       [AllowHtml] // Allow html in Intro property
       public string Intro {get; set;}

       [ScaffoldColumn(false)]
       public string ComplicatedValue {get; set;}

}
</code>```

In controller's Create action

```<code>[HttpPost]
public ActionResult Create(Person o, FormCollection collection)
{

// whatever code here;

}
</code>```

If you run it,

input plain text for Intro, no
problem happens.

input html content for Intro, no matter how you set
your configuration file, it will
tells "A potential dangerous ..."

I DO find the reason of this problem.

If you change the function to

```<code>public ActionResult Create(Person o) // Get rid of the *FormCollection collection*
{

// whatever code here;

}
</code>```

This will eliminate the "potential dangerous" error.

But my problem is that for my application, I have to use the secondary parameter FormCollection collection in the Create Action method, because I need to use some other control values and server variable to assign a calculated value to the ComplicatedValue property.

If any expert of ASP.NET MVC3 have met the same problem as me, and found a solution, please kindly let me know.

答:
have you tried

[Bind(Exclude="ComplicatedValue")]

:

```<code>[HttpPost]
public ActionResult Create([Bind(Exclude="ComplicatedValue")]Person o)
{
}
</code>```

?

with that it allows you to exclude setting ComplicatedValue property on the form and still submit the object as a Person class.

hope that helps

Body:
The question is very simple:

Say you have a model called Person

public class Person
{

       public int PersonID {get; set;}

       public string Name {get; set;}

       [AllowHtml] // Allow html in Intro property
       public string Intro {get; set;}

       [ScaffoldColumn(false)]
       public string ComplicatedValue {get; set;}

}

In controller's Create action

[HttpPost]
public ActionResult Create(Person o, FormCollection collection)
{

// whatever code here;

}

If you run it,

input plain text for Intro, no
problem happens.

input html content for Intro, no matter how you set
your configuration file, it will
tells "A potential dangerous ..."

I DO find the reason of this problem.

If you change the function to

public ActionResult Create(Person o) // Get rid of the *FormCollection collection*
{

// whatever code here;

}

This will eliminate the "potential dangerous" error.

But my problem is that for my application, I have to use the secondary parameter FormCollection collection in the Create Action method, because I need to use some other control values and server variable to assign a calculated value to the ComplicatedValue property.

If any expert of ASP.NET MVC3 have met the same problem as me, and found a solution, please kindly let me know.

Body:
have you tried

[Bind(Exclude="ComplicatedValue")]

:

[HttpPost]
public ActionResult Create([Bind(Exclude="ComplicatedValue")]Person o)
{
}

?

with that it allows you to exclude setting ComplicatedValue property on the form and still submit the object as a Person class.

hope that helps


问:
Difficult XML to Dictionary in Python
I am finding difficult parsing this XML:

```<code><menuItems>
    <menuItem>
        <text>Auto 4-spd, 6 cyl, 3.8 L, 3.8N</text>
        <value>14864</value>
    </menuItem>
    <menuItem>
        <text>Auto 4-spd, 8 cyl, 4.6 L</text>
        <value>14866</value>
    </menuItem>
    <menuItem>
        <text>Man 5-spd, 6 cyl, 3.8 L</text>
        <value>14865</value>
    </menuItem>
</menuItems>
</code>```

I am doing it like this:

```<code>list = []
response = et.XML(urllib.request.urlopen(url).read())
for i, child in enumerate(response):
    for subchild in child:
        lista.append({subchild.tag : subchild.text})
</code>```

So when I print the list, item by item, I receive this:

```<code>{'text': 'Auto 4-spd, 6 cyl, 3.8 L, 3.8N'}
{'value': '14864'}
{'text': 'Auto 4-spd, 8 cyl, 4.6 L'}
{'value': '14866'}
{'text': 'Man 5-spd, 6 cyl, 3.8 L'}
{'value': '14865'}
</code>```

Instead of that, I would like to receive something like this:

```<code>{'Auto 4-spd, 6 cyl, 3.8 L, 3.8N': '14864'}
{'Auto 4-spd, 8 cyl, 4.6 L': '14866'}
{'Man 5-spd, 6 cyl, 3.8 L': '14865'}
</code>```

答:
```<code>lista = []
response = et.XML(xml)
for i, child in enumerate(response):
    text = child.find('text').text
    value = child.find('value').text
    lista.append({text: value})
</code>```

Title: Difficult XML to Dictionary in Python

Body:
I am finding difficult parsing this XML:

<menuItems>
    <menuItem>
        <text>Auto 4-spd, 6 cyl, 3.8 L, 3.8N</text>
        <value>14864</value>
    </menuItem>
    <menuItem>
        <text>Auto 4-spd, 8 cyl, 4.6 L</text>
        <value>14866</value>
    </menuItem>
    <menuItem>
        <text>Man 5-spd, 6 cyl, 3.8 L</text>
        <value>14865</value>
    </menuItem>
</menuItems>

I am doing it like this:

list = []
response = et.XML(urllib.request.urlopen(url).read())
for i, child in enumerate(response):
    for subchild in child:
        lista.append({subchild.tag : subchild.text})

So when I print the list, item by item, I receive this:

{'text': 'Auto 4-spd, 6 cyl, 3.8 L, 3.8N'}
{'value': '14864'}
{'text': 'Auto 4-spd, 8 cyl, 4.6 L'}
{'value': '14866'}
{'text': 'Man 5-spd, 6 cyl, 3.8 L'}
{'value': '14865'}

Instead of that, I would like to receive something like this:

{'Auto 4-spd, 6 cyl, 3.8 L, 3.8N': '14864'}
{'Auto 4-spd, 8 cyl, 4.6 L': '14866'}
{'Man 5-spd, 6 cyl, 3.8 L': '14865'}


问:
Embedding tables of data into a DocuSign template
I've got a form (in an ASP.NET application) that a person will add multiple rows to that represent items they are wishing to purchase. These items I want to display on a DocuSign document for them to sign.

Since there could be 1 item, or there could be 100, I'm not quite sure how to embed a field in the DocuSign template that I can populate with this data, they all seem to be for a single item when you use the DocuSign API to set a value.

答:
With DocuSign, the field values you specify are overlayed onto the (static) document(s) that you specify. In other words, there's no DocuSign functionality that would automatically scale the size of a table (number of rows) based on the number of rows of data you specify.

However, if you know the range of possible row counts that your table could possibly contain, you could still achieve the end result that you're seeking. For example, let's say you know your table will always contain between 1 and 10 rows. You could create 10 separate documents -- the first one with a 1-row table, the second with a 2-row table, the third with a 3-row table, etc. Then, at runtime, when you know how many rows of data the table will contain, use the API to add the appropriate document to the Envelope (or, if you've created a Template in DocuSign for each of the 10 documents, specify the appropriate Template for the Envelope). Obviously this approach doesn't scale well, and makes document maintenance a challenge (since if you need to make a change to the underlying document at any point in the future, you'll need to do that change to N documents) -- but it's the only way to solve for the scenario that you've described.

Note:  If your possible range for number of rows is a large number (like 100, for example) -- you don't necessarily have to create 100 documents, as long as you're okay with tables containing empty rows. For example, if there could be a maximum of 100 rows, you could just create 10 documents -- the first one with a 10-row table, the second with a 20-row table, and so on. Then at runtime, if there are less than 10 items for the table, you'd use document #1; if there are between 11-20 items, you'd use document #2, etc. Using this example, your table could end up containing up to 9 empty rows (for example, if there are 11 items, you'd add them to a table that contains 20 rows, leaving the final 9 rows of the table empty). This obviously isn't ideal, but would likely be preferable (from an initial effort standpoint, and a doc maintenance standpoint) to creating 100 different documents.


问:
Why oracle sql not allow sysdate in table creation time for count age?
Query....
I want to try to make check constraints on birthdate and check age should be greater than 18.

```<code>Create table emp
(
Birthdate date,
Check( MONTHS_BETWEEN(SYSDATE,Birthdate))
);
</code>```

Error on above query....why?
Anyone help me...

Why oracle sql not allow sysdate in table creation time for count age?

答:
Maybe try:</p>

```<code>SQL> create table person
(name varchar2(100),
dob date,
created_date date default sysdate not null,
constraint dob_check check
     (
        dob <= add_months(trunc(created_date), (12*18)*-1)
     )
)
Table created.
SQL> insert into person(name,dob) values ('Bob', to_date('19740101','YYYYMMDD'))
1 row created.
SQL> commit
Commit complete.
SQL> insert into person(name,dob) values ('Jane', to_date('20050101','YYYYMMDD'))
insert into person(name,dob) values ('Jane', to_date('20050101','YYYYMMDD'))
Error at line 17
ORA-02290: check constraint (MYUSER.DOB_CHECK) violated
</code>```

Body:
Query....
I want to try to make check constraints on birthdate and check age should be greater than 18.

Create table emp
(
Birthdate date,
Check( MONTHS_BETWEEN(SYSDATE,Birthdate))
);

Error on above query....why?
Anyone help me...

Why oracle sql not allow sysdate in table creation time for count age?

Body:
Maybe try:

SQL> create table person
(name varchar2(100),
dob date,
created_date date default sysdate not null,
constraint dob_check check
     (
        dob <= add_months(trunc(created_date), (12*18)*-1)
     )
)
Table created.
SQL> insert into person(name,dob) values ('Bob', to_date('19740101','YYYYMMDD'))
1 row created.
SQL> commit
Commit complete.
SQL> insert into person(name,dob) values ('Jane', to_date('20050101','YYYYMMDD'))
insert into person(name,dob) values ('Jane', to_date('20050101','YYYYMMDD'))
Error at line 17
ORA-02290: check constraint (MYUSER.DOB_CHECK) violated


问:
how to do an array with ngFor
i have a code of html like this.

```<code><ul>
    <li *ngFor="let dataMakanan of hehe">
      {{ dataMakanan.makanan }}<br>
      {{ dataMakanan.deskripsi }}<br>
      <ion-icon name="remove"(click)="kurangPorsi()"></ion-icon> {{counter}} <ion-icon name="add" (click)="tambahPorsi()"></ion-icon>

    </li>
  </ul>
</code>```

this code means that i want to show the hehe as much as it gets and i want to do an increment or decrement on each value. But when i do the increment or decrement it will affect to all data.

For example it shows 3 data on the screen and i want to increment it..
All of data was plus by one, but all i want is to increment spesific data that i click.

i use firebase and ionic

i just want to do it flexible, not for 1 user only..

答:
You just need to have counter for each object in your hehe array.

html:

```<code><ul>
    <li *ngFor="let dataMakanan of hehe; let i = index">
        {{ dataMakanan.makanan }}<br>
        {{ dataMakanan.deskripsi }}<br>
        <ion-icon name="remove" (click)="kurangPorsi(i)"></ion-icon>
        <!-- instead of common counter, we use separate counter for each object -->
        {{dataMakanan.counter}}
        <ion-icon name="add" (click)="tambahPorsi(i)"></ion-icon>
    </li>
</ul>
</code>```

ts:

```<code>public hehe = [
    { makanan: 'name1', deskripsi: 'description1', counter: 0 },
    { makanan: 'name2', deskripsi: 'description2', counter: 0 },
]

kurangPorsi(index: number) {
    this.hehe[index].counter--;
}

tambahPorsi(index: number) {
    this.hehe[index].counter++;
}
</code>```

Title: how to do an array with ngFor

Body:
i have a code of html like this.

      {{ dataMakanan.makanan }}

      {{ dataMakanan.deskripsi }}

      <ion-icon name="remove"(click)="kurangPorsi()"></ion-icon> {{counter}} <ion-icon name="add" (click)="tambahPorsi()"></ion-icon>

this code means that i want to show the hehe as much as it gets and i want to do an increment or decrement on each value. But when i do the increment or decrement it will affect to all data.

For example it shows 3 data on the screen and i want to increment it..
All of data was plus by one, but all i want is to increment spesific data that i click.

i use firebase and ionic

i just want to do it flexible, not for 1 user only..

Body:
You just need to have counter for each object in your hehe array.

html:

<ul>
    <li *ngFor="let dataMakanan of hehe; let i = index">
        {{ dataMakanan.makanan }}<br>
        {{ dataMakanan.deskripsi }}<br>
        <ion-icon name="remove" (click)="kurangPorsi(i)"></ion-icon>
        <!-- instead of common counter, we use separate counter for each object -->
        {{dataMakanan.counter}}
        <ion-icon name="add" (click)="tambahPorsi(i)"></ion-icon>
    </li>
</ul>

ts:

public hehe = [
    { makanan: 'name1', deskripsi: 'description1', counter: 0 },
    { makanan: 'name2', deskripsi: 'description2', counter: 0 },
]

kurangPorsi(index: number) {
    this.hehe[index].counter--;
}

tambahPorsi(index: number) {
    this.hehe[index].counter++;
}


问:
Not receiving messages between two IOS devices using Socket.io
I am trying to create a chat app on IOS devices using Socket.io.
 Here the problem... when I emit a message from the IOS app to a socket I receive it on Node but the users from the IOS App subscribed to this socket not. If I do the emit to this socket from Node all users subscribed receive it but if the emit comes out from the app the users of the app do not receive it.

Node:

```<code>io.on('connection', function(socket){
  console.log('a user connected');
  socket.on('4-1status', function (from, msg) {
    console.log('receive it');
  });
});
</code>```

IOS:

 Init SocketClient and sockets.

```<code>Constants.SocketClient = SocketIOClient(socketURL: URL(string: Constants.baseUrlSocket)!, config: [.log(true), .compress])
        Constants.SocketClient.on(clientEvent: .connect) {data, ack in
            print("socket connected")
        }
Constants.SocketClient.on("4-1status") {[weak self] dataArray, ack in
                print("Recive")
                self?.statusChangeDelegate?.statusChange(values: dataArray[0] as! NSDictionary)
            }

Constants.SocketClient.connect()
</code>```

Emit message to socket:

```<code>Constants.SocketClient.emit("4-1status", ["id": Constants.me.id, "status": "0"])
</code>```

答: The correct way to do this is to send the info through a broadcast in the server and then send it to a specific socket.</p>

Body:
I am trying to create a chat app on IOS devices using Socket.io.
 Here the problem... when I emit a message from the IOS app to a socket I receive it on Node but the users from the IOS App subscribed to this socket not. If I do the emit to this socket from Node all users subscribed receive it but if the emit comes out from the app the users of the app do not receive it.

Node:

io.on('connection', function(socket){
  console.log('a user connected');
  socket.on('4-1status', function (from, msg) {
    console.log('receive it');
  });
});

IOS:

 Init SocketClient and sockets.

Constants.SocketClient = SocketIOClient(socketURL: URL(string: Constants.baseUrlSocket)!, config: [.log(true), .compress])
        Constants.SocketClient.on(clientEvent: .connect) {data, ack in
            print("socket connected")
        }
Constants.SocketClient.on("4-1status") {[weak self] dataArray, ack in
                print("Recive")
                self?.statusChangeDelegate?.statusChange(values: dataArray[0] as! NSDictionary)
            }

Constants.SocketClient.connect()

Emit message to socket:

Constants.SocketClient.emit("4-1status", ["id": Constants.me.id, "status": "0"])