问:
Is there a way in pd.read_csv to replace NaN value with other character?
I have some data in csv file.
Because it is collected from machine,all lines should be number but some NaN values exists in some lines.And the machine can auto replace these NaN values with a string '-'.

My question is how to set params of pd.read_csv() to auto replace '-'values with zero from csv file?

答:
You can try something like this : </p>

```<code>import pandas

df = pandas.read_csv('somefile.txt')

df = df.fillna(0)
</code>```

<p>Hope that'll help ! </p>

Body:
You can try something like this :

import pandas

df = pandas.read_csv('somefile.txt')

df = df.fillna(0)

Hope that'll help !


来源: stackexchange

问:
Waiting for a javascript promise to complete (when I have no other options...)
Before you all start screaming about refactoring and callbacks, read the question fully, please :)

I have the following situation in javascript (code simplified for convenience):

```<code>    function myFunc(){
        var myItems = getItemsAsync(); //this returns a promise

        return {
            settings: {
                type: "items",
                component: "accordion",
                items: myItems //WRONG! This is a promise, not the data itself!
            }
        }
    }
</code>```

Here's the situation: I have an external framework that calls myFunc and expects the returned object {settings: etc...} to have all values already filled in, including the items sub-object. I have no control over how this framework calls myFunc, so I cannot change it to accept a promise or partial result, the returned object must be "ready" when myFunc returns.

Now, as you can see, here's the problem: to obtain the items I need to call an API that is asynchronous by design, and returns a promise. Unfortunately, this API is also out of my control, so I cannot modify it to work synchronously.

So basically I am at a stalemate: I have to synchronously return a complete object, but one of the pieces of that object can only be obtained asynchronously!!

Is there a way out of this? All the similar questions I've seen here on SO suggest that waiting for a promise to be complete cannot be done... is it true?

I know what you're all dying to say: "CHANGE EITHER THE CALLER OR THE API", but unfortunately they are both components that are totally out of my control, as they're part of existing systems that i CANNOT modify (due to bureaucratic, rather than technical, reasons)

Any ideas to get out of this?

答:
Well, luckily for me I found out that the framework I mentioned in my question (the one that calls myFunc) has an initialization phase where I can inject as many promises as I want, and the framework will wait for them to complete before proceeding and calling the other stuff, including myFunc, so I was able to build my items object during this initialization phase and after that it was ready to be used.

This solves my problem, tho it doesn't answer my original question. I'll still wait a couple of days to see if someone knows of a workaround, but from what I've read in the meantime it appears what I want cannot be done.

ContentLicense: CC BY-SA 3.0

Body:
Before you all start screaming about refactoring and callbacks, read the question fully, please :)

I have the following situation in javascript (code simplified for convenience):

    function myFunc(){
        var myItems = getItemsAsync(); //this returns a promise

        return {
            settings: {
                type: "items",
                component: "accordion",
                items: myItems //WRONG! This is a promise, not the data itself!
            }
        }
    }

Here's the situation: I have an external framework that calls myFunc and expects the returned object {settings: etc...} to have all values already filled in, including the items sub-object. I have no control over how this framework calls myFunc, so I cannot change it to accept a promise or partial result, the returned object must be "ready" when myFunc returns.

Now, as you can see, here's the problem: to obtain the items I need to call an API that is asynchronous by design, and returns a promise. Unfortunately, this API is also out of my control, so I cannot modify it to work synchronously.

So basically I am at a stalemate: I have to synchronously return a complete object, but one of the pieces of that object can only be obtained asynchronously!!

Is there a way out of this? All the similar questions I've seen here on SO suggest that waiting for a promise to be complete cannot be done... is it true?

I know what you're all dying to say: "CHANGE EITHER THE CALLER OR THE API", but unfortunately they are both components that are totally out of my control, as they're part of existing systems that i CANNOT modify (due to bureaucratic, rather than technical, reasons)

Any ideas to get out of this?


问:
How to know in Talend if tMySQLInput will overwrite data?
I have one already existing Talend Open Studio tMySQLInput component with some sql code inside it, in order to retrieve some joined columns linked to a tMySQLOuput component (pointing to an already existing MySQL table) with few records.

QUESTION:
Will the "tMySQLInput" component overwrite the already existing table data that the tMySQLOutput component relates to? I mean is there an option to check in the tMySQLInput our output in order to say, overwrite each time this job is executed ?

Thank you all.

答:
Yes, there is an option where in tMySQLOutput where you can specify what action you want to do to your table. Follow following steps:

Go to component tab of tMySQLOutput, it will open the basic settings of this component.

If you will look closer you will find Action on table. This is the action which you can perform on the table which is pointed by tMySQLOutput. It has options as Default, Drop and Create Table etc.

Then you have Action on data. These are the options which you can perform on the data like Insert, Update etc.

In your case I suppose you can choose Action on Table as Default and Action on Data as Insert. Default action would not do anything on the table and Insert option would insert the records at the end of table. But in case of Insert if you will have duplicate rows then job would stop the moment it will find any duplicate row.


问:
UIStackView subviews with size classes
Trying to achieve UIStackView with 2 labels for iPhone and 3 labels for iPad using size classes.

View hierarchy

Default size class

```<code>[UIStackView]
  [UILabel 1] [UILabel2]
[UIStackView]
</code>```

RxR size class

```<code>[UIStackView]
  [UILabel 1] [UILabel2] [UILabel3]
[UIStackView]
</code>```

It looks exactly as expected in Storyboard as you can see in the above screenshots but on simulator iPad view is messed up.

iPhone Output (okay)

iPad Portrait Output (messed up)

iPad Landscape Output (messed up)

What's happening in iPad?? Is it a bug or I'm missing something?
Thanks.

I have created a sample project.

答:
Follow below steps to achieve your requirements :

Drag one horizontal Stackview in to your interface builder

set it's constraints like : top,leading, =trailing and fixed height

Drag and drop three labels in to it and select all together and set one constraint : Equal width

now select second or middle label and from attribute inspector click on + button beside installed and select Regular for both width and height. It will add regular,regular variation and uncheck the checkbox for that R,R variation. Refer below screen shot for better understanding,

And you are done! now you your center label will not show in iPad and every label will be displayed in iPhone!

See below result screenshot of iphone and ipad in my case!

iPhone :

iPad :

Update :

If you want two to hide label in iPhone and show in iPad then add one more variation : Compact Width Regular Height for middle label and uncheck the checkbox to uninstall. Refer below screenshot,

Title: UIStackView subviews with size classes

Body:
Trying to achieve UIStackView with 2 labels for iPhone and 3 labels for iPad using size classes.

View hierarchy

Default size class

[UIStackView]
  [UILabel 1] [UILabel2]
[UIStackView]

RxR size class

[UIStackView]
  [UILabel 1] [UILabel2] [UILabel3]
[UIStackView]

It looks exactly as expected in Storyboard as you can see in the above screenshots but on simulator iPad view is messed up.

iPhone Output (okay)

iPad Portrait Output (messed up)

iPad Landscape Output (messed up)

What's happening in iPad?? Is it a bug or I'm missing something?
Thanks.

I have created a sample project.


问:
How to understand if device screen is being recorded in IOS 11
I have an application that it has copyrighted content. I don't want users to record it. If they start recording screen I want my app to catch this. What is the function to catch if the screen is being recorded?

I don't want to prevent, I want to understand and catch it.

Note: Some answers indicate solutions including AirPlay and Mirroring. What I want is to only catch screen recording either started before or during app. I want to allow users to use AirPlay and Mirroring.

答:
Use UIScreen.main.isCaptured to get current status. Than, you need to listen to new notification UIScreenCapturedDidChangeNotification. When recording status will change, you need to do some action (for example stop playback ..etc.). Remember this is iOS11+ only.

Code fragments:

```<code>if (@available(iOS 11.0, *)) {
  [[NSNotificationCenter defaultCenter] addObserver:self
                    selector:@selector(capturedChange)
   name:UIScreenCapturedDidChangeNotification object:nil];
}

- (void)capturedChange {
    if (@available(iOS 11.0, *)) {
    NSLog(@"Recording Status: %s", [UIScreen mainScreen].isCaptured ? "true" : "false");
        //do something
    }
}
</code>```

Body:
Use UIScreen.main.isCaptured to get current status. Than, you need to listen to new notification UIScreenCapturedDidChangeNotification. When recording status will change, you need to do some action (for example stop playback ..etc.). Remember this is iOS11+ only.

Code fragments:

if (@available(iOS 11.0, *)) {
  [[NSNotificationCenter defaultCenter] addObserver:self
                    selector:@selector(capturedChange)
   name:UIScreenCapturedDidChangeNotification object:nil];
}

- (void)capturedChange {
    if (@available(iOS 11.0, *)) {
    NSLog(@"Recording Status: %s", [UIScreen mainScreen].isCaptured ? "true" : "false");
        //do something
    }
}


问:
Interface builder doesn't allow adding Table View Cell
For an alert dialog, I added a UITableView, then while I try to Table View Cell the Interface Builders doesn't accept dropping Table View Cell "on" table view, please check screenshot, I should mention the root is UIView, not UIViewController:

答:
You are using XIB with UITableView so You can't directly add cell of table view same like StoryBoard but You need to create separate XIB of UITableViewCell use with your table view.

For more information look at below.

How do you load custom UITableViewCells from Xib files?


问:
WebGL: How to handle context resources after init
I am writing a small WebGL engine and I was wondering if there is any good reason to keep gl context resources that are created and then buffered or compiled and saved in another object? For example: I create buffers for positions, normals, uv and indices and then buffer it into an VAO. Is it good practice to delete the buffers (i.e., all buffers except VAO) after saved in the VAO (i.e., after initialization) or could I use the buffers at some other point (and delete resources when the corresponding object is destroyed explicitly)? Same goes for createShader and deleteShader calls: after compilation and saving into a program object, can I safely delete the vsh, fsh Shaders created or could I reuse them at some other point?</p>

答:
The VAO does not contain vertices data, it only stores, so to say, states of pointers configuration on bound buffers. Ressources deletion is however somewhat fuzzy, since ressources need to be unbound to be released. Anyway as long you need vertices data to draw, these data needs to be in memory, and these data are not (conceptually) referenced by the VAO, but by the VBO. In the "worst" case (i never tested), if you request a VBO deletion while the VAO still in use, maybe you simply lose access to the VBO, but data still in memory. The logical way is to keep your VBO references as long you use these data to draw something. This way you keep access and control to the data. Once you want to delete all stuff, you first delete the VAO, then the related VBO(s).

For shaders this is not the same, and here, you can detach and delete shader objects once the shader program is linked, as long you don't need to link another program with the same shader object, allowing you to save memory. Here is an explanation here, relative to OpenGL, but which is equally true for WebGL: Proper way to delete GLSL shader?


问:
How to change text in multiple lines / places of a Textbox in FabricJS?
I need to replace text of particular selection when the input value has been changed.

On the initial rendering, I get an object of selections and fields.

Secondly, inputs get values of fields.

Assume I'm changing a value of the Line input, since this field controls two lines, both of those green texts should be replaced with the new one.

http://jsfiddle.net/hkvmLwfu/

Tnx

////////////////////////////////////////////////////////////////////////
/////////////// THIS FUNCTION NEEDS TO BE DEVELOPED ////////////////////
////////////////////////////////////////////////////////////////////////

