问:
Iframe moves content down from neighbour element
I'm using display: table-* to style a basic structure.

#page {
  display: table;
  width: 1000px;
  margin: 0 auto;
}

#events,
#righ_sidebar {
  display: table-cell;
}

#events {
  width: 75%;
}

#righ_sidebar {
  width: 25%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="page">
  <div id="events">
    <h1>Events</h1>

    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
      in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    </p>

    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
      in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    </p>
  </div>

  <div id="righ_sidebar">
    <iframe id="up2europe" marginheight="5" marginwidth="5" src="https://www.up2europe.eu/widget/go/181d4bdc08289da3d78b79ee5f9e7e2d"></iframe>
  </div>
</div></code>```

The problem is that the iframe from #righ_sidebar it moves down the content from #events. How to use iframe and display table-* together, but correctly aligned?

答: add style float:left; for '#events' and float:right; for #righ_sidebar

Body:
I'm using display: table-* to style a basic structure.

#page {
  display: table;
  width: 1000px;
  margin: 0 auto;
}

#events,
#righ_sidebar {
  display: table-cell;
}

#events {
  width: 75%;
}

#righ_sidebar {
  width: 25%;
}

Events

      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
      in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
      in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

The problem is that the iframe from #righ_sidebar it moves down the content from #events. How to use iframe and display table-* together, but correctly aligned?


来源: stackexchange

问:
Run Java Script in Wordpress
I have bought one WordPress theme which have Live Chat button in header. Its support link to open chat. But I have got java script to open button. I am learning php and does not know how can I run java script on button press WordPress.

I have code in wordpress header theme is like below

```<code><?php }if( !empty( $king->cfg['topInfoLiveChat'] ) ){ ?>
                <a href="<?php echo esc_attr( $king->cfg['topInfoLiveChat'] ); ?>" class="chat">
                    <i class="fa fa-comments-o"></i> <?php _e('Live Chat', 'arkahost' ); ?>
                </a>
</code>```

Zopim chat have given me script to run is like below.

```<code>$zopim.livechat.window.show();
</code>```

They have given example to include like below

```<code><a href="javascript:$zopim.livechat.window.show()"><img src="INSERT_IMG_SRC_HERE"/></a>
</code>```

But if I use like above my design getting changed. Anyone can please help me how can I integrate this script in my above codes ?

Thanks

答:
If you would like to add the code in JS like:

```<code>$zopim.livechat.window.show();
</code>```

and fire it on click event on your button, you need just to add the script (if you have jquery) to your file (with button):

```<code><script type="text/javascript">
  jQuery('a.chat').on('click', function(e) {
    e.preventDefault();
    $zopim.livechat.window.show();
  });
</script>
</code>```

or add it to the JS file, that included into your page:

```<code>jQuery('a.chat').on('click', function(e) {
    e.preventDefault();
    $zopim.livechat.window.show();
  });
</code>```

Where a.chat is the link ( tag) and .chat is the class name of your link, like in your example. You can add the parrent elements.

e.preventDefault() - default event for the link will not fire

Thanks

ContentLicense: CC BY-SA 3.0

Title: Run Java Script in Wordpress

Body:
I have bought one WordPress theme which have Live Chat button in header. Its support link to open chat. But I have got java script to open button. I am learning php and does not know how can I run java script on button press WordPress.

I have code in wordpress header theme is like below

<?php }if( !empty( $king->cfg['topInfoLiveChat'] ) ){ ?>
                <a href="<?php echo esc_attr( $king->cfg['topInfoLiveChat'] ); ?>" class="chat">
                     <?php _e('Live Chat', 'arkahost' ); ?>

Zopim chat have given me script to run is like below.

$zopim.livechat.window.show();

They have given example to include like below

But if I use like above my design getting changed. Anyone can please help me how can I integrate this script in my above codes ?

Thanks

Body:
If you would like to add the code in JS like:

$zopim.livechat.window.show();

and fire it on click event on your button, you need just to add the script (if you have jquery) to your file (with button):

<script type="text/javascript">
  jQuery('a.chat').on('click', function(e) {
    e.preventDefault();
    $zopim.livechat.window.show();
  });
</script>

or add it to the JS file, that included into your page:

jQuery('a.chat').on('click', function(e) {
    e.preventDefault();
    $zopim.livechat.window.show();
  });

Where a.chat is the link (<a href=""></a> tag) and .chat is the class name of your link, like in your example. You can add the parrent elements.

e.preventDefault() - default event for the link will not fire

Thanks


问:
Android Layout: position element below lowest view
I've attached a picture to better illustrate what I'm going for.

I have two LinearLayouts positioned side by side. Both are able to expand vertically, using wrap_content. I would like to position another container (HorizontalScrollView) below whichever one has the greater height. It's currently set to go below the right-most column, as generally it is taller, but in some cases the ScrollView will cover up the content in the left-most column. Is there a way to set this in the .xml file or will I need to resort to setting this in my onCreate method?

答:
I would like to position another
  container (HorizontalScrollView) below
  whichever one has the greater height.

You have to set it programmatically in the onConfigurationChanged method. So that it can work properly after the device's orientation changes.

ContentLicense: CC BY-SA 2.5


问:
What should be the word vectors of token <pad>, <unknown>, <go>, <EOS> before sent into RNN?
In word embedding, what should be a good vector representation for the start_tokens _PAD, _UNKNOWN, _GO, _EOS? </p>

答:
As far as I understand you can represent these tokens by any vector.

Here's why:

Inputting a sequence of words to your model, you first convert each word to an ID and then look in your embedding-matrix which vector corresponds to that ID. With that vector, you train your model. But the embedding-matrix just contains also trainable weights which will be adjusted during training. The vector-representations from your pretrained vectors just serve as a good point to start to yield good results.

Thus, it doesn't matter that much what your special tokens are represented by in the beginning as their representation will change during training.


问:
Change element in arraylist to true from user input
```<code>package issue;
import java.util.*;

public class Issue {

    private static ArrayList<Object> list = new ArrayList<Object>();

    public static ArrayList<Object> getArrayStringList(){
        for (Object o : list)
            System.out.println("["+o+"]");
        return list;
    }

    public static void removeIssue(){
        for (int i = 0; i<list.size(); i++){;
            System.out.println("["+"["+i+"] "+list.get(i)+"]");
        }
        Scanner scan = new Scanner(System.in);
        System.out.println("Which one would you like to mark as solved?");
        int choice = scan.nextInt();

       ##This is where my problem is ##
        Object issue = list.get(choice);
        issue
    }

    public static void addIssue(){
        Scanner scan = new Scanner(System.in);
        String text= scan.nextLine();
        newIssue issue = new newIssue(text);
        list.add(issue);
    }
}
</code>```

I want the user input to choose the appropriate element in the ArrayList and then set it to true using the newIssue class. But I can't figure out how to

```<code>package issue;

public class newIssue {

    public String issueText;
    public boolean returned = false;

    public newIssue(String issueText){
        this.issueText = issueText;
    }

    public String toString(){
        return issueText + returned;
    }
}
</code>```

答:
Create list as:

```<code>private static ArrayList<newIssue> list = new ArrayList<>();
</code>```

Then you can do:

```<code>newIssue issue = list.get(choice);
issue.returned = true;
</code>```

Body:
package issue;
import java.util.*;

public class Issue {

    private static ArrayList<Object> list = new ArrayList<Object>();

    public static ArrayList<Object> getArrayStringList(){
        for (Object o : list)
            System.out.println("["+o+"]");
        return list;
    }

    public static void removeIssue(){
        for (int i = 0; i<list.size(); i++){;
            System.out.println("["+"["+i+"] "+list.get(i)+"]");
        }
        Scanner scan = new Scanner(System.in);
        System.out.println("Which one would you like to mark as solved?");
        int choice = scan.nextInt();

       ##This is where my problem is ##
        Object issue = list.get(choice);
        issue
    }

    public static void addIssue(){
        Scanner scan = new Scanner(System.in);
        String text= scan.nextLine();
        newIssue issue = new newIssue(text);
        list.add(issue);
    }
}

I want the user input to choose the appropriate element in the ArrayList and then set it to true using the newIssue class. But I can't figure out how to

package issue;

public class newIssue {

    public String issueText;
    public boolean returned = false;

    public newIssue(String issueText){
        this.issueText = issueText;
    }

    public String toString(){
        return issueText + returned;
    }
}

Body:
Create list as:

private static ArrayList<newIssue> list = new ArrayList<>();

Then you can do:

newIssue issue = list.get(choice);
issue.returned = true;


问:
can't add 'allUsers' to GCP project
I have a GCP project and just for testing purpose, I want to grant the permission to 'allUsers'. But when I am trying to add, I am getting error Members of type allUsers and allAuthenticatedUsers cannot be added to this resource. Can somebody help me to understand what I am doing wrong or missing here? Thanks

答:
The member types permission used to grant allUser or allAuthenticatedUser access to certain Google Cloud resources such as buckets cannot be applied as project roles to projects.
Google Cloud projects provide different levels of access control that are different from those used with buckets, as explained in the following Access Control for Projects using IAM documentation.

There is a three-level  policy hierarchy in Google Cloud that puts projects and resources as separate entities. In this hierarchy, policies are inheritable but do have different access control models which are not interchangeable.

You can grant to a Google Cloud project the following permissions:

roles/owner  - Full access to all resources.

roles/editor - Edit access to all resources.

roles/viewer - Read access to all resources.

roles/browser - Access to browse resources in the project.

The above project permissions can be fine-tuned at the resource level using member types as  explained above.

Title: can't add 'allUsers' to GCP project


问:
Stored Procedure Efficiency - Null Input Parameters and Where clauses
I like to minimize the number of stored procedures I have by having a bunch of input parameters all defaulting to NULL and then those same parameters included in the WHERE with a test for Equality or NULL.

How inefficient is this in relation to query performance - verses writing stored procedure for 1 specific tasks? e.g. Select by UserId only, select by Username/Password, select by FirstName/LastName...

Example:

```<code>CREATE PROC dbo.up_Select_User

  @UserId int = NULL
, @Username varchar(255) = NULL
, @Password varchar(255) = NULL
, @FirstName varchar(50) = NULL
, @LastName varchar(50) = NULL
, @IsActive bit = NULL

SELECT UserId, Username, FirstName, LastName, EmailAddress
FROM dbo.[User]
WHERE (UserId = @UserId OR @UserId IS NULL)
AND (Username = @Username OR @Username IS NULL)
AND (Password = @Password OR @Password IS NULL)
AND (FirstName = @FirstName OR @FirstName IS NULL)
AND (LastName = @LastName OR @LastName IS NULL)
AND (IsActive = @IsActive OR @IsActive IS NULL)
</code>```

Some additional info - may not be relevant... I am using entity framework 4 to map to stored procedures using a mix of normal entities and complex types depending on the query results.

答:
we use this way to filter

```<code>AND (CASE @UserId WHEN NULL THEN @UserId ELSE UserId END) = @UserId
</code>```

We don't have performance problems with large data on SqlServer with the solution.

Some of the application views (like report overviews pages) have more than 20 filter settings and it works good with the CASE WHEN construct.

Edit:
These SET options have to be set

```<code>SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
</code>```

Body:
I like to minimize the number of stored procedures I have by having a bunch of input parameters all defaulting to NULL and then those same parameters included in the WHERE with a test for Equality or NULL.

How inefficient is this in relation to query performance - verses writing stored procedure for 1 specific tasks? e.g. Select by UserId only, select by Username/Password, select by FirstName/LastName...

Example:

CREATE PROC dbo.up_Select_User

  @UserId int = NULL
, @Username varchar(255) = NULL
, @Password varchar(255) = NULL
, @FirstName varchar(50) = NULL
, @LastName varchar(50) = NULL
, @IsActive bit = NULL

SELECT UserId, Username, FirstName, LastName, EmailAddress
FROM dbo.[User]
WHERE (UserId = @UserId OR @UserId IS NULL)
AND (Username = @Username OR @Username IS NULL)
AND (Password = @Password OR @Password IS NULL)
AND (FirstName = @FirstName OR @FirstName IS NULL)
AND (LastName = @LastName OR @LastName IS NULL)
AND (IsActive = @IsActive OR @IsActive IS NULL)

Some additional info - may not be relevant... I am using entity framework 4 to map to stored procedures using a mix of normal entities and complex types depending on the query results.

Body:
we use this way to filter

AND (CASE @UserId WHEN NULL THEN @UserId ELSE UserId END) = @UserId

We don't have performance problems with large data on SqlServer with the solution.

Some of the application views (like report overviews pages) have more than 20 filter settings and it works good with the CASE WHEN construct.

Edit:
These SET options have to be set

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF


问:
Moving select file types to new directory based on dictionary
I  am trying to move specific filetypes to a new directory based on a nested dictionary.

For example, (to separate video and photo files) move media files defined in config[key1][other_file] to OTHERMEDIA for each camera models in their respective folders:

```<code>001__=d5
    OTHERMEDIA                                   #move files to here
    IMAGES
        [mix of mediafiles in subdirectories]    #move files from here
002__=alpha9
    OTHERMEDIA                                   #move files to here
    IMAGES
        [mix of mediafiles in subdirectories]    #move files from here
</code>```

Code gives shutil.move(os.path.join(root,files), os.path.join(destinationpath,files)). What I am doing wrong?

```<code>import shutil
import os
config = {
    'd5': {},
    'alpha9': {},
    'g7': {},
}
config['d5']['other_file'] = ('avi', 'AVI')
config['alpha9']['other_file'] = ('jpg', 'JPG')
config['g7']['other_file'] = ('mp4', 'MP4')

destinationpath = 'OTHERMEDIA'
root = os.getcwd()
for camID in config:
    for dir in next(os.walk(root))[1]:
        if dir.endswith(camID):
            for path, dirs, files in os.walk(os.path.join(root, dir)):
                for f in files:
                    if any([f.lower().endswith(x) for x in config[camID]["other_file"]]):
                        os.path.join(path, f). files, os.path.join(destinationpath,files)
</code>```

答:
You're doing os.path.join(path, files) when you should be doing os.path.join(path, f). files is the entire iterable; f is the specific file.

Also, as an aside, since you're looking at f.lower(), you don't need to compare it with the capitalized versions of the file extensions.

Body:
I  am trying to move specific filetypes to a new directory based on a nested dictionary.

For example, (to separate video and photo files) move media files defined in config[key1][other_file] to OTHERMEDIA for each camera models in their respective folders:

001__=d5
    OTHERMEDIA                                   #move files to here
    IMAGES
        [mix of mediafiles in subdirectories]    #move files from here
002__=alpha9
    OTHERMEDIA                                   #move files to here
    IMAGES
        [mix of mediafiles in subdirectories]    #move files from here

Code gives shutil.move(os.path.join(root,files), os.path.join(destinationpath,files)). What I am doing wrong?

import shutil
import os
config = {
    'd5': {},
    'alpha9': {},
    'g7': {},
}
config['d5']['other_file'] = ('avi', 'AVI')
config['alpha9']['other_file'] = ('jpg', 'JPG')
config['g7']['other_file'] = ('mp4', 'MP4')

destinationpath = 'OTHERMEDIA'
root = os.getcwd()
for camID in config:
    for dir in next(os.walk(root))[1]:
        if dir.endswith(camID):
            for path, dirs, files in os.walk(os.path.join(root, dir)):
                for f in files:
                    if any([f.lower().endswith(x) for x in config[camID]["other_file"]]):
                        os.path.join(path, f). files, os.path.join(destinationpath,files)


问:
NodeJS/MongoDB - Error: Can't set headers after they are sent
I got this helper function:

```<code>const Account = require('../models/account');

exports.sendInvites = (accountIds, invite, callback) => {

  if (!accountIds) {

    callback('No account ids provided', null, null);

    return;
  }

  accountIds.forEach((id) => {
    Account.findOneAndUpdate({_id: id}, {$push: {organisationInvites: invite}}, callback);
  });
};
</code>```

Then I have this route:

```<code>router.post('/organisations', auth.verifyToken, (req, res, next) => {

  const organisation = new Organisation({
    name: req.body.name,
    email: req.body.email,
    admins: [req.body.createdBy],
    createdBy: req.body.createdBy
  });

  organisation.save((err, organisation) => {

    if (err) {

      return res.status(500).json({
        error: err,
        data: null
      });
    }

    organisationUtils.sendInvites(req.body.invites, {
      inviter: req.body.createdBy,
      organisation: organisation._id
    }, (err, account, response) => {

      if (err) {

        return res.status(500).json({
          error: err,
          data: null
        });
      }

      res.json({
        error: null,
        data: organisation
      });
    });
  });
});
</code>```

I get a Error: Can't set headers after they are sent. error for the

```<code>res.json({
  error: null,
  data: organisation
});
</code>```

part but I can't understand why this is happening. I tried looking at the accepted answer here Error: Can't set headers after they are sent to the client, did some digging but couldn't find any specific reason still what's happening in my particular example above. Any ideas?

答:
You are calling the callback multiple times, and so res.json multiple times. Gather the data from all database request then perform an unique res.json.

```<code>accountIds.forEach((id) => {
    Account.findOneAndUpdate(
                              {_id: id},
                              {$push: {organisationInvites: invite}},
                               callback,
                            );
});
</code>```

Something like :

```<code>    var allData = [];
    var nbRequestDone = 0;

    var waitAllCallback = function (data, err) {
       if (err) {
         callback(err);

         nbRequestDone = accountIds.length;

         return;
       }

       nbRequestDone += 1;

       allData.push(data);

       if (nbRequestDone === accountIds.length) {
         callback(false, allData);
       }
    };

    accountIds.forEach((id) => {
      Account.findOneAndUpdate(..., waitAllCallback);
    });
</code>```

Body:
I got this helper function:

const Account = require('../models/account');

exports.sendInvites = (accountIds, invite, callback) => {

  if (!accountIds) {

    callback('No account ids provided', null, null);

    return;
  }

  accountIds.forEach((id) => {
    Account.findOneAndUpdate({_id: id}, {$push: {organisationInvites: invite}}, callback);
  });
};

Then I have this route:

router.post('/organisations', auth.verifyToken, (req, res, next) => {

  const organisation = new Organisation({
    name: req.body.name,
    email: req.body.email,
    admins: [req.body.createdBy],
    createdBy: req.body.createdBy
  });

  organisation.save((err, organisation) => {

    if (err) {

      return res.status(500).json({
        error: err,
        data: null
      });
    }

    organisationUtils.sendInvites(req.body.invites, {
      inviter: req.body.createdBy,
      organisation: organisation._id
    }, (err, account, response) => {

      if (err) {

        return res.status(500).json({
          error: err,
          data: null
        });
      }

      res.json({
        error: null,
        data: organisation
      });
    });
  });
});

I get a Error: Can't set headers after they are sent. error for the

res.json({
  error: null,
  data: organisation
});

part but I can't understand why this is happening. I tried looking at the accepted answer here Error: Can't set headers after they are sent to the client, did some digging but couldn't find any specific reason still what's happening in my particular example above. Any ideas?

Body:
You are calling the callback multiple times, and so res.json multiple times. Gather the data from all database request then perform an unique res.json.

accountIds.forEach((id) => {
    Account.findOneAndUpdate(
                              {_id: id},
                              {$push: {organisationInvites: invite}},
                               callback,
                            );
});

Something like :

    var allData = [];
    var nbRequestDone = 0;

    var waitAllCallback = function (data, err) {
       if (err) {
         callback(err);

         nbRequestDone = accountIds.length;

         return;
       }

       nbRequestDone += 1;

       allData.push(data);

       if (nbRequestDone === accountIds.length) {
         callback(false, allData);
       }
    };

    accountIds.forEach((id) => {
      Account.findOneAndUpdate(..., waitAllCallback);
    });


问:
UnsatisfiedLinkError about Static Member initialized in class in ndk r15
I encounter a problem about UnsatisfiedLinkError.

My code is :

```<code>class ClassA
{
public:
  static const int MY_ENUM_1 = 0;
};
</code>```

I use Android Studio build my code to .a.

And then I write .so for link the interface of my lib via JNI.

I build the project successfully. But it occur an error about this while run-time,

 java.lang.UnsatisfiedLinkError: dlopen failed: cannot locate symbol "_ZN12LaChenEngine14GraphicsSystem22VertexBufferAccessList12DYNAMIC_DRAWE
```

LaChenEngine is the namespace.

GraphicsSystem is the namespace in LaChenEngine.

VertexBufferAccessList is my class for declaring all enum.

DYNAMIC_DRAW is one of enum in class VertexBufferAccessList.

Is this problem about version in ndk?

By the way, I develop my library on Windows Platform.

答:
One possible cause is that one project defines a extern "C" function, and the other assumes that it is a C++ function.
More info: https://stackoverflow.com/a/1041880/755804

Another guess: check if that function is there in your .so, and if not, find out where it is.

In general, how I would approach such linkage problem is: I would start with a hello-jni application, adding one feature at a time (another library, C++ functions, C++ functions in name spaces, etc.)

Body:
I encounter a problem about UnsatisfiedLinkError.

My code is :

class ClassA
{
public:
  static const int MY_ENUM_1 = 0;
};

I use Android Studio build my code to .a.

And then I write .so for link the interface of my lib via JNI.

I build the project successfully. But it occur an error about this while run-time,

 java.lang.UnsatisfiedLinkError: dlopen failed: cannot locate symbol "_ZN12LaChenEngine14GraphicsSystem22VertexBufferAccessList12DYNAMIC_DRAWE

LaChenEngine is the namespace.

GraphicsSystem is the namespace in LaChenEngine.

VertexBufferAccessList is my class for declaring all enum.

DYNAMIC_DRAW is one of enum in class VertexBufferAccessList.

Is this problem about version in ndk?

By the way, I develop my library on Windows Platform.


问:
ASP.NET MVC 3.0 Razor, load View from anywhere out of the box?
Is it true that it is possible to load View from anywhere without
implementation of custom VirtualPathProvider in MVC 3.0?

If it is true how to do it?

Basically it is not a problem to implement custom VirtualPathProvider which would load the
View from anywhere but my implementation working only in MVC 2.0 and not working wih MVC 3.0, fore some reason method GetFile newer called for not existed views in MVC 3.0 and in that case I am getting "Server Error in '/' Application."

I followed the same code for my custom VirtualPathProvider from here: http://buildstarted.com/2010/09/28/mvc-3-razor-view-engine-without-a-controller/

UPDATE 1

OK i did fix my problem with my custom VirtualPathProvider after i put registration of my custom VirtualPathProvider provider first line in the Application_Start()

```<code>    protected void Application_Start()
    {
        //Should be first line before routes and areas registration.
        HostingEnvironment.RegisterVirtualPathProvider(new MyVirtualPathProvider());

        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }
</code>```

When registration of custom VirtualPathProvider in Global.asax.cs folowing after AreaRegistration.RegisterAllAreas(); or RegisterRoutes(RouteTable.Routes); method method override VirtualFile GetFile(string virtualPath) wont work for "virtual Views".

UPDATE 2

does it means that the classes RazorView and RazorViewEngineRender is the answer?

UPDATE 3

If i have string representation of my razor view which does not exists in the file system (e.g i store razor views in database) how may i render it using this kind of approach http://buildstarted.com/2010/09/28/mvc-3-razor-view-engine-without-a-controller/

For example string representation of my View looks like this:

```<code>"@{
    ViewBag.Title = ""About Us"";
}

<h2>About</h2>
<p>
     Put content here.
</p>"
</code>```

UPDATE 4

Now i see, to be able to use @Html.<something> custom TemplateBase should be implemented.
The sample of implementation of HtmlTemplateBase<T> could be fount here http://www.fidelitydesign.net/?p=239, but it won't work with RazorEngine v2, i am successfully getting template compiled, then after assembly loaded method public override void Execute() won't be executed i am getting an error: The method or operation is not implemented (stacktrace: http://tinypic.com/r/dcow4/7)

To make “public override T Model” happened i did change declaration of “public TModel Model” to “public virtual TModel Model” in “public abstract class TemplateBase : TemplateBase, ITemplate”. May be there is some another changes should be done? Or something in HtmlTemplateBase<T> should be done another way?

答: I ran into a similar issue implementing a VirtualPathProvider for embedded resource views. The solution was to implement GetFolder as well as GetFile. The view engine doesn't just call GetFile when you request that view. On the first request it looks through the views folder to find all available views. If that call doesn't include your database views in the list, they won't be found when you try to load them.</p>

Body:
Is it true that it is possible to load View from anywhere without
implementation of custom VirtualPathProvider in MVC 3.0?

If it is true how to do it?

Basically it is not a problem to implement custom VirtualPathProvider which would load the
View from anywhere but my implementation working only in MVC 2.0 and not working wih MVC 3.0, fore some reason method GetFile newer called for not existed views in MVC 3.0 and in that case I am getting "Server Error in '/' Application."

I followed the same code for my custom VirtualPathProvider from here: http://buildstarted.com/2010/09/28/mvc-3-razor-view-engine-without-a-controller/

UPDATE 1

OK i did fix my problem with my custom VirtualPathProvider after i put registration of my custom VirtualPathProvider provider first line in the Application_Start()

    protected void Application_Start()
    {
        //Should be first line before routes and areas registration.
        HostingEnvironment.RegisterVirtualPathProvider(new MyVirtualPathProvider());

        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }

When registration of custom VirtualPathProvider in Global.asax.cs folowing after AreaRegistration.RegisterAllAreas(); or RegisterRoutes(RouteTable.Routes); method method override VirtualFile GetFile(string virtualPath) wont work for "virtual Views".

UPDATE 2

does it means that the classes RazorView and RazorViewEngineRender is the answer?

UPDATE 3

If i have string representation of my razor view which does not exists in the file system (e.g i store razor views in database) how may i render it using this kind of approach http://buildstarted.com/2010/09/28/mvc-3-razor-view-engine-without-a-controller/

For example string representation of my View looks like this:

"@{
    ViewBag.Title = ""About Us"";
}

