问:
VB.net, WPF and nested Datamodel: Best way to write back into Database?
I'm pretty new to VB.net and WPF. However I have some experience in mainly PHP and JAVA programming. I managed to push myself through most of the traps that came across my way but now I have stumbled over something for which I belive there must be already a smart way to solve.

Here is what I mean:

I'm using VB.net, WPF and a MS Access Database. This is not negotiable and I'm not able to use another database. My Datamodel consists of serveral nested objects like this:

```<code>Public Class subSubObject
    Public Property id as int32
    Public Property description as string
End Class

Public Class subObject
    Public Property id as int32
    Public Property description as string
    Public Property subSubObjects as list (of subSubObject)
End Class

Public Class MainObject
    Public Property id as int32
    Public Property description as string
    Public Property subObjects as list (of subObject)
End Class

Public Class DataModel
    Public Property MainObjects as list (of MainObject)
End Class
</code>```

I'm using an OLEDB connection to read the information from the database and create the corresponding objects to reflect my database model. So on this moment Database and Datamodel are identical.
Now I use a WPF datagrid with row details to perfom changes to the datamodel. This means I delete Objects, create new Objects and new Sub-Objects etc. The IDs are managed by the database engine and not by the application. I if I enter a new Dataset into the Database it will get a new ID autmatically.

```<code><DataGrid x:Name="dgDataModel"
    AutoGenerateColumns="true" CanUserAddRows="true" ItemsSource="{Binding DataModel}">

            <DataGrid.Columns>
                <DataGridTemplateColumn Width="*">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>

                            <DataGrid x:Name="dgMainObjects"
                                AutoGenerateColumns="False" CanUserAddRows="True" ItemsSource="{Binding Path=MainObjects}"
                                IsReadOnly="False">

                                <DataGrid.Columns>
                                    <DataGridTextColumn Header="ID" Binding="{Binding Path=ID}" IsReadOnly="True" />
                                    <DataGridTextColumn Header="Description" Binding="{Binding Path=Description}" />
                                </DataGrid.Columns>

                                <DataGrid.RowDetailsTemplate>
                                    <DataTemplate>
                                        <DataGrid  x:Name="dgRegelsaetze" AutoGenerateColumns="False" ItemsSource="{Binding Path=subObjects}">

                                            <DataGrid.Columns>
                                                <DataGridTextColumn Header="ID" Binding="{Binding Path=ID}"/>
                                                <DataGridTextColumn Header="Description" Binding="{Binding Description}" />
                                            </DataGrid.Columns>

                                            <DataGrid.RowDetailsTemplate>
                                                <DataTemplate>

                                                    <DataGrid x:Name="dgSubSubObjects"
                                                        AutoGenerateColumns="False" ItemsSource="{Binding Path=SubSubObjects}">

                                                        <DataGrid.Columns>
                                                            <DataGridTextColumn Header="ID" Binding="{Binding Path=RegelID}" IsReadOnly="True"/>
                                                            <DataGridTextColumn Header="Beschreibung" Binding="{Binding RegelBeschr}" />
                                                        </DataGrid.Columns>

                                                </DataTemplate>
                                        </DataGrid>
                                    <DataTemplate>
                                </DataGrid.RowDetailsTemplate>

                            </DataGrid>

                        </DataTemplate>
                    </DataGrid.RowDetailsTemplate>

                </DataGrid>

            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
    </DataGrid.Columns>

</DataGrid>
</code>```

This code will not work. It's just to give you an idea how the application is built. Now after I changed the datamodel using the wpf datagrid I have to write the changes back to the database. Mostly there is no problem about that. I just do regular INSERT and UPDATE operations. But I noticed that the delete operations are the problems here. This is because after I deleted an Object by pressing DEL in the datagrid it is gone leaving no sign it ever existerd. As there is no ID or anything else left I'm not able to create the needed DELETE operations in SQL.

So I tried to solve this by using the CommandManager.PreviewExecuted property of the datagrids. It would give me the opportunity to define a sub that would catch a deleted Object and save it in a seperate list. I could use this list to create the DELETE commands later. At least that was my idea.

Unfortunately I found out that the command is run for every level of the cascade. So when I delete let's say an instance of subSubObject in the third level of my datagrid the sub is fired for alle the lower levels as well. So I'm ending up with a list that is not only filled with the deleted objects but with all it's parent objects as well.

To be honest I can't belive that the deleteion process is so complicated. I don't think I'm the first person ever with this problem so there must be an elegant way to solve this. Does anyone of you have an idea?

Thanks in advance.
Daniel

答:
Assuming you're using an ObservableCollection for MainObjects collection, you'll have to handle the CollectionChanged event. Looks like you could also change to a BindingList.

StackOver reference to switching to a BindingList

CodeProject article referenced in the above StackOverflow post for handling deletes with the ObservableCollection CollectionChanged event.

Body:
I'm pretty new to VB.net and WPF. However I have some experience in mainly PHP and JAVA programming. I managed to push myself through most of the traps that came across my way but now I have stumbled over something for which I belive there must be already a smart way to solve.

Here is what I mean:

I'm using VB.net, WPF and a MS Access Database. This is not negotiable and I'm not able to use another database. My Datamodel consists of serveral nested objects like this:

Public Class subSubObject
    Public Property id as int32
    Public Property description as string
End Class

Public Class subObject
    Public Property id as int32
    Public Property description as string
    Public Property subSubObjects as list (of subSubObject)
End Class

Public Class MainObject
    Public Property id as int32
    Public Property description as string
    Public Property subObjects as list (of subObject)
End Class

Public Class DataModel
    Public Property MainObjects as list (of MainObject)
End Class

I'm using an OLEDB connection to read the information from the database and create the corresponding objects to reflect my database model. So on this moment Database and Datamodel are identical.
Now I use a WPF datagrid with row details to perfom changes to the datamodel. This means I delete Objects, create new Objects and new Sub-Objects etc. The IDs are managed by the database engine and not by the application. I if I enter a new Dataset into the Database it will get a new ID autmatically.

<DataGrid x:Name="dgDataModel"
    AutoGenerateColumns="true" CanUserAddRows="true" ItemsSource="{Binding DataModel}">

            <DataGrid.Columns>
                <DataGridTemplateColumn Width="*">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>

                            <DataGrid x:Name="dgMainObjects"
                                AutoGenerateColumns="False" CanUserAddRows="True" ItemsSource="{Binding Path=MainObjects}"
                                IsReadOnly="False">

                                <DataGrid.Columns>
                                    <DataGridTextColumn Header="ID" Binding="{Binding Path=ID}" IsReadOnly="True" />
                                    <DataGridTextColumn Header="Description" Binding="{Binding Path=Description}" />
                                </DataGrid.Columns>

                                <DataGrid.RowDetailsTemplate>
                                    <DataTemplate>
                                        <DataGrid  x:Name="dgRegelsaetze" AutoGenerateColumns="False" ItemsSource="{Binding Path=subObjects}">

                                            <DataGrid.Columns>
                                                <DataGridTextColumn Header="ID" Binding="{Binding Path=ID}"/>
                                                <DataGridTextColumn Header="Description" Binding="{Binding Description}" />
                                            </DataGrid.Columns>

                                            <DataGrid.RowDetailsTemplate>
                                                <DataTemplate>

                                                    <DataGrid x:Name="dgSubSubObjects"
                                                        AutoGenerateColumns="False" ItemsSource="{Binding Path=SubSubObjects}">

                                                        <DataGrid.Columns>
                                                            <DataGridTextColumn Header="ID" Binding="{Binding Path=RegelID}" IsReadOnly="True"/>
                                                            <DataGridTextColumn Header="Beschreibung" Binding="{Binding RegelBeschr}" />
                                                        </DataGrid.Columns>

                                                </DataTemplate>
                                        </DataGrid>
                                    <DataTemplate>
                                </DataGrid.RowDetailsTemplate>

                            </DataGrid>

                        </DataTemplate>
                    </DataGrid.RowDetailsTemplate>

                </DataGrid>

            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
    </DataGrid.Columns>

</DataGrid>

This code will not work. It's just to give you an idea how the application is built. Now after I changed the datamodel using the wpf datagrid I have to write the changes back to the database. Mostly there is no problem about that. I just do regular INSERT and UPDATE operations. But I noticed that the delete operations are the problems here. This is because after I deleted an Object by pressing DEL in the datagrid it is gone leaving no sign it ever existerd. As there is no ID or anything else left I'm not able to create the needed DELETE operations in SQL.

So I tried to solve this by using the CommandManager.PreviewExecuted property of the datagrids. It would give me the opportunity to define a sub that would catch a deleted Object and save it in a seperate list. I could use this list to create the DELETE commands later. At least that was my idea.

Unfortunately I found out that the command is run for every level of the cascade. So when I delete let's say an instance of subSubObject in the third level of my datagrid the sub is fired for alle the lower levels as well. So I'm ending up with a list that is not only filled with the deleted objects but with all it's parent objects as well.

To be honest I can't belive that the deleteion process is so complicated. I don't think I'm the first person ever with this problem so there must be an elegant way to solve this. Does anyone of you have an idea?

Thanks in advance.
Daniel


来源: stackexchange

问:
Which programming language Google app engine is most likely to work with next and why?
Their roadmap says their next release will be in March 2009, and that they'll be adding a new 'runtime language'. I'm hoping its either Java or PHP but realy not sure, and would like to know which language is the most probable so i can plan accordingly for a project I plan on hosting with google app engine.

Any ideas?

答:
Languages used for production code inside Google are limited to C++, Java, Python, and JavaScript.

Apps Engine already runs Python, so what's next?

It's most likely JavaScript. I recall Steve Yegge working on a Rails equivalent for JavaScript. See Stevey's Blog Rants: Rhino on Rails.

Java is less likely, but possible. Java servlet containers tend to be heavy-weight.

C++ is possible (Native Client and Chrome are two examples of sandboxed C++ code), but unlikely at this point.

OwnerDisplayName: Click Upvote

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Click Upvote


问:
jquery hyperlink in firefox
I have the code below which checks if a user is logged in, if they are it echo's out a javascript function hideLogin() otherwise it will echo the function showLogin() . This works fine on every browser I have tested in, but firefox. The link is not clickable, where as it is in every other browser I tested in.

```<code><div id="account">
<script type="text/javascript">
<?php
if(loggedIn())
{
    echo "hideLogin();";
}
else
{
    echo "showLogin();";
}
?>
</script>

</div>
function hideLogin()
{
        $('#accountAccess').html('Welcome <?php echo $_SESSION["firstName"]; ?> |  <a href="logout.php">Logout</a>');
}

function showLogin()
{
    $('#accountAccess').html('Welcome Guest | <a href="javascript:void(0);" id="login_link">Login</a>');
}
</code>```