function replaceTextBySelection(fieldId, fieldValue, canvas, text){

}

////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
var canvas = new fabric.Canvas('paper');
canvas.setHeight(300);
canvas.setWidth(500);

var text = new fabric.Textbox('Sample Line 1 Line 2 Line 3', {
  left: 50,
  top: 10,
  fontFamily: 'arial',
  fill: '#333',
  fontSize: 50
});
canvas.add(text);
canvas.renderAll();

const fields = {
 FIELD_1: {
     value: "Sample",
        color: '#F00'
    },
    FIELD_2: {
     value: "Line",
        color: '#0F0'
    }
}

selections = [
    {
        rowId: 0,
        offset: 0,
        length: 6,
        field: "FIELD_1"
    },
    {
        rowId: 1,
        offset: 0,
        length: 4,
        field: "FIELD_2"
    },
    {
        rowId: 2,
        offset: 0,
        length: 4,
        field: "FIELD_2"
    }
]

selections.map((obj)=>{
    text.setSelectionStart(obj.offset);
    text.setSelectionEnd(obj.offset + obj.length);
    text.setSelectionStyles();

    for (let i = text.selectionStart; i < text.selectionEnd; i++) {
      text.insertCharStyleObject(obj.rowId, i, {
        textBackgroundColor: fields[obj.field].color
      })
    }
    canvas.renderAll();
    return obj;
});

$('#FIELD_1').val( fields['FIELD_1'].value );
$('#FIELD_2').val( fields['FIELD_2'].value );