About

     Put content here.

"

UPDATE 4

Now i see, to be able to use @Html.<something> custom TemplateBase should be implemented.
The sample of implementation of HtmlTemplateBase<T> could be fount here http://www.fidelitydesign.net/?p=239, but it won't work with RazorEngine v2, i am successfully getting template compiled, then after assembly loaded method public override void Execute() won't be executed i am getting an error: The method or operation is not implemented (stacktrace: http://tinypic.com/r/dcow4/7)

To make “public override T Model” happened i did change declaration of “public TModel Model” to “public virtual TModel Model” in “public abstract class TemplateBase : TemplateBase, ITemplate”. May be there is some another changes should be done? Or something in HtmlTemplateBase<T> should be done another way?


问:
How to set which solution when creating Entity definition using the WebAPI
Context

I would like to create a custom Entity using the Dynamics 365 WebAPI. When reading the official documentation Create and update entity definitions using the Web API I can not find traces where to set which Solution is the target of the Entity Creation

Question

How and where to set in which Solution is the target the Create Entity operation?

答:
It would appear that after creating the entity you could use the Web API's Add Solution Component Action.

In this article, David Yack has an example of using this action to add a Web Resource to a Solution via his Web API helper library.

This article lists the component types. Entity is 1.


问:
How to set focus on a particular row in a datagrid/gridview?
I have a datagrid/gridview. I'm populating the grid with 10 rows initially. On a button click every time,I'm keeping on adding 10 rows to the datagrid/gridview. Now I want to set the focus to the last row every time the grid is populated. I can get the index of that row,but I can't set focus to that particular row.