Any ideas? Thanks.

答:
Hi. Can you please try this

```<code><div id="account">
<!-- No need for script tag <script type="text/javascript">  -->
<?php
if(loggedIn())
{
    echo "hideLogin();";
}
else
{
    echo "showLogin();";
}
?>
<!-- No need for script tag </script> -->

</div>
function hideLogin()
{
        $('#accountAccess').html('Welcome <?php echo $_SESSION["firstName"]; ?> |  <a href="logout.php">Logout</a>');
}

function showLogin()
{
    $('#accountAccess').html('Welcome Guest | <a href="javascript:void(0);" id="login_link">Login</a>');
}
</code>```

Title: jquery hyperlink in firefox

Body:
I have the code below which checks if a user is logged in, if they are it echo's out a javascript function hideLogin() otherwise it will echo the function showLogin() . This works fine on every browser I have tested in, but firefox. The link is not clickable, where as it is in every other browser I tested in.

function hideLogin()
{
        $('#accountAccess').html('Welcome <?php echo $_SESSION["firstName"]; ?> |  Logout');
}

function showLogin()
{
    $('#accountAccess').html('Welcome Guest | Login');
}

Any ideas? Thanks.

Body:
Hi. Can you please try this

<div id="account">
<!-- No need for script tag <script type="text/javascript">  -->
<?php
if(loggedIn())
{
    echo "hideLogin();";
}
else
{
    echo "showLogin();";
}
?>
<!-- No need for script tag </script> -->

</div>
function hideLogin()
{
        $('#accountAccess').html('Welcome <?php echo $_SESSION["firstName"]; ?> |  <a href="logout.php">Logout</a>');
}

function showLogin()
{
    $('#accountAccess').html('Welcome Guest | <a href="javascript:void(0);" id="login_link">Login</a>');
}


问:
Is there a way to use parameters in Jenkins job description field?
I have a job creator job that creates other jobs in jenkins and I would like to use the created jobs name in the description.

For example for name "JobXX" i would like to have:
"This is documentation for JobXX etc.."

In "Execute shell" build step I can refer to the jobs name via $JOB_NAME parameter but that does not seem to work in the description field.

Any ideas on how to do this? Or if it's even possible?

答:
Never used it, but take a look to the Project Description Setter Plugin:
https://wiki.jenkins.io/display/JENKINS/Project+Description+Setter+Plugin

In this blog it explains better how to use it:
http://www.tothenew.com/blog/setting-dynamic-project-description-and-build-description-in-jenkins/

Among the different variables you can use there is {PROJECT_NAME} which fits your needs.

Besides this, this plugin allows you also to automatically set descriptions to each specific build.

ContentLicense: CC BY-SA 3.0


问:
configure: error: memcache support requires ZLIB.
When try to configuring memcache with php in xmapp server by following steps shows error.

#  /opt/lampp/bin/phpize

```<code>Configuring for:
PHP Api Version:         20131106
Zend Module Api No:      20131226
Zend Extension Api No:   220131226

# ./configure --enable-memcache --with-php-config=/opt/lampp/bin/php-config
</code>```

Show errors:

hecking for the location of ZLIB... no checking for the location of
  zlib... configure: error: memcache support requires ZLIB. Use
  --with-zlib-dir= to specify prefix where ZLIB include and library are located

答:
```<code>sudo apt-get install zlib1g-dev
</code>```

<p>for debian stretch </p>

Body:
When try to configuring memcache with php in xmapp server by following steps shows error.

#  /opt/lampp/bin/phpize

Configuring for:
PHP Api Version:         20131106
Zend Module Api No:      20131226
Zend Extension Api No:   220131226

# ./configure --enable-memcache --with-php-config=/opt/lampp/bin/php-config

Show errors:

hecking for the location of ZLIB... no checking for the location of
  zlib... configure: error: memcache support requires ZLIB. Use
  --with-zlib-dir= to specify prefix where ZLIB include and library are located

Body:
sudo apt-get install zlib1g-dev

for debian stretch


问:
How can I stub a constructor in node.js using sinon in a Cloud Functions for Firebase project?
I'm using GeoFire in a Cloud Functions for Firebase project I want to unit test.

In my original code GeoFire is used like this:

```<code>GeoFire = request('geofire');

...

var catGeoFire = new GeoFire(catGeofireRef);
return catGeoFire.set(storeId, [lat, lon]).then( () => {
    console.log("Added store " + storeId + " to GeoFire" );
        return Promise.resolve();
    });
</code>```

I need to stub both the call to the GeoFire constructor and the GeoFire().set() method.

I tried:

```<code>const geofireStub = sinon.stub(GeoFire, 'set').resolves();
</code>```

But I received the error:

```<code>TypeError: Cannot stub non-existent own property set
</code>```

I also tried:

```<code>const setStub = sinon.stub().resolves();
const geofireStub = sinon.stub(GeoFire).returns({set: setStub});
</code>```

And I receive the error:

```<code>TypeError: Cannot stub non-existent own property set
</code>```

Both errors happen at the geofireStub line.

Reading the sinon documentation I understood that I can stub an object's methods. However in this case GeoFire isn't an object; it is a constructor function. So I don't really know how can I stub it without having an associated object.

Thanks!

答:
You need something like this, using rewire:

// target.js
var GeoFire = require('geofire');

var catGeoFire = new GeoFire(catGeofireRef);
return catGeoFire.set(storeId, [lat, lon]).then(() => {
  console.log("Added store " + storeId + " to GeoFire" );
  return Promise.resolve();
});

// test.js
var GeoFire = require('geofire');
var rewire = require('rewire')
var target = rewire('./target')

describe('target', () => {
  it('test case', () => {
    // arrange

    // configure instance
    var geoFireStub = sinon.createStubInstance(GeoFire)
    geoFireStub.set.resolves()

    // configure constuctor
    var GeoFireMock = sinon.stub().returns(geoFireStub)

    // 'GeoFire' is a mocked variable here
    var revert = rewire('GeoFire', GeoFireMock)

    // act (call tested module)
    target()

    // assert (should is just for example)
    should(GeoFireMock).calledWithNew(/* params*/)
    should(geoFireStub.set).calledWith(/* params*/)

    //cleanup (rewire and stubs, prefer to use sandbox)
    revert();
    ...

  })
})```

Body:
I'm using GeoFire in a Cloud Functions for Firebase project I want to unit test.

In my original code GeoFire is used like this:

GeoFire = request('geofire');

...

var catGeoFire = new GeoFire(catGeofireRef);
return catGeoFire.set(storeId, [lat, lon]).then( () => {
    console.log("Added store " + storeId + " to GeoFire" );
        return Promise.resolve();
    });

I need to stub both the call to the GeoFire constructor and the GeoFire().set() method.

I tried:

const geofireStub = sinon.stub(GeoFire, 'set').resolves();

But I received the error:

TypeError: Cannot stub non-existent own property set

I also tried:

const setStub = sinon.stub().resolves();
const geofireStub = sinon.stub(GeoFire).returns({set: setStub});

And I receive the error:

TypeError: Cannot stub non-existent own property set

Both errors happen at the geofireStub line.

Reading the sinon documentation I understood that I can stub an object's methods. However in this case GeoFire isn't an object; it is a constructor function. So I don't really know how can I stub it without having an associated object.

Thanks!

ContentLicense: CC BY-SA 4.0


问:
Issue with the webpack-bundler
I am trying to compile all my tsx files which are in a folder using webpack-bundler ins a single bundle.js file.
my webpack.config.js is as this:

```<code>var glob = require('glob');
module.exports = {
    entry: toObject(glob.sync('./src/editor/**/*.ts*')),
    output: {
        filename: "bundle.js",
        path: __dirname + "/out",
        library:'bundle',
        libraryTarget:'var'
    },

    // Enable sourcemaps for debugging webpack's output.
    devtool: "source-map",

    resolve: {
        // Add '.ts' and '.tsx' as resolvable extensions.
        extensions: [".ts", ".tsx", ".js", ".json"]
    },

    module: {
        rules: [
            // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
            { test: /\.tsx?$/, loader: "awesome-typescript-loader" },

            // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
            { enforce: "pre", test: /\.js$/, loader: "source-map-loader" }
        ]
    },

    // When importing a module whose path matches one of the following, just
    // assume a corresponding global variable exists and use that instead.
    // This is important because it allows us to avoid bundling all of our
    // dependencies, which allows browsers to cache those libraries between builds.

};
function toObject(paths) {
  var ret = {};

  paths.forEach(function(path) {
    // you can define entry names mapped to [name] here
    ret[path.split('/').slice(-1)[0]] = path;
  });

  return ret;
}
</code>```

Now when i am trying to compile it it is giving me the error as

"Conflict: Multiple assets emit to the same filename [bundle].js".
The same error is coming for each and every file.
The files are individual in themselves.

can someone tell me the way of doing it?

答:
It seems that you have multiple entry points but they are compiling to a file with the same name - bundle.js. Try to replace:

```<code>output: {
        filename: "bundle.js",
        path: __dirname + "/out",
        library:'bundle',
        libraryTarget:'var'
    }
</code>```

with

```<code>output: {
        filename: "[name].js",
        path: __dirname + "/out",
        library:'bundle',
        libraryTarget:'var'
    }