$("input").keyup(function(t){
 replaceTextBySelection(this.id, this.value, canvas, text);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.19/fabric.min.js"></script>
<canvas id="paper" width="400" height="400" style="border:1px solid #ccc"></canvas>
<input type="text" id="FIELD_1" />
<br/>
<input type="text" id="FIELD_2" /></code>```

答:
Your example complicates things because the selections object reasons about rows, but the text doesn't actually contain rows, only spaces that get wrapped to a new line.

It gets easier if you define your text instead as

var text = new fabric.Textbox('Sample\nLine 1\nLine 2\nLine 3', {
  left: 50,
  top: 10,
  fontFamily: 'arial',
  fill: '#333',
  fontSize: 50
});

Using this text I have created a functional example: http://jsfiddle.net/hkvmLwfu/12/. I'm not sure this is entirely how you want it, but you should be able to pick it up from here.

Body:
I need to replace text of particular selection when the input value has been changed.

On the initial rendering, I get an object of selections and fields.

Secondly, inputs get values of fields.

Assume I'm changing a value of the Line input, since this field controls two lines, both of those green texts should be replaced with the new one.

http://jsfiddle.net/hkvmLwfu/

Tnx

////////////////////////////////////////////////////////////////////////
/////////////// THIS FUNCTION NEEDS TO BE DEVELOPED ////////////////////
////////////////////////////////////////////////////////////////////////

function replaceTextBySelection(fieldId, fieldValue, canvas, text){

}

////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
var canvas = new fabric.Canvas('paper');
canvas.setHeight(300);
canvas.setWidth(500);

var text = new fabric.Textbox('Sample Line 1 Line 2 Line 3', {
  left: 50,
  top: 10,
  fontFamily: 'arial',
  fill: '#333',
  fontSize: 50
});
canvas.add(text);
canvas.renderAll();

const fields = {
 FIELD_1: {
     value: "Sample",
        color: '#F00'
    },
    FIELD_2: {
     value: "Line",
        color: '#0F0'
    }
}

selections = [
    {
        rowId: 0,
        offset: 0,
        length: 6,
        field: "FIELD_1"
    },
    {
        rowId: 1,
        offset: 0,
        length: 4,
        field: "FIELD_2"
    },
    {
        rowId: 2,
        offset: 0,
        length: 4,
        field: "FIELD_2"
    }
]

selections.map((obj)=>{
    text.setSelectionStart(obj.offset);
    text.setSelectionEnd(obj.offset + obj.length);
    text.setSelectionStyles();

    for (let i = text.selectionStart; i < text.selectionEnd; i++) {
      text.insertCharStyleObject(obj.rowId, i, {
        textBackgroundColor: fields[obj.field].color
      })
    }
    canvas.renderAll();
    return obj;
});

$('#FIELD_1').val( fields['FIELD_1'].value );
$('#FIELD_2').val( fields['FIELD_2'].value );

$("input").keyup(function(t){
 replaceTextBySelection(this.id, this.value, canvas, text);
});

<canvas id="paper" width="400" height="400" style="border:1px solid #ccc"></canvas>
<input type="text" id="FIELD_1" />

<input type="text" id="FIELD_2" />

ContentLicense: CC BY-SA 4.0


问:
Internationalized strings in Eclipse plugin.xml file are not found when installed in Eclipse application
I have created 2 plugins, implementing an ODA driver plugin and its UI plugin for the BIRT extension to Eclipse.

My plugins both work as expected when eclipse starts up another eclipse application where I can then test the plugins I am developing. However, when I install my plugins into an Eclipse application and then start it from a Windows shortcut, the plugins work but and language keys specified in the plugin.xml files are not found.

For example, in my plugin.xml file for the ODA Driver plugin I set the attributes 'id' to '%oda.data.source.id' and the data source 'defaultDisplayName' to '%data.source.name'.
I then, in a file 'language.properties', have defined the values for both of these keys (where the keys don't have the preceeding % character).

When running the plugins that have been installed into the dropins/plugins directory of an Eclipse application, the wizard for creating my ODA data source names is as '%data.source.name' and saves the data source in the rptdesign (XML) file with an ID of '%oda.data.source.id'.

Since 'language' is not the default name for the properties file I went into the manifest for both plugins and changed the 'Bundle-Localization' attribute to 'language'. The language file is located in the root directory of both of my plugins.

The properties file is definitely found, since I use the two language files to store other strings used by the plugins, looked up using a java ResourceBundle. The strings are always found whether the plugins are run from Eclipse application loading another, or when properly installed in the dropins/plugins directory of an Eclipse application.

Why are the installed plugins not finding language keys reference in the plugin.xml files? There are not errors in the logs and the language.properties files are clearly accessible...

Thanks in advance.

答:
Are you sure the plugin.properties file is included in your build?
On the Build page of the manifest, make sure it's checked so it gets put into the
plugin jar file.</p>

ContentLicense: CC BY-SA 2.5


问:
Increment number with Delay (C#)
i have a button when i click on it it increases the number in a text block by one.
But i want to show increment with few millisecond wait.

XAML

```<code><TextBlock Name="DisplayTextBlock" FontSize="50" HorizontalAlignment="Center" VerticalAlignment="Top"/>

<Button Name="CountingButton" Height="80" Width="150" HorizontalAlignment="Center" VerticalAlignment="Bottom" Click="CountingButton_Click"/>
</code>```

C#

```<code>int i = 0;

private void CountingButton_Click(object sender, RoutedEventArgs e)
{
    do
    {
        i++;

        DisplayTextBlock.Text = i.ToString();
    }
    while(//something is on)
}
</code>```

so how can i add wait...

答:
I think what you're looking for is sleep:

```<code>System.Threading.Thread.Sleep(x);
</code>```

If not Delay would work too:

```<code>await System.Threading.Tasks.Delay(x);
</code>```

Title: Increment number with Delay (C#)

Body:
i have a button when i click on it it increases the number in a text block by one.
But i want to show increment with few millisecond wait.

XAML

<TextBlock Name="DisplayTextBlock" FontSize="50" HorizontalAlignment="Center" VerticalAlignment="Top"/>

<Button Name="CountingButton" Height="80" Width="150" HorizontalAlignment="Center" VerticalAlignment="Bottom" Click="CountingButton_Click"/>

C#

int i = 0;

private void CountingButton_Click(object sender, RoutedEventArgs e)
{
    do
    {
        i++;

        DisplayTextBlock.Text = i.ToString();
    }
    while(//something is on)
}

so how can i add wait...

Body:
I think what you're looking for is sleep:

System.Threading.Thread.Sleep(x);

If not Delay would work too:

await System.Threading.Tasks.Delay(x);


问:
Select distinct for one column
I have a compound primary key where the single parts are potentially random. They aren't in any particular order and one can be unique or they can be all the same.

I do not care which row I get. This is like "Just pick one from each group".

My table:

```<code>KeyPart1 KeyPart2 KeyPart3 colA colB colD
11       21       39                 d1
11       22       39                 d2
12       21       39                 d2
12       22       39                 d3
13       21       38                 d3
13       22       38                 d5

</code>```

Now what I want is to get for each entry in colD one row, I do not care which one.

```<code>KeyPart1 KeyPart2 KeyPart3 colA colB colD
11       21       39                 d1
12       21       39                 d2
12       22       39                 d3
13       22       38                 d5
</code>```

答:
The following should work in almost any version of DB2:

```<code>select t.*
from (select t.*,
             row_number() over (partition by KeyPart1, KeyPart2
                                order by KeyPart1
                               ) as seqnum
      from t
     ) t
where seqnum = 1;
</code>```

If you only care about column d, and the first two key parts, then you can use group by:

```<code>select KeyPart1, KeyPart2, min(colD)
from t
group by KeyPart1, KeyPart2;
</code>```

Title: Select distinct for one column

Body:
I have a compound primary key where the single parts are potentially random. They aren't in any particular order and one can be unique or they can be all the same.

I do not care which row I get. This is like "Just pick one from each group".

My table:

KeyPart1 KeyPart2 KeyPart3 colA colB colD
11       21       39                 d1
11       22       39                 d2
12       21       39                 d2
12       22       39                 d3
13       21       38                 d3
13       22       38                 d5

Now what I want is to get for each entry in colD one row, I do not care which one.

KeyPart1 KeyPart2 KeyPart3 colA colB colD
11       21       39                 d1
12       21       39                 d2
12       22       39                 d3
13       22       38                 d5

Body:
The following should work in almost any version of DB2:

select t.*
from (select t.*,
             row_number() over (partition by KeyPart1, KeyPart2
                                order by KeyPart1
                               ) as seqnum
      from t
     ) t
where seqnum = 1;

If you only care about column d, and the first two key parts, then you can use group by:

select KeyPart1, KeyPart2, min(colD)
from t
group by KeyPart1, KeyPart2;


问:
How to hide specific div when clicked outside the element having same class in multiple div
I have the following code snippet where I want to hide specific div having same class name. I have multiple divs having same class name and event need to be triggered outside the actionLinks class. But I am little bit confused how to do this. can you guide me?

$(document).on("click", ".actionLinks", function() {
  $('.mainAction').hide();
  $(this).prev('.mainAction').show();
});

$(document).not(".actionLinks").on("click", function() {
  $('.mainAction').hide();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="mainAction" style="display: none;">
  Action 1
  Action 2
  Action 3
</div>
<div class="actionLinks">
  Link one
</div>
<div class="mainAction" style="display: none;">
  Action 1
  Action 2
  Action 3
</div>
<div class="actionLinks">
  Link two
</div>
<div class="mainAction" style="display: none;">
  Action 1
  Action 2
  Action 3
</div>
<div class="actionLinks">
  Link three
</div>
<div class="mainAction" style="display: none;">
  Action 1
  Action 2
  Action 3
</div>
<div class="actionLinks">
  Link four
</div>
<div class="mainAction" style="display: none;">
  Action 1
  Action 2
  Action 3
</div>
<div class="actionLinks">
  Link five
</div>
<div class="mainAction" style="display: none;">
  Action 1
  Action 2
  Action 3
</div>
<div class="actionLinks">
  Link six
</div>
<div class="mainAction" style="display: none;">
  Action 1
  Action 2
  Action 3
</div>
<div class="actionLinks">
  Link seven
</div>

<p>
  Lorem ipsum dolor sit amet, consectetur adipisicing 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></code>```

答:
Append click event to body to catch every click event and check whether it contains your class.

```<code>document.body.addEventListener('click', (e) => {
    if(!e.target.classList.contains("mainAction")) {
        hideElem(openedMainActionElement);
    }
});
</code>```

Body:
I have the following code snippet where I want to hide specific div having same class name. I have multiple divs having same class name and event need to be triggered outside the actionLinks class. But I am little bit confused how to do this. can you guide me?

$(document).on("click", ".actionLinks", function() {
  $('.mainAction').hide();
  $(this).prev('.mainAction').show();
});

$(document).not(".actionLinks").on("click", function() {
  $('.mainAction').hide();
});

  Action 1
  Action 2
  Action 3

  Link one

  Action 1
  Action 2
  Action 3

  Link two

  Action 1
  Action 2
  Action 3

  Link three

  Action 1
  Action 2
  Action 3

  Link four

  Action 1
  Action 2
  Action 3

  Link five

  Action 1
  Action 2
  Action 3

  Link six

  Action 1
  Action 2
  Action 3

  Link seven

  Lorem ipsum dolor sit amet, consectetur adipisicing 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.

Body:
Append click event to body to catch every click event and check whether it contains your class.

document.body.addEventListener('click', (e) => {
    if(!e.target.classList.contains("mainAction")) {
        hideElem(openedMainActionElement);
    }
});


问:
Regex to disallow all symbols that windows doesnt allow in its file/folder names
The symbols not allowed in filename or folder name in windows are \ / : * ? " < > |. I wrote a regex for it but not able to write regex to exclude " (double quotes).

```<code>Regex regex = new Regex(@"^[\\\/\:\*\?\'\<\>\|]+$");
</code>```

Tried as below but it didnt work:

```<code>Regex regex = new Regex(@"^[\\\/\:\*\?\'\<\>\|"]+$");
</code>```

EDIT:
I am particularly looking for code with regex itself and hence its not a duplicate.

Help is greatly appreciated. Thanks.

答:
@Allrameest answer using Path.GetInvalidFileNameChars() is probably the one you should use.

What I wanted to address is the fact that your regex is actually wrong or very ineffective (I don't know what exectly you wanted to do).

So, using:

```<code>var regex = new Regex(@"^[\\\/\:\*\?\'\<\>\|]+$");
</code>```

mean you match a string which consists ONLY of "forbidden" characters (BTW, I think single quote ' is not invalid). Is it what you want? Don't think so. What you did is:

^ start of the string

[...]+ invalid characters only (at least once)

$ end of the string

Maybe you wanted @"^[^...]+$" (hat used twice)?

Anyway, solution for your problem (with regex) is:

don't use ^ or $ just try to find any of those and bomb out quickly

in raw string (the one starting with @") you escape double quotes by doubling it.

So, the right regex is:

```<code>var regex = new Regex(@"[\\\/\:\*\?\""\<\>\|]");
if (regex.Match(filename).Success) {
    throw new ArgumentException("Bad filename");
}
</code>```

Just find any and bomb out.

UPDATE by @JohnLBevan

```<code>var regex = new Regex(
    "[" + Regex.Escape(new string(Path.GetInvalidFileNameChars())) + "]");
if (regex.Match(filename).Success) {
    throw new ArgumentException("Bad filename");
}
</code>```

(Not using string.Format(...) as this Regex should be static and precompiled anyway)

Body:
The symbols not allowed in filename or folder name in windows are \ / : * ? " < > |. I wrote a regex for it but not able to write regex to exclude " (double quotes).

Regex regex = new Regex(@"^[\\\/\:\*\?\'\<\>\|]+$");

Tried as below but it didnt work:

Regex regex = new Regex(@"^[\\\/\:\*\?\'\<\>\|"]+$");

EDIT:
I am particularly looking for code with regex itself and hence its not a duplicate.

Help is greatly appreciated. Thanks.

Body:
@Allrameest answer using Path.GetInvalidFileNameChars() is probably the one you should use.

What I wanted to address is the fact that your regex is actually wrong or very ineffective (I don't know what exectly you wanted to do).

So, using:

var regex = new Regex(@"^[\\\/\:\*\?\'\<\>\|]+$");

mean you match a string which consists ONLY of "forbidden" characters (BTW, I think single quote ' is not invalid). Is it what you want? Don't think so. What you did is:

^ start of the string

[...]+ invalid characters only (at least once)

$ end of the string

Maybe you wanted @"^[^...]+$" (hat used twice)?

Anyway, solution for your problem (with regex) is:

don't use ^ or $ just try to find any of those and bomb out quickly

in raw string (the one starting with @") you escape double quotes by doubling it.

So, the right regex is:

var regex = new Regex(@"[\\\/\:\*\?\""\<\>\|]");
if (regex.Match(filename).Success) {
    throw new ArgumentException("Bad filename");
}

Just find any and bomb out.

UPDATE by @JohnLBevan

var regex = new Regex(
    "[" + Regex.Escape(new string(Path.GetInvalidFileNameChars())) + "]");
if (regex.Match(filename).Success) {
    throw new ArgumentException("Bad filename");
}

(Not using string.Format(...) as this Regex should be static and precompiled anyway)


问:
MariaDB's ORDER BY clause does not sort ascending?
I have the below simple SQL, which is executed against my MariaDB database.

The expected behavior is that the result is sorted by 'day' ASCENDING.  However, when executed, the results are sorted in DESCENDING order.  Very strange.

```<code>SELECT *
FROM
(
    SELECT `day`,`count`
    FROM
    (
        SELECT
            DATE(`date`) AS `day`,
            COUNT(*) as `count`
        FROM `message` m
        GROUP BY DATE(`date`)
        ORDER BY `day` DESC, `count` DESC
    ) AS q
    ORDER BY `day` ASC
) AS q
</code>```

If I comment out the ORDER BY inside the inner query, the outer ORDER BY works correctly and sorts the results in ascending order without problem.

The problem I have is that the code inside the inner loop is generated code, so I can't remove that inner ORDER BY.

Why does MariaDB behave in this way?  Is there some way to change the outer ORDER BY so that it gets the priority is deserves?

Note:  I am using MariaDB version:  10.0.24-MariaDB

答:
So, i worked it out.

According to MariaDB, the SQL standard does not require the ORDER BY of a subquery to be respected (unless it would affect the actual rows returned):

https://mariadb.com/kb/en/library/why-is-order-by-in-a-from-subquery-ignored/

If I move the ORDER BY to the very outside query, then it works as expected.

Body:
I have the below simple SQL, which is executed against my MariaDB database.

The expected behavior is that the result is sorted by 'day' ASCENDING.  However, when executed, the results are sorted in DESCENDING order.  Very strange.

SELECT *
FROM
(
    SELECT `day`,`count`
    FROM
    (
        SELECT
            DATE(`date`) AS `day`,
            COUNT(*) as `count`
        FROM `message` m
        GROUP BY DATE(`date`)
        ORDER BY `day` DESC, `count` DESC
    ) AS q
    ORDER BY `day` ASC
) AS q

If I comment out the ORDER BY inside the inner query, the outer ORDER BY works correctly and sorts the results in ascending order without problem.

The problem I have is that the code inside the inner loop is generated code, so I can't remove that inner ORDER BY.

Why does MariaDB behave in this way?  Is there some way to change the outer ORDER BY so that it gets the priority is deserves?

Note:  I am using MariaDB version:  10.0.24-MariaDB


问:
Use Bundle-NativeCode on Linux does not work
I create a plugin which includes the following folder structure:

src

native/so/libsystemcommand.so

META-INF/MANIFEST.MF

The manifest include the command

```<code>Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Commands Plug-in
Bundle-SymbolicName: de.system.commands;singleton:=true
Bundle-Version: 1.0.0
Bundle-Activator: de.system.commands.CommandsPlugin
Bundle-Localization: plugin
Bundle-NativeCode: native/so/libsystemcommand.so; osname = Linux; processor = x86
Require-Bundle: org.eclipse.core.runtime,
 org.apache.commons.logging
Eclipse-AutoStart: true
Export-Package: de.system.commands,
 de.system.commands.jni,
 de.system.commands.utils
Bundle-ClassPath: .
</code>```

The build.properties looks like

```<code>source.. = src/
output.. = bin/
bin.includes = META-INF/,\
               .,\
               native/
</code>```

In the start method of my Activator class I call

```<code>System.loadLibrary("systemcommand");
</code>```

At runtime the library is not found and a UnsatisfiedLinkError is thrown.

```<code>java.lang.UnsatisfiedLinkError: no libsystemcommand in java.library.path
</code>```

Do I have to set more attributes in the plugin? Do I have to unzip some informations on the target platform?

EDIT:

```<code>java.library.path=/opt/jdk/j2re1.4.2_16/lib/i386/client:/opt/jdk/j2re1.4.2_16/lib/i386:/opt/jdk/j2re1.4.2_16/../lib/i386::/opt/dsa/lib:/opt/dsa/lib
</code>```

答:
The lib has to be in your filesystem (not in an archive file).
Then you can either use the linux environment variable LD_LIBRARY_PATH pointing to the lib or define the property java.library.path

OwnerDisplayName: Markus Lausberg

Body:
I create a plugin which includes the following folder structure:

src

native/so/libsystemcommand.so

META-INF/MANIFEST.MF

The manifest include the command

Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Commands Plug-in
Bundle-SymbolicName: de.system.commands;singleton:=true
Bundle-Version: 1.0.0
Bundle-Activator: de.system.commands.CommandsPlugin
Bundle-Localization: plugin
Bundle-NativeCode: native/so/libsystemcommand.so; osname = Linux; processor = x86
Require-Bundle: org.eclipse.core.runtime,
 org.apache.commons.logging
Eclipse-AutoStart: true
Export-Package: de.system.commands,
 de.system.commands.jni,
 de.system.commands.utils
Bundle-ClassPath: .

The build.properties looks like

source.. = src/
output.. = bin/
bin.includes = META-INF/,\
               .,\
               native/

In the start method of my Activator class I call

System.loadLibrary("systemcommand");

At runtime the library is not found and a UnsatisfiedLinkError is thrown.

java.lang.UnsatisfiedLinkError: no libsystemcommand in java.library.path

Do I have to set more attributes in the plugin? Do I have to unzip some informations on the target platform?

EDIT:

java.library.path=/opt/jdk/j2re1.4.2_16/lib/i386/client:/opt/jdk/j2re1.4.2_16/lib/i386:/opt/jdk/j2re1.4.2_16/../lib/i386::/opt/dsa/lib:/opt/dsa/lib

LastEditorDisplayName: Markus Lausberg

OwnerDisplayName: flolo

LastEditorDisplayName: flolo


问:
CRM 2016 - How to create a parent-child relationship with multiple parent types?
I have an entity - EntityZ, which has a ParentId where ParentId could be EntityA.Id, EntityB.Id or EntityC.Id. Is it possible to create this in MS Dynamics CRM 2016? If yes, how? I've looked but couldn't find a similar question or any help on the web.

答:
I think it is worth nothing that Dynamics 365 does contain and out-of-box "polymorphic" customer field.

This field can link to either an Account or Contact:

And while it can be kludgy, another option would be to create 3 lookups and only populate one. Once one is populated you could hide the other two. Or, you could have a "Parent Type" option set to determine which lookup to show.

It would be a bit messy to show three lookups in a view, with only one populated, so you might also want a Parent Name text field in to which you could concatenate the type and name. You could use a workflow to populate it, and then use it in views and reports.


问:
Disable part of textarea content
I have textarea with a static content. So I disabled the textarea to prevent any modification in the content. But I want to modify some part of this content. How can I do this ?

I have created a select box as follows :

```<code><div class="scroll-inside">
    <?php if($transactionalTemplates->num_rows() > 0) {
        foreach($transactionalTemplates->result_array() as $template) { ?>
            <a href="#" class="transactionalTemplate" data-text="<?php echo $template['TemplateText']?>">
                <?php echo $template['TemplateText'];?>
            </a>

    <?php   }
       }
   ?>
</div>
</code>```

When I select an item, the selected item will pasted to the following textarea

```<code><textarea placeholder="Enter your message here.." maxlength="160" class="messageTransactional" name="messageTransactional" id="messageTransactionalEnglish"></textarea>
</code>```

here is my script code:

```<code>$('.transactionalTemplate').click(function() {
        $('.messageTransactional').val($(this).data('text'));
        flag = true;
        $('.messageTransactional').keypress(function(e) {
            e.preventDefault();
        });
    });
</code>```

After adding the content to textarea, I prevent typing new content using the above function.
here is an example:

Suppose Dear (123), thanks for registering with us. Please subscribe our new offer to send unlimited SMS. For details please call (123) is my content.

I need to edit this content as Dear John, thanks for registering with us. Please subscribe our new offer to send unlimited SMS. For details please call 91xxxxxxxx

Which means, I need to change the content in paranthesis, keeping the format static.

答:
I was bored so did a pretty cool solution, it's not perfect though and still needs work for production.

const $editable = $('.editable')
const $inputs = $('.input')
const $save = $('#save')

const popup = function(e) {
  const $this = $(this)
  $this
    .find('input')
    .addClass('active')
    .focus()
}

const onBlur = function(e) {
  const $this = $(this)
  const $parent = $this.parent()
  const value = $this.val()

  $parent.find('input')
    .removeClass('active')

  if (value) {
    $parent
      .find('.value')
      .text($this.val())
  }
}

const onSave = function(e) {
  const $pre = $('pre')
  console.log('save', $pre.text())
}

$editable.on('click', popup)
$inputs.on('blur', onBlur)
$save.on('click', onSave)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  padding: 1em;
}

pre {
  white-space: normal;
  font-family: sans-serif;
}

.editable {
  border-bottom: 1px dotted #3cf;
  color: #3cf;
  min-width: 1em;
  min-height: 1em;
  position: relative;
}

.editable input {
  position: absolute;
  width: 80px;
  transform: translate(-70px, 0%);
  border: 1px solid #aaa;
  padding: .5em;
  border-radius: 5px;
  text-align: center;
  opacity: 0;
  visibility: hidden;
  transition: .4s opacity ease, .4s transform;
}

.editable input:focus,
.editable input.active {
  transform: translate(-70px, -100%);
  opacity: 1;
  visibility: visible;
  outline: none;
}

.editable:focus {
  outline: none;
}

.button {
  float: right;
  padding: .5em 2em;
}</code>```

<input type="hidden" name="messageTransactional" />

Dear name<input type="text" class="input" />, thanks for registering with us. Please subscribe our new offer to send unlimited SMS. For details please call phone<input type="text" class="input" /> is my content.
```

<button id="save" class="button">save</button></code>```

Title: Disable part of textarea content

Body:
I have textarea with a static content. So I disabled the textarea to prevent any modification in the content. But I want to modify some part of this content. How can I do this ?

I have created a select box as follows :

    <?php if($transactionalTemplates->num_rows() > 0) {
        foreach($transactionalTemplates->result_array() as $template) { ?>
            <a href="#" class="transactionalTemplate" data-text="<?php echo $template['TemplateText']?>">
                <?php echo $template['TemplateText'];?>

    <?php   }
       }
   ?>

When I select an item, the selected item will pasted to the following textarea

<textarea placeholder="Enter your message here.." maxlength="160" class="messageTransactional" name="messageTransactional" id="messageTransactionalEnglish"></textarea>

here is my script code:

$('.transactionalTemplate').click(function() {
        $('.messageTransactional').val($(this).data('text'));
        flag = true;
        $('.messageTransactional').keypress(function(e) {
            e.preventDefault();
        });
    });

After adding the content to textarea, I prevent typing new content using the above function.
here is an example:

Suppose Dear (123), thanks for registering with us. Please subscribe our new offer to send unlimited SMS. For details please call (123) is my content.

I need to edit this content as Dear John, thanks for registering with us. Please subscribe our new offer to send unlimited SMS. For details please call 91xxxxxxxx

Which means, I need to change the content in paranthesis, keeping the format static.

Body:
I was bored so did a pretty cool solution, it's not perfect though and still needs work for production.

const $editable = $('.editable')
const $inputs = $('.input')
const $save = $('#save')

const popup = function(e) {
  const $this = $(this)
  $this
    .find('input')
    .addClass('active')
    .focus()
}

const onBlur = function(e) {
  const $this = $(this)
  const $parent = $this.parent()
  const value = $this.val()

  $parent.find('input')
    .removeClass('active')

  if (value) {
    $parent
      .find('.value')
      .text($this.val())
  }
}

const onSave = function(e) {
  const $pre = $('pre')
  console.log('save', $pre.text())
}

$editable.on('click', popup)
$inputs.on('blur', onBlur)
$save.on('click', onSave)

body {
  padding: 1em;
}

pre {
  white-space: normal;
  font-family: sans-serif;
}

.editable {
  border-bottom: 1px dotted #3cf;
  color: #3cf;
  min-width: 1em;
  min-height: 1em;
  position: relative;
}

.editable input {
  position: absolute;
  width: 80px;
  transform: translate(-70px, 0%);
  border: 1px solid #aaa;
  padding: .5em;
  border-radius: 5px;
  text-align: center;
  opacity: 0;
  visibility: hidden;
  transition: .4s opacity ease, .4s transform;
}

.editable input:focus,
.editable input.active {
  transform: translate(-70px, -100%);
  opacity: 1;
  visibility: visible;
  outline: none;
}

.editable:focus {
  outline: none;
}

.button {
  float: right;
  padding: .5em 2em;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" name="messageTransactional" />

<pre id=="messageTransactional">
Dear <span class="editable" id="name"><span class="value">name</span><input type="text" class="input" /></span>, thanks for registering with us. Please subscribe our new offer to send unlimited SMS. For details please call <span class="editable" id="phone"><span class="value">phone</span><input type="text" class="input" /></span> is my content.
</pre>

<button id="save" class="button">save</button>


问:
GoogleMaps : Check if given marker position co ordinate is a road
I have this project which uses GMSKit(GoogleMap kit) in iOS(ObjectiveC) and there is a requirement that some random points are to be generated near the user's current location.

I have successfully generated random points but now what I want is to generate some random points at say _0.5kms away from the user and the random points has to fall on a road.

I have gone through most of the stackoverflow questions and answers and referred so many other google sites which give idea about this.

Can someone help me with this issue ? I am very confused. Thanks to everyone in advance. Happy Coding.

答:
You can use Google's Road API for that. It has two calls that you can use to find roads near certain coordinate(s).

https://developers.google.com/maps/documentation/roads/intro

1. Snap to roads:

You send a path of coordinates to the API and it returns another path of consists of roads (as Google places ids) that are close to your path. This only works for a path (a list of coordinates)

https://developers.google.com/maps/documentation/roads/snap

2. Nearest roads:

If you want to find the nearest roads to one single coordinate you can use the nearest roads call. It takes coordinate(s) as parameter and returns a list of roads that are near that point. This works with a single coordinate so it might be more useful in your case.

https://developers.google.com/maps/documentation/roads/nearest

Boths calls return coordinates and google places ids for the found roads. You can then check the distance to your point to check if you are on a road. You can use these id in other Google APIs (e.g. Google Places API) to get more information on the found roads.


问:
How to retrieve some specific rows and columns from an excel sheet?

I am reading an xlsx file using java (Apache POI).

I have created a Document class (having all excel column heading as variables)

i have to read each row in the excel and map to the Document class by creating a collection of Document class.

The problem I am facing is that I have to start reading from row 2 and from column 7 to column 35 and map the corresponding values to the document class.

Unable to to figure out exactly how the code should be ?

I have written the following lines of code.

```<code> List sheetData = new ArrayList();
        InputStream excelFile = new BufferedInputStream(new FileInputStream("D:\\Excel file\\data.xlsx"));
        Workbook workBook = new XSSFWorkbook(excelFile); // Creates Workbook
        XSSFSheet sheet = (XSSFSheet) workBook.getSheet("Daily");
        DataFormatter formatter = new DataFormatter();
        for (int i = 7; i <= 35; i++) {
            XSSFRow row = sheet.getRow(i);
            Cell cell = row.getCell(i);
            String val = formatter.formatCellValue(cell);
            sheetData.add(val);
        }
</code>```

答:
Assuming I've understood your question correctly, I believe you want to process every row which exists from row 2 onwards to the end of the file, and for each of those rows consider the cells in columns 7 through 35. I believe you also might need to process those values, but you haven't said how, so for this example I'll just stuff them in a list of strings and hope for the best...

This is based on the Apache POI documentation for iterating over rows and cells

```<code>File excelFile = new File("D:\\Excel file\\data.xlsx");
Workbook workBook = WorkbookFactory.create(excelFile);
Sheet sheet = workBook.getSheet("Daily");
DataFormatter formatter = new DataFormatter();

// Start from the 2nd row, processing all to the end
// Note - Rows and Columns in Apache POI are 0-based not 1-based
for (int rn=1; rn<=sheet.getLastRowNum(); rn++) {
   Row row = sheet.getRow(rn);
   if (row == null) {
      // Whole row is empty. Handle as required here
      continue;
   }
   List<String> values = new ArrayList<String>();
   for (int cn=6; cn<35; cn++) {
      Cell cell = row.getCell(cn);
      String val = null;
      if (cell != null) { val = formatter.formatCellValue(cell); }
      if (val == null || val.isEmpty()) {
         // Cell is empty. Handle as required here
      }
      // Save the value to list. Save to an object instead if required
      values.append(val);
   }
}
workBook.close();
</code>```

Depending on your business requirements, put in logic for handling blank rows and cells. Then, do whatever you need to do with the values you find, again as per your business requirements!

Body:
I am reading an xlsx file using java (Apache POI).

I have created a Document class (having all excel column heading as variables)

i have to read each row in the excel and map to the Document class by creating a collection of Document class.

The problem I am facing is that I have to start reading from row 2 and from column 7 to column 35 and map the corresponding values to the document class.

Unable to to figure out exactly how the code should be ?

I have written the following lines of code.

 List sheetData = new ArrayList();
        InputStream excelFile = new BufferedInputStream(new FileInputStream("D:\\Excel file\\data.xlsx"));
        Workbook workBook = new XSSFWorkbook(excelFile); // Creates Workbook
        XSSFSheet sheet = (XSSFSheet) workBook.getSheet("Daily");
        DataFormatter formatter = new DataFormatter();
        for (int i = 7; i <= 35; i++) {
            XSSFRow row = sheet.getRow(i);
            Cell cell = row.getCell(i);
            String val = formatter.formatCellValue(cell);
            sheetData.add(val);
        }

Body:
Assuming I've understood your question correctly, I believe you want to process every row which exists from row 2 onwards to the end of the file, and for each of those rows consider the cells in columns 7 through 35. I believe you also might need to process those values, but you haven't said how, so for this example I'll just stuff them in a list of strings and hope for the best...

This is based on the Apache POI documentation for iterating over rows and cells

File excelFile = new File("D:\\Excel file\\data.xlsx");
Workbook workBook = WorkbookFactory.create(excelFile);
Sheet sheet = workBook.getSheet("Daily");
DataFormatter formatter = new DataFormatter();

// Start from the 2nd row, processing all to the end
// Note - Rows and Columns in Apache POI are 0-based not 1-based
for (int rn=1; rn<=sheet.getLastRowNum(); rn++) {
   Row row = sheet.getRow(rn);
   if (row == null) {
      // Whole row is empty. Handle as required here
      continue;
   }
   List<String> values = new ArrayList<String>();
   for (int cn=6; cn<35; cn++) {
      Cell cell = row.getCell(cn);
      String val = null;
      if (cell != null) { val = formatter.formatCellValue(cell); }
      if (val == null || val.isEmpty()) {
         // Cell is empty. Handle as required here
      }
      // Save the value to list. Save to an object instead if required
      values.append(val);
   }
}
workBook.close();

Depending on your business requirements, put in logic for handling blank rows and cells. Then, do whatever you need to do with the values you find, again as per your business requirements!


问:
@PrePersist EventListener alternative for spring-data-mongo
I created a Repository to  auto increment the id of @Document but right now I need to explicitly call the @Id setter method to set the new id.
Is there a way I can do this using listeners like in JPA @PrePersist

```<code>@Repository
interface UserRepository : MongoRepository<User, Long>, UserRepositoryCustom

interface UserRepositoryCustom {
    fun save(user: User): User
}

class UserRepositoryImpl(private val mongoOperations: MongoOperations, private val sequenceRepository: SequenceRepository) : UserRepositoryCustom {

    override fun save(user: User): User {
        // need to call this line for every @Document
        user.id = sequenceRepository.getNextId(User.SEQUENCE_KEY)

        mongoOperations.insert(user)
        return user
    }
}
</code>```

GitHub Code

If I implement my code like this I need to call sequenceRepository.getNextId(...) for each and every document before I save it.

In JPA we can use EventListeners like @PrePersist. Is there spring-data-mongo alternative or similar function like to achieve this?

答:
In Spring data mongo provides event listeners. For example, You can extend AbstractMongoEventListener class and override the below method to achieve the PrePersist equivalent,

```<code>public void onBeforeSave(BeforeSaveEvent<E> event) {
    if (LOG.isDebugEnabled()) {
      LOG.debug("onBeforeSave({}, {})", event.getSource(), event.getDBObject());
    }
}
</code>```

Body:
I created a Repository to  auto increment the id of @Document but right now I need to explicitly call the @Id setter method to set the new id.
Is there a way I can do this using listeners like in JPA @PrePersist

@Repository
interface UserRepository : MongoRepository<User, Long>, UserRepositoryCustom

interface UserRepositoryCustom {
    fun save(user: User): User
}

class UserRepositoryImpl(private val mongoOperations: MongoOperations, private val sequenceRepository: SequenceRepository) : UserRepositoryCustom {

    override fun save(user: User): User {
        // need to call this line for every @Document
        user.id = sequenceRepository.getNextId(User.SEQUENCE_KEY)

        mongoOperations.insert(user)
        return user
    }
}

GitHub Code

If I implement my code like this I need to call sequenceRepository.getNextId(...) for each and every document before I save it.

In JPA we can use EventListeners like @PrePersist. Is there spring-data-mongo alternative or similar function like to achieve this?

Body:
In Spring data mongo provides event listeners. For example, You can extend AbstractMongoEventListener class and override the below method to achieve the PrePersist equivalent,

public void onBeforeSave(BeforeSaveEvent<E> event) {
    if (LOG.isDebugEnabled()) {
      LOG.debug("onBeforeSave({}, {})", event.getSource(), event.getDBObject());
    }
}


问:
Salesforce application - table xpath not working
This is a Salesforce application, I want to collect a value from table (datatable), below is the HTML code

```<code><table class="slds-table forceRecordLayout slds-table--header-fixed slds-table--edit slds-table--bordered resizable-cols slds-table--resizable-cols uiVirtualDataTable" data-aura-rendered-by="519:0" data-aura-class="uiVirtualDataTable" style="width: 1256px;">
<thead data-aura-rendered-by="520:0">
<tfoot data-aura-rendered-by="523:0"></tfoot>
<tbody data-aura-rendered-by="524:0">
<tr>
<td class="slds-cell-edit slds-cell-edit slds-cell-error errorColumn cellContainer" tabindex="-1" data-aura-rendered-by="809:0">
<td class="slds-cell-edit cellContainer" tabindex="-1" data-aura-rendered-by="833:0">
<th class="slds-cell-edit cellContainer" scope="row" tabindex="-1" data-aura-class="forceInlineEditCell" data-aura-rendered-by="850:0">
<span class="slds-grid slds-grid--align-spread forceInlineEditCell" data-aura-rendered-by="866:0" data-aura-class="forceInlineEditCell">
<a class="slds-truncate outputLookupLink slds-truncate forceOutputLookup" data-refid="recordId" data-recordid="a2F46000000Y3s0EAC"
 data-special-link="true" href="#/sObject/a2F46000000Y3s0EAC/view" target="_blank" rel="noreferrer" title="QE"
 data-aura-rendered-by="860:0" data-aura-class="forceOutputLookup">QE</a>
<span class="triggerContainer" data-aura-rendered-by="868:0">
</span>
</th>
</tr>
</tbody>
</table>
</code>```

I want to scrape the QE value from the table it's located in the first row.

Below is my xpath:

```<code>driver.findElement(By.xpath("//table[@class='slds-table forceRecordLayout slds-table--header-fixed slds-table--edit slds-table--bordered\n" +
" resizable-cols slds-table--resizable-cols uiVirtualDataTable']/tbody/tr/th/span")).getText();
</code>```

Using the table class name to frame this xpath, but I am getting Unable to locate element

Error description:

```<code>no such element: Unable to locate element: {"method":"xpath","selector":"//table[@class='slds-table forceRecordLayout slds-table--header-fixed slds-table--edit slds-table--bordered
 resizable-cols slds-table--resizable-cols uiVirtualDataTable']/tbody/tr/th/span"}
  (Session info: chrome=61.0.3163.100)
  (Driver info: chromedriver=2.29.461591 (62ebf098771772160f391d75e589dc567915b233),platform=Windows NT 6.1.7601 SP1 x86) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 300.01 seconds
</code>```

Note: When i execute my xpath in FirePath , its finding correctly, but while executing its not finding

答:
As you are working with chromedriver=2.29 as per the Release Notes chromedriver=2.29 supports Supports Chrome v56-58. So as we are working with chrome=61.0 we need to upgrade the  chromedriver binary to minimum v2.32.

Next, to scrape the text QE value from the table you can use the following code block :

```<code>System.out.println(driver.findElement(By.xpath("//th[@class='slds-cell-edit cellContainer']/span/a[@class='slds-truncate outputLookupLink slds-truncate forceOutputLookup']")).getAttribute("innerHTML"));
</code>```

Body:
This is a Salesforce application, I want to collect a value from table (datatable), below is the HTML code

QE

I want to scrape the QE value from the table it's located in the first row.

Below is my xpath:

driver.findElement(By.xpath("//table[@class='slds-table forceRecordLayout slds-table--header-fixed slds-table--edit slds-table--bordered\n" +
" resizable-cols slds-table--resizable-cols uiVirtualDataTable']/tbody/tr/th/span")).getText();

Using the table class name to frame this xpath, but I am getting Unable to locate element

Error description:

no such element: Unable to locate element: {"method":"xpath","selector":"//table[@class='slds-table forceRecordLayout slds-table--header-fixed slds-table--edit slds-table--bordered
 resizable-cols slds-table--resizable-cols uiVirtualDataTable']/tbody/tr/th/span"}
  (Session info: chrome=61.0.3163.100)
  (Driver info: chromedriver=2.29.461591 (62ebf098771772160f391d75e589dc567915b233),platform=Windows NT 6.1.7601 SP1 x86) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 300.01 seconds

Note: When i execute my xpath in FirePath , its finding correctly, but while executing its not finding

Body:
As you are working with chromedriver=2.29 as per the Release Notes chromedriver=2.29 supports Supports Chrome v56-58. So as we are working with chrome=61.0 we need to upgrade the  chromedriver binary to minimum v2.32.

Next, to scrape the text QE value from the table you can use the following code block :

System.out.println(driver.findElement(By.xpath("//th[@class='slds-cell-edit cellContainer']/span/a[@class='slds-truncate outputLookupLink slds-truncate forceOutputLookup']")).getAttribute("innerHTML"));


问:
Superfish Menu - Display subitems left if there is not enough screenspace on the right
I have 3 level menu.
I want the sub menus to be open in left direction instead of right when there is not enough screenspace to show them.

Please take a look at the screenshot to get the exact idea.

I want to use the onBeforeShow() function of superfish menu to fix this, but I am not able to make it work as desired.

Here's my code so far:

```<code>$("ul.sf-menu").superfish({
    delay: 1000,
    speed: 'fast',
    disableHI: true,
    onBeforeShow: function()
    {
      thisWidth = $(this).width();
      if  ( thisWidth > 0 )
      {
        thisParent = this.parent();
        parentLeft = thisParent.offset().left;
        parentWidth = this.parent().width();
        parentRight = parentWidth + parentLeft ;

        mainLeft =  document
          .getElementsByClassName('sf-menu')[0].offsetLeft;

        mainRight = document
          .getElementsByClassName('sf-menu')[0].offsetWidth;

        if  ( ( thisWidth + parentLeft ) < ( mainLeft + mainRight ) )
        {
          if  ( thisWidth > ( parentLeft + parentHeight ) )
          {
            $(this).css('left', - (parentLeft - mainLeft));
          }
          else
          {
            // open left
            $(this).css('left', - (thisWidth - parentWidth));
          }
        }
      }
    }
});
</code>```

答:
Though it is very old post, I am sharing a solution which worked for me as it may help someone and save time.
I am facing this issue with latest jquery superfish menu 1.7.9. I found another jquery plugin 'Supposition' in that forum to solve this issue.

```<code>(function($) { //create closure so we can safely use $ as alias for jQuery

  $(document).ready(function() {

    // initialise plugin
    var example = $('#example').superfish({
      //add options here if required
    }).supposition();

  });

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

jsfiddle link1
jsfiddle link2

Body:
I have 3 level menu.
I want the sub menus to be open in left direction instead of right when there is not enough screenspace to show them.

Please take a look at the screenshot to get the exact idea.

I want to use the onBeforeShow() function of superfish menu to fix this, but I am not able to make it work as desired.

Here's my code so far:

$("ul.sf-menu").superfish({
    delay: 1000,
    speed: 'fast',
    disableHI: true,
    onBeforeShow: function()
    {
      thisWidth = $(this).width();
      if  ( thisWidth > 0 )
      {
        thisParent = this.parent();
        parentLeft = thisParent.offset().left;
        parentWidth = this.parent().width();
        parentRight = parentWidth + parentLeft ;

        mainLeft =  document
          .getElementsByClassName('sf-menu')[0].offsetLeft;

        mainRight = document
          .getElementsByClassName('sf-menu')[0].offsetWidth;

        if  ( ( thisWidth + parentLeft ) < ( mainLeft + mainRight ) )
        {
          if  ( thisWidth > ( parentLeft + parentHeight ) )
          {
            $(this).css('left', - (parentLeft - mainLeft));
          }
          else
          {
            // open left
            $(this).css('left', - (thisWidth - parentWidth));
          }
        }
      }
    }
});

Body:
Though it is very old post, I am sharing a solution which worked for me as it may help someone and save time.
I am facing this issue with latest jquery superfish menu 1.7.9. I found another jquery plugin 'Supposition' in that forum to solve this issue.

(function($) { //create closure so we can safely use $ as alias for jQuery

  $(document).ready(function() {

    // initialise plugin
    var example = $('#example').superfish({
      //add options here if required
    }).supposition();

  });

})(jQuery);

jsfiddle link1
jsfiddle link2


问:
glib g main loop callback called more than one time without reason
I want to have a process with it g_main_loop that call a callback on incoming character within a file descriptor.

So I try with the above code on my board with the /home/dev file manually create.

Without doing something more than launching this code, callback is continuelly call.

I don't understand why. I expected callback to be call only if I write within /home/dev file. Is it an f_open file option issue ? Or am I not doing the right thing for the file descriptor considers data as read ?

```<code>#include <stdio.h>
#include <glib.h>
#include <glib/gstdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

gboolean cb_1 (GIOChannel *source, GIOCondition condition, gpointer data);

int main(void)
{
  GMainLoop* mainloop;
  int fd;
  GIOChannel* channel;

  mainloop = g_main_loop_new(NULL, TRUE);

  fd=g_open("/home/dev", O_RDONLY, O_NONBLOCK);

  channel=g_io_channel_unix_new(fd);

  g_io_add_watch(channel, G_IO_IN, cb_1, NULL);

  g_main_loop_run(mainloop);

  g_main_loop_unref(mainloop);
}

gboolean cb_1 (GIOChannel *source, GIOCondition condition, gpointer data)
{
  gchar** line=NULL;
  GIOStatus status;
  GError* error;

  printf("cb\n");

  status=g_io_channel_read_line(source, line, NULL, NULL, &error);

  if(G_IO_STATUS_NORMAL == status)
  {
    printf("callback : data : %s\n", *line);
    g_free(*line);
  }

  return TRUE;
}
</code>```

答:
Opening a file and creating a channel will trigger your callback whenever file is available to read.

In Linux, you need inotify watchers to achieve what you want. Below is the code snippet which helps you to understand it. In the callback method you need to read struct inotify_event to know the event for which your callback is called. Read inotify man page for complete details on possible mask that you can use. You may also need flags like IN_CREATE | IN_DELETE.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <glib.h>
#include <sys/inotify.h>

GMainLoop *mainloop;

static gboolean inotify_data(GIOChannel * channel, GIOCondition cond, gpointer user_data)
{
     printf("event on GIOChannel\n");
     char buffer[256];
     gsize bytes_read;

     GIOStatus status = g_io_channel_read_chars(channel, buffer, sizeof(buffer) - 1, &bytes_read, NULL);

     /* buffer can have multiple inotify_event structs which contains
      * details of what event, which file triggered this callback.
      */
     return TRUE;
}

int main(void)
{
     int fd, wd;
     GIOChannel *channel;

     mainloop = g_main_loop_new(NULL, FALSE);

     fd = inotify_init();
     if (fd < 0) {
          exit(EXIT_FAILURE);
     }

     wd = inotify_add_watch(fd, "/home/test", IN_OPEN | IN_MODIFY);

    channel = g_io_channel_unix_new(fd);
    if (!channel) {
        close(fd);
        exit(EXIT_FAILURE);
    }
    g_io_channel_set_close_on_unref(channel, TRUE);
    g_io_channel_set_encoding(channel, NULL, NULL);
    g_io_channel_set_buffered(channel, FALSE);

    g_io_add_watch(channel, G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR, inotify_data, NULL);

    g_main_loop_run(mainloop);

    return 0;
}
</code>```

Body:
I want to have a process with it g_main_loop that call a callback on incoming character within a file descriptor.

So I try with the above code on my board with the /home/dev file manually create.

Without doing something more than launching this code, callback is continuelly call.

I don't understand why. I expected callback to be call only if I write within /home/dev file. Is it an f_open file option issue ? Or am I not doing the right thing for the file descriptor considers data as read ?

#include <stdio.h>
#include <glib.h>
#include <glib/gstdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

gboolean cb_1 (GIOChannel *source, GIOCondition condition, gpointer data);

int main(void)
{
  GMainLoop* mainloop;
  int fd;
  GIOChannel* channel;

  mainloop = g_main_loop_new(NULL, TRUE);

  fd=g_open("/home/dev", O_RDONLY, O_NONBLOCK);

  channel=g_io_channel_unix_new(fd);

  g_io_add_watch(channel, G_IO_IN, cb_1, NULL);

  g_main_loop_run(mainloop);

  g_main_loop_unref(mainloop);
}

gboolean cb_1 (GIOChannel *source, GIOCondition condition, gpointer data)
{
  gchar** line=NULL;
  GIOStatus status;
  GError* error;

  printf("cb\n");

  status=g_io_channel_read_line(source, line, NULL, NULL, &error);

  if(G_IO_STATUS_NORMAL == status)
  {
    printf("callback : data : %s\n", *line);
    g_free(*line);
  }

  return TRUE;
}

Body:
Opening a file and creating a channel will trigger your callback whenever file is available to read.

In Linux, you need inotify watchers to achieve what you want. Below is the code snippet which helps you to understand it. In the callback method you need to read struct inotify_event to know the event for which your callback is called. Read inotify man page for complete details on possible mask that you can use. You may also need flags like IN_CREATE | IN_DELETE.

#include <stdio.h>
#include <stdlib.h>
#include <glib.h>
#include <sys/inotify.h>

GMainLoop *mainloop;

static gboolean inotify_data(GIOChannel * channel, GIOCondition cond, gpointer user_data)
{
     printf("event on GIOChannel\n");
     char buffer[256];
     gsize bytes_read;

     GIOStatus status = g_io_channel_read_chars(channel, buffer, sizeof(buffer) - 1, &bytes_read, NULL);

     /* buffer can have multiple inotify_event structs which contains
      * details of what event, which file triggered this callback.
      */
     return TRUE;
}

int main(void)
{
     int fd, wd;
     GIOChannel *channel;

     mainloop = g_main_loop_new(NULL, FALSE);

     fd = inotify_init();
     if (fd < 0) {
          exit(EXIT_FAILURE);
     }

     wd = inotify_add_watch(fd, "/home/test", IN_OPEN | IN_MODIFY);

    channel = g_io_channel_unix_new(fd);
    if (!channel) {
        close(fd);
        exit(EXIT_FAILURE);
    }
    g_io_channel_set_close_on_unref(channel, TRUE);
    g_io_channel_set_encoding(channel, NULL, NULL);
    g_io_channel_set_buffered(channel, FALSE);

    g_io_add_watch(channel, G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR, inotify_data, NULL);

    g_main_loop_run(mainloop);

    return 0;
}


问:
List names as JSON object name
i am facing the problem of JSON object naming in R.

```<code> df = list(`Choose to and fro flights` =  data.frame(sec =c('15:31:36' ,'15:31:37'),label=c("Choose to and fro flights","Choose to and fro flights"),responseCode = c( 200, 200), Counting=c(9,1)),
 `Details` = data.frame(sec = c("15:31:37" ,"15:31:37","15:31:38","15:31:39"),label = c("Details","Details","Details","Details"),responseCode = c("200","Non HTTP response code: org.apache.http.NoHttpResponseException","200","200"), Counting=c(2,2,5,1)))
</code>```

i want the label name is same as the JSON object name here
i am trying with following code but it's not give correct answer

```<code>toJSON(list(ResponseCode=lapply(seq_along(df), function(i) {    list(R_C_seconds=df[[i]]$sec,R_C_labels=df[[i]]$label,R_C_responseCode=df[[i]]$responseCode,R_C_Count=df[[i]]$Counting)})))
</code>```

is my output:

i want replace the  0 and 1 with label names.

答:
lapply() sets names on the result if the original argument has names. So, instead of seq_along(df), you need to build a named vector like this:

```<code>idx <- seq_along(df)
names(idx) <- names(df)
</code>```

or you can pass df itself to lapply():

reprex::reprex_info()
#> Created by the reprex package v0.1.1.9000 on 2017-11-14

df <- list(
  `Choose to and fro flights` =  data.frame(sec = c('15:31:36', '15:31:37'),
                                            label = c("Choose to and fro flights", "Choose to and fro flights"),
                                            responseCode = c( 200, 200),
                                            Counting = c(9,1)),
  `Details` = data.frame(sec = c("15:31:37", "15:31:37", "15:31:38", "15:31:39"),
                         label = c("Details", "Details", "Details", "Details"),
                         responseCode = c("200", "Non HTTP response code: org.apache.http.NoHttpResponseException", "200", "200"),
                         Counting=c(2,2,5,1))
)

jsonlite::toJSON(
  list(
    ResponseCode = lapply(df, function(x) {
      list(
        R_C_seconds      = x$sec,
        R_C_labels       = x$label,
        R_C_responseCode = x$responseCode,
        R_C_Count        = x$Counting
      )
    })
  ),
  pretty = TRUE
)
#> {
#>   "ResponseCode": {
#>     "Choose to and fro flights": {
#>       "R_C_seconds": ["15:31:36", "15:31:37"],
#>       "R_C_labels": ["Choose to and fro flights", "Choose to and fro flights"],
#>       "R_C_responseCode": [200, 200],
#>       "R_C_Count": [9, 1]
#>     },
#>     "Details": {
#>       "R_C_seconds": ["15:31:37", "15:31:37", "15:31:38", "15:31:39"],
#>       "R_C_labels": ["Details", "Details", "Details", "Details"],
#>       "R_C_responseCode": ["200", "Non HTTP response code: org.apache.http.NoHttpResponseException", "200", "200"],
#>       "R_C_Count": [2, 2, 5, 1]
#>     }
#>   }
#> }
```

Title: List names as JSON object name

Body:
i am facing the problem of JSON object naming in R.

 df = list(`Choose to and fro flights` =  data.frame(sec =c('15:31:36' ,'15:31:37'),label=c("Choose to and fro flights","Choose to and fro flights"),responseCode = c( 200, 200), Counting=c(9,1)),
 `Details` = data.frame(sec = c("15:31:37" ,"15:31:37","15:31:38","15:31:39"),label = c("Details","Details","Details","Details"),responseCode = c("200","Non HTTP response code: org.apache.http.NoHttpResponseException","200","200"), Counting=c(2,2,5,1)))

i want the label name is same as the JSON object name here
i am trying with following code but it's not give correct answer

toJSON(list(ResponseCode=lapply(seq_along(df), function(i) {    list(R_C_seconds=df[[i]]$sec,R_C_labels=df[[i]]$label,R_C_responseCode=df[[i]]$responseCode,R_C_Count=df[[i]]$Counting)})))

is my output:

i want replace the  0 and 1 with label names.

Body:
lapply() sets names on the result if the original argument has names. So, instead of seq_along(df), you need to build a named vector like this:

idx <- seq_along(df)
names(idx) <- names(df)

or you can pass df itself to lapply():

reprex::reprex_info()
#> Created by the reprex package v0.1.1.9000 on 2017-11-14

df <- list(
  `Choose to and fro flights` =  data.frame(sec = c('15:31:36', '15:31:37'),
                                            label = c("Choose to and fro flights", "Choose to and fro flights"),
                                            responseCode = c( 200, 200),
                                            Counting = c(9,1)),
  `Details` = data.frame(sec = c("15:31:37", "15:31:37", "15:31:38", "15:31:39"),
                         label = c("Details", "Details", "Details", "Details"),
                         responseCode = c("200", "Non HTTP response code: org.apache.http.NoHttpResponseException", "200", "200"),
                         Counting=c(2,2,5,1))
)

jsonlite::toJSON(
  list(
    ResponseCode = lapply(df, function(x) {
      list(
        R_C_seconds      = x$sec,
        R_C_labels       = x$label,
        R_C_responseCode = x$responseCode,
        R_C_Count        = x$Counting
      )
    })
  ),
  pretty = TRUE
)
#> {
#>   "ResponseCode": {
#>     "Choose to and fro flights": {
#>       "R_C_seconds": ["15:31:36", "15:31:37"],
#>       "R_C_labels": ["Choose to and fro flights", "Choose to and fro flights"],
#>       "R_C_responseCode": [200, 200],
#>       "R_C_Count": [9, 1]
#>     },
#>     "Details": {
#>       "R_C_seconds": ["15:31:37", "15:31:37", "15:31:38", "15:31:39"],
#>       "R_C_labels": ["Details", "Details", "Details", "Details"],
#>       "R_C_responseCode": ["200", "Non HTTP response code: org.apache.http.NoHttpResponseException", "200", "200"],
#>       "R_C_Count": [2, 2, 5, 1]
#>     }
#>   }
#> }


问:
Is there a way in pd.read_csv to replace NaN value with other character?
I have some data in csv file.
Because it is collected from machine,all lines should be number but some NaN values exists in some lines.And the machine can auto replace these NaN values with a string '-'.

My question is how to set params of pd.read_csv() to auto replace '-'values with zero from csv file?

答:
while reading the csv file you can use the parameter na_values:

```<code>df = pd.read_csv('file.csv',na_values='-')
</code>```

Edit:
you can then convert nan to 0 by:

```<code>df.fillna(0,1,inplace=True)
</code>```

Body:
while reading the csv file you can use the parameter na_values:

df = pd.read_csv('file.csv',na_values='-')

Edit:
you can then convert nan to 0 by:

df.fillna(0,1,inplace=True)


问:
Unable to locate the Javac Compiler
I tried to mvn install and got this message:

```<code>Compilation failure
Unable to locate the Javac Compiler in:
  /usr/lib/jvm/java-7-openjdk-amd64/jre/../lib/tools.jar
Please ensure you are using JDK 1.4 or above and
not a JRE (the com.sun.tools.javac.Main class is required).
In most cases you can change the location of your Java
installation by setting the JAVA_HOME environment variable.
</code>```

Well, there is an open jdk, I also downloaded another one. I tried to point JAVA_HOME to both, now it is set:

```<code>JAVA_HOME=/usr/lib/jvm/jdk1.7.0_03
export JAVA_HOME
PATH=$PATH:$JAVA_HOME/bin
export PATH
</code>```

I also tried to choose one of those open with sudo update-alternatives --config java but got the same error with different jdk versions in it.

How can I fix that? Thanks in advance.

答:
I faced similar error on an ubuntu machine while running a maven build from Jenkins. If output of 'javac -version' prompts below messages:

"The program 'javac' can be found in the following packages:
  default-jdk
  ecj
  gcj-5-jdk
  openjdk-8-jdk-headless
  gcj-4.8-jdk
  gcj-4.9-jdk
  openjdk-9-jdk-headless
Try: apt install "

Then you can install "openjdk-8-jdk-headless" using:

apt install openjdk-8-jdk-headless

This solved my problem and the maven build went through ok.

Title: Unable to locate the Javac Compiler

Body:
I tried to mvn install and got this message:

Compilation failure
Unable to locate the Javac Compiler in:
  /usr/lib/jvm/java-7-openjdk-amd64/jre/../lib/tools.jar
Please ensure you are using JDK 1.4 or above and
not a JRE (the com.sun.tools.javac.Main class is required).
In most cases you can change the location of your Java
installation by setting the JAVA_HOME environment variable.

Well, there is an open jdk, I also downloaded another one. I tried to point JAVA_HOME to both, now it is set:

JAVA_HOME=/usr/lib/jvm/jdk1.7.0_03
export JAVA_HOME
PATH=$PATH:$JAVA_HOME/bin
export PATH

I also tried to choose one of those open with sudo update-alternatives --config java but got the same error with different jdk versions in it.

How can I fix that? Thanks in advance.


问:
Is there a native interface that matches "string" and "Object that implements __toString()"?
We have objects that implement __toString():

```<code>class Foo {
    public function __toString()
    {
        return 'bar';
    }
}
</code>```

Then we have functions that return either string or object that implement __toString(), like the example above.

While using return type string for strings works of course:

```<code>function getString():string {
    return 'Works!';
}
</code>```

Returning object of type Foo does not work, because it's not a string:

```<code>function getString(Foo $foo):string {
    return $foo; // Fatal TypeError!
}
</code>```

Is there any PHP interface that we can use to type hint both string and objects that implement that unknown interface, e.g. Printable or Stringable (lol)?

The goal is to being able to return either string or objects that implement a specific interface (which would enforce the implementation of __toString).

答:
You could box your string in a wrapper class that just takes the string in the c-tor and has a toString() method that returns it.

This wrapper class would implement your Stringable interface, as do your other classes.

Then you can provide a return-type hinted method that returns objects of type Stringable.

This method can decide whether it returns one of your objects or just a wrapper for a string, as all of them implement Stringable.

However, this is to be balanced against just returning mixed and checking the returned value type in your calling method.

Further, if your objects implement the magic method __toString, then all your calling methods could always apply a cast (string) on the returned value.

If the returned value is a string, then it just keeps being a string.

If it is one of your objects that implements the magic method, then you'll get the string.

Yet you won't have the return-type hint in that case.

Body:
We have objects that implement __toString():

class Foo {
    public function __toString()
    {
        return 'bar';
    }
}

Then we have functions that return either string or object that implement __toString(), like the example above.

While using return type string for strings works of course:

function getString():string {
    return 'Works!';
}

Returning object of type Foo does not work, because it's not a string:

function getString(Foo $foo):string {
    return $foo; // Fatal TypeError!
}

Is there any PHP interface that we can use to type hint both string and objects that implement that unknown interface, e.g. Printable or Stringable (lol)?

The goal is to being able to return either string or objects that implement a specific interface (which would enforce the implementation of __toString).


问:
Compare only time from datetime in entity framework 6 with odp.net Oracle 12c
I am using entity framework 6 with oracle and Sql. Timespan datatype is not working with oracle. so i changed datatype to datetime. now i want to compare only time in datetime with Linq query. ex.

```<code>var db0010016 = _idb0010016Rep.GetAll().Where(e => e.ExecutionTime.TimeOfDay == viewmodel.ExecutionTime).FirstOrDefault();
</code>```

in above example e.ExecutionTime is datetime  and viewmodel.ExecutionTime is timespan. i am using timeofday function to convert it to timespan

above query failed to execute so i used DbFunctions.CreateTime() function

```<code>var db0010016 = _idb0010016Rep.FindBy(e => DbFunctions.CreateTime(e.ExecutionTime.Hour, e.ExecutionTime.Minute, e.ExecutionTime.Second) == exetime).FirstOrDefault();
</code>```

above ex exetime is timespan.still i am getting below error

```<code>{"Invalid parameter binding\r\nParameter name: ParameterName"}
</code>```

答:
if you want to compare only the time you can use the supported EDM canonical functions from DbFunctions (see here).
Unfortunately DbFunction.CreateTime is not supported.

Still, if you are interested in a comparison for example at the level of seconds, you can do something like this:

```<code>        var refTime = new DateTime(2017, 12, 13, 09, 30, 31);
        using (this.ctx = new MyContext())
        {
            var results = this.ctx.Groupings.Where(e => DbFunctions.DiffSeconds(e.EndDate, refTime) % 86400 == 0).ToList();
        }
</code>```

Here you take the difference in seconds using the EDM function DiffSeconds and make the modulus with the number of seconds in a day.

The query that gets executed is:

```<code>select
  "Extent1"."GROUP_TYPE" as "GROUP_TYPE",
  "Extent1"."GROUP_ENTITY_ID" as "GROUP_ENTITY_ID",
  "Extent1"."ITEM_ENTITY_ID" AS "ITEM_ENTITY_ID",
  "Extent1"."DATE_START" as "DATE_START",
  "Extent1"."DATE_END" AS "DATE_END"
from "MYSCHEMA"."ENTITY_GROUP_REL" "Extent1" where (0 = (mod( extract( day from ( cast(:p__linq__0 as timestamp(9)) -  cast("Extent1"."DATE_END" as timestamp(9))))*24*60*60 +  extract( hour from( cast(:p__linq__0 as timestamp(9)) -  cast("Extent1"."DATE_END" as timestamp(9))))*60*60 +  extract( minute from ( cast(:p__linq__0 as timestamp(9)) -  cast("Extent1"."DATE_END" as timestamp(9))))*60 +  extract( second from ( cast(:p__linq__0 as timestamp(9)) -  cast("Extent1"."DATE_END" as timestamp(9)))) ,86400)))
</code>```

As you can see it translates correctly to the oracle functions server-side.

I hope it helps,

Nicola

Body:
I am using entity framework 6 with oracle and Sql. Timespan datatype is not working with oracle. so i changed datatype to datetime. now i want to compare only time in datetime with Linq query. ex.

var db0010016 = _idb0010016Rep.GetAll().Where(e => e.ExecutionTime.TimeOfDay == viewmodel.ExecutionTime).FirstOrDefault();

in above example e.ExecutionTime is datetime  and viewmodel.ExecutionTime is timespan. i am using timeofday function to convert it to timespan

above query failed to execute so i used DbFunctions.CreateTime() function

var db0010016 = _idb0010016Rep.FindBy(e => DbFunctions.CreateTime(e.ExecutionTime.Hour, e.ExecutionTime.Minute, e.ExecutionTime.Second) == exetime).FirstOrDefault();

above ex exetime is timespan.still i am getting below error

{"Invalid parameter binding\r\nParameter name: ParameterName"}

Body:
if you want to compare only the time you can use the supported EDM canonical functions from DbFunctions (see here).
Unfortunately DbFunction.CreateTime is not supported.

Still, if you are interested in a comparison for example at the level of seconds, you can do something like this:

        var refTime = new DateTime(2017, 12, 13, 09, 30, 31);
        using (this.ctx = new MyContext())
        {
            var results = this.ctx.Groupings.Where(e => DbFunctions.DiffSeconds(e.EndDate, refTime) % 86400 == 0).ToList();
        }

Here you take the difference in seconds using the EDM function DiffSeconds and make the modulus with the number of seconds in a day.

The query that gets executed is:

select
  "Extent1"."GROUP_TYPE" as "GROUP_TYPE",
  "Extent1"."GROUP_ENTITY_ID" as "GROUP_ENTITY_ID",
  "Extent1"."ITEM_ENTITY_ID" AS "ITEM_ENTITY_ID",
  "Extent1"."DATE_START" as "DATE_START",
  "Extent1"."DATE_END" AS "DATE_END"
from "MYSCHEMA"."ENTITY_GROUP_REL" "Extent1" where (0 = (mod( extract( day from ( cast(:p__linq__0 as timestamp(9)) -  cast("Extent1"."DATE_END" as timestamp(9))))*24*60*60 +  extract( hour from( cast(:p__linq__0 as timestamp(9)) -  cast("Extent1"."DATE_END" as timestamp(9))))*60*60 +  extract( minute from ( cast(:p__linq__0 as timestamp(9)) -  cast("Extent1"."DATE_END" as timestamp(9))))*60 +  extract( second from ( cast(:p__linq__0 as timestamp(9)) -  cast("Extent1"."DATE_END" as timestamp(9)))) ,86400)))

As you can see it translates correctly to the oracle functions server-side.

I hope it helps,

Nicola


问:
Disk persistent cache in ehcache 3.4 is using (leaking?) direct memory
I am running a web application that makes use of Ehcache 3.4.0.  I have a cache configuration that defines a simple default of 1000 in-memory objects:

```<code><cache-template name="default">
    <key-type>java.lang.Object</key-type>
    <value-type>java.lang.Object</value-type>
    <heap unit="entries">1000</heap>
</cache-template>
</code>```

I then have some disk-based caches that use this default template, but override all values (generated programmatically, so that's why they even use the default template at all) like so:

```<code><cache alias='runViewCache' uses-template='default'>
    <key-type>java.lang.String</key-type>
    <value-type>java.lang.String</value-type>
    <resources>
        <heap unit='entries'>1</heap>
        <disk unit='GB' persistent='true'>1</disk>
    </resources>
</cache>
</code>```

As data is written into my disk-based cache, direct/off-heap memory is used by the JVM, and never freed.  Even clearing the cache does not free the memory.  The memory used is directly related (nearly byte-for-byte as far as I can tell) to the data written to the disk-based cache.

The authoritative tier for this cache is an instance of org.ehcache.impl.internal.store.disk.OffHeapDiskStore.

This appears to be a memory leak (memory is consumed and never freed) but I am by no means an expert at configuring ehcache.  Can anyone suggest a configuration change that will cause my disk tier to NOT use off-heap memory?  Or, is there something else that I am just completely misunderstanding that someone else can point out?

Thank you!

答:
How do you measure "used"?

TL;DR No, disk tier does not waste RAM.

As of v3.0.0 Ehcache uses memory mapped files for disk persistence:

Replacement of the port of Ehcache 2.x open source disk store by one that leverages the offheap library and memory mapped files.

This means, Ehcache uses in-memory address space to access files on disk. This does consume 0 bytes of your RAM. (At least directly. As @louis-jacomet already stated, the OS can decide to cache parts of the files in RAM.)

When you're running on Linux you should compare the VIRT and RES values of your process. VIRT is the amount of virtual bytes used by the process. RES is the amount of real RAM (RESident) bytes used by the process. VIRT should increase, while disk store cache is populated, but RES should remain pretty stable.

Body:
I am running a web application that makes use of Ehcache 3.4.0.  I have a cache configuration that defines a simple default of 1000 in-memory objects:

<cache-template name="default">
    <key-type>java.lang.Object</key-type>
    <value-type>java.lang.Object</value-type>
    <heap unit="entries">1000</heap>
</cache-template>

I then have some disk-based caches that use this default template, but override all values (generated programmatically, so that's why they even use the default template at all) like so:

<cache alias='runViewCache' uses-template='default'>
    <key-type>java.lang.String</key-type>
    <value-type>java.lang.String</value-type>
    <resources>
        <heap unit='entries'>1</heap>
        <disk unit='GB' persistent='true'>1</disk>
    </resources>
</cache>

As data is written into my disk-based cache, direct/off-heap memory is used by the JVM, and never freed.  Even clearing the cache does not free the memory.  The memory used is directly related (nearly byte-for-byte as far as I can tell) to the data written to the disk-based cache.

The authoritative tier for this cache is an instance of org.ehcache.impl.internal.store.disk.OffHeapDiskStore.

This appears to be a memory leak (memory is consumed and never freed) but I am by no means an expert at configuring ehcache.  Can anyone suggest a configuration change that will cause my disk tier to NOT use off-heap memory?  Or, is there something else that I am just completely misunderstanding that someone else can point out?

Thank you!


问:
Email Worksheet when multiple sheets are Open
Just wanted to know i have opened a workbook and under that there are multiple sheets with different names , now i need to email sheet with name Combined , however i am getting an error on the below code , please help i am getting compile error </p>

```<code>Sub Mail_ActiveSheet()
'Working in Excel 2000-2016
    Dim FileExtStr As String
    Dim FileFormatNum As Long
    Dim Sourcewb As Workbook
    Dim Destwb As Workbook
    Dim TempFilePath As String
    Dim TempFileName As String
    Dim OutApp As Object
    Dim OutMail As Object

    With Application
    .ScreenUpdating = False
    .EnableEvents = False
End With

Set Sourcewb = ActiveWorkbook

'Copy the ActiveSheet to a new workbook
ActiveSheet.Copy=>Sheets ("Combined").copy

Set Destwb = ActiveWorkbook

'Determine the Excel version and file extension/format
With Destwb
    If Val(Application.Version) < 12 Then
        'You use Excel 97-2003
        FileExtStr = ".xls": FileFormatNum = -4143
    Else
        'You use Excel 2007-2016
        Select Case Sourcewb.FileFormat
        Case 51: FileExtStr = ".xlsx": FileFormatNum = 51
        Case 52:
            If .HasVBProject Then
                FileExtStr = ".xlsm": FileFormatNum = 52
            Else
                FileExtStr = ".xlsx": FileFormatNum = 51
            End If
        Case 56: FileExtStr = ".xls": FileFormatNum = 56
        Case Else: FileExtStr = ".xlsb": FileFormatNum = 50
        End Select
    End If
End With

'    'Change all cells in the worksheet to values if you want
'    With Destwb.Sheets(1).UsedRange
'        .Cells.Copy
'        .Cells.PasteSpecial xlPasteValues
'        .Cells(1).Select
'    End With
'    Application.CutCopyMode = False

'Save the new workbook/Mail it/Delete it
TempFilePath = Environ$("temp") & "\"
TempFileName = "Part of " & Sourcewb.Name & " " & Format(Now, "dd-mmm-yy h-mm-ss")

Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)

With Destwb
    .SaveAs TempFilePath & TempFileName & FileExtStr, FileFormat:=FileFormatNum
    On Error Resume Next
    With OutMail
        .to = "sachin.gupta2209@gmail.com"
        .CC = "sachin.gupta2209@gmail.com;"
        .BCC = ""
        .Subject = "Samples"
        .Body = "Hi Please find attached"
        .Attachments.Add Destwb.FullName
        'You can add other files also like this
        '.Attachments.Add ("C:\test.txt")
        .Send   'or use .Display
    End With
    On Error GoTo 0
    .Close savechanges:=False
End With

'Delete the file you have send
Kill TempFilePath & TempFileName & FileExtStr

Set OutMail = Nothing
Set OutApp = Nothing

With Application
    .ScreenUpdating = True
    .EnableEvents = True
    End With
End Sub
</code>```

答:
Although you haven't said where the error is being thrown, I would say that you need to change the code on line 20 from:

```<code>ActiveSheet.Copy=>Sheets ("Combined").copy
</code>```

to:

```<code>sourcewb.Sheets("Combined").Copy
</code>```

in order to create the new active workbook set as Destwb to be emailed afterwards.

Body:
Just wanted to know i have opened a workbook and under that there are multiple sheets with different names , now i need to email sheet with name Combined , however i am getting an error on the below code , please help i am getting compile error

Sub Mail_ActiveSheet()
'Working in Excel 2000-2016
    Dim FileExtStr As String
    Dim FileFormatNum As Long
    Dim Sourcewb As Workbook
    Dim Destwb As Workbook
    Dim TempFilePath As String
    Dim TempFileName As String
    Dim OutApp As Object
    Dim OutMail As Object

    With Application
    .ScreenUpdating = False
    .EnableEvents = False
End With

Set Sourcewb = ActiveWorkbook

'Copy the ActiveSheet to a new workbook
ActiveSheet.Copy=>Sheets ("Combined").copy

Set Destwb = ActiveWorkbook

'Determine the Excel version and file extension/format
With Destwb
    If Val(Application.Version) < 12 Then
        'You use Excel 97-2003
        FileExtStr = ".xls": FileFormatNum = -4143
    Else
        'You use Excel 2007-2016
        Select Case Sourcewb.FileFormat
        Case 51: FileExtStr = ".xlsx": FileFormatNum = 51
        Case 52:
            If .HasVBProject Then
                FileExtStr = ".xlsm": FileFormatNum = 52
            Else
                FileExtStr = ".xlsx": FileFormatNum = 51
            End If
        Case 56: FileExtStr = ".xls": FileFormatNum = 56
        Case Else: FileExtStr = ".xlsb": FileFormatNum = 50
        End Select
    End If
End With

'    'Change all cells in the worksheet to values if you want
'    With Destwb.Sheets(1).UsedRange
'        .Cells.Copy
'        .Cells.PasteSpecial xlPasteValues
'        .Cells(1).Select
'    End With
'    Application.CutCopyMode = False

'Save the new workbook/Mail it/Delete it
TempFilePath = Environ$("temp") & "\"
TempFileName = "Part of " & Sourcewb.Name & " " & Format(Now, "dd-mmm-yy h-mm-ss")

Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)

With Destwb
    .SaveAs TempFilePath & TempFileName & FileExtStr, FileFormat:=FileFormatNum
    On Error Resume Next
    With OutMail
        .to = "sachin.gupta2209@gmail.com"
        .CC = "sachin.gupta2209@gmail.com;"
        .BCC = ""
        .Subject = "Samples"
        .Body = "Hi Please find attached"
        .Attachments.Add Destwb.FullName
        'You can add other files also like this
        '.Attachments.Add ("C:\test.txt")
        .Send   'or use .Display
    End With
    On Error GoTo 0
    .Close savechanges:=False
End With

'Delete the file you have send
Kill TempFilePath & TempFileName & FileExtStr

Set OutMail = Nothing
Set OutApp = Nothing

With Application
    .ScreenUpdating = True
    .EnableEvents = True
    End With
End Sub

Body:
Although you haven't said where the error is being thrown, I would say that you need to change the code on line 20 from:

ActiveSheet.Copy=>Sheets ("Combined").copy

to:

sourcewb.Sheets("Combined").Copy

in order to create the new active workbook set as Destwb to be emailed afterwards.