Do anyone of you have any idea how to do it in C#?

答:
Try this, it's work for me</p>

```<code>   public static void ItemSetFocus(DataGrid Dg, int SelIndex)
    {
        if (Dg.Items.Count >= 1 && SelIndex < Dg.Items.Count)
        {
           Dg.ScrollIntoView(Dg.Items.GetItemAt(SelIndex));
           Dg.SelectionMode = DataGridSelectionMode.Single;
           Dg.SelectionUnit = DataGridSelectionUnit.FullRow;
           Dg.SelectedIndex = SelIndex;
           DataGridRow row = (DataGridRow)Dg.ItemContainerGenerator.ContainerFromIndex(SelIndex);
                row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
        }
    }
</code>```

Body:
Try this, it's work for me

   public static void ItemSetFocus(DataGrid Dg, int SelIndex)
    {
        if (Dg.Items.Count >= 1 && SelIndex < Dg.Items.Count)
        {
           Dg.ScrollIntoView(Dg.Items.GetItemAt(SelIndex));
           Dg.SelectionMode = DataGridSelectionMode.Single;
           Dg.SelectionUnit = DataGridSelectionUnit.FullRow;
           Dg.SelectedIndex = SelIndex;
           DataGridRow row = (DataGridRow)Dg.ItemContainerGenerator.ContainerFromIndex(SelIndex);
                row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
        }
    }


答: Remember use 'jQuery' instead of '$' in wordrpess. </p>

Title: Run Java Script in Wordpress


问:
What are the ZeroMQ valid .recv() flags?
In pyzmq Socket.recv_pyobj, you can supply an optional parameter int flags, which can be 'Any valid .recv() flag'. Unfortunately I can't find any reference as to what these flags actually are.

So, what are the valid .recv() flags in ZeroMQ?

I've tagged this question with both the pyzmq and zeromq tags because I believe the answer may not be specific to pyzmq.

答:
Since ZeroMQ v.2.x .recv() method supports ZMQ_NOBLOCK flag and ZMQ_RCVMORE flag.

The flags argument, as defined in the API, is a combination of the flags.