</code>```

That way you'll get a separate bundle for each of your .ts files.

OR

Specify a single file name for the entry point of your app:

```<code>entry: './src/editor/somefolder/app.ts',
</code>```

Title: Issue with the webpack-bundler

Body:
I am trying to compile all my tsx files which are in a folder using webpack-bundler ins a single bundle.js file.
my webpack.config.js is as this:

var glob = require('glob');
module.exports = {
    entry: toObject(glob.sync('./src/editor/**/*.ts*')),
    output: {
        filename: "bundle.js",
        path: __dirname + "/out",
        library:'bundle',
        libraryTarget:'var'
    },

    // Enable sourcemaps for debugging webpack's output.
    devtool: "source-map",

    resolve: {
        // Add '.ts' and '.tsx' as resolvable extensions.
        extensions: [".ts", ".tsx", ".js", ".json"]
    },

    module: {
        rules: [
            // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
            { test: /\.tsx?$/, loader: "awesome-typescript-loader" },

            // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
            { enforce: "pre", test: /\.js$/, loader: "source-map-loader" }
        ]
    },

    // When importing a module whose path matches one of the following, just
    // assume a corresponding global variable exists and use that instead.
    // This is important because it allows us to avoid bundling all of our
    // dependencies, which allows browsers to cache those libraries between builds.

};
function toObject(paths) {
  var ret = {};

  paths.forEach(function(path) {
    // you can define entry names mapped to [name] here
    ret[path.split('/').slice(-1)[0]] = path;
  });

  return ret;
}

Now when i am trying to compile it it is giving me the error as

"Conflict: Multiple assets emit to the same filename [bundle].js".
The same error is coming for each and every file.
The files are individual in themselves.

can someone tell me the way of doing it?

Body:
It seems that you have multiple entry points but they are compiling to a file with the same name - bundle.js. Try to replace:

output: {
        filename: "bundle.js",
        path: __dirname + "/out",
        library:'bundle',
        libraryTarget:'var'
    }

with

output: {
        filename: "[name].js",
        path: __dirname + "/out",
        library:'bundle',
        libraryTarget:'var'
    }

That way you'll get a separate bundle for each of your .ts files.

OR

Specify a single file name for the entry point of your app:

entry: './src/editor/somefolder/app.ts',


问:
Optional parameters in python dict
Is there a way to include optional parameters into Python dictionary?

For example, I have the following return statements for get requests. They are dependent on the input and mostly identical.

If the region is passed as an input parameter, we have:

```<code>if region:
    return {
        'success': True,
        'result': {
            'country': country,
            'region': region, #  optional region param
            'cities': cities
        }
    }
</code>```

If the city is passed:

```<code>if city:
    return {
        'success': True,
        'result': {
            'country': country,
            'city': city, #  optional city param
            'cities': cities
        }
    }
</code>```

If nor city or region are passed:

```<code>return {
    'success': True,
    'result': {
        'country': country,
        'cities': cities
    }
}
</code>```

What I want is to have one return statement:

```<code>return {
    'success': True,
    'result': {
        'country': country,
        if region: 'region': region, #  I know this and the next lines don't work
        if city: 'city': city,
        'cities': cities
    }
}
</code>```

答:
Option 1

As mentioned in other answers, create a dictionary locally, and add optional parameters along the way.

Option 2

When using the dictionary returned from your function, use

retdict.get('city', 'defaultvalue') instead of retdict['city'] to make sure your don't fail on trying to get a non-existent parameter.

Option 3

Use defaultdict. Some easy-to-understand examples are listed in the Python Docs and here

Title: Optional parameters in python dict

Body:
Is there a way to include optional parameters into Python dictionary?

For example, I have the following return statements for get requests. They are dependent on the input and mostly identical.

If the region is passed as an input parameter, we have:

if region:
    return {
        'success': True,
        'result': {
            'country': country,
            'region': region, #  optional region param
            'cities': cities
        }
    }

If the city is passed:

if city:
    return {
        'success': True,
        'result': {
            'country': country,
            'city': city, #  optional city param
            'cities': cities
        }
    }

If nor city or region are passed:

return {
    'success': True,
    'result': {
        'country': country,
        'cities': cities
    }
}

What I want is to have one return statement:

return {
    'success': True,
    'result': {
        'country': country,
        if region: 'region': region, #  I know this and the next lines don't work
        if city: 'city': city,
        'cities': cities
    }
}


问:
Lost all my changes after git rebase --skip
I was working on a branch, after I commited my changes and tried to push them it said that I had diverged and needed to pull the most recent changes.

I did git pull --rebase which caused an rebase conflict. I couldt identify where the problem was. So I did git rebase --skip which seems to have reverted my changes to a version that is behind my commit.

Is it possible to reset to my commit that I tried to push? I did git reflog to find the commit ID. And then I tried git reset *commitID* But it does not seem to work. It does not reset. What can I do?

答: I did a git reset --hard *comitID*. Still dont know why a "normal" reset didnt work.


问:
What can I use to write a image with GTM?
I have to use a tag img with a dynamic URL, but the custom image option of GTM I can't build the URL dynamic, I can use variables but for example, I cannot do a join to an array.
So I tried document.write() the image but it doesn't make any request. The code is similiar to this.

```<code><script>
  var data = '<img src="https://dynamicURL.com/?var=test1^test2^test3”>';

  document.write(data);
</script>
</code>```

The option of document.write is turned on.

答:
If you need the image to send data to end endpoint you can use the custom image tag template.

If for some reason you insist on custom HTML you can use a custom HTML tag and do:

```<code><script>
var img = new Image();
img.src = "https://dynamicURL.com/?var=test1^test2^test3";
</script>
</code>```

Do not use document.write, that's just horrible.

To send data the image does not actually be inserted into the DOM. If you want the image to appear in any specific place you need to select and element, create the Image, and then append the image to the element.

Body:
I have to use a tag img with a dynamic URL, but the custom image option of GTM I can't build the URL dynamic, I can use variables but for example, I cannot do a join to an array.
So I tried document.write() the image but it doesn't make any request. The code is similiar to this.

The option of document.write is turned on.

Body:
If you need the image to send data to end endpoint you can use the custom image tag template.

If for some reason you insist on custom HTML you can use a custom HTML tag and do:

<script>
var img = new Image();
img.src = "https://dynamicURL.com/?var=test1^test2^test3";
</script>

Do not use document.write, that's just horrible.

To send data the image does not actually be inserted into the DOM. If you want the image to appear in any specific place you need to select and element, create the Image, and then append the image to the element.


问:
Post action option for SQL*Loader
In my project, we are using SQL*Loader for loading a set of data. If this load is successful we want to execute another SQL instruction. Does SQL*Loader have any option for that?</p>

答:
I don't know of any inbuilt feature to do things on success, rather you can write a wrapper to do so. The return codes come handy here

For Linux and UNIX operating systems, the exit codes are as follows:

```<code>EX_SUCC 0
EX_FAIL 1
EX_WARN 2
EX_FTL  3
</code>```

For Windows operating systems, the exit codes are as follows:

```<code>EX_SUCC 0
EX_FAIL 1
EX_WARN 2
EX_FTL  4
</code>```

Title: Post action option for SQL*Loader

Body:
I don't know of any inbuilt feature to do things on success, rather you can write a wrapper to do so. The return codes come handy here

For Linux and UNIX operating systems, the exit codes are as follows:

EX_SUCC 0
EX_FAIL 1
EX_WARN 2
EX_FTL  3

For Windows operating systems, the exit codes are as follows:

EX_SUCC 0
EX_FAIL 1
EX_WARN 2
EX_FTL  4


问:
Iterating over pandas rows to get minimum
Here is my dataframe:

```<code>Date         cell         tumor_size(mm)
25/10/2015    113           51
22/10/2015    222           50
22/10/2015    883           45
20/10/2015    334           35
19/10/2015    564           47
19/10/2015    123           56
22/10/2014    345           36
13/12/2013    456           44
</code>```

What I want to do is compare the size of the tumors detected on the different days. Let's consider the cell 222 as an example; I want to compare its size to different cells but detected on earlier days e.g. I will not compare its size with cell 883, because they were detected on the same day. Or I will not compare it with cell 113, because it was detected later on.
As my dataset is too large, I have iterate over the rows. If I explain it in a non-pythonic way:

```<code>for the cell 222:
     get_size_distance(absolute value):
          (50 - 35 = 15), (50 - 47 = 3), (50 - 56 = 6), (50 - 36 = 14), (44 - 36 = 8)
     get_minumum = 3, I got this value when I compared it with 564, so I will name it as a pait for the cell 222
Then do it for the cell 883
</code>```

The resulting output should look like this:

```<code>   Date         cell         tumor_size(mm)   pair    size_difference
    25/10/2015    113           51            222        1
    22/10/2015    222           50            123        6
    22/10/2015    883           45            456        1
    20/10/2015    334           35            345        1
    19/10/2015    564           47            456        3
    19/10/2015    123           56            456        12
    22/10/2014    345           36            456        8
    13/12/2013    456           44            NaN        NaN
</code>```

I will really appreciate your help

答:
It's not pretty, but I believe it does the trick

```<code>a = pd.read_clipboard()
# Cut off last row since it was a faulty date. You can skip this.
df = a.copy().iloc[:-1]

# Convert to dates and order just in case (not really needed I guess).
df['Date'] = df.Date.apply(lambda x: datetime.strptime(x, '%d/%m/%Y'))
df.sort_values('Date', ascending=False)
# Rename column
df = df.rename(columns={"tumor_size(mm)": 'tumor_size'})

# These will be our lists of pairs and size differences.
pairs = []
diffs = []

# Loop over all unique dates
for date in df.Date.unique():
    # Only take dates earlier then current date.
    compare_df = df.loc[df.Date < date].copy()
    # Loop over each cell for this date and find the minimum
    for row in df.loc[df.Date == date].itertuples():
        # If no cells earlier are available use nans.
        if compare_df.empty:
            pairs.append(float('nan'))
            diffs.append(float('nan'))
        # Take lowest absolute value and fill in otherwise
        else:
            compare_df['size_diff'] = abs(compare_df.tumor_size - row.tumor_size)
            row_of_interest = compare_df.loc[compare_df.size_diff == compare_df.size_diff.min()]
            pairs.append(row_of_interest.cell.values[0])
            diffs.append(row_of_interest.size_diff.values[0])

df['pair'] = pairs
df['size_difference'] = diffs
</code>```

returns:

```<code>Date    cell    tumor_size  pair    size_difference
0   2015-10-25  113 51  222.0   1.0
1   2015-10-22  222 50  564.0   3.0
2   2015-10-22  883 45  564.0   2.0
3   2015-10-20  334 35  345.0   1.0
4   2015-10-19  564 47  345.0   11.0
5   2015-10-19  123 56  345.0   20.0
6   2014-10-22  345 36  NaN NaN
</code>```

Body:
Here is my dataframe:

Date         cell         tumor_size(mm)
25/10/2015    113           51
22/10/2015    222           50
22/10/2015    883           45
20/10/2015    334           35
19/10/2015    564           47
19/10/2015    123           56
22/10/2014    345           36
13/12/2013    456           44

What I want to do is compare the size of the tumors detected on the different days. Let's consider the cell 222 as an example; I want to compare its size to different cells but detected on earlier days e.g. I will not compare its size with cell 883, because they were detected on the same day. Or I will not compare it with cell 113, because it was detected later on.
As my dataset is too large, I have iterate over the rows. If I explain it in a non-pythonic way:

for the cell 222:
     get_size_distance(absolute value):
          (50 - 35 = 15), (50 - 47 = 3), (50 - 56 = 6), (50 - 36 = 14), (44 - 36 = 8)
     get_minumum = 3, I got this value when I compared it with 564, so I will name it as a pait for the cell 222
Then do it for the cell 883

The resulting output should look like this:

   Date         cell         tumor_size(mm)   pair    size_difference
    25/10/2015    113           51            222        1
    22/10/2015    222           50            123        6
    22/10/2015    883           45            456        1
    20/10/2015    334           35            345        1
    19/10/2015    564           47            456        3
    19/10/2015    123           56            456        12
    22/10/2014    345           36            456        8
    13/12/2013    456           44            NaN        NaN

I will really appreciate your help

Body:
It's not pretty, but I believe it does the trick

a = pd.read_clipboard()
# Cut off last row since it was a faulty date. You can skip this.
df = a.copy().iloc[:-1]

# Convert to dates and order just in case (not really needed I guess).
df['Date'] = df.Date.apply(lambda x: datetime.strptime(x, '%d/%m/%Y'))
df.sort_values('Date', ascending=False)
# Rename column
df = df.rename(columns={"tumor_size(mm)": 'tumor_size'})

# These will be our lists of pairs and size differences.
pairs = []
diffs = []

# Loop over all unique dates
for date in df.Date.unique():
    # Only take dates earlier then current date.
    compare_df = df.loc[df.Date < date].copy()
    # Loop over each cell for this date and find the minimum
    for row in df.loc[df.Date == date].itertuples():
        # If no cells earlier are available use nans.
        if compare_df.empty:
            pairs.append(float('nan'))
            diffs.append(float('nan'))
        # Take lowest absolute value and fill in otherwise
        else:
            compare_df['size_diff'] = abs(compare_df.tumor_size - row.tumor_size)
            row_of_interest = compare_df.loc[compare_df.size_diff == compare_df.size_diff.min()]
            pairs.append(row_of_interest.cell.values[0])
            diffs.append(row_of_interest.size_diff.values[0])

df['pair'] = pairs
df['size_difference'] = diffs

returns:

Date    cell    tumor_size  pair    size_difference
0   2015-10-25  113 51  222.0   1.0
1   2015-10-22  222 50  564.0   3.0
2   2015-10-22  883 45  564.0   2.0
3   2015-10-20  334 35  345.0   1.0
4   2015-10-19  564 47  345.0   11.0
5   2015-10-19  123 56  345.0   20.0
6   2014-10-22  345 36  NaN NaN


问:
Webgraphviz output does not wrap around the page for decision tree
I need the image of the complete tree that I generated but it does not wrap around neither there is a download or save image option.
The only remaining option is to take a screenshot which doesn't capture the entire tree.

How do I get the entire tree?

I've generated a tree using this method in Spyder

```<code>#Displaying the decision tree
from sklearn import tree
#from StringIO import StringIO
from io import StringIO
#from StringIO import StringIO
with open("classifier.txt", "w") as f:
 f = tree.export_graphviz(classifier, out_file=f)
</code>```

This generates a file classifer.txt which when copied and pasted into http://webgraphviz.com/ generates a decision tree

Here is the image of the output

The snapshot has zoomed out to the maximum possible extent.

答:
Ok So I've fixed the solution by doing some extensive googling and now am able to save it as a png.

Displaying the decision tree

```<code>graph=pydotplus.graph_from_dot_data(out.getvalue())

“’ # Display inline image of Tree - Inline image is not useful

Img=(Image(graph.create_png()))

display(Img)

”’

#Write image to file so it can be rotated and expanded

graph.write_png('Your_File_Name.png’)
</code>```

Body:
I need the image of the complete tree that I generated but it does not wrap around neither there is a download or save image option.
The only remaining option is to take a screenshot which doesn't capture the entire tree.

How do I get the entire tree?

I've generated a tree using this method in Spyder

#Displaying the decision tree
from sklearn import tree
#from StringIO import StringIO
from io import StringIO
#from StringIO import StringIO
with open("classifier.txt", "w") as f:
 f = tree.export_graphviz(classifier, out_file=f)

This generates a file classifer.txt which when copied and pasted into http://webgraphviz.com/ generates a decision tree

Here is the image of the output

The snapshot has zoomed out to the maximum possible extent.

Body:
Ok So I've fixed the solution by doing some extensive googling and now am able to save it as a png.

Displaying the decision tree

graph=pydotplus.graph_from_dot_data(out.getvalue())

“’ # Display inline image of Tree - Inline image is not useful

Img=(Image(graph.create_png()))

display(Img)

”’

#Write image to file so it can be rotated and expanded

graph.write_png('Your_File_Name.png’)


问:
Error Configuration : Unable to locate Spring NamespaceHandler for XML schema namespace
I am getting below error in spring service application. Please help me anyone.Context initialization failed due to below error.

Error

Context initialization failed
rg.springframework.beans.factory.parsing.BeanDefinitionParsingException:
Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schem/integration/ftp]
Spring configuration

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:int="http://www.springframework.org/schema/integration"
   xmlns:int-ftp="http://www.springframework.org/schema/integration/ftp"
   xsi:schemaLocation="http://www.springframework.org/schema/integration/ftp
http://www.springframework.org/schema/integration/ftp/spring-integration-
ftp.xsd
            http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="ftpClientFactory" class="org.springframework.integration.ftp.session.DefaultFtpSessionFactory">
    <property name="host" value="test.rebex.net"/>
    <property name="port" value="21"/>
    <property name="username" value="demo"/>
    <property name="password" value="password"/>
</bean>

<int-ftp:inbound-channel-adapter id="ftpInbound"
            channel="ftpChannel"
            session-factory="ftpClientFactory"
            filename-pattern="readme.txt"
            auto-create-local-directory="true"
            delete-remote-files="false"
            remote-directory="/pub/example/"
            local-directory="C:/Users/TOOW10/temp/">
        <int:poller fixed-rate="1000"/>
</int-ftp:inbound-channel-adapter>

<int:channel id="ftpChannel">
    <int:queue/>
</int:channel>
</code>```

pom.xml

```<code>    <dependencies>
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-server</artifactId>
        <version>2.25.1</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.5</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.annotation/jsr250-api -->
    <!-- https://mvnrepository.com/artifact/com.google.code.findbugs/jsr305 -->
    <dependency>
        <groupId>com.google.code.findbugs</groupId>
        <artifactId>jsr305</artifactId>
        <version>2.0.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.json/json -->
    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.9</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.integration</groupId>
        <artifactId>spring-integration-core</artifactId>
        <version>4.1.2.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>com.hybris.datahub</groupId>
        <artifactId>datahub-extension-sdk</artifactId>
        <version>6.5.0.0-RC3</version>
        <scope>provided</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework.integration/spring-integration-ftp -->
    <dependency>
        <groupId>org.springframework.integration</groupId>
        <artifactId>spring-integration-ftp</artifactId>
        <version>4.1.0.RELEASE</version>
    </dependency>

</dependencies>
<properties>
    <spring.version>4.3.3.RELEASE</spring.version>
</properties>
</code>```

答:
It appears you have a new line between integration- and ftp.xsd. I get a different error with that but it should be fixed.

If that's not the problem, there's something wrong with your classpath. Double check that maven has put the spring-integration-ftp jar on the classpath.

Body:
I am getting below error in spring service application. Please help me anyone.Context initialization failed due to below error.

Error

Context initialization failed
rg.springframework.beans.factory.parsing.BeanDefinitionParsingException:
Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schem/integration/ftp]
Spring configuration

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:int="http://www.springframework.org/schema/integration"
   xmlns:int-ftp="http://www.springframework.org/schema/integration/ftp"
   xsi:schemaLocation="http://www.springframework.org/schema/integration/ftp
http://www.springframework.org/schema/integration/ftp/spring-integration-
ftp.xsd
            http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="ftpClientFactory" class="org.springframework.integration.ftp.session.DefaultFtpSessionFactory">
    <property name="host" value="test.rebex.net"/>
    <property name="port" value="21"/>
    <property name="username" value="demo"/>
    <property name="password" value="password"/>
</bean>

<int-ftp:inbound-channel-adapter id="ftpInbound"
            channel="ftpChannel"
            session-factory="ftpClientFactory"
            filename-pattern="readme.txt"
            auto-create-local-directory="true"
            delete-remote-files="false"
            remote-directory="/pub/example/"
            local-directory="C:/Users/TOOW10/temp/">
        <int:poller fixed-rate="1000"/>
</int-ftp:inbound-channel-adapter>

<int:channel id="ftpChannel">
    <int:queue/>
</int:channel>

pom.xml

    <dependencies>
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-server</artifactId>
        <version>2.25.1</version>
    </dependency>

    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.5</version>
    </dependency>

    <dependency>
        <groupId>com.google.code.findbugs</groupId>
        <artifactId>jsr305</artifactId>
        <version>2.0.1</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.9</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.integration</groupId>
        <artifactId>spring-integration-core</artifactId>
        <version>4.1.2.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>com.hybris.datahub</groupId>
        <artifactId>datahub-extension-sdk</artifactId>
        <version>6.5.0.0-RC3</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.integration</groupId>
        <artifactId>spring-integration-ftp</artifactId>
        <version>4.1.0.RELEASE</version>
    </dependency>

</dependencies>
<properties>
    <spring.version>4.3.3.RELEASE</spring.version>
</properties>


问:
How to work out the complexity of an algorithm?
I have two questions for algorithm analysis, and would like to know how to determine the complexity of the following two:

First:

```<code>For(int i=2; i<n; i=i*i*i)
{
  //something O(1)
}
</code>```

Second:

```<code>n/1 + n/2 + n/3 +...+ n/n
</code>```

答:
To the first:

It will be infinite, because 1*1*1 = 1 so i is always 1 and will never be >= n.

The second algorithm is not really an algorithm but the addition runs in O(n).

Body:
I have two questions for algorithm analysis, and would like to know how to determine the complexity of the following two:

First:

For(int i=2; i<n; i=i*i*i)
{
  //something O(1)
}

Second:

n/1 + n/2 + n/3 +...+ n/n


问:
How to copy paste a modal
For a school project I want to make modals for every student in my class. My problem is that only the first modal is working.

// Get the modal
var modal = document.getElementById('myModal');

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the  element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on the button, open the modal
btn.onclick = function() {
  modal.style.display = "block";
}

// When the user clicks on  (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* The Modal (background) */