Be also informed, that respective third party language bindings / wrappers  { may | do } provide their respective own ( typically #define'd constant names ), so the best place to check is the pyzmq source code.

So far a python was equipped with these flag-constants in this manner:

```<code>import zmq

print( zmq.__version__ )
2.1.11

print( zmq.NOBLOCK )
1

print( zmq.RCVMORE )
13

print( zmq.Socket.recv.__doc__ )
...
</code>```

Body:
Since ZeroMQ v.2.x .recv() method supports ZMQ_NOBLOCK flag and ZMQ_RCVMORE flag.

The flags argument, as defined in the API, is a combination of the flags.

Be also informed, that respective third party language bindings / wrappers  { may | do } provide their respective own ( typically #define'd constant names ), so the best place to check is the pyzmq source code.

So far a python was equipped with these flag-constants in this manner:

import zmq

print( zmq.__version__ )
2.1.11

print( zmq.NOBLOCK )
1

print( zmq.RCVMORE )
13

print( zmq.Socket.recv.__doc__ )
...


问:
Does Perl initialize variables in a sub that returns nothing before the declaration of the variables
```<code>sub Thing {
  my $self = shift;
  if ($self->{validationTest} != 1) {return;}

  my $data = 'Hello, World!';
  return $data;
}
</code>```

What happens to $data if the IF conditional is true and the sub is returned early?

答: When the if condition is true, Thing() returns undef. The variable $data is not even created.

Body:
sub Thing {
  my $self = shift;
  if ($self->{validationTest} != 1) {return;}

  my $data = 'Hello, World!';
  return $data;
}

What happens to $data if the IF conditional is true and the sub is returned early?


问:
Automatically wrap text to a width in RaphaelJS?
I am currently trying to add some text, which is added dynamically, using RaphaelJS.  I want the text to break at 200 pixels, then continue on the next line. Just like if you had a regular DIV with a width in HTML.

https://jsfiddle.net/qLvuztcy/

I've tried something like:

```<code>.text {
    width: 200px;
    max-width: 200px; //and this
}
</code>```

But that's not how it works, unfortunately. Does anyone know how I can achieve this? I know that adding a \n to the text will make a new line, but I'm not sure how to achieve what I want.

答:
I found an answer for Snap.svg which I've modified a bit. It works perfectly, however.

```<code>function text(x, y, txt, max_width, element_class) {
    var abc = "abcdefghijklmnopqrstuvwxyzæøåABCDEFGHIJKLMNOPQRSTUVWXYZÆØÅ";
    var temp = rsr.text(50, 50, abc);
    temp.node.classList.add("text");
    var letter_width = temp.getBBox().width / abc.length;
    temp.remove();

    var heights = [];

    var loopLines = txt.split("\n");
    for (j = 0; j < loopLines.length; j++) {
        var words = loopLines[j].split(" ");
        var width_so_far = 0,
            current_line = 0,
            lines = [''];
        for (var i = 0; i < words.length; i++) {
            var l = words[i].length;
            if (width_so_far + (l * letter_width) > max_width) {
                lines.push('');
                current_line++;
                width_so_far = 0;
            }
            width_so_far += l * letter_width;
            lines[current_line] += words[i] + " ";
        }

        if (j > 0) {
            y += heights[j - 1];
        }

        lines = lines.join("\n");
        var t = rsr.text(x, y, lines);
        $(t.node).find("tspan").attr("dy", "1.2em");
        t.node.classList.add(element_class);
        heights.push(t.getBBox().height);
    }
}
</code>```

Requires jQuery, as I am doing the find("tspan") with jQuery (might as well, since I use it other places as well).

I've modified it to now support \n in your strings as well.

Body:
I am currently trying to add some text, which is added dynamically, using RaphaelJS.  I want the text to break at 200 pixels, then continue on the next line. Just like if you had a regular DIV with a width in HTML.

https://jsfiddle.net/qLvuztcy/

I've tried something like:

.text {
    width: 200px;
    max-width: 200px; //and this
}

But that's not how it works, unfortunately. Does anyone know how I can achieve this? I know that adding a \n to the text will make a new line, but I'm not sure how to achieve what I want.

Body:
I found an answer for Snap.svg which I've modified a bit. It works perfectly, however.

function text(x, y, txt, max_width, element_class) {
    var abc = "abcdefghijklmnopqrstuvwxyzæøåABCDEFGHIJKLMNOPQRSTUVWXYZÆØÅ";
    var temp = rsr.text(50, 50, abc);
    temp.node.classList.add("text");
    var letter_width = temp.getBBox().width / abc.length;
    temp.remove();

    var heights = [];

    var loopLines = txt.split("\n");
    for (j = 0; j < loopLines.length; j++) {
        var words = loopLines[j].split(" ");
        var width_so_far = 0,
            current_line = 0,
            lines = [''];
        for (var i = 0; i < words.length; i++) {
            var l = words[i].length;
            if (width_so_far + (l * letter_width) > max_width) {
                lines.push('');
                current_line++;
                width_so_far = 0;
            }
            width_so_far += l * letter_width;
            lines[current_line] += words[i] + " ";
        }

        if (j > 0) {
            y += heights[j - 1];
        }

        lines = lines.join("\n");
        var t = rsr.text(x, y, lines);
        $(t.node).find("tspan").attr("dy", "1.2em");
        t.node.classList.add(element_class);
        heights.push(t.getBBox().height);
    }
}

Requires jQuery, as I am doing the find("tspan") with jQuery (might as well, since I use it other places as well).

I've modified it to now support \n in your strings as well.


问:
Validating Bootstrap date-time picker in Laravel request
I am using Bootstrap datetime picker and I am trying to validate the date in my controller but it always gives me an error saying the format is not right!.

However I can create a new Carbon date object from the request data just fine but I cannot validate the request object using the same format.

This throws an error saying the from does not match format d M Y - H:i

```<code>$request->validate([
            'from' => 'date_format:"d M Y - H:i"|required|before:till',
            'till' => 'date_format:"d M Y - H:i"|required|after:from'
    ]);
</code>```

But this code works, if I use the data without any validation.

```<code>$ride->from = Carbon::createFromFormat('d M Y - H:i', $request->from)->toDateTimeString();
$ride->till = Carbon::createFromFormat('d M Y - H:i', $request->till)->toDateTimeString();
</code>```

Note:
The bootstrap dateTimePicker has format: "dd MM yyyy - hh:ii" but I understand javascript format differs from php format.

What is going wrong here?

Edit: These are the input dates obtained from dumping the request object.

```<code>  "from" => "16 November 2017 - 14:10"
  "till" => "06 November 2017 - 12:00"
</code>```

答:
Because using before and after for date is goes to strtotime for checking check this in doc

And 16 Nov 2017 - 12:10 is not valid date check not valid date Also check after removing - valid date

So I suggest you to convert like this

```<code>$from = str_replace("-","",$request->from);
$to = str_replace("-","",$request->to);
$request->validate([
        'from' => 'date_format:"d M Y - H:i"|required|before:'.$to,
        'till' => 'date_format:"d M Y - H:i"|required|after:'.$from
]);
</code>```

Body:
I am using Bootstrap datetime picker and I am trying to validate the date in my controller but it always gives me an error saying the format is not right!.

However I can create a new Carbon date object from the request data just fine but I cannot validate the request object using the same format.

This throws an error saying the from does not match format d M Y - H:i

$request->validate([
            'from' => 'date_format:"d M Y - H:i"|required|before:till',
            'till' => 'date_format:"d M Y - H:i"|required|after:from'
    ]);

But this code works, if I use the data without any validation.

$ride->from = Carbon::createFromFormat('d M Y - H:i', $request->from)->toDateTimeString();
$ride->till = Carbon::createFromFormat('d M Y - H:i', $request->till)->toDateTimeString();

Note:
The bootstrap dateTimePicker has format: "dd MM yyyy - hh:ii" but I understand javascript format differs from php format.

What is going wrong here?

Edit: These are the input dates obtained from dumping the request object.

  "from" => "16 November 2017 - 14:10"
  "till" => "06 November 2017 - 12:00"

Body:
Because using before and after for date is goes to strtotime for checking check this in doc

And 16 Nov 2017 - 12:10 is not valid date check not valid date Also check after removing - valid date

So I suggest you to convert like this

$from = str_replace("-","",$request->from);
$to = str_replace("-","",$request->to);
$request->validate([
        'from' => 'date_format:"d M Y - H:i"|required|before:'.$to,
        'till' => 'date_format:"d M Y - H:i"|required|after:'.$from
]);


问:
Linux - Splash screen for Java application
On Windows I use Exe4J to start my Java Application. This has the following advantages:

Splashscreen which shows before Java starts

Possibility to update a Label on the splash screen during the startup, until the application is folly loaded ("Initializing Flux compensator","Reordering high nibbles", etc.)

Now I want to implement this on Linux. I start my App with a Shell script, but would love an easy way to show some kind of splash GUI with a label on it, which I can update from my shell script during startup.

Is there an easy way to fire up a minimal GUI from a shell script, and to update the label in it from the shell script, without having to compile a separate executable for it for linux (and maybe even Mac OS X)?

PS: I don't want to use the Java build in splash screen because of the Label which has to be updated dynamically.

答:
You could use Python (or some other scripting language that exposes GUI functionality) from your script.

http://docs.python.org/faq/gui.html


问:
How to save font style and font size to rich text file in java
Hello I am currently working on a java text editor for a module in college.  I am having some trouble getting the font styles and sizes to save to a rich text file I am currently using the printwriter method to write the text in the text area to the file.  I have included my saveFile code below.  This my first time posting so sorry if there's anything wrong with my post, thanks in advance.</p>

```<code>public class saveFile  implements ActionListener
{

    @Override
    public void actionPerformed(ActionEvent e){
        //allow user to enter file name
        String s = JOptionPane.showInputDialog("Input name of file:");
        String w = "";
        try
        {
            //Allow user to enter directory
            w = JOptionPane.showInputDialog("Input Directory where you want the file:\n"
                    + "eg C:\\ for C drive");
        }
        catch(Exception writeFile)
        {
            JOptionPane.showMessageDialog(null, "Task could not be completed\nPlease try again"
                    ,"File Write Error", JOptionPane.ERROR_MESSAGE, null);
        }
        //try catch block
        try
        {
            //check if fields are null or empty
            if(!(s.isEmpty() && w.isEmpty()) && (w != null && s != null))
            {
                try
                {
                    //Create new file and append with .rtf
                    File userFile =  new File(w + s + ".rtf");
                    PrintWriter file = new PrintWriter(userFile);
                    //set files content = text
                    file.print(text.getText());
                    file.close();
                    File dir = new File(w);
                    if(dir.exists())
                    {
                        JOptionPane.showMessageDialog(null, "File " +  s + " created\n" + "Saved in " + w, null,JOptionPane.PLAIN_MESSAGE );
                    }
                    else
                    {
                        throw new Exception();
                    }

                }
                catch(Exception fileNotCreatedException)
                {
                    JOptionPane.showMessageDialog(null,"File not created\n"
                            + "Please check to see directory exists","File Error",
                            JOptionPane.ERROR_MESSAGE, null);
                    fileNotCreatedException.printStackTrace();
                }

            }
        }
</code>```

答:
If you are working in swing with a JTextPane using content type text/rtf, then the RTFEditorKit is used for the StyledDocument.

```<code>OutputStream out = new FileOutputStream(userFile);
StyledDocument doc = textPane.getStyledDocument();
StyledEditorKit editorKit = textPane.getStyledEditorKit();
editorKit.write(out, doc, 0, doc.getLength());
</code>```

As the HTMLEditorKit also is StyledDocument based, it might sometimes pay to first experiment with HTML, as the HTML syntax is easier.

Body:
Hello I am currently working on a java text editor for a module in college.  I am having some trouble getting the font styles and sizes to save to a rich text file I am currently using the printwriter method to write the text in the text area to the file.  I have included my saveFile code below.  This my first time posting so sorry if there's anything wrong with my post, thanks in advance.

public class saveFile  implements ActionListener
{

    @Override
    public void actionPerformed(ActionEvent e){
        //allow user to enter file name
        String s = JOptionPane.showInputDialog("Input name of file:");
        String w = "";
        try
        {
            //Allow user to enter directory
            w = JOptionPane.showInputDialog("Input Directory where you want the file:\n"
                    + "eg C:\\ for C drive");
        }
        catch(Exception writeFile)
        {
            JOptionPane.showMessageDialog(null, "Task could not be completed\nPlease try again"
                    ,"File Write Error", JOptionPane.ERROR_MESSAGE, null);
        }
        //try catch block
        try
        {
            //check if fields are null or empty
            if(!(s.isEmpty() && w.isEmpty()) && (w != null && s != null))
            {
                try
                {
                    //Create new file and append with .rtf
                    File userFile =  new File(w + s + ".rtf");
                    PrintWriter file = new PrintWriter(userFile);
                    //set files content = text
                    file.print(text.getText());
                    file.close();
                    File dir = new File(w);
                    if(dir.exists())
                    {
                        JOptionPane.showMessageDialog(null, "File " +  s + " created\n" + "Saved in " + w, null,JOptionPane.PLAIN_MESSAGE );
                    }
                    else
                    {
                        throw new Exception();
                    }

                }
                catch(Exception fileNotCreatedException)
                {
                    JOptionPane.showMessageDialog(null,"File not created\n"
                            + "Please check to see directory exists","File Error",
                            JOptionPane.ERROR_MESSAGE, null);
                    fileNotCreatedException.printStackTrace();
                }

            }
        }

Body:
If you are working in swing with a JTextPane using content type text/rtf, then the RTFEditorKit is used for the StyledDocument.

OutputStream out = new FileOutputStream(userFile);
StyledDocument doc = textPane.getStyledDocument();
StyledEditorKit editorKit = textPane.getStyledEditorKit();
editorKit.write(out, doc, 0, doc.getLength());

As the HTMLEditorKit also is StyledDocument based, it might sometimes pay to first experiment with HTML, as the HTML syntax is easier.


问:
Updating column with unique constraint/index in Firebird in multiple rows
I have a table that looks like this:

```<code>CREATE TABLE SCHEDULE (
    RCDNO              INTEGER NOT NULL,
    MASTCONNO          INTEGER NOT NULL,
    ROWNO              INTEGER DEFAULT 0 NOT NULL,
    EDITTIMESTAMP      TIMESTAMP
)
ALTER TABLE SCHEDULE ADD CONSTRAINT PK_SCHEDULE PRIMARY KEY (RCDNO);
CREATE UNIQUE INDEX IDX_SCHEDULE_3 ON SCHEDULE (MASTCONNO, ROWNO);
</code>```

I can run a query like this:

```<code>select mastconno, rowno, rcdno, edittimestamp
from schedule
where mastconno = 12
order by rowno desc
</code>```

and I get this:

Due to a bug in the app code, the time portion of the edittimestamp is missing but that's of no consequence here. The records are nonetheless listed in desc order of entry by ROWNO. That's what the design of this table is meant to facilitate.

What I tried to do is this...

```<code>update SCHEDULE
set ROWNO = (ROWNO + 1)
where MASTCONNO = 12
</code>```

... in preparation for the insert of a new ROWNO=0 record, I get this error:

```<code>attempt to store duplicate value (visible to active transactions) in unique index "IDX_SCHEDULE_3".
Problematic key value is ("MASTCONNO" = 12, "ROWNO" = 3).
</code>```

Incidently I have an exact copy of the table in MS SQL Server, and I didn't have this problem there. This seems to be specific to the way Firebird works.

So then I tried this, hoping that Firebird would "feed" values from the IN predicate to the UPDATE in a non-offending order.

```<code>update SCHEDULE
set ROWNO = (ROWNO + 1)
where MASTCONNO = 12 and
ROWNO in (select ROWNO from SCHEDULE
where MASTCONNO = 12 order by ROWNO DESC)
</code>```

Sadly the response was the same as before. ROWNO 3 is being duplicated by the update statement.

答:
With the unique index (MASTCONNO, ROWNO) in place, I have tested the following:

```<code>update SCHEDULE
set ROWNO = (ROWNO + 1)
where MASTCONNO = 12
order by ROWNO DESC
</code>```

Works correctly!

```<code>update SCHEDULE
set ROWNO = (ROWNO - 1)
where MASTCONNO = 12
order by ROWNO ASC
</code>```

Also works correctly!

Thanks very much Mark Rotteveel.

Body:
I have a table that looks like this:

CREATE TABLE SCHEDULE (
    RCDNO              INTEGER NOT NULL,
    MASTCONNO          INTEGER NOT NULL,
    ROWNO              INTEGER DEFAULT 0 NOT NULL,
    EDITTIMESTAMP      TIMESTAMP
)
ALTER TABLE SCHEDULE ADD CONSTRAINT PK_SCHEDULE PRIMARY KEY (RCDNO);
CREATE UNIQUE INDEX IDX_SCHEDULE_3 ON SCHEDULE (MASTCONNO, ROWNO);

I can run a query like this:

select mastconno, rowno, rcdno, edittimestamp
from schedule
where mastconno = 12
order by rowno desc

and I get this:

Due to a bug in the app code, the time portion of the edittimestamp is missing but that's of no consequence here. The records are nonetheless listed in desc order of entry by ROWNO. That's what the design of this table is meant to facilitate.

What I tried to do is this...

update SCHEDULE
set ROWNO = (ROWNO + 1)
where MASTCONNO = 12

... in preparation for the insert of a new ROWNO=0 record, I get this error:

attempt to store duplicate value (visible to active transactions) in unique index "IDX_SCHEDULE_3".
Problematic key value is ("MASTCONNO" = 12, "ROWNO" = 3).

Incidently I have an exact copy of the table in MS SQL Server, and I didn't have this problem there. This seems to be specific to the way Firebird works.

So then I tried this, hoping that Firebird would "feed" values from the IN predicate to the UPDATE in a non-offending order.

update SCHEDULE
set ROWNO = (ROWNO + 1)
where MASTCONNO = 12 and
ROWNO in (select ROWNO from SCHEDULE
where MASTCONNO = 12 order by ROWNO DESC)

Sadly the response was the same as before. ROWNO 3 is being duplicated by the update statement.

Body:
With the unique index (MASTCONNO, ROWNO) in place, I have tested the following:

update SCHEDULE
set ROWNO = (ROWNO + 1)
where MASTCONNO = 12
order by ROWNO DESC

Works correctly!

update SCHEDULE
set ROWNO = (ROWNO - 1)
where MASTCONNO = 12
order by ROWNO ASC

Also works correctly!

Thanks very much Mark Rotteveel.


问:
Choosing rows based on grouping condition and field condition
I would like to know how could I choose out these plots where I have together trees "HB" and "KU"?

This is an example of my dataset:

```<code>       plot ID             tree
1    10000503711            LV
2  1000057448111            LV
3  1000057448111            HB
4  1000057448111            KU
5    10000603711            LV
6  1000063448111            TM
7  1000063448111            KS
</code>```

So the result should be something like this (it shouldn't erase other tree species from my dataset but it should choose those plot ID-s where there are both "KU" and "HB"):

```<code>   2  1000057448111            LV
   3  1000057448111            HB
   4  1000057448111            KU
</code>```

Note that some plots have multiple trees growing in them resulting multiple rows per plot. And some plots only have one tree species.

Thank you for your help!

答:
Using dplyr this could be done. But aggregate could also be used.

Edit: using a new dataset to handle this test case of containing both HB and KU.

```<code>options(scipen = 50)
library(dplyr)
ss <- read.table(text = "       plot ID             tree
                 1    10000503711            LV
                 2  1000057448111            LV
                 3  1000057448111            HB
                 4  1000057448111            KU
                 5    10000603711            LV
                 5    10000603711            HB
                 6  1000063448111            TM
                 7  1000063448111            KS", header = T)

ss %>%
  group_by(ID) %>%
  mutate(trees = paste0(tree, collapse = "_")) %>%
  filter(grepl('HB_KU|KU_HB',trees)) %>%  distinct(ID) %>%
  inner_join(.,ss)
</code>```

Output:

```<code>Joining, by = "ID"
# A tibble: 3 x 3
# Groups:   ID [?]
             ID  plot   tree
          <dbl> <int> <fctr>
1 1000057448111     2     LV
2 1000057448111     3     HB
3 1000057448111     4     KU
</code>```

Body:
I would like to know how could I choose out these plots where I have together trees "HB" and "KU"?

This is an example of my dataset:

       plot ID             tree
1    10000503711            LV
2  1000057448111            LV
3  1000057448111            HB
4  1000057448111            KU
5    10000603711            LV
6  1000063448111            TM
7  1000063448111            KS

So the result should be something like this (it shouldn't erase other tree species from my dataset but it should choose those plot ID-s where there are both "KU" and "HB"):

   2  1000057448111            LV
   3  1000057448111            HB
   4  1000057448111            KU

Note that some plots have multiple trees growing in them resulting multiple rows per plot. And some plots only have one tree species.

Thank you for your help!

Body:
Using dplyr this could be done. But aggregate could also be used.

Edit: using a new dataset to handle this test case of containing both HB and KU.

options(scipen = 50)
library(dplyr)
ss <- read.table(text = "       plot ID             tree
                 1    10000503711            LV
                 2  1000057448111            LV
                 3  1000057448111            HB
                 4  1000057448111            KU
                 5    10000603711            LV
                 5    10000603711            HB
                 6  1000063448111            TM
                 7  1000063448111            KS", header = T)

ss %>%
  group_by(ID) %>%
  mutate(trees = paste0(tree, collapse = "_")) %>%
  filter(grepl('HB_KU|KU_HB',trees)) %>%  distinct(ID) %>%
  inner_join(.,ss)

Output:

Joining, by = "ID"
# A tibble: 3 x 3
# Groups:   ID [?]
             ID  plot   tree
          <dbl> <int> <fctr>
1 1000057448111     2     LV
2 1000057448111     3     HB
3 1000057448111     4     KU


问:
Using CSS-Grid Layout in Angular
I am fairly new to Angular (and SPA/Web development in general) and trying to get Angular working together with the new CSS-Grid layout.

Chances are I am simply not importing/injecting a required module but in any case cannot get this to work without getting errors. I did search but could not really find any guide or tutorial for this (Angular and CSS-Grid). There is some information about the CSS-Grid of course but close to nothing related to Angular.

I tried for example the following (taken from here http://maddesigns.de/css-grid-layout-2764.html):

/* CSS */
.wrapper {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
}

   ```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <!-- HTML -->
<div class="wrapper">
   <div class="box a">.a</div>
   <div class="box b">.b</div>
   <div class="box c">.c</div>
   <div class="box d">.d</div>
 </div></code>```

That snippet works here ('Run Code snippet').

But if I create a new angular/CLI project and copy the code straight to app.component.css and app.component.html (probably a bit naive) then it is kind of working but in Firefox I am also getting the error "Error when processing the value 'display'. Declaration ignored." (translated manually from German to English)

This makes me believe I am missing something fundamentally I am not aware of.

答:
The code is fine, the issue turned out to be browser related which just shows how new I am to web development.

I tested some browsers:

IE 11: does not work, exception

Chrome 62: works, no warnings

Firefox 56: works, but shows the warning mentioned in the question

Firefox 57 (Quantum): works, no warnings

Title: Using CSS-Grid Layout in Angular

Body:
I am fairly new to Angular (and SPA/Web development in general) and trying to get Angular working together with the new CSS-Grid layout.

Chances are I am simply not importing/injecting a required module but in any case cannot get this to work without getting errors. I did search but could not really find any guide or tutorial for this (Angular and CSS-Grid). There is some information about the CSS-Grid of course but close to nothing related to Angular.

I tried for example the following (taken from here http://maddesigns.de/css-grid-layout-2764.html):

/* CSS */
.wrapper {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
}

.a

.b

.c

.d

That snippet works here ('Run Code snippet').

But if I create a new angular/CLI project and copy the code straight to app.component.css and app.component.html (probably a bit naive) then it is kind of working but in Firefox I am also getting the error "Error when processing the value 'display'. Declaration ignored." (translated manually from German to English)

This makes me believe I am missing something fundamentally I am not aware of.


问:
Spring boot actuator CPU usage differs from Cloudwatch
We have a spring boot app running inside a Docker container.  Spring boot Actuator reports 4-5% CPU usage, but cloudwatch reports 50-55%. Why is there a discrepancy? Are these stats measuring different things?  </p>

答:
Spring Boot inside the Docker container would give you a CPU usage of your container.

CloudWatch is reporting the CPU Utilization of your Instance. It is reported by the hypervisor and thus is quite accurate.


问:
Reaching Form Instances
I'm creating a level editor application designed in a MDI project. The application has two main view modes, the WorldEditor mode and ObjectEditor mode. Depending on the mode, I want a separate property window to show a property setup specific for the current mode.

I've thought of using the Activated event, and from that event tell the property form to load the appropriate setup. I need to reach the PropertyForm from within the World or Object Form class to accomplish this. This is where I'm stuck.

I believe I should be able to solve this by declaring the PropertyForm class as static. Since I only use one of it's types at a time, I want to be able to reach it globally. However declaring a form class as static gives me compiler errors. I'm doing it wrong, if it's even possible.

How can I reach and search for different forms that are active in the application?

答:
Sounds to me like your MDI parent form (which knows which of the MDI child windows is active) should hold a reference to the Property form. Add an event handler to each created child window's Activated event, using a function in your parent form that uses the information from the activated child window to set up the Property form correctly.

Sesh's answer regarding a Singleton may apply as well, though that's really another question.

OwnerDisplayName: Erik

Title: Reaching Form Instances

OwnerDisplayName: Harper Shelby


问:
Missing on-screen keyboard for Flash/Flex web application on Android?
I have an enterprise Flex web application, served up over https, that runs fine on Flash player 10.0 and beyond on a desktop computer/browser.

However, when I run it from my HTC Incredible with Android 2.2 the app loads fine, but there is no on-screen keyboard and so I cannot log in.  I can see the blinking cursor inside the username and password text fields.  I can switch between them.  I can even hit the login button and see an authentication error!

According to Adobe this should Just Work.  Any ideas?  I wanna show off our spanking new app to strangers at the bus stop!

答:
The spark components in Flex 4 are not currently optimized for mobile.  The next release of Flex codenamed "Hero" will provide mobile optimized skins for the spark TextInput/TextArea components.  These skins are based on TextField and they are also optimized for performance with ActionScript skins and a more appropriate default size. Text support in the current Hero preview release is minimal, but the final release will be more robust, for example supporting scrolling in a TextArea.  Check out the spec for more information: http://opensource.adobe.com/wiki/display/flexsdk/Mobile+Text+Components

It's probably worthwhile to note that the mobile features in Hero are designed with standalone mobile applications in mind, not browser-based applications.  That said you might be able to grab those mobile skins and try using them in a browser-based Flex application compiled with Hero.


问:
Mysql and phpmyadmin installation in RaspberryPi 3
I am trying to install mysql and phpmyadmin in my raspberrypi 3. I have followed many tutorials on the internet and specifically this link
https://www.youtube.com/watch?v=ozo_npQMQS8

now the problem is that while installing mysql i dont get any window in the command line asking for the password hence i am not able to set the root password..
I am able to get into mysql by "sudo"

sudo mysql -u root

but i am not able to login through the password.
the situation is same for the phpmyadmin. the installation is correct but i am not able to login with the password.
Thanks

答:
So i figure out the problem is with the plugin. so i have to set the plugin to mysql_native_password.

To check the plugin type

```<code>USE mysql;
SELECT User, Host, plugin FROM mysql.user;
</code>```

You may see that mysql_native_password is not there..

so to setup you may write these commands..

```<code>sudo mysql -u root

 mysql> USE mysql;
 mysql> UPDATE user SET
 plugin='mysql_native_password' WHERE User='root'; mysql> FLUSH
 PRIVILEGES; mysql> exit;

 $ service mysql restart
</code>```

So now you will be able to login both in phpmyadmin and in console through root password.

Body:
So i figure out the problem is with the plugin. so i have to set the plugin to mysql_native_password.

To check the plugin type

USE mysql;
SELECT User, Host, plugin FROM mysql.user;

You may see that mysql_native_password is not there..

so to setup you may write these commands..

sudo mysql -u root

 mysql> USE mysql;
 mysql> UPDATE user SET
 plugin='mysql_native_password' WHERE User='root'; mysql> FLUSH
 PRIVILEGES; mysql> exit;

 $ service mysql restart

So now you will be able to login both in phpmyadmin and in console through root password.


问:
HardFault cortex, how do i debug it
I'm using a cortex m4 with freertos and i receive the following error

```<code>Err: -110595: Hardfault occurred!
</code>```

I have no idea what to check.
The meaning is CRIT_ERR_HARD_FAULT but how do i trace it back?

答:
It's always tricky and there is no common checklist what should be checked to give you 100% chance for quick success here.

Anyway checking several registers' values should give you enough information to proceed. To do it, you have to know what's the procedure of entering an exception - especially what's happening with core registers and the stack: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0553a/Babefdjc.html

If you can use online debugging, put a breakpoint in hard fault handler and check the following:

stacked PC - as written in the article above, on exception entry ARM core automatically pushes registers r0,r1,r2,r3,sp,lr,pc and psr on stack. Look it up to check where the program was before execution

current LR - to verify if you came from Thread mode (normal program execution) or another interrupt compare current LR with the table in the article

ISR_NUMBER in IPSR being part of current PSR - to verify whether in fact hard fault exception occurred or your hard fault handler is used as a sink for all types of faults

CFSR and other fault related registers in SCB - it should give you more information what's exactly caused the problem. Since SCB is a peripheral block, it's not visible in most IDEs by default. Install peripheral plugin or simply access addresses via memory inspection window  http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0553a/Cihcfefj.html

If you're unable to do online debugging, you'll need a feature which will dump these registers somehow.

Good luck!

Title: HardFault cortex, how do i debug it

Body:
I'm using a cortex m4 with freertos and i receive the following error

Err: -110595: Hardfault occurred!

I have no idea what to check.
The meaning is CRIT_ERR_HARD_FAULT but how do i trace it back?


问:
Kafka Spark Stream throws Exception:No current assignment for partition
Below is my scala code to create spark kafka stream:

```<code>val kafkaParams = Map[String, Object](
"bootstrap.servers" -> "server110:2181,server110:9092",
"zookeeper" -> "server110:2181",
"key.deserializer" -> classOf[StringDeserializer],
"value.deserializer" -> classOf[StringDeserializer],
"group.id" -> "example",
"auto.offset.reset" -> "latest",
"enable.auto.commit" -> (false: java.lang.Boolean)
)
val topics = Array("ABTest")
val stream = KafkaUtils.createDirectStream[String, String](
ssc,
PreferConsistent,
Subscribe[String, String](topics, kafkaParams)
)
</code>```

But after run for 10 hours, it throws exceptions:

```<code>2017-02-10 10:56:20,000 INFO [JobGenerator] internals.ConsumerCoordinator: **Revoking previously assigned partitions** [ABTest-0, ABTest-1] for group example
2017-02-10 10:56:20,000 INFO [JobGenerator] internals.AbstractCoordinator: (Re-)joining group example
2017-02-10 10:56:20,011 INFO [JobGenerator] internals.AbstractCoordinator: (Re-)joining group example
2017-02-10 10:56:40,057 INFO [JobGenerator] internals.AbstractCoordinator: Successfully joined group example with generation 5
2017-02-10 10:56:40,058 INFO [JobGenerator] internals.ConsumerCoordinator: **Setting newly assigned partitions** [ABTest-1] for group example
2017-02-10 10:56:40,080 ERROR [JobScheduler] scheduler.JobScheduler: Error generating jobs for time 1486695380000 ms
java.lang.IllegalStateException: No current assignment for partition ABTest-0
at org.apache.kafka.clients.consumer.internals.SubscriptionState.assignedState(SubscriptionState.java:231)
at org.apache.kafka.clients.consumer.internals.SubscriptionState.needOffsetReset(SubscriptionState.java:295)
at org.apache.kafka.clients.consumer.KafkaConsumer.seekToEnd(KafkaConsumer.java:1169)
at org.apache.spark.streaming.kafka010.DirectKafkaInputDStream.latestOffsets(DirectKafkaInputDStream.scala:179)
at org.apache.spark.streaming.kafka010.DirectKafkaInputDStream.compute(DirectKafkaInputDStream.scala:196)
at org.apache.spark.streaming.dstream.DStream$$anonfun$getOrCompute$1$$anonfun$1$$anonfun$apply$7.apply(DStream.scala:341)
at org.apache.spark.streaming.dstream.DStream$$anonfun$getOrCompute$1$$anonfun$1$$anonfun$apply$7.apply(DStream.scala:341)
at scala.util.DynamicVariable.withValue(DynamicVariable.scala:58)
at org.apache.spark.streaming.dstream.DStream$$anonfun$getOrCompute$1$$anonfun$1.apply(DStream.scala:340)
at org.apache.spark.streaming.dstream.DStream$$anonfun$getOrCompute$1$$anonfun$1.apply(DStream.scala:340)
at org.apache.spark.streaming.dstream.DStream.createRDDWithLocalProperties(DStream.scala:415)
at org.apache.spark.streaming.dstream.DStream$$anonfun$getOrCompute$1.apply(DStream.scala:335)
at org.apache.spark.streaming.dstream.DStream$$anonfun$getOrCompute$1.apply(DStream.scala:333)
at scala.Option.orElse(Option.scala:289)
at org.apache.spark.streaming.dstream.DStream.getOrCompute(DStream.scala:330)
at org.apache.spark.streaming.dstream.ForEachDStream.generateJob(ForEachDStream.scala:48)
at org.apache.spark.streaming.DStreamGraph$$anonfun$1.apply(DStreamGraph.scala:117)
at org.apache.spark.streaming.DStreamGraph$$anonfun$1.apply(DStreamGraph.scala:116)
at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:241)
at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:241)
at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
at scala.collection.TraversableLike$class.flatMap(TraversableLike.scala:241)
at scala.collection.AbstractTraversable.flatMap(Traversable.scala:104)
at org.apache.spark.streaming.DStreamGraph.generateJobs(DStreamGraph.scala:116)
at org.apache.spark.streaming.scheduler.JobGenerator$$anonfun$3.apply(JobGenerator.scala:248)
at org.apache.spark.streaming.scheduler.JobGenerator$$anonfun$3.apply(JobGenerator.scala:246)
at scala.util.Try$.apply(Try.scala:192)
at org.apache.spark.streaming.scheduler.JobGenerator.generateJobs(JobGenerator.scala:246)
at org.apache.spark.streaming.scheduler.JobGenerator.org$apache$spark$streaming$scheduler$JobGenerator$$processEvent(JobGenerator.scala:182)
at org.apache.spark.streaming.scheduler.JobGenerator$$anon$1.onReceive(JobGenerator.scala:88)
at org.apache.spark.streaming.scheduler.JobGenerator$$anon$1.onReceive(JobGenerator.scala:87)
at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48)
</code>```

Obviously , The partition ABTestMsg-0 has already be revoked for this consumer, but it seems that the spark streaming consumer are not aware of that and continue to consume data of this revoked topic-partition , so the exception occurs and the total spark job aborted.
I think the kafka rebalance event is very normal , how can I modify my code to make Spark streaming deal with the partition-revoke event correctly?

答: It took me a while to figure this one out. It happens because of rebalancing. Instead of Subscribe ConsumerStrategy use Assign.</p>

Body:
Below is my scala code to create spark kafka stream:

val kafkaParams = Map[String, Object](
"bootstrap.servers" -> "server110:2181,server110:9092",
"zookeeper" -> "server110:2181",
"key.deserializer" -> classOf[StringDeserializer],
"value.deserializer" -> classOf[StringDeserializer],
"group.id" -> "example",
"auto.offset.reset" -> "latest",
"enable.auto.commit" -> (false: java.lang.Boolean)
)
val topics = Array("ABTest")
val stream = KafkaUtils.createDirectStream[String, String](
ssc,
PreferConsistent,
Subscribe[String, String](topics, kafkaParams)
)

But after run for 10 hours, it throws exceptions:

2017-02-10 10:56:20,000 INFO [JobGenerator] internals.ConsumerCoordinator: **Revoking previously assigned partitions** [ABTest-0, ABTest-1] for group example
2017-02-10 10:56:20,000 INFO [JobGenerator] internals.AbstractCoordinator: (Re-)joining group example
2017-02-10 10:56:20,011 INFO [JobGenerator] internals.AbstractCoordinator: (Re-)joining group example
2017-02-10 10:56:40,057 INFO [JobGenerator] internals.AbstractCoordinator: Successfully joined group example with generation 5
2017-02-10 10:56:40,058 INFO [JobGenerator] internals.ConsumerCoordinator: **Setting newly assigned partitions** [ABTest-1] for group example
2017-02-10 10:56:40,080 ERROR [JobScheduler] scheduler.JobScheduler: Error generating jobs for time 1486695380000 ms
java.lang.IllegalStateException: No current assignment for partition ABTest-0
at org.apache.kafka.clients.consumer.internals.SubscriptionState.assignedState(SubscriptionState.java:231)
at org.apache.kafka.clients.consumer.internals.SubscriptionState.needOffsetReset(SubscriptionState.java:295)
at org.apache.kafka.clients.consumer.KafkaConsumer.seekToEnd(KafkaConsumer.java:1169)
at org.apache.spark.streaming.kafka010.DirectKafkaInputDStream.latestOffsets(DirectKafkaInputDStream.scala:179)
at org.apache.spark.streaming.kafka010.DirectKafkaInputDStream.compute(DirectKafkaInputDStream.scala:196)
at org.apache.spark.streaming.dstream.DStream$$anonfun$getOrCompute$1$$anonfun$1$$anonfun$apply$7.apply(DStream.scala:341)
at org.apache.spark.streaming.dstream.DStream$$anonfun$getOrCompute$1$$anonfun$1$$anonfun$apply$7.apply(DStream.scala:341)
at scala.util.DynamicVariable.withValue(DynamicVariable.scala:58)
at org.apache.spark.streaming.dstream.DStream$$anonfun$getOrCompute$1$$anonfun$1.apply(DStream.scala:340)
at org.apache.spark.streaming.dstream.DStream$$anonfun$getOrCompute$1$$anonfun$1.apply(DStream.scala:340)
at org.apache.spark.streaming.dstream.DStream.createRDDWithLocalProperties(DStream.scala:415)
at org.apache.spark.streaming.dstream.DStream$$anonfun$getOrCompute$1.apply(DStream.scala:335)
at org.apache.spark.streaming.dstream.DStream$$anonfun$getOrCompute$1.apply(DStream.scala:333)
at scala.Option.orElse(Option.scala:289)
at org.apache.spark.streaming.dstream.DStream.getOrCompute(DStream.scala:330)
at org.apache.spark.streaming.dstream.ForEachDStream.generateJob(ForEachDStream.scala:48)
at org.apache.spark.streaming.DStreamGraph$$anonfun$1.apply(DStreamGraph.scala:117)
at org.apache.spark.streaming.DStreamGraph$$anonfun$1.apply(DStreamGraph.scala:116)
at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:241)
at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:241)
at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
at scala.collection.TraversableLike$class.flatMap(TraversableLike.scala:241)
at scala.collection.AbstractTraversable.flatMap(Traversable.scala:104)
at org.apache.spark.streaming.DStreamGraph.generateJobs(DStreamGraph.scala:116)
at org.apache.spark.streaming.scheduler.JobGenerator$$anonfun$3.apply(JobGenerator.scala:248)
at org.apache.spark.streaming.scheduler.JobGenerator$$anonfun$3.apply(JobGenerator.scala:246)
at scala.util.Try$.apply(Try.scala:192)
at org.apache.spark.streaming.scheduler.JobGenerator.generateJobs(JobGenerator.scala:246)
at org.apache.spark.streaming.scheduler.JobGenerator.org$apache$spark$streaming$scheduler$JobGenerator$$processEvent(JobGenerator.scala:182)
at org.apache.spark.streaming.scheduler.JobGenerator$$anon$1.onReceive(JobGenerator.scala:88)
at org.apache.spark.streaming.scheduler.JobGenerator$$anon$1.onReceive(JobGenerator.scala:87)
at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48)

Obviously , The partition ABTestMsg-0 has already be revoked for this consumer, but it seems that the spark streaming consumer are not aware of that and continue to consume data of this revoked topic-partition , so the exception occurs and the total spark job aborted.
I think the kafka rebalance event is very normal , how can I modify my code to make Spark streaming deal with the partition-revoke event correctly?


问:
Is it possible to bind a class member in kodein?
There is 2 classes:

A - base class

B - class of member of A

with implementation something like this:

```<code>class A {
   val b : B = B()
}

class B
</code>```

Problem

Is it possible to create a binding for b to hide redundant info about b source in common classes?

Kodein declaration:

```<code>override val kodein by Kodein.lazy {

    bind<A>() with singleton { A() }
    bind<B>() with "a.b some impl???"

}
</code>```

Usecase

```<code>class Usecase(kodein : Kodein){

    val b : B = kodein.instance()

}
</code>```

答:
Very simple :

```<code>bind<B>() with provider { instance<A>().b }
</code>```

The provider binding is the simplest one : it will call the provided function everytime.
The function itself runs inside a Kodein context, hence the use of the instance function.

Body:
There is 2 classes:

A - base class

B - class of member of A

with implementation something like this:

class A {
   val b : B = B()
}

class B

Problem

Is it possible to create a binding for b to hide redundant info about b source in common classes?

Kodein declaration:

override val kodein by Kodein.lazy {

    bind() with singleton { A() }
    bind() with "a.b some impl???"

}

Usecase

class Usecase(kodein : Kodein){

    val b : B = kodein.instance()

}

Body:
Very simple :

bind<B>() with provider { instance<A>().b }

The provider binding is the simplest one : it will call the provided function everytime.
The function itself runs inside a Kodein context, hence the use of the instance function.


问:
Iframe moves content down from neighbour element
I'm using display: table-* to style a basic structure.

#page {
  display: table;
  width: 1000px;
  margin: 0 auto;
}

#events,
#righ_sidebar {
  display: table-cell;
}

#events {
  width: 75%;
}

#righ_sidebar {
  width: 25%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="page">
  <div id="events">
    <h1>Events</h1>

    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
      in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    </p>

    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
      in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    </p>
  </div>

  <div id="righ_sidebar">
    <iframe id="up2europe" marginheight="5" marginwidth="5" src="https://www.up2europe.eu/widget/go/181d4bdc08289da3d78b79ee5f9e7e2d"></iframe>
  </div>
</div></code>```

The problem is that the iframe from #righ_sidebar it moves down the content from #events. How to use iframe and display table-* together, but correctly aligned?

答:
You can do it with the Flexbox:

#page {
  display: flex; /* displays flex-items (children) inline */
  width: 1000px;
  margin: 0 auto;
}

#events {
  flex: 3; /* 75% */
}

#righ_sidebar {
  flex: 1; /* 25% */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="page">
  <div id="events">
    <h1>Events</h1>
    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
      in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    </p>
    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
      in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    </p>
  </div>
  <div id="righ_sidebar">
    <iframe id="up2europe" marginheight="5" marginwidth="5" src="https://www.up2europe.eu/widget/go/181d4bdc08289da3d78b79ee5f9e7e2d"></iframe>
  </div>
</div></code>```

Body:
I'm using display: table-* to style a basic structure.

#page {
  display: table;
  width: 1000px;
  margin: 0 auto;
}

#events,
#righ_sidebar {
  display: table-cell;
}

#events {
  width: 75%;
}