.modal {
  display: none;
  /* Hidden by default */
  position: fixed;
  /* Stay in place */
  z-index: 1;
  /* Sit on top */
  left: 0;
  top: 0;
  width: 100%;
  /* Full width */
  height: 100%;
  /* Full height */
  overflow: auto;
  /* Enable scroll if needed */
  background-color: rgb(0, 0, 0);
  /* Fallback color */
  background-color: rgba(0, 0, 0, 0.4);
  /* Black w/ opacity */
}

/* Modal Content/Box */

.modal-content {
  background-color: #fefefe;
  margin: 14% auto;
  /* 15% from the top and centered */
  padding: 20px;
  border: none;
  width: 80%;
  /* Could be more or less, depending on screen size */
  box-shadow: 0 10px 20px 0px rgba(0, 0, 0, 0.5);
}

/* The Close Button */

.close {
  color: #aaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}

/* Button Design */

#myBtn {
  background-image: url(/images/blank-profile-picture-973460_960_720.png);
  font-family: Lato-Bold;
  font-size: 20px;
  background-color: rgb(55, 154, 177);
  background-size: cover;
  width: 300px;
  height: 300px;
  margin: 10px;
  float: left;
  text-align: center;
  color: white;
  border: 0;
  cursor: pointer;
}

p.Info {
  font-family: Lato-regular;
  font-size: 15px;
  color: rgb(40, 40, 40);
}</code>```

<button id="myBtn">Anthony</button>

    ×

      Nachname:König
 Vorname:Anthony

 Geburtstag:24.12.1998

 Herkunft:Deutschland

 Adresse:xxxxxxxxxxxxxxxxx

 Mobilnummer:xxxxxxxxxxxxxx

 E-Mail:xxxxxxxxxxxxxxxxxbr> Fachlicher Schwerpunkt:Programmieren
 Hobbys:Basketball, Tennis, Krafttraining, Gaming und Fussball.
 Socialmedia:url Facebook: url Instagram:
 Snapcode: anthony.k1ng

<button id="myBtn">David</button>

    ×

      Nachname:König
 Vorname:Anthony

 Geburtstag:24.12.1998

 Herkunft:Deutschland

 Adresse:xxxxxxxxxxxxxxxxxxxxxx

 Mobilnummer:xxxxxxxxxxxxxxxxxx

 E-Mail:xxxxxxxxxxxxxxxx

 Fachlicher Schwerpunkt:Programmieren
 Hobbys:Basketball, Tennis, Krafttraining, Gaming und Fussball.
 Socialmedia:url Facebook: url Instagram:
 Snapcode: anthony.k1ng

```

答:
From you codes, you gave the two modals the same id myModal. In html, an Id can exist only once on the page. The first modal where that Id exist will be the only one triggered as same thing goes for your buttons too.
Change the individual Id of the buttons and also of the modals and then target them respectively based on the button clicked. Same thing should be done for your close button too

Change your JavaScript to this

```<code> var modal1 = document.getElementById('myModal1');
var modal2 = document.getElementById('myModal2');
// Get the button that opens the modal
var btn1 = document.getElementById("myBtn1");
var btn2 = document.getElementById("myBtn2");

// Get the <span> element that closes the modal
var span1 = document.getElementById("close1");
var span2 = document.getElementById("close2");
// When the user clicks on the button, open the modal
btn1.onclick = function() {
    modal1.style.display = "block";
}
btn2.onclick = function() {
    modal2.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span1.onclick = function() {
    modal1.style.display = "none";
}
span2.onclick = function() {
    modal2.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal1) {
        modal1.style.display = "none";
    }
    if (event.target == modal2) {
        modal2.style.display = "none";
    }
}
</code>```

And Your html to this

```<code>   <!-- Trigger/Open The Modal -->
<button id="myBtn1" class="myBtn">Anthony</button>

<!-- The Modal -->
<div id="myModal1" class="modal">

<!-- Modal content -->
<div class="modal-content">
<span class="close" id="close1">×</span>
<p class="Info">
Nachname:König<br>
Vorname:Anthony<br>
Geburtstag:24.12.1998<br>
Herkunft:Deutschland<br>
Adresse:xxxxxxxxxxxxxxxxx<br>
Mobilnummer:xxxxxxxxxxxxxx<br>
E-Mail:xxxxxxxxxxxxxxxxxbr>
Fachlicher Schwerpunkt:Programmieren<br>
Hobbys:Basketball, Tennis, Krafttraining, Gaming und Fussball.<br>
Socialmedia:url Facebook: url Instagram:<br>
Snapcode: anthony.k1ng<br>
</p>
</div>

</div>
 <!-- Trigger/Open The Modal -->
<button id="myBtn2" class="myBtn">David</button>

<!-- The Modal -->
<div id="myModal2" class="modal">

<!-- Modal content -->
<div class="modal-content">
<span class="close" id="close2">×</span>
<p class="Info">
Nachname:König<br>
Vorname:Anthony<br>
Geburtstag:24.12.1998<br>
Herkunft:Deutschland<br>
Adresse:xxxxxxxxxxxxxxxxxxxxxx<br>
Mobilnummer:xxxxxxxxxxxxxxxxxx<br>
E-Mail:xxxxxxxxxxxxxxxx<br>
Fachlicher Schwerpunkt:Programmieren<br>
Hobbys:Basketball, Tennis, Krafttraining, Gaming und Fussball.<br>
Socialmedia:url Facebook: url Instagram:<br>
Snapcode: anthony.k1ng<br>
</p>
</div>

</div>
</code>```

And then the CSS
/* The Modal (background) */

```<code>.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content/Box */
.modal-content {
    background-color: #fefefe;
    margin: 14% auto; /* 15% from the top and centered */
    padding: 20px;
    border: none;
    width: 80%; /* Could be more or less, depending on screen size */
        box-shadow: 0 10px 20px 0px rgba(0, 0, 0, 0.5);
}

/* The Close Button */
.close {
    color: #aaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: black;
    text-decoration: none;
    cursor: pointer;
}
/* Button Design */
.myBtn {
  background-image: url(/images/blank-profile-picture-973460_960_720.png);
   font-family: Lato-Bold;
   font-size: 20px;
   background-color: rgb(55, 154, 177);
   background-size:cover;
   width: 300px;
   height: 300px;
   margin: 10px;
   float: left;
   text-align: center;
   color:white;
   border:0;
   cursor: pointer;
}

p.Info {
     font-family: Lato-regular;
     font-size: 15px;
     color: rgb(40, 40, 40);

}
</code>```

Title: How to copy paste a modal

Body:
For a school project I want to make modals for every student in my class. My problem is that only the first modal is working.

// Get the modal
var modal = document.getElementById('myModal');

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the  element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on the button, open the modal
btn.onclick = function() {
  modal.style.display = "block";
}

// When the user clicks on  (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}

/* The Modal (background) */

.modal {
  display: none;
  /* Hidden by default */
  position: fixed;
  /* Stay in place */
  z-index: 1;
  /* Sit on top */
  left: 0;
  top: 0;
  width: 100%;
  /* Full width */
  height: 100%;
  /* Full height */
  overflow: auto;
  /* Enable scroll if needed */
  background-color: rgb(0, 0, 0);
  /* Fallback color */
  background-color: rgba(0, 0, 0, 0.4);
  /* Black w/ opacity */
}

/* Modal Content/Box */

.modal-content {
  background-color: #fefefe;
  margin: 14% auto;
  /* 15% from the top and centered */
  padding: 20px;
  border: none;
  width: 80%;
  /* Could be more or less, depending on screen size */
  box-shadow: 0 10px 20px 0px rgba(0, 0, 0, 0.5);
}

/* The Close Button */

.close {
  color: #aaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}

/* Button Design */

#myBtn {
  background-image: url(/images/blank-profile-picture-973460_960_720.png);
  font-family: Lato-Bold;
  font-size: 20px;
  background-color: rgb(55, 154, 177);
  background-size: cover;
  width: 300px;
  height: 300px;
  margin: 10px;
  float: left;
  text-align: center;
  color: white;
  border: 0;
  cursor: pointer;
}

p.Info {
  font-family: Lato-regular;
  font-size: 15px;
  color: rgb(40, 40, 40);
}

<button id="myBtn">Anthony</button>

    ×

      Nachname:König
 Vorname:Anthony

 Geburtstag:24.12.1998

 Herkunft:Deutschland

 Adresse:xxxxxxxxxxxxxxxxx

 Mobilnummer:xxxxxxxxxxxxxx

 E-Mail:xxxxxxxxxxxxxxxxxbr> Fachlicher Schwerpunkt:Programmieren
 Hobbys:Basketball, Tennis, Krafttraining, Gaming und Fussball.
 Socialmedia:url Facebook: url Instagram:
 Snapcode: anthony.k1ng

<button id="myBtn">David</button>

    ×

      Nachname:König
 Vorname:Anthony

 Geburtstag:24.12.1998

 Herkunft:Deutschland

 Adresse:xxxxxxxxxxxxxxxxxxxxxx

 Mobilnummer:xxxxxxxxxxxxxxxxxx

 E-Mail:xxxxxxxxxxxxxxxx

 Fachlicher Schwerpunkt:Programmieren
 Hobbys:Basketball, Tennis, Krafttraining, Gaming und Fussball.
 Socialmedia:url Facebook: url Instagram:
 Snapcode: anthony.k1ng

Body:
From you codes, you gave the two modals the same id myModal. In html, an Id can exist only once on the page. The first modal where that Id exist will be the only one triggered as same thing goes for your buttons too.
Change the individual Id of the buttons and also of the modals and then target them respectively based on the button clicked. Same thing should be done for your close button too

Change your JavaScript to this

 var modal1 = document.getElementById('myModal1');
var modal2 = document.getElementById('myModal2');
// Get the button that opens the modal
var btn1 = document.getElementById("myBtn1");
var btn2 = document.getElementById("myBtn2");

// Get the <span> element that closes the modal
var span1 = document.getElementById("close1");
var span2 = document.getElementById("close2");
// When the user clicks on the button, open the modal
btn1.onclick = function() {
    modal1.style.display = "block";
}
btn2.onclick = function() {
    modal2.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span1.onclick = function() {
    modal1.style.display = "none";
}
span2.onclick = function() {
    modal2.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal1) {
        modal1.style.display = "none";
    }
    if (event.target == modal2) {
        modal2.style.display = "none";
    }
}

And Your html to this

   <!-- Trigger/Open The Modal -->
<button id="myBtn1" class="myBtn">Anthony</button>

<!-- The Modal -->
<div id="myModal1" class="modal">