#righ_sidebar {
  width: 25%;
}

Events

      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
      in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
      in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

The problem is that the iframe from #righ_sidebar it moves down the content from #events. How to use iframe and display table-* together, but correctly aligned?

Body:
You can do it with the Flexbox:

#page {
  display: flex; /* displays flex-items (children) inline */
  width: 1000px;
  margin: 0 auto;
}

#events {
  flex: 3; /* 75% */
}

#righ_sidebar {
  flex: 1; /* 25% */
}

<div id="page">
  <div id="events">
    <h1>Events</h1>
    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
      in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    </p>
    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
      in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    </p>
  </div>
  <div id="righ_sidebar">
    <iframe id="up2europe" marginheight="5" marginwidth="5" src="https://www.up2europe.eu/widget/go/181d4bdc08289da3d78b79ee5f9e7e2d"></iframe>
  </div>
</div>

ContentLicense: CC BY-SA 4.0


问:
How to enable a button in a delphi form only if all combo boxes have the selection made
Need to check if multiple Combo boxes are not empty.
Tried for one combo box, how to apply the same to multiple.

```<code>if (combobox1.ItemIndex <> -1) then
  begin
     btnOK.Enabled := true;
  end
else
btnOK.Enabled := false;
</code>```

PS: I'm new to delphi please bear with mistakes, if any.

答:
The easiest would be a construct like this

```<code>if (ComboBox1.ItemIndex = -1) or (ComboBox2.ItemIndex = -1) or (ComboBox3.ItemIndex = -1) then
    Exit;

Button1.Enabled := true;
</code>```

This exits the procedure if any of the comboboxes has -1 selected. If all boxes are selected, the button gets enabled.

Or you could just bind them all together and write directly to the Enabled property

```<code>Button1.Enabled := (ComboBox1.ItemIndex <> -1) and (ComboBox2.ItemIndex <> -1) and (ComboBox3.ItemIndex <> -1);
</code>```

The most beautiful way, if you really have a lot of comboboxes is using arrays

```<code>procedure TForm1.SetButtonActive;
var
    boxes: array of TComboBox;
    box: TComboBox;
begin
    boxes := [ComboBox1, ComboBox2, ComboBox3];

    for box in boxes do
        if box.ItemIndex = -1 then
            Exit;

    Button1.Enabled := true;
end;
</code>```

Body:
Need to check if multiple Combo boxes are not empty.
Tried for one combo box, how to apply the same to multiple.

if (combobox1.ItemIndex <> -1) then
  begin
     btnOK.Enabled := true;
  end
else
btnOK.Enabled := false;

PS: I'm new to delphi please bear with mistakes, if any.