<!-- Modal content -->
<div class="modal-content">
<span class="close" id="close1">&times;</span>
<p class="Info">
Nachname:König<br>
Vorname:Anthony<br>
Geburtstag:24.12.1998<br>
Herkunft:Deutschland<br>
Adresse:xxxxxxxxxxxxxxxxx<br>
Mobilnummer:xxxxxxxxxxxxxx<br>
E-Mail:xxxxxxxxxxxxxxxxxbr>
Fachlicher Schwerpunkt:Programmieren<br>
Hobbys:Basketball, Tennis, Krafttraining, Gaming und Fussball.<br>
Socialmedia:url Facebook: url Instagram:<br>
Snapcode: anthony.k1ng<br>
</p>
</div>

</div>
 <!-- Trigger/Open The Modal -->
<button id="myBtn2" class="myBtn">David</button>

<!-- The Modal -->
<div id="myModal2" class="modal">

<!-- Modal content -->
<div class="modal-content">
<span class="close" id="close2">&times;</span>
<p class="Info">
Nachname:König<br>
Vorname:Anthony<br>
Geburtstag:24.12.1998<br>
Herkunft:Deutschland<br>
Adresse:xxxxxxxxxxxxxxxxxxxxxx<br>
Mobilnummer:xxxxxxxxxxxxxxxxxx<br>
E-Mail:xxxxxxxxxxxxxxxx<br>
Fachlicher Schwerpunkt:Programmieren<br>
Hobbys:Basketball, Tennis, Krafttraining, Gaming und Fussball.<br>
Socialmedia:url Facebook: url Instagram:<br>
Snapcode: anthony.k1ng<br>
</p>
</div>

</div>

And then the CSS
/* The Modal (background) */

.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content/Box */
.modal-content {
    background-color: #fefefe;
    margin: 14% auto; /* 15% from the top and centered */
    padding: 20px;
    border: none;
    width: 80%; /* Could be more or less, depending on screen size */
        box-shadow: 0 10px 20px 0px rgba(0, 0, 0, 0.5);
}

/* The Close Button */
.close {
    color: #aaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: black;
    text-decoration: none;
    cursor: pointer;
}
/* Button Design */
.myBtn {
  background-image: url(/images/blank-profile-picture-973460_960_720.png);
   font-family: Lato-Bold;
   font-size: 20px;
   background-color: rgb(55, 154, 177);
   background-size:cover;
   width: 300px;
   height: 300px;
   margin: 10px;
   float: left;
   text-align: center;
   color:white;
   border:0;
   cursor: pointer;
}

p.Info {
     font-family: Lato-regular;
     font-size: 15px;
     color: rgb(40, 40, 40);

}


问:
Resuming a thread by using notifyAll
Take the Pausing a Thread example. If I use notifyAll instead of notify, is there any side effect, and is it necessary?

答: In “Effective Java” item 69, Bloch suggests “always use notifyAll”.

Title: Resuming a thread by using notifyAll


问:
Xcode 9.1 - Ambigous reference to member filter
I already experienced this issue in the past, I fixed it.

But today I just download the new Xcode version 9.1 and my App is not building anymore, I got :

Ambiguous reference to member 'filter'

I don't know why, this is not the piece of code I was working on. The app is building/compiling fine since weeks.

When I check the Release Note on the Official Apple Website, I don't seem to find any reference to my issue.

So here is the piece of code that was working perfectly 2 hours ago :

```<code>var severeWeather: Results<SevereWeather>?
var vigiArray = Array<SevereWeather>()
var redCount: Int = 0

severeWeather = realm.objects(SevereWeather.self).filter(NSPredicate(format: "department != nil"))
.sorted(byKeyPath: "departmentNumber")

vigiArray = Array(severeWeather!)

redCount = vigiArray.filter { $0.dangerLevels.filter { $0.level.value == 4 }.count > 0 }.count
</code>```

What is wrong with my code ?

答:
RealmCollection also has a filter method, which is implemented differently. For some reason, Swift compiler doesn't know which one it should refer.

What about this:

```<code>redCount = vigiArray.filter {
    return $0.dangerLevels.filter(NSPredicate(format: "%K == %@", "level.value", NSNumber(integerLiteral: 4))).count > 0
}.count
</code>```

Instead of accessing each element in dangerLevels yourself, build Predicate and let realm do the job for you.

Replace your nest filter with this and it should be compiling just fine.

Body:
I already experienced this issue in the past, I fixed it.

But today I just download the new Xcode version 9.1 and my App is not building anymore, I got :

Ambiguous reference to member 'filter'

I don't know why, this is not the piece of code I was working on. The app is building/compiling fine since weeks.

When I check the Release Note on the Official Apple Website, I don't seem to find any reference to my issue.

So here is the piece of code that was working perfectly 2 hours ago :

var severeWeather: Results<SevereWeather>?
var vigiArray = Array<SevereWeather>()
var redCount: Int = 0

severeWeather = realm.objects(SevereWeather.self).filter(NSPredicate(format: "department != nil"))
.sorted(byKeyPath: "departmentNumber")

vigiArray = Array(severeWeather!)

redCount = vigiArray.filter { $0.dangerLevels.filter { $0.level.value == 4 }.count > 0 }.count

What is wrong with my code ?

Body:
RealmCollection also has a filter method, which is implemented differently. For some reason, Swift compiler doesn't know which one it should refer.

What about this:

redCount = vigiArray.filter {
    return $0.dangerLevels.filter(NSPredicate(format: "%K == %@", "level.value", NSNumber(integerLiteral: 4))).count > 0
}.count

Instead of accessing each element in dangerLevels yourself, build Predicate and let realm do the job for you.

Replace your nest filter with this and it should be compiling just fine.


问:
Is it bad practice to make a setter return "this"?
Is it a good or bad idea to make setters in java return "this"?

```<code>public Employee setName(String name){
   this.name = name;
   return this;
}
</code>```

This pattern can be useful because then you can chain setters like this:

```<code>list.add(new Employee().setName("Jack Sparrow").setId(1).setFoo("bacon!"));
</code>```

instead of this:

```<code>Employee e = new Employee();
e.setName("Jack Sparrow");
...and so on...
list.add(e);
</code>```

...but it sort of goes against standard convention. I suppose it might be worthwhile just because it can make that setter do something else useful. I've seen this pattern used some places (e.g. JMock, JPA), but it seems uncommon, and only generally used for very well defined APIs where this pattern is used everywhere.

Update:

What I've described is obviously valid, but what I am really looking for is some thoughts on whether this is generally acceptable, and if there are any pitfalls or related best practices. I know about the Builder pattern but it is a little more involved then what I am describing - as Josh Bloch describes it there is an associated static Builder class for object creation.

答:
It is better to use other language constructs if available.  For example, in Kotlin, you would use with, apply, or let.  If using this approach, you won't really need to return an instance from your setter.

This approach allows your client code to be:

Indifferent to the return type

Easier to maintain

Avoid compiler side effects

Here are some examples.

```<code>val employee = Employee().apply {
   name = "Jack Sparrow"
   id = 1
   foo = "bacon"
}

val employee = Employee()
with(employee) {
   name = "Jack Sparrow"
   id = 1
   foo = "bacon"
}

val employee = Employee()
employee.let {
   it.name = "Jack Sparrow"
   it.id = 1
   it.foo = "bacon"
}
</code>```

Body:
Is it a good or bad idea to make setters in java return "this"?

public Employee setName(String name){
   this.name = name;
   return this;
}

This pattern can be useful because then you can chain setters like this:

list.add(new Employee().setName("Jack Sparrow").setId(1).setFoo("bacon!"));

instead of this:

Employee e = new Employee();
e.setName("Jack Sparrow");
...and so on...
list.add(e);

...but it sort of goes against standard convention. I suppose it might be worthwhile just because it can make that setter do something else useful. I've seen this pattern used some places (e.g. JMock, JPA), but it seems uncommon, and only generally used for very well defined APIs where this pattern is used everywhere.

Update:

What I've described is obviously valid, but what I am really looking for is some thoughts on whether this is generally acceptable, and if there are any pitfalls or related best practices. I know about the Builder pattern but it is a little more involved then what I am describing - as Josh Bloch describes it there is an associated static Builder class for object creation.

Body:
It is better to use other language constructs if available.  For example, in Kotlin, you would use with, apply, or let.  If using this approach, you won't really need to return an instance from your setter.

This approach allows your client code to be:

Indifferent to the return type

Easier to maintain

Avoid compiler side effects

Here are some examples.

val employee = Employee().apply {
   name = "Jack Sparrow"
   id = 1
   foo = "bacon"
}

val employee = Employee()
with(employee) {
   name = "Jack Sparrow"
   id = 1
   foo = "bacon"
}

val employee = Employee()
employee.let {
   it.name = "Jack Sparrow"
   it.id = 1
   it.foo = "bacon"
}


问:
Spring Boot repository does not persist one-to-many relation
I have a Spring Boot app with JPA and H2 with two entities:

```<code>@Entity
@Table(name = "people")
public class Person {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "person_id")
    private long id;

    private String name;

    @OneToMany(mappedBy = "person", cascade = CascadeType.ALL)
    private Set<Skill> skills = new HashSet<Skill>();
}

@Entity
@Table(name = "skills")
public class Skill {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "skill_id")
    private long id;

    private String name;

    @ManyToOne
    @JoinColumn (name="person_id")
    @JsonBackReference
    private Person person;
}
</code>```

I have JPA repositories for the person entity:

```<code>@Repository
public interface PersonRepository extends CrudRepository<Person, Long> {
}
</code>```

When I try to save the following object, it returns the correct entity with skills included immediately, but when I call repository.find(<id-of-saved-entity>), the skills are empty (so they did not get persisted):

```<code>{ "name": "Test", "skills": [ { "name": "Skill1" }, { "name": "Skill2"} ] }
</code>```

Could someone help me out and tell me what is wrong with my mapping and configuration?

答:
Here is an answer for spring data REST (HATEOAS) repositories. They say, you have to send a PUT request to the association resource that contains the URI of the [parent] resource

```<code>curl -i -X PUT -H "Content-Type:text/uri-list" -d "http://localhost:8080/libraries/1" http://localhost:8080/books/1/library
</code>```

http://www.baeldung.com/spring-data-rest-relationships

I hope the link helps.

Body:
I have a Spring Boot app with JPA and H2 with two entities:

@Entity
@Table(name = "people")
public class Person {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "person_id")
    private long id;

    private String name;

    @OneToMany(mappedBy = "person", cascade = CascadeType.ALL)
    private Set<Skill> skills = new HashSet<Skill>();
}