Body:
The easiest would be a construct like this

if (ComboBox1.ItemIndex = -1) or (ComboBox2.ItemIndex = -1) or (ComboBox3.ItemIndex = -1) then
    Exit;

Button1.Enabled := true;

This exits the procedure if any of the comboboxes has -1 selected. If all boxes are selected, the button gets enabled.

Or you could just bind them all together and write directly to the Enabled property

Button1.Enabled := (ComboBox1.ItemIndex <> -1) and (ComboBox2.ItemIndex <> -1) and (ComboBox3.ItemIndex <> -1);

The most beautiful way, if you really have a lot of comboboxes is using arrays

procedure TForm1.SetButtonActive;
var
    boxes: array of TComboBox;
    box: TComboBox;
begin
    boxes := [ComboBox1, ComboBox2, ComboBox3];

    for box in boxes do
        if box.ItemIndex = -1 then
            Exit;

    Button1.Enabled := true;
end;


问:
How to get local server host and port in Spring Boot?
I'm starting up a Spring Boot application with mvn spring-boot:run.

One of my @Controllers needs information about the host and port the application is listening on, i.e. localhost:8080 (or 127.x.y.z:8080). Following the Spring Boot documentation, I use the server.address and server.port properties:

```<code>@Controller
public class MyController {

    @Value("${server.address}")
    private String serverAddress;

    @Value("${server.port}")
    private String serverPort;

    //...

}
</code>```

When starting up the application with mvn spring-boot:run, I get the following exception:

```<code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myController': Injection of autowired dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not autowire field: ... String ... serverAddress; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'server.address' in string value "${server.address}"
</code>```

Both server.address and server.port cannot be autowired.

How can I find out the (local) host/address/NIC and port that a Spring Boot application is binding on?

答:
To get the port number in your code you can use the following:

```<code>@Autowired
Environment environment;

@GetMapping("/test")
String testConnection(){
    return "Your server is up and running at port: "+environment.getProperty("local.server.port");
}
</code>```

To understand the Environment property you can go through this
Spring boot Environment

Body:
I'm starting up a Spring Boot application with mvn spring-boot:run.

One of my @Controllers needs information about the host and port the application is listening on, i.e. localhost:8080 (or 127.x.y.z:8080). Following the Spring Boot documentation, I use the server.address and server.port properties:

@Controller
public class MyController {

    @Value("${server.address}")
    private String serverAddress;

    @Value("${server.port}")
    private String serverPort;

    //...

}

When starting up the application with mvn spring-boot:run, I get the following exception:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myController': Injection of autowired dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not autowire field: ... String ... serverAddress; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'server.address' in string value "${server.address}"

Both server.address and server.port cannot be autowired.

How can I find out the (local) host/address/NIC and port that a Spring Boot application is binding on?

Body:
To get the port number in your code you can use the following:

@Autowired
Environment environment;

@GetMapping("/test")
String testConnection(){
    return "Your server is up and running at port: "+environment.getProperty("local.server.port");
}

To understand the Environment property you can go through this
Spring boot Environment


问:
How to get the highest key from dictionary (python)?
I'm new to Python and I am having a small problem I want to solve

```<code>a={"1" : 3, "2" : 3, "6":3}
</code>```

I have this dic and I would like to get the maximum key out of him
for example in the dictionary above I would like to get the key 6 as a value

答:
For a simple, functional approach:

```<code>max(map(int,a))
</code>```

This applies the int function to each key of a using map to convert the keys as strings to integers, then finds the maximum of these using max.

Body:
I'm new to Python and I am having a small problem I want to solve

a={"1" : 3, "2" : 3, "6":3}

I have this dic and I would like to get the maximum key out of him
for example in the dictionary above I would like to get the key 6 as a value

Body:
For a simple, functional approach:

max(map(int,a))

This applies the int function to each key of a using map to convert the keys as strings to integers, then finds the maximum of these using max.


答:
Don't parse this manually; Python has the urllib.parse.parse_qs function that does exactly what you want.

```<code>from urllib.parse import parse_qs
parse_qs(line)
</code>```

In Python 2 this is in the urlparse module:

```<code>from urlparse import parse_qs
</code>```

Title: how to transform the string into a dict in python?

Body:
app=related_query&type=json&src=sm_rec&count=20&sc=structure_web_info&uid=d4a048cc49a11ad0f98d83608c44b554%7C26858319344%7C%7C1508669758&uuid=d4a048cc49a11ad0f98d83608c44b554%7C26858319344%7C%7C1508669758&query=%E5%8E%86%E5%8F%B2%E6%B4%BB%E4%B8%A4%E7%99%BE%E5%B2%81%E4%BB%A5%E4%B8%8A%E7%9A%84&url=http%3A%2F%2Fwww.360doc.cn%2Farticle%2F150887_537727792.html&from=ucframe&title=%E5%8E%86%E5%8F%B2%E4%B8%8A%E6%9C%80%E9%95%BF%E5%AF%BF%E7%9A%84%E4%BA%BA%2C%E6%B4%BB%E5%88%B0%E4%B8%A4%E7%99%BE%E5%B2%81%E7%9A%84%E5%A5%A5%E7%A7%98&weini_sn=0

In [38]: line[str].split('&')
Out[38]:
['app=related_query',
 'type=json',
 'src=sm_rec',
 'count=20',
 'sc=structure_web_info',
 'uid=d4a048cc49a11ad0f98d83608c44b554%7C26858319344%7C%7C1508669758',
 'uuid=d4a048cc49a11ad0f98d83608c44b554%7C26858319344%7C%7C1508669758',
 'query=%E5%8E%86%E5%8F%B2%E6%B4%BB%E4%B8%A4%E7%99%BE%E5%B2%81%E4%BB%A5%E4%B8%8A%E7%9A%84',
 'url=http%3A%2F%2Fwww.360doc.cn%2Farticle%2F150887_537727792.html',
 'from=ucframe',
 'title=%E5%8E%86%E5%8F%B2%E4%B8%8A%E6%9C%80%E9%95%BF%E5%AF%BF%E7%9A%84%E4%BA%BA%2C%E6%B4%BB%E5%88%B0%E4%B8%A4%E7%99%BE%E5%B2%81%E7%9A%84%E5%A5%A5%E7%A7%98',
 'weini_sn=0',
 'bucket=']

How to transform the original string into a dictionary which has key value. Thanks.

Body:
Don't parse this manually; Python has the urllib.parse.parse_qs function that does exactly what you want.

from urllib.parse import parse_qs
parse_qs(line)

In Python 2 this is in the urlparse module:

from urlparse import parse_qs


问:
Include error messages from testthat in R markdown document
I want to include error messages in an R markdown pdf report. This works well:

```<code>---
output: pdf_document
---

This will be knitted and show the error message in the pdf.
```{r, error = TRUE}
stopifnot(2 == 3)
```
</code>```

However, if I try the same approach with an error that comes from testthat, my document does not knit anymore.

```<code>---
output: pdf_document
---

This will not knit
```{r, error = TRUE}
library(testthat)
expect_equal(2, 3)
```
</code>```

Why is that? And what can I do to include error messages from testthat's expect_something functions without wrapping them up in a test?

I think this must be possible since Hadley Wickham includes many error messages in his book R packages that come directly from expect_something-functions.

This is related, but not answered in Include errors in R markdown package vignette and How to skip error checking at Rmarkdown compiling?

答:
Create a test:</p>

```<code>```{r, error = TRUE}
library(testthat)
test_that("Test A", {
  expect_equal(2, 3)
})
```
</code>```

Body:
I want to include error messages in an R markdown pdf report. This works well:

---
output: pdf_document
---

This will be knitted and show the error message in the pdf.
```{r, error = TRUE}
stopifnot(2 == 3)
```

However, if I try the same approach with an error that comes from testthat, my document does not knit anymore.

---
output: pdf_document
---

This will not knit
```{r, error = TRUE}
library(testthat)
expect_equal(2, 3)
```

Why is that? And what can I do to include error messages from testthat's expect_something functions without wrapping them up in a test?

I think this must be possible since Hadley Wickham includes many error messages in his book R packages that come directly from expect_something-functions.

This is related, but not answered in Include errors in R markdown package vignette and How to skip error checking at Rmarkdown compiling?

Body:
Create a test:

```{r, error = TRUE}
library(testthat)
test_that("Test A", {
  expect_equal(2, 3)
})
```