@Entity
@Table(name = "skills")
public class Skill {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "skill_id")
    private long id;

    private String name;

    @ManyToOne
    @JoinColumn (name="person_id")
    @JsonBackReference
    private Person person;
}

I have JPA repositories for the person entity:

@Repository
public interface PersonRepository extends CrudRepository<Person, Long> {
}

When I try to save the following object, it returns the correct entity with skills included immediately, but when I call repository.find(<id-of-saved-entity>), the skills are empty (so they did not get persisted):

{ "name": "Test", "skills": [ { "name": "Skill1" }, { "name": "Skill2"} ] }

Could someone help me out and tell me what is wrong with my mapping and configuration?

Body:
Here is an answer for spring data REST (HATEOAS) repositories. They say, you have to send a PUT request to the association resource that contains the URI of the [parent] resource

curl -i -X PUT -H "Content-Type:text/uri-list" -d "http://localhost:8080/libraries/1" http://localhost:8080/books/1/library

http://www.baeldung.com/spring-data-rest-relationships

I hope the link helps.


问:
How do I connect to an older sql database using LocalDb in VS 2012?
I am trying to construct a connection string to a 2008 SQL Express database file in VS 2012. I am getting an error dialog:

This database file is not compatible with the current instance of SQL
  Server. To resolve this issue, you must upgrade the database file by
  creating a new data connection, or you must modify the existing
  connection to this database file. For more information, see
  http://go.microsoft.com/fwlink/?LinkId=235986

I followed the link to Microsoft's always wonderfully helpful documentation (cough, cough..). When I went through the upgrade database function, I was not presented with a prompt to upgrade the file. I was really hoping to use LocalDb instead of having to do a install of SQL Express 2008.  Any thoughts?

OTHER: Why hasn't Visual Studio implemented clicking on links in the error dialogs after all these years? Is it really hard to implement?

答:
open sql server management studio
connect localDB
remove deattach same name  mdf file
then attach your mdf file

go to visual studio
in server explorer-> dataconnection
right click on your database ->  modify connection -> text connection -> click OK


问:
Javascript regex get only page number from URL
i have URL like
https://example.com/my-list/page/35/?a=45&b=56

I want to get page number using regex that is after /page/ in url,
the result i want is 35

答:
There's 2 easy ways you could do it using RegEx:

The first way:

```<code>var s = "https://example.com/my-list/page/35/?a=45&b=56";
//  First way uses capture groups based on what comes before the page number: "/page/"
s.match(/\/page\/(\d*)/)[1]; // "35"
</code>```

The second way:

```<code>//  The second involves using capture grouping based on the search param that appears to follow.
//  However, this way might not be ideal as you may extend the URI and make a major change that would then require an edit to this. Of course, that could happen with the previous as well.

s.match(/(\d*)(?=\/\?)/)[0]  //  "35"
</code>```

You can also split the string, and then use regex to grab just the beginning of the string:

```<code>s.split("/page/")[1].match(/^\d*/);  //  "35"
</code>```

You could also simply split the whole string based on the most common element: "/". If your URI pattern is always the same, then this is probably one of the most simply and easy to read solutions. However, if the URI pattern changes to have more fields, then you may have to adjust the index number.

```<code>s.split("/")[5]  //  "35"
</code>```

You could also use substr based on the index of "page". The problem with this is the page number might be 1 digit, 2 digits, or more:

```<code>s.substr(s.indexOf("page/")+5, 2)  //  "35"
//  +5 due to length of phrase i use
</code>```

You could use the substr and index grab the string you want, having the page number at the very start of the string. Then use regex to pull the number and have it rest at 0 index. This might be more practical in case, for whatever reason, there is no page number. For instance, the user ends up at the "page" index base.

```<code>s.substr(s.indexOf("page/")+5).match(/^\d*/)[0]  //  35
</code>```

Body:
There's 2 easy ways you could do it using RegEx:

The first way:

var s = "https://example.com/my-list/page/35/?a=45&b=56";
//  First way uses capture groups based on what comes before the page number: "/page/"
s.match(/\/page\/(\d*)/)[1]; // "35"

The second way:

//  The second involves using capture grouping based on the search param that appears to follow.
//  However, this way might not be ideal as you may extend the URI and make a major change that would then require an edit to this. Of course, that could happen with the previous as well.

s.match(/(\d*)(?=\/\?)/)[0]  //  "35"

You can also split the string, and then use regex to grab just the beginning of the string:

s.split("/page/")[1].match(/^\d*/);  //  "35"

You could also simply split the whole string based on the most common element: "/". If your URI pattern is always the same, then this is probably one of the most simply and easy to read solutions. However, if the URI pattern changes to have more fields, then you may have to adjust the index number.

s.split("/")[5]  //  "35"

You could also use substr based on the index of "page". The problem with this is the page number might be 1 digit, 2 digits, or more:

s.substr(s.indexOf("page/")+5, 2)  //  "35"
//  +5 due to length of phrase i use

You could use the substr and index grab the string you want, having the page number at the very start of the string. Then use regex to pull the number and have it rest at 0 index. This might be more practical in case, for whatever reason, there is no page number. For instance, the user ends up at the "page" index base.

s.substr(s.indexOf("page/")+5).match(/^\d*/)[0]  //  35


问:
PHP IPv6 and IPv4 Addresses specific access to webpage
I want to restrict access to users who are not connected to one of the WIFI's of a specific company.
So for instance, we have a company and this company has 2 different WIFI networks to connect. I want to only give access to a page if the client is connected by one of these WIFI's.

The IPv4 of one of the WIFI's is for instance: 123.45.65.101

The IPv6 of the other WIFI is for instance:
2000:980:ce5:1:4dd9:47ad:ff9b:4454

The following PHP script worked perfectly in time there was only a IPv4 address:

```<code>if(!in_array($_SERVER['REMOTE_ADDR'], $ip_adres_allow) && !in_array($_SERVER["HTTP_X_FORWARDED_FOR"], $ip_adres_allow)) {

    die("You can't access this webpage, please try again by your employee.");

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

Where $ip_adres_allow -> array of values stored in database

My questions are:

I know IPv4 addresses are the same per WIFI, they wont change. But is a IPv6 address the same? I've tracked some IPv6 addresses from the company and they like to seem to start with 2000:980:ce5:1:XXXX:XXXX:XXXX:XXXX. (whereas the X's are not the same) Does this mean a WIFI has a range of IPv6?

Is 2000:980:ce5:1:4dd9:47ad:ff9b:4454 the same WIFI as 2000:980:ce5:1:55de:de7d:df6e:ea62 for instance? Or is this DEFINITELY SURE that it is another WIFI network?

Is there a way to modify the PHP script above to check if a client is connected to one of the WIFI's? Or should this script still work? Because the database is hardcoded with IPv6 and IPv4 addresses. And if IPv6 is one address, there might be someone that is connected to the WIFI but can't access the page because it is not an exact match of the value in the database.

Please correct me if im wrong.

Thanks for reading.

答:
As we discussed in our chat, below is a sample code to give you an idea on how to perform your checks.:

```<code>$checkip  = $_SERVER['Something with IP'];
$validate = '';

if($checkip == $_SERVER['Some IPv4'])
{
    $ip = the IPv4 address
    $validate = 4;
}
else
{
    $ip = the ipv6 IP
    $validate = 6;
}

if($validate == 4)
{
    $ip = echo substr($ip, 0, ???); // IPv4 address
}
else
{
    $ip = substr($ip, 0, 15); // 2000:950:ac2:3
}
</code>```

Again: this is just to give you an idea. You need to create your own function to use this correctly. I suggest to make this a function at the login, and give variables to your function. So you do not have to modify your script for other companies, only the variables your are sending. (function could simply return true or false;

Good luck man!

Body:
I want to restrict access to users who are not connected to one of the WIFI's of a specific company.
So for instance, we have a company and this company has 2 different WIFI networks to connect. I want to only give access to a page if the client is connected by one of these WIFI's.

The IPv4 of one of the WIFI's is for instance: 123.45.65.101

The IPv6 of the other WIFI is for instance:
2000:980:ce5:1:4dd9:47ad:ff9b:4454

The following PHP script worked perfectly in time there was only a IPv4 address:

if(!in_array($_SERVER['REMOTE_ADDR'], $ip_adres_allow) && !in_array($_SERVER["HTTP_X_FORWARDED_FOR"], $ip_adres_allow)) {

    die("You can't access this webpage, please try again by your employee.");

    exit();
}

Where $ip_adres_allow -> array of values stored in database

My questions are:

I know IPv4 addresses are the same per WIFI, they wont change. But is a IPv6 address the same? I've tracked some IPv6 addresses from the company and they like to seem to start with 2000:980:ce5:1:XXXX:XXXX:XXXX:XXXX. (whereas the X's are not the same) Does this mean a WIFI has a range of IPv6?

Is 2000:980:ce5:1:4dd9:47ad:ff9b:4454 the same WIFI as 2000:980:ce5:1:55de:de7d:df6e:ea62 for instance? Or is this DEFINITELY SURE that it is another WIFI network?

Is there a way to modify the PHP script above to check if a client is connected to one of the WIFI's? Or should this script still work? Because the database is hardcoded with IPv6 and IPv4 addresses. And if IPv6 is one address, there might be someone that is connected to the WIFI but can't access the page because it is not an exact match of the value in the database.

Please correct me if im wrong.

Thanks for reading.

Body:
As we discussed in our chat, below is a sample code to give you an idea on how to perform your checks.:

$checkip  = $_SERVER['Something with IP'];
$validate = '';

if($checkip == $_SERVER['Some IPv4'])
{
    $ip = the IPv4 address
    $validate = 4;
}
else
{
    $ip = the ipv6 IP
    $validate = 6;
}

if($validate == 4)
{
    $ip = echo substr($ip, 0, ???); // IPv4 address
}
else
{
    $ip = substr($ip, 0, 15); // 2000:950:ac2:3
}

Again: this is just to give you an idea. You need to create your own function to use this correctly. I suggest to make this a function at the login, and give variables to your function. So you do not have to modify your script for other companies, only the variables your are sending. (function could simply return true or false;

Good luck man!


问:
Need help with Windows Phone 7 image upload to webservice
Basically I have a rest webservice that is self hosted on a pc and I want to upload an image from a windows 7 phone.  A lot of this is new to me so I have been learning as I go.  My problem is that I can not upload an image to the webservice.

Below is the code that I am using.

I am testing with the wifi connection and it is up and working.
I am using Fiddler and I can see the requests going to and from the phone/pc

using the emulator I can sort of get this to work (i get a 200 code and can write the image to disk)

When I try to post with the actual device I get a 400 response code back.

Any help I can get would be great.  I have been spinning my wheels trying to solve this bug.

```<code>//webserice code
[ServiceContract]

public interface ItestService
{
  [OperationContract, WebInvoke(Method = "POST", UriTemplate = "PostTest/{targetID}")]
  string PostTest(string targetID, Stream image);
}

//from service def

public string PostTest(string targetID, System.IO.Stream image)
{
   string id = WriteImageToDisk(image, targetID);
   return id;
}

//phone code
private void SendImage1()
{
 string address = ServiceURI + "/PostTest";
 Uri baseAddress = new Uri(address);
 var req = HttpWebRequest.Create(baseAddress) as HttpWebRequest;
 req.Method = "POST";
 req.ContentType = "image/jpeg";
 req.BeginGetRequestStream(SendImagePost_Callback, req);
}

private void SendImagePost_Callback(IAsyncResult result)
{
  try
  {
     var req = result.AsyncState as HttpWebRequest;

     using (var strm = req.EndGetRequestStream(result))
     {
        var bytesToWrite = RawContent();
        strm.Write(bytesToWrite, 0, bytesToWrite.Length);
        strm.Flush();
     }

     req.BeginGetResponse(SendImageResponce_Callback, req);
  }
  catch (Exception ex)
  {
     DisplayMessage(this.txtError, ex.Message);
  }

}

 private void SendImageResponce_Callback(IAsyncResult result)
 {
    try
    {
       var req = result.AsyncState as HttpWebRequest;
       var strm = resp.GetResponseStream();
       var reader = new StreamReader(strm);

       DataContractSerializer ser = new DataContractSerializer(typeof(string));
       string id = ser.ReadObject(strm).ToString();
       DisplayMessage(this.txtAction, id);
    }
    catch (Exception ex)
    {
       DisplayMessage(this.txtError, ex.Message);
    }
 }
</code>```

答: It sounds like you have a connectivity issue to resolve. Perhaps try accessing your local service by IP, and check there is no firewall interception.</p>

Body:
Basically I have a rest webservice that is self hosted on a pc and I want to upload an image from a windows 7 phone.  A lot of this is new to me so I have been learning as I go.  My problem is that I can not upload an image to the webservice.

Below is the code that I am using.

I am testing with the wifi connection and it is up and working.
I am using Fiddler and I can see the requests going to and from the phone/pc

using the emulator I can sort of get this to work (i get a 200 code and can write the image to disk)

When I try to post with the actual device I get a 400 response code back.

Any help I can get would be great.  I have been spinning my wheels trying to solve this bug.

//webserice code
[ServiceContract]

public interface ItestService
{
  [OperationContract, WebInvoke(Method = "POST", UriTemplate = "PostTest/{targetID}")]
  string PostTest(string targetID, Stream image);
}

//from service def

public string PostTest(string targetID, System.IO.Stream image)
{
   string id = WriteImageToDisk(image, targetID);
   return id;
}

//phone code
private void SendImage1()
{
 string address = ServiceURI + "/PostTest";
 Uri baseAddress = new Uri(address);
 var req = HttpWebRequest.Create(baseAddress) as HttpWebRequest;
 req.Method = "POST";
 req.ContentType = "image/jpeg";
 req.BeginGetRequestStream(SendImagePost_Callback, req);
}

private void SendImagePost_Callback(IAsyncResult result)
{
  try
  {
     var req = result.AsyncState as HttpWebRequest;

     using (var strm = req.EndGetRequestStream(result))
     {
        var bytesToWrite = RawContent();
        strm.Write(bytesToWrite, 0, bytesToWrite.Length);
        strm.Flush();
     }

     req.BeginGetResponse(SendImageResponce_Callback, req);
  }
  catch (Exception ex)
  {
     DisplayMessage(this.txtError, ex.Message);
  }

}

 private void SendImageResponce_Callback(IAsyncResult result)
 {
    try
    {
       var req = result.AsyncState as HttpWebRequest;
       var strm = resp.GetResponseStream();
       var reader = new StreamReader(strm);

       DataContractSerializer ser = new DataContractSerializer(typeof(string));
       string id = ser.ReadObject(strm).ToString();
       DisplayMessage(this.txtAction, id);
    }
    catch (Exception ex)
    {
       DisplayMessage(this.txtError, ex.Message);
    }
 }


问:
What do pipes between brackets mean in a regex?
Reading this vim plugin I see this line:

```<code>syntax match tweeDelimiter "[<<|>>|\]\]|\[\[]"
</code>```

To me, that regex doesn't make much sense when it's surrounded by [].  According to this, "POSIX bracket expressions match one character out of a set of characters".

So isn't this matching < or > or [ or ]?  I know from context that it's trying to match << or >> or [[ or ]].

答:
That indeed looks like a bug in the plugin. If it wants to match pairs of those characters, it has to use plain regexp branches (\|), not a collection:

```<code><<\|>>\|\]\]\|\[\[
</code>```

If there were additional stuff to match, above would have to be enclosed in \%(...\) to group it. However, using [...] will match any of the contained characters; Vim just ignores the duplicate ones. As others have commented already, such could be written in shorter form, for example [][<>|].

So, if the plugin indeed mistakenly matches stuff like <> and <[ instead of just << and [[, please inform its author about the bug.

Body:
Reading this vim plugin I see this line:

syntax match tweeDelimiter "[<<|>>|\]\]|\[\[]"

To me, that regex doesn't make much sense when it's surrounded by [].  According to this, "POSIX bracket expressions match one character out of a set of characters".

So isn't this matching < or > or [ or ]?  I know from context that it's trying to match << or >> or [[ or ]].

Body:
That indeed looks like a bug in the plugin. If it wants to match pairs of those characters, it has to use plain regexp branches (\|), not a collection:

<<\|>>\|\]\]\|\[\[

If there were additional stuff to match, above would have to be enclosed in \%(...\) to group it. However, using [...] will match any of the contained characters; Vim just ignores the duplicate ones. As others have commented already, such could be written in shorter form, for example [][<>|].

So, if the plugin indeed mistakenly matches stuff like <> and <[ instead of just << and [[, please inform its author about the bug.


问:
Allman-style anonymous classes
Any recommendations on how to use anonymous classes while staying consistent with Allman indent style? I don't really like anything I've come up with, e.g.</p>

```<code>// Pass as parameter.
foo(new Clazz( )
    {
       // Do stuff.
    });

// Assign to variable.
Clazz bar = new Clazz( )
            {
               // Do stuff.
            };
</code>```

答:
This is what I've settled on.

```<code>Foo foo = new Foo()
{
    // Do stuff.
};
</code>```

And I just don't define anonymous classes inside method calls anymore.

Title: Allman-style anonymous classes

Body:
Any recommendations on how to use anonymous classes while staying consistent with Allman indent style? I don't really like anything I've come up with, e.g.

// Pass as parameter.
foo(new Clazz( )
    {
       // Do stuff.
    });

// Assign to variable.
Clazz bar = new Clazz( )
            {
               // Do stuff.
            };

Body:
This is what I've settled on.

Foo foo = new Foo()
{
    // Do stuff.
};

And I just don't define anonymous classes inside method calls anymore.


问:
Getting JSON values/properties from a file in a component in angular 4
There is a set of components in my Angular 4 app in which each component
requires a certain set of properties from a different JSON file which it shows on its template.
I have created a common JSON file containing all the properties and I load it when the app-component is called using a service that holds those properties array.

I then inject that same service into different components and fetch the populated array. The values show in the HTML all fine.

However, this approach seems to be a bit time consuming especially when the constants grow in size. Loading thousands of constants all at once and injecting them into different components where few of them are required is not a good approach.

I was willing to work on an approach where I create specific contansts JSON file for each component and somehow load it when the component is actually initialized. This way I can save the burden of a heavy JSON object and only those properties would be loaded that are required by that component.

The load() method in my constants service looks something like this:

```<code>@Injectable()
export class ConstantsService {
constructor(private http: HttpClient) {
    console.log('ConstantsService created');
}
    constants = {};
    load() {
        var constants = {};
        var cons = 'constants';

        var constantsResourceUrl =
            'path' + cons + '.json';

        this.http.get(constantsResourceUrl)
            .subscribe(result => {
                this.constants = result;
            },
            error => this.log.error(constantsResource + ' could not be loaded')
            );
    }
}
</code>```

And my Components look like this to get the value of the constants:

```<code>@Component({
  selector: 'xyz',
  templateUrl: './xyz.html',
  styleUrl: './xyz.css'
})
export class MyComponent {
  consts = {};

  constructor(private constantsService: ConstantsService) {

    consts = this.constantsService.constants;
  }
}
</code>```

Any help would be appreciated.

答:
If did have similar dilema. To use db or json files for settings/parametars behavior. Dynamic content end up in db, and at the end I found that is little stupid to fetch and use http request to get static json content since that could be bundled in source. I did split it and use in multiple exported constant in ts. file like:

export const dummyLookupConst = `{
    "queryNo": 0,
    "id": 250,
...}

and then import it into components by need.

Body:
There is a set of components in my Angular 4 app in which each component
requires a certain set of properties from a different JSON file which it shows on its template.
I have created a common JSON file containing all the properties and I load it when the app-component is called using a service that holds those properties array.

I then inject that same service into different components and fetch the populated array. The values show in the HTML all fine.

However, this approach seems to be a bit time consuming especially when the constants grow in size. Loading thousands of constants all at once and injecting them into different components where few of them are required is not a good approach.

I was willing to work on an approach where I create specific contansts JSON file for each component and somehow load it when the component is actually initialized. This way I can save the burden of a heavy JSON object and only those properties would be loaded that are required by that component.

The load() method in my constants service looks something like this:

@Injectable()
export class ConstantsService {
constructor(private http: HttpClient) {
    console.log('ConstantsService created');
}
    constants = {};
    load() {
        var constants = {};
        var cons = 'constants';

        var constantsResourceUrl =
            'path' + cons + '.json';

        this.http.get(constantsResourceUrl)
            .subscribe(result => {
                this.constants = result;
            },
            error => this.log.error(constantsResource + ' could not be loaded')
            );
    }
}

And my Components look like this to get the value of the constants:

@Component({
  selector: 'xyz',
  templateUrl: './xyz.html',
  styleUrl: './xyz.css'
})
export class MyComponent {
  consts = {};

  constructor(private constantsService: ConstantsService) {

    consts = this.constantsService.constants;
  }
}

Any help would be appreciated.