问:
Importing Excel to internal table with same layout
I know of function module ALSM_EXCEL_TO_INTERNAL_TABLE. This FM creates an internal table with three columns (row, column, value). But I want to create an internal table which has the same layout as my Excel sheet. How can I achieve this? </p>

答: If you upload the data with FM ALSM_EXCEL_TO_INTERNAL_TABLE, you can LOOP through the internal table this FM is uses (the one with row, column, value as you mentioned) and fill your own internal table (which looks like the Excel sheet) accordingly.</p>


来源: stackexchange

问:
Get the classname from multi class element which has underscore
I have an element like the following:

```<code><div class="busatt bus_12_1">data</div>   //classname->bus_databasevalue1_databasevalue2
</code>```

I need to get the class that has underscore in it.I cannot put this classname as ID name because it can be duplicated sometimes.

I need it something like this.

```<code>$('busatt').prop('class').match(some regex exp) should give me only ''bus_12_1'' .
</code>```

I know that ,we can get the classname like following:

```<code>  var classes = $('busatt').prop('class').split(' ');
  for(var i=0; i<classes.length; i++){
         if( classes[i].indexOf('_') != -1 )
         {
           alert(classes[i]);
         }
  }
</code>```

Can I get the result in a single line of code with regex or something like

答:
You can use the filter() function to reduce the set of matched elements.
this is a small demo:

$("div").filter(function() {
        return this.className.match(/\b\w*_\w*\b/);
    })
    .html("Matched!");```
<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>
<div class="busatt bus_12_1">data</div></code>```

EDIT BY TECHY:

I have used the following code and is working :

```<code>var new_class='';
new_class = $(this).prop('class').match(/\b\w*_\w*\b/).toString();
alert(new_class);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an element like the following:

data
   //classname->bus_databasevalue1_databasevalue2

I need to get the class that has underscore in it.I cannot put this classname as ID name because it can be duplicated sometimes.

I need it something like this.

$('busatt').prop('class').match(some regex exp) should give me only ''bus_12_1'' .

I know that ,we can get the classname like following:

  var classes = $('busatt').prop('class').split(' ');
  for(var i=0; i<classes.length; i++){
         if( classes[i].indexOf('_') != -1 )
         {
           alert(classes[i]);
         }
  }

Can I get the result in a single line of code with regex or something like

Body:
You can use the filter() function to reduce the set of matched elements.
this is a small demo:

$("div").filter(function() {
        return this.className.match(/\b\w*_\w*\b/);
    })
    .html("Matched!");

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="busatt bus_12_1">data</div>

EDIT BY TECHY:

I have used the following code and is working :

var new_class='';
new_class = $(this).prop('class').match(/\b\w*_\w*\b/).toString();
alert(new_class);


问:
Pivot for Unknown number of values in description- SQL Server 2008
May some one please help me how to get the result in SQL SERVER 2008</p>

答:
Are you trying to do something like this:

```<code>IF OBJECT_ID('tempdb..#TABLE') IS NOT NULL
BEGIN;
    DROP TABLE #TABLE;
END;

CREATE TABLE #TABLE
(
[Generic Name] varchar(15),
[Description]varchar(15)
)

INSERT #TABLE

SELECT 'RESISTOR',  'POWER' UNION ALL
SELECT 'RESISTOR',  'Type' UNION ALL
SELECT 'RESISTOR',  'DESIGN' UNION ALL
SELECT 'RESISTOR',  'Material' UNION ALL
SELECT 'OTHER',  'Other' UNION ALL
SELECT 'OTHER',  'Material';

DECLARE @cols NVARCHAR(MAX)
       ,@query NVARCHAR(MAX);

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Description)
                    from #TABLE
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

set @query = 'SELECT [Generic Name], ' + @cols + '
            FROM
            (
                SELECT [Generic Name], [Generic Name] AS [BaseName], [Description]
                from #TABLE
            ) DS
            pivot
            (
                COUNT([BaseName])
                for [Description] in (' + @cols + ')
            ) p '

            SELECT @query

execute(@query)
</code>```

This will show you the count (but if you have only one record for each description it will be only true/have or false/not have) of each generic name.

Body:
Are you trying to do something like this:

IF OBJECT_ID('tempdb..#TABLE') IS NOT NULL
BEGIN;
    DROP TABLE #TABLE;
END;

CREATE TABLE #TABLE
(
[Generic Name] varchar(15),
[Description]varchar(15)
)

INSERT #TABLE

SELECT 'RESISTOR',  'POWER' UNION ALL
SELECT 'RESISTOR',  'Type' UNION ALL
SELECT 'RESISTOR',  'DESIGN' UNION ALL
SELECT 'RESISTOR',  'Material' UNION ALL
SELECT 'OTHER',  'Other' UNION ALL
SELECT 'OTHER',  'Material';

DECLARE @cols NVARCHAR(MAX)
       ,@query NVARCHAR(MAX);

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Description)
                    from #TABLE
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

set @query = 'SELECT [Generic Name], ' + @cols + '
            FROM
            (
                SELECT [Generic Name], [Generic Name] AS [BaseName], [Description]
                from #TABLE
            ) DS
            pivot
            (
                COUNT([BaseName])
                for [Description] in (' + @cols + ')
            ) p '

            SELECT @query

execute(@query)

This will show you the count (but if you have only one record for each description it will be only true/have or false/not have) of each generic name.


问:
reflection method invocation for a dynamic object
I am creating a class (named haan.java) at runtime of my java application.
    The object of this class is inserted in a Oracle Coherence Cache
    When I get an object(tempHaan) from the cache, it is of type haan. But when I try to invoke the method of this object(tempHaan), I am getting the error "java.lang.IllegalArgumentException: object is not an instance of declaring class"

Error occurs at the line "Object invoke = methodgetHash.invoke(tempHaan, null);"

```<code>PFB the code:

NamedCache cacheConn;
CacheFactory.ensureCluster();
NamedCache cacheConnHaan = CacheFactory.getCache("Haan");
Class cls = null;
File f = new File(rtomProperties.getPropertyValue("pojoToBuild"));

try {
    ClassLoader currentThreadClassLoader = Thread.currentThread().getContextClassLoader();
    URLClassLoader cl = new URLClassLoader(new URL[] { f.toURI().toURL() },
        currentThreadClassLoader);
    Object tempHaan;
    cls = Class.forName(rtomProperties.getPropertyValue("pojoPackageLocation").concat(".haan"), true, cl);
    System.out.println("*************** the class is **********"
        + cls.newInstance().getClass().toString());
    System.out.println("******DONE LOADING");

    URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Class clazz = URLClassLoader.class;

    // Use reflection
    Method m = clazz.getDeclaredMethod("addURL", new Class[] { URL.class });
    m.setAccessible(true);
    URL ur = f.toURI().toURL();
    m.invoke(classLoader, new Object[] { ur });

    Thread.currentThread().getContextClassLoader().getResourceAsStream("context.xml");

    tempHaan = cacheConnHaan.get(aan);

    System.out.println("*************AFTER" + tempHaan.getClass().toString());

    System.out.println("*************tempHaan: "+tempHaan.toString());
    Class[] paramObject = new Class[1];
    paramObject[0] = Object.class;
    Method methodgetHash = null;
    Class noparams[] = {};
    methodgetHash = cls.getDeclaredMethod("getHash", noparams);
    Object temp = cls.newInstance();

    Object invoke = methodgetHash.invoke(tempHaan, null);
    key = (String) invoke;

    System.out.println("key for the record: " + key);
} catch (ClassNotFoundException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
} catch (InstantiationException e) {
    // TODO Auto-generated catch block
    System.out.println("******not instantiated");
    e.printStackTrace();
} catch (IllegalAccessException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (NullPointerException npe) {
    System.out.println("Hash-Aan mapping not found for aan " + aan);
    continue;
}
</code>```

答:
You dynamically create an ULRClassLoader for loading the class, i.e. the cached instance's class and the class you get the method to invoke from come from different classloaders leading to this error. You might get the declared method from the instance to be cached and cache it together with the instance or you retrieve the instance from the cache and get the method to be invoked by calling

```<code>Method methodgetHash = tempHaan.getDeclaredMethod("getHash", noparams);
</code>```

Caching the method together with the class to be cached would come with a performance-improvement BTW.

Body:
I am creating a class (named haan.java) at runtime of my java application.
    The object of this class is inserted in a Oracle Coherence Cache
    When I get an object(tempHaan) from the cache, it is of type haan. But when I try to invoke the method of this object(tempHaan), I am getting the error "java.lang.IllegalArgumentException: object is not an instance of declaring class"

Error occurs at the line "Object invoke = methodgetHash.invoke(tempHaan, null);"

PFB the code:

NamedCache cacheConn;
CacheFactory.ensureCluster();
NamedCache cacheConnHaan = CacheFactory.getCache("Haan");
Class cls = null;
File f = new File(rtomProperties.getPropertyValue("pojoToBuild"));

try {
    ClassLoader currentThreadClassLoader = Thread.currentThread().getContextClassLoader();
    URLClassLoader cl = new URLClassLoader(new URL[] { f.toURI().toURL() },
        currentThreadClassLoader);
    Object tempHaan;
    cls = Class.forName(rtomProperties.getPropertyValue("pojoPackageLocation").concat(".haan"), true, cl);
    System.out.println("*************** the class is **********"
        + cls.newInstance().getClass().toString());
    System.out.println("******DONE LOADING");

    URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Class clazz = URLClassLoader.class;

    // Use reflection
    Method m = clazz.getDeclaredMethod("addURL", new Class[] { URL.class });
    m.setAccessible(true);
    URL ur = f.toURI().toURL();
    m.invoke(classLoader, new Object[] { ur });

    Thread.currentThread().getContextClassLoader().getResourceAsStream("context.xml");

    tempHaan = cacheConnHaan.get(aan);

    System.out.println("*************AFTER" + tempHaan.getClass().toString());

    System.out.println("*************tempHaan: "+tempHaan.toString());
    Class[] paramObject = new Class[1];
    paramObject[0] = Object.class;
    Method methodgetHash = null;
    Class noparams[] = {};
    methodgetHash = cls.getDeclaredMethod("getHash", noparams);
    Object temp = cls.newInstance();

    Object invoke = methodgetHash.invoke(tempHaan, null);
    key = (String) invoke;

    System.out.println("key for the record: " + key);
} catch (ClassNotFoundException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
} catch (InstantiationException e) {
    // TODO Auto-generated catch block
    System.out.println("******not instantiated");
    e.printStackTrace();
} catch (IllegalAccessException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (NullPointerException npe) {
    System.out.println("Hash-Aan mapping not found for aan " + aan);
    continue;
}

Body:
You dynamically create an ULRClassLoader for loading the class, i.e. the cached instance's class and the class you get the method to invoke from come from different classloaders leading to this error. You might get the declared method from the instance to be cached and cache it together with the instance or you retrieve the instance from the cache and get the method to be invoked by calling

Method methodgetHash = tempHaan.getDeclaredMethod("getHash", noparams);

Caching the method together with the class to be cached would come with a performance-improvement BTW.


问:
XSLT missing linebreaks when selecting nodes by path expression
I am copying some nodes according to XSLT: Copy child elements of a complex type only once by using a path expression within a copy-of tag:

```<code><xsl:copy-of select="/xs:schema/xs:complexType[@name=current()/xs:element/@type]"/>
</code>```

In the output all linebreaks are missing at the elements processed by this statement. (Elesewhere they are shown) It looks like this:

```<code>...</xs:complexType><xs:complexType....
</code>```

I can only add linebreaks before and after, but not between them. How can i achive this? Thanx for your help!

答:
You provided too little data to attempt any testing. E.g. it is not clear, what output method uses your script.

Quite often XSLT script contains xsl:strip-space instruction, which causes normalization of text nodes.
This normalization a.o. changes "internal" sequences of "white" chars, including line breaks,
into a single space.

Maybe this is the cause.

Take alse a look at xsl:output instruction in your script.
Does it contain indent="yes" attribute?
If it doesn't, the output contains no line breaks between output elements.

Maybe your script contains in some places output of explicite line breaks
(e.g. <xsl:text>&#aA;</xsl:text>), so these line breaks are rendered.

But if you have no indent="yes" attribute, then no line breaks are inserted
"automatically" between consecutive elements.

Body:
I am copying some nodes according to XSLT: Copy child elements of a complex type only once by using a path expression within a copy-of tag:

<xsl:copy-of select="/xs:schema/xs:complexType[@name=current()/xs:element/@type]"/>

In the output all linebreaks are missing at the elements processed by this statement. (Elesewhere they are shown) It looks like this:

...</xs:complexType><xs:complexType....

I can only add linebreaks before and after, but not between them. How can i achive this? Thanx for your help!


问:
Wordpress custom API development
Below is the code I am using

```<code>add_action( 'rest_api_init', 'add_custom_users_api');

function add_custom_users_api(){
   register_rest_route( 'testing', '/users', array(
     'methods' => 'GET',
     'callback' => 'get_custom_users_data',
   ));
}

function get_custom_users_data($data){
    //get users by market
    $result = "Testing this";
    return $result;
}
</code>```

Below is the response I am getting

答:
Try This

```<code>add_action( 'rest_api_init', 'add_custom_users_api');

function add_custom_users_api(){
    register_rest_route( 'testing', '/users', array(
        'methods' => 'GET',
        'callback' => 'get_custom_users_data',
    ));
}

function get_custom_users_data($data){
    //get users by market
    $result = "Testing this";
    return $result;
}
</code>```

http://localhost/wordpress/wp-json/testing/users

Title: Wordpress custom API development

Body:
Below is the code I am using

add_action( 'rest_api_init', 'add_custom_users_api');

function add_custom_users_api(){
   register_rest_route( 'testing', '/users', array(
     'methods' => 'GET',
     'callback' => 'get_custom_users_data',
   ));
}

function get_custom_users_data($data){
    //get users by market
    $result = "Testing this";
    return $result;
}

Below is the response I am getting

Body:
Try This

add_action( 'rest_api_init', 'add_custom_users_api');

function add_custom_users_api(){
    register_rest_route( 'testing', '/users', array(
        'methods' => 'GET',
        'callback' => 'get_custom_users_data',
    ));
}

function get_custom_users_data($data){
    //get users by market
    $result = "Testing this";
    return $result;
}

http://localhost/wordpress/wp-json/testing/users


问:
AnguarJS expression error on goland
I am developing an AngularJS application on Goland.

Goland claims error on an expression {{ count * times }} as below.

I am enabling AngularJS plugin on Goland as below.

Why {{count * times}} got error on Goland? How can I fix?

答:
Go uses {{ and }} as the default template tags. In the case that these tags conflict with other template tags as in AngularJS, we can use other tags.

```<code>indexTmpl = template.New("index.html").Delims("<<", ">>")
indexTmpl, _ = indexTmpl.ParseFiles("index.html")
</code>```

For more Info: Golang and AngularJS template conflict

Title: AnguarJS expression error on goland

Body:
Go uses {{ and }} as the default template tags. In the case that these tags conflict with other template tags as in AngularJS, we can use other tags.

indexTmpl = template.New("index.html").Delims("<<", ">>")
indexTmpl, _ = indexTmpl.ParseFiles("index.html")

For more Info: Golang and AngularJS template conflict


问:
How to query for Test Step count in VSTS Test Cases?
Our team is in the process of migrating to VSTS and is creating new Test cases as well as recreating Test Cases from old Word documents. Some Test Cases were created as placeholders to be backfilled with Test Steps at a later time.

Is it possible to retrieve the count of steps in a test case?

答:
You can retrieve the count of test case steps through API:</p>

```<code>var u = new Uri("https://XXX.visualstudio.com");
            var c = new VssClientCredentials();
            TfsTeamProjectCollection _tfs = new TfsTeamProjectCollection(u, c);
            _tfs.EnsureAuthenticated();

            ITestManagementService test_service = (ITestManagementService)_tfs.GetService(typeof(ITestManagementService));
            ITestManagementTeamProject project = test_service.GetTeamProject("[team project]");

            ITestPlan plan = project.TestPlans.Find([test plan id]);

            ITestCase testcase = project.TestCases.Find([test case id]);

            Console.WriteLine(testcase.Actions.Count);
            Console.Read();
</code>```

Body:
You can retrieve the count of test case steps through API:

var u = new Uri("https://XXX.visualstudio.com");
            var c = new VssClientCredentials();
            TfsTeamProjectCollection _tfs = new TfsTeamProjectCollection(u, c);
            _tfs.EnsureAuthenticated();

            ITestManagementService test_service = (ITestManagementService)_tfs.GetService(typeof(ITestManagementService));
            ITestManagementTeamProject project = test_service.GetTeamProject("[team project]");

            ITestPlan plan = project.TestPlans.Find([test plan id]);

            ITestCase testcase = project.TestCases.Find([test case id]);

            Console.WriteLine(testcase.Actions.Count);
            Console.Read();


问:
MVVM DataTemplate Binding Issue
Perhaps this is a case of too much cold medicine, but I just can't seem to get this Binding correct.

Here is the (simplified) Window, with the a DataTemplate for each ViewModel type, which should just show an associated View:

```<code><Window ...>
    <Window.Resources>
        <DataTemplate DataType="{x:Type local:DefaultViewViewModel">
            <local:DefaultView />
        </DataTemplate>

        <DataTemplate DataType="{x:Type other:AnotherViewModel">
            <other:AnotherView />
        </DataTemplate>
    </Window.Resources>

    <Grid>
        <ContentControl Content="{Binding CurrentViewModel}" />
    </Grid>
</Window>
</code>```

Here is some of the MainViewModel (the actual ShowABCView methods are Command functions that do more than is shown here, for brevity):

```<code>class MainViewModel : ViewModelBase
{
    private Stack<ViewModelBase> mContentViewStack;

    public MainViewModel()
    {
        mContentViewStack = new Stack<ViewModelBase>();
        ShowDefaultView();
    }

    public ViewModelBase CurrentViewModel
    {
        get { return mContentViewStack.Peek(); }
    }

    private ShowDefaultView()
    {
        DefaultViewViewModel viewModel = new DefaultViewViewModel();
        mContentViewStack.Push(viewModel);
        NotifyPropertyChanged("CurrentViewModel");
    }

    private ShowAnotherView()
    {
        AnotherViewModel viewModel = new AnotherViewModel();
        mContentViewStack.Push(viewModel);
        NotifyPropertyChanged("CurrentViewModel");
    }
}
</code>```

And the MainWindow startup code:

```<code>public MainWindow()
{
    this.DataContext = new MainViewModel();
}
</code>```

When I run this, I get the error

System.Windows.Data.Error: 40:
  BindingExpression path error:
  'Content' property not found on
  'object' 'DefaultViewViewModel'

I know I'm missing something obvious here, but the Nyquil and friends betray me...

*EDIT - DefaultViewViewModel and DefaultView *

DefaultViewViewModel:

```<code>// ViewModelBase is basically just a wrapper for INotifyPropertyChanged,
// plus some other common-to-my-project properties
// (NOT INCLUDING A Content PROPERTY)
class DefaultViewViewModel : ViewModelBase
{
    public DefaultViewViewModel() : base()
   {
   }
}
</code>```

DefaultView:

```<code><UserControl ...>
    <TextBlock Text="Some Hard Coded Text Formatted To My Liking" />
</UserControl>
</code>```

答:
Found the answer upstream from where I was looking.  There was an incorrect binding (used regular Binding without RelativeSource of the TemplatedParent) in the base View control that all of our Views use.

No more Nyquil for me...

ContentLicense: CC BY-SA 2.5

Title: MVVM DataTemplate Binding Issue

Body:
Perhaps this is a case of too much cold medicine, but I just can't seem to get this Binding correct.

Here is the (simplified) Window, with the a DataTemplate for each ViewModel type, which should just show an associated View:

<Window ...>
    <Window.Resources>
        <DataTemplate DataType="{x:Type local:DefaultViewViewModel">
            <local:DefaultView />
        </DataTemplate>

        <DataTemplate DataType="{x:Type other:AnotherViewModel">
            <other:AnotherView />
        </DataTemplate>
    </Window.Resources>

    <Grid>
        <ContentControl Content="{Binding CurrentViewModel}" />
    </Grid>
</Window>

Here is some of the MainViewModel (the actual ShowABCView methods are Command functions that do more than is shown here, for brevity):

class MainViewModel : ViewModelBase
{
    private Stack<ViewModelBase> mContentViewStack;

    public MainViewModel()
    {
        mContentViewStack = new Stack<ViewModelBase>();
        ShowDefaultView();
    }

    public ViewModelBase CurrentViewModel
    {
        get { return mContentViewStack.Peek(); }
    }

    private ShowDefaultView()
    {
        DefaultViewViewModel viewModel = new DefaultViewViewModel();
        mContentViewStack.Push(viewModel);
        NotifyPropertyChanged("CurrentViewModel");
    }

    private ShowAnotherView()
    {
        AnotherViewModel viewModel = new AnotherViewModel();
        mContentViewStack.Push(viewModel);
        NotifyPropertyChanged("CurrentViewModel");
    }
}

And the MainWindow startup code:

public MainWindow()
{
    this.DataContext = new MainViewModel();
}

When I run this, I get the error

System.Windows.Data.Error: 40:
  BindingExpression path error:
  'Content' property not found on
  'object' 'DefaultViewViewModel'

I know I'm missing something obvious here, but the Nyquil and friends betray me...

*EDIT - DefaultViewViewModel and DefaultView *

DefaultViewViewModel:

// ViewModelBase is basically just a wrapper for INotifyPropertyChanged,
// plus some other common-to-my-project properties
// (NOT INCLUDING A Content PROPERTY)
class DefaultViewViewModel : ViewModelBase
{
    public DefaultViewViewModel() : base()
   {
   }
}

DefaultView:

<UserControl ...>
    <TextBlock Text="Some Hard Coded Text Formatted To My Liking" />
</UserControl>


问:
update property using map versus object.assign
When I use redux I have to care for immutable object, but in pure react, I often update my property in arrays using map

```<code>handleAgeChangedUser = e => {
    const { users, selectedUser } = this.state;

    this.setState(
      {
        users: users.map(o => {
          return o.id === selectedUser.id ? selectedUser : o;
        })
      },
      () => {
        this.ageInput.value = "";
      }
    );
  };
</code>```

Demo https://codesandbox.io/s/z358py2y2p

What's the limitation of this approach and what's other alternative? I remember without es6, I have to use loadash, or worse, back in the day I have to findIndex, then loop manually just to do this simple operation.

答:
What's the limitation of this approach and what's other alternative?

There are two aspects in question - pure technical and architectural.

First, React performs shallow comparation by default and it's not recommend to implement deep equal logic (https://reactjs.org/docs/react-component.html#shouldcomponentupdate ), that's why immutable-like solutions (immutable.js, seamless-immutable) allows to solve that problem without harming performance.

Second, state-ful components itself is bad architectural solution, because of business logic is distributed between many components and data flow is not unidirectional, which is incompatible with functional approach. So, flux-based solution with immutable provider is best.

Body:
When I use redux I have to care for immutable object, but in pure react, I often update my property in arrays using map

handleAgeChangedUser = e => {
    const { users, selectedUser } = this.state;

    this.setState(
      {
        users: users.map(o => {
          return o.id === selectedUser.id ? selectedUser : o;
        })
      },
      () => {
        this.ageInput.value = "";
      }
    );
  };

Demo https://codesandbox.io/s/z358py2y2p

What's the limitation of this approach and what's other alternative? I remember without es6, I have to use loadash, or worse, back in the day I have to findIndex, then loop manually just to do this simple operation.


问:
Different behaviour shown when running the same code for a file and for a list
I have observed this unusual behaviour when I try to do a string slicing on the words in a file and the words in a list.Both the results are quite different.

For example I have a file 'words.txt' which contains the following content

```<code>POPE
POPS
ROPE
POKE
COPE
PAPE
NOPE
POLE
</code>```

When I write the below piece of code, I expect to get a list of words with last letter omitted.

```<code>with open("words.txt", "r") as fo:
    for l in fo:
        print(l[:-1])
</code>```

But instead I get this result below.No string slicing takes place and the words are similar as before.

```<code>POPE
POPS
ROPE
POKE
COPE
PAPE
NOPE
POLE
</code>```

But if I write the below code, I get what I want

```<code>lis = ["POPE", "POPS", "ROPE", "POKE", "COPE", "PAPE", "NOPE", "POLE"]
for i in lis:
    print(i[:-1])
</code>```

I am able to delete the last letter of each of the words as expected.

```<code>POP
POP
ROP
POK
COP
PAP
NOP
POL
</code>```

So why do I see two different results for the same operation [: -1] ?

答:
The line ends with \n in files where as you dont need line endings in lists.

Your actual file contents are as follows

```<code>POPE\n
POPS\n
ROPE\n
POKE\n
COPE\n
PAPE\n
NOPE\n
POLE\n
</code>```

hence the print(l[:-1]) is actually trimming the line ending i.e. \n.

To verify this, declare an empty list before the loop, and add each line to that list and print it. You will find the that the lines contain the \n on every line

```<code>stuff = []

with open("words.txt", "r") as fo:
     for line in fo:
         stuff.append(line)

print stuff
</code>```

this will print ['POPE\n', 'POPS\n', 'ROPE\n', 'POKE\n']

If I am not wrong, you want to carry out the slicing operation on the file contents. I think you should look into strip() method.

Body:
I have observed this unusual behaviour when I try to do a string slicing on the words in a file and the words in a list.Both the results are quite different.

For example I have a file 'words.txt' which contains the following content

POPE
POPS
ROPE
POKE
COPE
PAPE
NOPE
POLE

When I write the below piece of code, I expect to get a list of words with last letter omitted.

with open("words.txt", "r") as fo:
    for l in fo:
        print(l[:-1])

But instead I get this result below.No string slicing takes place and the words are similar as before.

POPE
POPS
ROPE
POKE
COPE
PAPE
NOPE
POLE

But if I write the below code, I get what I want

lis = ["POPE", "POPS", "ROPE", "POKE", "COPE", "PAPE", "NOPE", "POLE"]
for i in lis:
    print(i[:-1])

I am able to delete the last letter of each of the words as expected.

POP
POP
ROP
POK
COP
PAP
NOP
POL

So why do I see two different results for the same operation [: -1] ?

Body:
The line ends with \n in files where as you dont need line endings in lists.

Your actual file contents are as follows

POPE\n
POPS\n
ROPE\n
POKE\n
COPE\n
PAPE\n
NOPE\n
POLE\n

hence the print(l[:-1]) is actually trimming the line ending i.e. \n.

To verify this, declare an empty list before the loop, and add each line to that list and print it. You will find the that the lines contain the \n on every line

stuff = []

with open("words.txt", "r") as fo:
     for line in fo:
         stuff.append(line)

print stuff

this will print ['POPE\n', 'POPS\n', 'ROPE\n', 'POKE\n']

If I am not wrong, you want to carry out the slicing operation on the file contents. I think you should look into strip() method.


问:
Different result mappings for the same query but with variable column - MyBatis 3
I need to get different java Pojo result mapping from same query with different  column in sql "Where" condition.
Es.

```<code>@Select("Select field1,fiel2,...,fieldn From table where #{column}=1")
List<Pojo> getGenericDetails(@Param(column));
</code>```

Mybatis "discriminator" doesn't make the job.
Can anyone know how to do that?

Thanks in advance

答:
If want to get different java Pojo result mapping from the same query with different column in SQL "Where" condition, I will try the following:

```<code>@Select("Select field1,fiel2,...,fieldn From table where #{column}=1")
List<Map<String,Object>> getGenericDetails(@Param(column));
</code>```

as a result, the key in the map is the field1,fiel2,...,fieldn the value will be the result of field1,fiel2,...,fieldn.

Hope the above helps.

Body:
I need to get different java Pojo result mapping from same query with different  column in sql "Where" condition.
Es.

@Select("Select field1,fiel2,...,fieldn From table where #{column}=1")
List<Pojo> getGenericDetails(@Param(column));

Mybatis "discriminator" doesn't make the job.
Can anyone know how to do that?

Thanks in advance

Body:
If want to get different java Pojo result mapping from the same query with different column in SQL "Where" condition, I will try the following:

@Select("Select field1,fiel2,...,fieldn From table where #{column}=1")
List<Map<String,Object>> getGenericDetails(@Param(column));

as a result, the key in the map is the field1,fiel2,...,fieldn the value will be the result of field1,fiel2,...,fieldn.

Hope the above helps.


问:
flex box button element not getting 50% of width

div{
  display:flex;
  border:1px solid red;
}

div button{
  flex:0 0 1;
  border:1px solid gray;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
   <button>Button one</button>
   <button>Button two</button>
</div></code>```

答:
First, you have a typo "dispaly:flex;". :)

Second, just put flex-grow: 1; on the buttons.

Example code:

```<code>div{
  display:flex;
  border:1px solid red;
}

div button{
  flex-grow: 1;
  border:1px solid gray;
}
</code>```

Hope it helps.

Body:
div{
  display:flex;
  border:1px solid red;
}

div button{
  flex:0 0 1;
  border:1px solid gray;
}

   <button>Button one</button>
   <button>Button two</button>

Body:
First, you have a typo "dispaly:flex;". :)

Second, just put flex-grow: 1; on the buttons.

Example code:

div{
  display:flex;
  border:1px solid red;
}

div button{
  flex-grow: 1;
  border:1px solid gray;
}

Hope it helps.


问:
Set PDF to print with no scaling
I am generating a PDF (using fpdf) and I am wondering if there is a way to set the document's properties to to default to print with no scaling.

So when you select print from the print dialogue menu, scaling is set to none. I'm trying to determine if this is a user setting or something I can control in the creation of the PDF.

Thanks in advance.

答:
well i'm not sure if you mean somethink like this:
http://www.fpdf.org/en/doc/setdisplaymode.htm

or no "scaling" for images?

```<code>$im2 = pdf_open_image_file($dokument, 'jpeg', 'example.jpg');
pdf_place_image($dokument, $im2, 395, 655, 1.0); /* 1.0 = qualiti/scaling - 1.0 is original .../*
pdf_close_image($dokument, $im2);
</code>```

Title: Set PDF to print with no scaling

Body:
well i'm not sure if you mean somethink like this:
http://www.fpdf.org/en/doc/setdisplaymode.htm

or no "scaling" for images?

$im2 = pdf_open_image_file($dokument, 'jpeg', 'example.jpg');
pdf_place_image($dokument, $im2, 395, 655, 1.0); /* 1.0 = qualiti/scaling - 1.0 is original .../*
pdf_close_image($dokument, $im2);


问:
WebGL Cel Shading in image processing
What is the best way to implement a WebGL shader for a toon / cel shading / borderlands style / vectorized-like effect on an image?

I know the outlines can be generated using sobel or Frei-chen filters, but most resources  I have found about the colours have been for 3D models.

The desired result is something similar to this, though, the quality is not a priority, as this will be implemented on a video feed, if feasible.

http://www.instructables.com/id/Cel-Shading-Real-Life-Pictures/

答: I don't know of any simple GLSLish way of cartoonifying an image. AFAIK that requires way more image analysis than simple GLSL based post processing algorithms can do. The closest I can think of is just to lower the color resolution, maybe using a 3d tone mapping texture for more control and use nearest neighbor filtering instead of linear filter. Another might be to try to quantize by hsv or hsl (whereas posterization quantizes by rgb) also I think you can do the same using tone-mapping you just need to generate the ramp cube using HSL quantization instead of RGB quantization. You might also do a blur step or reduce the resolution before quantizing.</p>

Title: WebGL Cel Shading in image processing


问:
Python: define arguments of a function which include the arguments of the other function
Please let me know if there are duplicated ones (I believe there are) and I will remove the post. I am just not sure about the jargon for this question.

When writing a new function augmented_func which contains the other function already defined original_func, I am trying to avoid defining arguments that are already in original_func:

```<code>def original_func(a1, a2 ,a3):
    print(a1, a2, a3)

def augmented_func(b, a1, a2, a3):
    print(original_func(a1, a2, a3), b)
</code>```

How do I avoid writing a's when defining augmented_func, and make it simpler especially when the number of arguments for original_func is more than, say, three in the example?

答:
Use * notation for an arbitrary number of positional arguments:

```<code>def augmented_func(b, *args):
    print(original_func(*args), b)

augmented_func('b', 1, 2, 3)
</code>```

Or use keyword arguments with **:

```<code>def augmented_func(b, **kwargs):
    print(original_func(**kwargs), b)

augmented_func('b', a1=1, a2=2, a3=3)
</code>```

Body:
Please let me know if there are duplicated ones (I believe there are) and I will remove the post. I am just not sure about the jargon for this question.

When writing a new function augmented_func which contains the other function already defined original_func, I am trying to avoid defining arguments that are already in original_func:

def original_func(a1, a2 ,a3):
    print(a1, a2, a3)

def augmented_func(b, a1, a2, a3):
    print(original_func(a1, a2, a3), b)

How do I avoid writing a's when defining augmented_func, and make it simpler especially when the number of arguments for original_func is more than, say, three in the example?

Body:
Use * notation for an arbitrary number of positional arguments:

def augmented_func(b, *args):
    print(original_func(*args), b)

augmented_func('b', 1, 2, 3)

Or use keyword arguments with **:

def augmented_func(b, **kwargs):
    print(original_func(**kwargs), b)

augmented_func('b', a1=1, a2=2, a3=3)


问:
I have an article table that stores the user id, article id and the article view and i want to retrieve the id where they are greater than 50
I have an article table that stores the user id, article id, and the article views. I want to get all the users from this table and order them by their total article views (sum) > 50.

See the table below.

```<code>id | user_id | article_id | views
1      2          1          34
2      2          2          26
3      3          3          19
4      3          4          26
5      4          5          40
6      4          6          29
</code>```

I want to get something like this.

```<code>user_id | views
 2          60
 4          69
</code>```

Body:
I have an article table that stores the user id, article id, and the article views. I want to get all the users from this table and order them by their total article views (sum) > 50.

See the table below.

id | user_id | article_id | views
1      2          1          34
2      2          2          26
3      3          3          19
4      3          4          26
5      4          5          40
6      4          6          29

I want to get something like this.

user_id | views
 2          60
 4          69

Body:
You would probably want to use an aggragating function sum to total up the views and then use group by to give the desired response.

mysql> describe `blah`;
+------------+------------------+------+-----+---------+----------------+
| Field      | Type             | Null | Key | Default | Extra          |
+------------+------------------+------+-----+---------+----------------+
| id         | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| user_id    | int(11)          | YES  |     | NULL    |                |
| article_id | int(11)          | YES  |     | NULL    |                |
| views      | int(11)          | YES  |     | NULL    |                |
+------------+------------------+------+-----+---------+----------------+

mysql> select * from blah;
+----+---------+------------+-------+
| id | user_id | article_id | views |
+----+---------+------------+-------+
|  1 |       2 |          1 |    34 |
|  2 |       2 |          2 |    26 |
|  3 |       3 |          3 |    19 |
|  4 |       3 |          4 |    26 |
|  5 |       4 |          5 |    40 |
|  6 |       4 |          6 |    29 |
+----+---------+------------+-------+

/* use `SUM` and `GROUP BY` to give desired output */
mysql> select `user_id`, sum( `views` ) from `blah` group by `user_id`;
+---------+----------------+
| user_id | sum( `views` ) |
+---------+----------------+
|       2 |             60 |
|       3 |             45 |
|       4 |             69 |
+---------+----------------+

To limit the records to above 50

mysql> select `user_id`, sum( `views` ) as 'total' from `blah` group by `user_id`
       having `total` > 50;
+---------+-------+
| user_id | total |
+---------+-------+
|       2 |    60 |
|       4 |    69 |
+---------+-------+


问:
System.AccessViolationException : .NET Runtime Error c# worker thread
I have a picturebox in my windows form that renders a stream from my camera it uses a worker thread as you can see :

```<code> VideoFileReader reader = new VideoFileReader();
        Thread Proceso1;
        Proceso1 = new Thread(new ThreadStart(updateui));

        public void updateui()
        {
            try
            {
                reader.Open(RTSPAddress);
                while (true)
                {

                    var previousFrame = pictureRTSP.BackgroundImage;

                    Bitmap currentFrame = reader.ReadVideoFrame();

                        pictureRTSP.BackgroundImage = currentFrame;
                    if (previousFrame != null)
                        this.Invoke(new MethodInvoker(delegate () {
                            previousFrame.Dispose();
                        }));
                }
                reader.Close();

            }
            catch(ArgumentException ee)
            {
                //Text = ee.ToString();
            }
        }
</code>```

I dispose the previous frame because of memory usage .In my form i have a button that use pictureRTSP.BackgroundImage to detect the plate in the video.But when i clicked on button for several time i get this error :

```<code>Application: nMCR.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.AccessViolationException
   at <Module>.av_read_frame(libffmpeg.AVFormatContext*, libffmpeg.AVPacket*)
   at Accord.Video.FFMPEG.VideoFileReader.readVideoFrame(Int32, System.Drawing.Imaging.BitmapData)
   at Accord.Video.FFMPEG.VideoFileReader.ReadVideoFrame()
   at nMCR.form.MainForm.updateui()
   at System.Threading.ThreadHelper.ThreadStart_Context(System.Object)
   at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
   at System.Threading.ThreadHelper.ThreadStart()
</code>```

My button code:

BitmapImage bmImage = null;

```<code>        if (IsRTSP)
        {
            //FinalImage = new Bitmap(_snapshotHandler.TakeSnapshot().ToImage());

                FinalImage = new Bitmap(pictureRTSP.BackgroundImage);

            //Bitmap img = (Bitmap)Image.FromStream(FinalImage);
            bmImage = new BitmapImage();

            using (MemoryStream memStream2 = new MemoryStream())
            {
                FinalImage.Save(memStream2, System.Drawing.Imaging.ImageFormat.Png);
                memStream2.Position = 0;

                bmImage.BeginInit();
                bmImage.CacheOption = BitmapCacheOption.OnLoad;
                bmImage.UriSource = null;
                bmImage.StreamSource = memStream2;
                bmImage.EndInit();
            }
</code>```

答:
First you have a problem in opening the video reader, I think there is a problem in the Platform target of your solution, try making it 32 bit, some libraries that are using C++ native dlls inside may be 32 bit, and doesn't work with AnyCPU.

Secondly You are changing the background image of the picturebox from a thread other than the main thread :

try calling Invoke when changing picturebox image :

```<code>this.Invoke(new Action(()=>  pictureRTSP.BackgroundImage = currentFrame ));
</code>```

Body:
I have a picturebox in my windows form that renders a stream from my camera it uses a worker thread as you can see :

 VideoFileReader reader = new VideoFileReader();
        Thread Proceso1;
        Proceso1 = new Thread(new ThreadStart(updateui));

        public void updateui()
        {
            try
            {
                reader.Open(RTSPAddress);
                while (true)
                {

                    var previousFrame = pictureRTSP.BackgroundImage;

                    Bitmap currentFrame = reader.ReadVideoFrame();

                        pictureRTSP.BackgroundImage = currentFrame;
                    if (previousFrame != null)
                        this.Invoke(new MethodInvoker(delegate () {
                            previousFrame.Dispose();
                        }));
                }
                reader.Close();

            }
            catch(ArgumentException ee)
            {
                //Text = ee.ToString();
            }
        }

I dispose the previous frame because of memory usage .In my form i have a button that use pictureRTSP.BackgroundImage to detect the plate in the video.But when i clicked on button for several time i get this error :

Application: nMCR.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.AccessViolationException
   at <Module>.av_read_frame(libffmpeg.AVFormatContext*, libffmpeg.AVPacket*)
   at Accord.Video.FFMPEG.VideoFileReader.readVideoFrame(Int32, System.Drawing.Imaging.BitmapData)
   at Accord.Video.FFMPEG.VideoFileReader.ReadVideoFrame()
   at nMCR.form.MainForm.updateui()
   at System.Threading.ThreadHelper.ThreadStart_Context(System.Object)
   at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
   at System.Threading.ThreadHelper.ThreadStart()

My button code:

BitmapImage bmImage = null;

        if (IsRTSP)
        {
            //FinalImage = new Bitmap(_snapshotHandler.TakeSnapshot().ToImage());

                FinalImage = new Bitmap(pictureRTSP.BackgroundImage);

            //Bitmap img = (Bitmap)Image.FromStream(FinalImage);
            bmImage = new BitmapImage();

            using (MemoryStream memStream2 = new MemoryStream())
            {
                FinalImage.Save(memStream2, System.Drawing.Imaging.ImageFormat.Png);
                memStream2.Position = 0;

                bmImage.BeginInit();
                bmImage.CacheOption = BitmapCacheOption.OnLoad;
                bmImage.UriSource = null;
                bmImage.StreamSource = memStream2;
                bmImage.EndInit();
            }

Body:
First you have a problem in opening the video reader, I think there is a problem in the Platform target of your solution, try making it 32 bit, some libraries that are using C++ native dlls inside may be 32 bit, and doesn't work with AnyCPU.

Secondly You are changing the background image of the picturebox from a thread other than the main thread :

try calling Invoke when changing picturebox image :

this.Invoke(new Action(()=>  pictureRTSP.BackgroundImage = currentFrame ));


问:
Unexpected date calculation result
I have a method to view a calendar in Java that calculates the date by year, day of the week and week-number.

Now when I calculates the dates from 2017 everything works. But when I calculates the dates from January 2018 it takes the dates of year 2017.

My code looks like

```<code>import java.time.temporal.IsoFields;
import java.time.temporal.ChronoField;
import java.time.LocalDate;

// .....

LocalDate desiredDate = LocalDate.now()
                    .with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, 1)
                    .with(ChronoField.DAY_OF_WEEK, 1)
                    .withYear(2018);
</code>```

Which results in 2018-01-02 and it should be 2018-01-01. How is this possible?

答:
The order of invoked methods seems matter.

It you invoke them by descending time-granularity (year, week of week and day of week), you get the correct result :

```<code>long weekNumber = 1;
long dayOfWeek = 1;
int year = 2018;

LocalDate desiredDate = LocalDate.now()
    .withYear(year)
    .with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, weekNumber)
    .with(ChronoField.DAY_OF_WEEK, dayOfWeek );

System.out.println(desiredDate);
</code>```

2018-01-01

Note that the problem origin comes from :

```<code>.with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, weekNumber)
</code>```

that sets the week number (1 to 53) according to the current year.

The Java LocalDate API cannot adapt this value if then you change the year with  .withYear(year) as the week number information is not kept in the LocalDate instance.

You can indeed see in LocalDate implementation that LocalDate instances are defined by only 3 field : year, month and day.

```<code>public final class LocalDate
        implements Temporal, TemporalAdjuster, ChronoLocalDate, Serializable {
    ...
    private final int year;
    /**
     * The month-of-year.
     */
    private final short month;
    /**
     * The day-of-month.
     */
    private final short day;
    ...
}
</code>```

So to be precise, the important thing is that :

.withYear(year) be invoked before

```<code>.with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, weekNumber);
</code>```

Title: Unexpected date calculation result

Body:
I have a method to view a calendar in Java that calculates the date by year, day of the week and week-number.

Now when I calculates the dates from 2017 everything works. But when I calculates the dates from January 2018 it takes the dates of year 2017.

My code looks like

import java.time.temporal.IsoFields;
import java.time.temporal.ChronoField;
import java.time.LocalDate;

// .....

LocalDate desiredDate = LocalDate.now()
                    .with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, 1)
                    .with(ChronoField.DAY_OF_WEEK, 1)
                    .withYear(2018);

Which results in 2018-01-02 and it should be 2018-01-01. How is this possible?

Body:
The order of invoked methods seems matter.

It you invoke them by descending time-granularity (year, week of week and day of week), you get the correct result :

long weekNumber = 1;
long dayOfWeek = 1;
int year = 2018;

LocalDate desiredDate = LocalDate.now()
    .withYear(year)
    .with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, weekNumber)
    .with(ChronoField.DAY_OF_WEEK, dayOfWeek );

System.out.println(desiredDate);

2018-01-01

Note that the problem origin comes from :

.with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, weekNumber)

that sets the week number (1 to 53) according to the current year.

The Java LocalDate API cannot adapt this value if then you change the year with  .withYear(year) as the week number information is not kept in the LocalDate instance.

You can indeed see in LocalDate implementation that LocalDate instances are defined by only 3 field : year, month and day.

public final class LocalDate
        implements Temporal, TemporalAdjuster, ChronoLocalDate, Serializable {
    ...
    private final int year;
    /**
     * The month-of-year.
     */
    private final short month;
    /**
     * The day-of-month.
     */
    private final short day;
    ...
}

So to be precise, the important thing is that :

.withYear(year) be invoked before

.with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, weekNumber);


问:
How to find missing elements in a list?
I have a target list as

```<code>target_list = ['one', 'two', 'three','four', 'five']
</code>```

And a output list as

```<code>output_list = ['two','three','four', 'five']
</code>```

The target_list is fixed, while the output_list will change depending on the output of some function. I want to find which element will be missed in the target_list based on the observation from output_list.

As in the above example, the element one is missing. I also want to count the number of missing element. Could you help me to do it in python?

答:
```<code>target_list=['one', 'two', 'three','four', 'five']
output_list=['two','three','four', 'five']

l = [x for x in target_list if x not in output_list]
print("Number of items missing: " + len(l))

for x in target_list:
    if x in l:
        print(x + " is missing")
    else:
        print(x + " is not missing")
</code>```

Output

```<code>one is missing
two is not missing
three is not missing
four is not missing
five is not missing
</code>```

Title: How to find missing elements in a list?

Body:
I have a target list as

target_list = ['one', 'two', 'three','four', 'five']

And a output list as

output_list = ['two','three','four', 'five']

The target_list is fixed, while the output_list will change depending on the output of some function. I want to find which element will be missed in the target_list based on the observation from output_list.

As in the above example, the element one is missing. I also want to count the number of missing element. Could you help me to do it in python?

Body:
target_list=['one', 'two', 'three','four', 'five']
output_list=['two','three','four', 'five']

l = [x for x in target_list if x not in output_list]
print("Number of items missing: " + len(l))

for x in target_list:
    if x in l:
        print(x + " is missing")
    else:
        print(x + " is not missing")

Output

one is missing
two is not missing
three is not missing
four is not missing
five is not missing


问:
How to get data value of one input field from a list?
How can I get the value of the first input field from a list?

```<code><button id="hello">get data</button><br><br>
   <table> <td><label for="voucher_<?php echo $counter; ?>">D/N Number <?php echo $counter; ?></label><br>
    <input type="text" name="voucher_<?php echo $counter; ?>" class="input-field exsmall-input" value="<?php echo $voucher; ?>" placeholder="D/N Number" id="voucher_<?php echo $counter; ?>" required>
    </td></table>
</code>```

When I run the above code the number of rows varies depending on the counter.If I want to get the value of the first DN number ,what shall I do ?

```<code>$(document).ready(function(){
    $('#hello').click(function(){
          var name = $("#voucher").val();
        alert(name);
    });
});
</code>```

When I run this javascript I get undefined vales.

答:
The reason you are getting the error is because you have used wrong selector to target input element. input element do not have id voucher. You need to put the ID to make existing code work.

Or, You can use attribute starts with selector here from current HTML:

```<code> $('#hello').click(function(){
      var name = $("input[name^='voucher_']").val();
      alert(name);
});
</code>```

Body:
How can I get the value of the first input field from a list?

<button id="hello">get data</button>

 <label for="voucher_<?php echo $counter; ?>">D/N Number <?php echo $counter; ?>

    <input type="text" name="voucher_<?php echo $counter; ?>" class="input-field exsmall-input" value="<?php echo $voucher; ?>" placeholder="D/N Number" id="voucher_<?php echo $counter; ?>" required>

When I run the above code the number of rows varies depending on the counter.If I want to get the value of the first DN number ,what shall I do ?

$(document).ready(function(){
    $('#hello').click(function(){
          var name = $("#voucher").val();
        alert(name);
    });
});

When I run this javascript I get undefined vales.

Body:
The reason you are getting the error is because you have used wrong selector to target input element. input element do not have id voucher. You need to put the ID to make existing code work.

Or, You can use attribute starts with selector here from current HTML:

 $('#hello').click(function(){
      var name = $("input[name^='voucher_']").val();
      alert(name);
});


问:
Sorting Service Bus Queue Messages
i was wondering if there is a way to implement metadata or even multiple metadata to a service bus queue message to be used later on in an application to sort on but still maintaining FIFO in the queue.

So in short, what i want to do is:
Maintaining Fifo, that s First in First Out structure in the queue, but as the messages are coming and inserted to the queue from different Sources i want to be able to sort from which source the message came from with for example metadata.

I know this is possible with Topics where you can insert a property to the message, but also i am unsure if it is possible to implement multiple properties into the topic message.

Hope i made my self clear on what i am asking is possible.

答:
i was wondering if there is a way to implement metadata or even multiple metadata to a service bus queue message to be used later on in an application to sort on but still maintaining FIFO in the queue.

To maintain FIFO in the queue, you'd have to use Message Sessions. Without message sessions you would not be able to maintain FIFO in the queue itself. You would be able to set a custom property and use it in your application and sort out messages once they are received out of order, but you won't receive message in FIFO order as were asking in your original question.

If you drop the requirement of having an order preserved on the queue, the the answer @Mikhail has provided will be suitable for in-process sorting based on custom property(s). Just be aware that in-process sorting will be not a trivial task.

Title: Sorting Service Bus Queue Messages

ContentLicense: CC BY-SA 4.0


问:
Is there a cron-like implementation of ScheduledExecutorService in Java?
The ScheduledExecutorService in Java is pretty handy for repeating tasks with either fixed intervals or fixed delay. I was wondering if there is an something like the existing ScheduledExecutorService that lets you specify a time of day to schedule the task at, rather than an interval i.e. "I want this task to fire at 10am each day".

I know you can achieve this with Quartz, but I'd rather not use that library if possible (it's a great library but I'd rather not have the dependency for a few reasons).

答:
A bit more searching has turned up CronExecutorService in HA-JDBC. Interestingly, it has a dependency on Quartz for its CronExpression class, but that's it. That's not too bad.

Update: I've fixed the broken links to point at new versions, but I don't know if that is the only dependency any more

OwnerDisplayName: GaryF


问:
Detect wrong character encodings using python
I'm new to serious programming and I was trying to write a python program where I encountered strings in this form while reading from a file:

Îêåàí Åëüçè - Ìàéæå âåñíà

Ëÿïèñ Òðóáåöêîé - Ñâÿùåííûé Îãîíü

which is actually supposed to be in cyrillic (cp-1251), so this string is the victim of wrong encoding (I found it after long searching, with the help of this site:Universal Cyrillic Decoder)

Also using detect function in chardet module could find it

```<code>chardet.detect('Îêåàí Åëüçè - Ìàéæå âåñíà'.decode('utf-8').encode('windows-1252'))
</code>```

which gives:

{'confidence': 0.7679697235616183, 'encoding': 'windows-1251'}

after doing the following I'm able to get the intended string

```<code>string.decode('utf-8').encode('windows-1252').decode('windows-1251').encode('utf-8')
</code>```

which gives:

Океан Ельзи - Майже весна   and

Коррозия Металла - Война Миров

respectively for the aforementioned strings.

My question is: Is there anyway to detect such strings?
Here are some other strings which I haven't even found a way to correct:

Isao Sasaki - ¨¬¡Æ¨¬¡ÆAI¨¬¡Æ (A Different Farewell) (¡¾¢¬Cy¨ù¡¾ AU¡Æi)

Yoon K. Lee & Salzburg Kammerp - ³»¸¶À½

⁂晉䤠圠牥潂⁹䬨牡慭牴湯捩删浥硩䴠楡⥮

Ã�Ã�Ã³Ã´Ã¥ÃµÃ¡ Ã¼Ã´Ã© Ã¯ Ã£Ã�Ã¬Ã¯Ã² Ã�Ã´Ã¡Ã
Ã¬Ã©Ã¡ Ã¡Ã°Ã«Ã� ÃµÃ°Ã¼Ã¨Ã¥Ã³Ã§.

Much grateful for your replies.

答:
Well, that Cyrillic string isn't in cp-1251. As you seem to have found out, it has been encoded "twice". Most likely somebody took a binary string in cp1251 believed it was in utf8 and encoded it in cp1252, or something like that.

No automatic check could figure that out.

```<code>>>> print 'Îêåàí Åëüçè - Ìàéæå âåñíà'.decode('utf8').encode('latin1').decode('cp1251')
Океан Ельзи - Майже весна
</code>```

works. The latter look like UTF8, in that it supports both single and multibyte characters, but it's not UTF8. so again some sort of incorrect transformaton has been done. Going through all possible combinations until one work is probably the only possibility.

Body:
I'm new to serious programming and I was trying to write a python program where I encountered strings in this form while reading from a file:

Îêåàí Åëüçè - Ìàéæå âåñíà

Ëÿïèñ Òðóáåöêîé - Ñâÿùåííûé Îãîíü

which is actually supposed to be in cyrillic (cp-1251), so this string is the victim of wrong encoding (I found it after long searching, with the help of this site:Universal Cyrillic Decoder)

Also using detect function in chardet module could find it

chardet.detect('Îêåàí Åëüçè - Ìàéæå âåñíà'.decode('utf-8').encode('windows-1252'))

which gives:

{'confidence': 0.7679697235616183, 'encoding': 'windows-1251'}

after doing the following I'm able to get the intended string

string.decode('utf-8').encode('windows-1252').decode('windows-1251').encode('utf-8')

which gives:

Океан Ельзи - Майже весна   and

Коррозия Металла - Война Миров

respectively for the aforementioned strings.

My question is: Is there anyway to detect such strings?
Here are some other strings which I haven't even found a way to correct:

Isao Sasaki - ¨¬¡Æ¨¬¡ÆAI¨¬¡Æ (A Different Farewell) (¡¾¢¬Cy¨ù¡¾ AU¡Æi)

Yoon K. Lee & Salzburg Kammerp - ³»¸¶À½

⁂晉䤠圠牥潂⁹䬨牡慭牴湯捩删浥硩䴠楡⥮

Ã�Ã�Ã³Ã´Ã¥ÃµÃ¡ Ã¼Ã´Ã© Ã¯ Ã£Ã�Ã¬Ã¯Ã² Ã�Ã´Ã¡Ã
Ã¬Ã©Ã¡ Ã¡Ã°Ã«Ã� ÃµÃ°Ã¼Ã¨Ã¥Ã³Ã§.

Much grateful for your replies.

Body:
Well, that Cyrillic string isn't in cp-1251. As you seem to have found out, it has been encoded "twice". Most likely somebody took a binary string in cp1251 believed it was in utf8 and encoded it in cp1252, or something like that.

No automatic check could figure that out.

>>> print 'Îêåàí Åëüçè - Ìàéæå âåñíà'.decode('utf8').encode('latin1').decode('cp1251')
Океан Ельзи - Майже весна

works. The latter look like UTF8, in that it supports both single and multibyte characters, but it's not UTF8. so again some sort of incorrect transformaton has been done. Going through all possible combinations until one work is probably the only possibility.


问:
getting distinct count on join of two tables
I have 2 tables where primary key of first table is used as foreign key for second table. In first table primary key is having unique values but in second table as foreign key it is having duplicate values as well. Now i want count from both the tables at same time and using left join for that.
I have tried the following query :-

```<code> select distinct count(c.joined) as joined,
    count(t.JobReqID),t.Country from txrecruitment as t
    left join CandidateDetails as c on t.JobReqID=c.Jobreqid
    where t.status='open'
    group by t.Country
</code>```

The count value of count(t.JobReqID) is not giving count of distinct JobReqId which i want. The result of count is counting the multiple instances of 2nd table also which i want to remove.
What should be the right way to do this. Any help is welcomed!!

答:
Count using DISTINCT for the JobReqID like below :

```<code>select count(c.joined) as joined, count(distinct t.JobReqID), t.Country
from txrecruitment as t
left join CandidateDetails as c on t.JobReqID=c.Jobreqid
where t.status='open'
group by t.Country
</code>```

Body:
I have 2 tables where primary key of first table is used as foreign key for second table. In first table primary key is having unique values but in second table as foreign key it is having duplicate values as well. Now i want count from both the tables at same time and using left join for that.
I have tried the following query :-

 select distinct count(c.joined) as joined,
    count(t.JobReqID),t.Country from txrecruitment as t
    left join CandidateDetails as c on t.JobReqID=c.Jobreqid
    where t.status='open'
    group by t.Country

The count value of count(t.JobReqID) is not giving count of distinct JobReqId which i want. The result of count is counting the multiple instances of 2nd table also which i want to remove.
What should be the right way to do this. Any help is welcomed!!

Body:
Count using DISTINCT for the JobReqID like below :

select count(c.joined) as joined, count(distinct t.JobReqID), t.Country
from txrecruitment as t
left join CandidateDetails as c on t.JobReqID=c.Jobreqid
where t.status='open'
group by t.Country


答:
What you need is GROUP BY, SUM() and HAVING

You need GROUP BY to tell mysql that you are grouping entries of the same user together into one entry. You need SUM(views) to tell mysql that all the entries for views for the same user need to be added together. Finally, you need HAVING to tell mysql that there is a condition on the group-by-level that needs to be fulfilled in order to be considered a valid result.

```<code>SELECT user_id, SUM(views) AS views
FROM table GROUP
GROUP BY user_id
HAVING SUM(views) > 50
</code>```

Title: I have an article table that stores the user id, article id and the article view and i want to retrieve the id where they are greater than 50

Body:
What you need is GROUP BY, SUM() and HAVING

You need GROUP BY to tell mysql that you are grouping entries of the same user together into one entry. You need SUM(views) to tell mysql that all the entries for views for the same user need to be added together. Finally, you need HAVING to tell mysql that there is a condition on the group-by-level that needs to be fulfilled in order to be considered a valid result.

SELECT user_id, SUM(views) AS views
FROM table GROUP
GROUP BY user_id
HAVING SUM(views) > 50


问:
How to get Facebook Picture and Friends using Azure Mobile Services?
Is it possible to get Facebook Profile Picture and user friends using Azure Mobile services Claims or any other way?

On the azure backend as shown below,

User picture is missing there if it is not public profile. It looks
like public profile is only link to facebook profile

I set user_friends but when I request identites with the code below,
i see 9 claims (name, surname, fullname, gender, profile etc.) but I
dont get any friends information.

Code I am using is simply

```<code> identities = await App.Client.InvokeApiAsync<List<AppServiceIdentity>>("/.auth/me");
</code>```

According to the documentation, it should return what i set in the backend as dictionary of claims type and value.

I am able to achieve this using simple http request as below

```<code>  var requestUrl = $"https://graph.facebook.com/v2.11/me/friends?fields=id,picture.width(72).height(72),name&access_token=" + accessToken;
</code>```

But i want a general solution using azure backend if possible?

答:
AFAIK, your could only retrieve the basic profile (name, picture, email,etc.) from the current authenticated user. Per my understanding, if you hope your mobile app backend would handle the requests against the Graph API of facebook stead of retrieving the access token and send request in your mobile client, you could create a custom Web API and use the following code to get the access token and send request in your mobile backend:

// Get the credentials for the logged-in user.
var credentials =
    await this.User
    .GetAppServiceIdentityAsync<FacebookCredentials>(this.Request);

if (credentials.Provider == "Facebook")
{
    // Create a query string with the Facebook access token.
    var requestUrl = $"https://graph.facebook.com/v2.11/me/friends?fields=id,picture.width(72).height(72),name&access_token=" + credentials.AccessToken;

    // Create an HttpClient request.
    var client = new System.Net.Http.HttpClient();

    // Request the current user info from Facebook.
    var resp = await client.GetAsync(requestUrl);
    resp.EnsureSuccessStatusCode();

    // Do something here with the Facebook user information.
    var fbInfo = await resp.Content.ReadAsStringAsync();
}
```

For your mobile client, you could leverage InvokeApiAsync to call the related custom Web API provided by your mobile backend. More details, you could refer to How to: Work with authentication and Custom HTTP Endpoints.

Body:
Is it possible to get Facebook Profile Picture and user friends using Azure Mobile services Claims or any other way?

On the azure backend as shown below,

User picture is missing there if it is not public profile. It looks
like public profile is only link to facebook profile

I set user_friends but when I request identites with the code below,
i see 9 claims (name, surname, fullname, gender, profile etc.) but I
dont get any friends information.

Code I am using is simply

 identities = await App.Client.InvokeApiAsync<List<AppServiceIdentity>>("/.auth/me");

According to the documentation, it should return what i set in the backend as dictionary of claims type and value.

I am able to achieve this using simple http request as below

  var requestUrl = $"https://graph.facebook.com/v2.11/me/friends?fields=id,picture.width(72).height(72),name&access_token=" + accessToken;

But i want a general solution using azure backend if possible?

Body:
AFAIK, your could only retrieve the basic profile (name, picture, email,etc.) from the current authenticated user. Per my understanding, if you hope your mobile app backend would handle the requests against the Graph API of facebook stead of retrieving the access token and send request in your mobile client, you could create a custom Web API and use the following code to get the access token and send request in your mobile backend:

// Get the credentials for the logged-in user.
var credentials =
    await this.User
    .GetAppServiceIdentityAsync<FacebookCredentials>(this.Request);

if (credentials.Provider == "Facebook")
{
    // Create a query string with the Facebook access token.
    var requestUrl = $"https://graph.facebook.com/v2.11/me/friends?fields=id,picture.width(72).height(72),name&access_token=" + credentials.AccessToken;

    // Create an HttpClient request.
    var client = new System.Net.Http.HttpClient();

    // Request the current user info from Facebook.
    var resp = await client.GetAsync(requestUrl);
    resp.EnsureSuccessStatusCode();

    // Do something here with the Facebook user information.
    var fbInfo = await resp.Content.ReadAsStringAsync();
}

For your mobile client, you could leverage InvokeApiAsync to call the related custom Web API provided by your mobile backend. More details, you could refer to How to: Work with authentication and Custom HTTP Endpoints.


问:
How to divide page into two areas (div) with percentage ratio

#container {
  position: absolute;
  width: 100%;
  overflow-y: scroll;
  top: 30px;
  table {
    margin-bottom: 0;
  }
  th {
    //max-width: 150px;
    word-wrap: break-word;
  }
  td {
    max-width: 100000px;
  }
}

#down_container {}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <p>
    this div (with table) should has 70% screen and top = 30px;

  </p>
  <table border="1">
    <tr>
      <th>Short fs [dsadas]</th>
      <th>Short fs[dsadas]</th>
      <th>Short fs[dsadas]</th>
      <th>Short fs[dsadas]</th>
      <th>Short fs[dsadas]</th>
      <th>Short fs[dsadas]</th>
      <th>Short fs[dsadas]</th>
      <th>Short fs[dsadas]</th>
      <th>Short fs[dsadas]</th>
      <th>Short fs[dsadas]</th>
      <th>Short fs[dsadas]</th>
      <th>Short fs[dsadas]</th>
      <th>Very long long long long long</th>
    </tr>
    <tr>
      <td>1</td>
      <td>Longlonglong</td>
      <td>Long long long</td>
      <td>Short Header</td>
      <td>Long long long</td>
      <td>Long long long</td>
      <td>Short Header</td>
      <td>Long long long</td>
      <td>Long long long</td>
      <td>Short Header</td>
      <td>Long long long</td>
      <td>Long long long</td>
      <td>Long long long long long</td>
    </tr>
    <tr>
      <td>1</td>
      <td>Longlonglong</td>
      <td>Long long long</td>
      <td>Short Header</td>
      <td>Long long long</td>
      <td>Long long long</td>
      <td>Short Header</td>
      <td>Long long long</td>
      <td>Long long long</td>
      <td>Short Header</td>
      <td>Long long long</td>
      <td>Long long long</td>
      <td>Long long long long long</td>
    </tr>
    <tr>
      <tr>
        <td>1</td>
        <td>Longlojjjjjjjjjjjnglong</td>
        <td>Long long long</td>
        <td>Short Header</td>
        <td>Long long long</td>
        <td>Long long long</td>
        <td>Short Header</td>
        <td>Long long long</td>
        <td>Long long long</td>
        <td>Short Header</td>
        <td>Long long long</td>
        <td>Long long long</td>
        <td>Longlonglonglonglong</td>
      </tr>
      <tr>
        <td>1</td>
        <td>Longlojjjjjjjjjjjnglong</td>
        <td>Long long long</td>
        <td>Short Header</td>
        <td>Long long long</td>
        <td>Long long long</td>
        <td>Short Header</td>
        <td>Long long long</td>
        <td>Long long long</td>
        <td>Short Header</td>
        <td>Long long long</td>
        <td>Long long long</td>
        <td>Long long long long long</td>
      </tr>
      <tr>
        <td>1</td>
        <td>Longlonglong</td>
        <td>Long long long</td>
        <td>Short Header</td>
        <td>Long long long</td>
        <td>Long long long</td>
        <td>Short Header</td>
        <td>Long long long</td>
        <td>Long long long</td>
        <td>Short Header</td>
        <td>Long long long</td>
        <td>Long long long</td>
        <td>Long long long long long</td>
      </tr>
      <tr>
        <td>1</td>
        <td>Longlonglong</td>
        <td>Long long long</td>
        <td>Short Header</td>
        <td>Long long long</td>
        <td>Long long long</td>
        <td>Short Header</td>
        <td>Long long long</td>
        <td>Long long long</td>
        <td>Short Header</td>
        <td>Long long long</td>
        <td>Long long long</td>
        <td>Long long long long long</td>
      </tr>
      <tr>
        <td>1</td>
        <td>Longlonglong</td>
        <td>Long long long</td>
        <td>Short Header</td>
        <td>Long long long</td>
        <td>Long long long</td>
        <td>Short Header</td>
        <td>Long long long</td>
        <td>Long long long</td>
        <td>Short Header</td>
        <td>Long long long</td>
        <td>Long long long</td>
        <td>Long long long long long</td>
      </tr>
  </table>
  <div id="down_container">
    <p>
      this div should has own srollback (left-up) and (right-left) and should has 30% screen

    </p>

  </div>
</div></code>```

Can you help me to divide these div to two parts (upper and down) ? I would like to divide in ration equals to 70%:30%.

答:
.left{
  float:left;
  width:70%;
  overflow-x:auto;
  white-space: nowrap;
}
.right{
  float:left;
  width:30%;
  overflow-x:auto;
  white-space: nowrap;
}
.clearfix{
  clear:both;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="left">
  <table>
    <tr>
      <td>...</td>
      <td>...</td>
    </tr>
    <tr>
      <td>...</td>
      <td>...</td>
    </tr>
    <tr>
      <td>...</td>
      <td>...</td>
    </tr>
  </table>
</div>
<div class="right">
  <p>....</p>
</div>
<div class="clearfix"></div></code>```

Hope this will help you

Body:
#container {
  position: absolute;
  width: 100%;
  overflow-y: scroll;
  top: 30px;
  table {
    margin-bottom: 0;
  }
  th {
    //max-width: 150px;
    word-wrap: break-word;
  }
  td {
    max-width: 100000px;
  }
}

#down_container {}

    this div (with table) should has 70% screen and top = 30px;

      Short fs [dsadas]
      Short fs[dsadas]
      Short fs[dsadas]
      Short fs[dsadas]
      Short fs[dsadas]
      Short fs[dsadas]
      Short fs[dsadas]
      Short fs[dsadas]
      Short fs[dsadas]
      Short fs[dsadas]
      Short fs[dsadas]
      Short fs[dsadas]
      Very long long long long long

      1
      Longlonglong
      Long long long
      Short Header
      Long long long
      Long long long
      Short Header
      Long long long
      Long long long
      Short Header
      Long long long
      Long long long
      Long long long long long

      1
      Longlonglong
      Long long long
      Short Header
      Long long long
      Long long long
      Short Header
      Long long long
      Long long long
      Short Header
      Long long long
      Long long long
      Long long long long long

        1
        Longlojjjjjjjjjjjnglong
        Long long long
        Short Header
        Long long long
        Long long long
        Short Header
        Long long long
        Long long long
        Short Header
        Long long long
        Long long long
        Longlonglonglonglong

        1
        Longlojjjjjjjjjjjnglong
        Long long long
        Short Header
        Long long long
        Long long long
        Short Header
        Long long long
        Long long long
        Short Header
        Long long long
        Long long long
        Long long long long long

        1
        Longlonglong
        Long long long
        Short Header
        Long long long
        Long long long
        Short Header
        Long long long
        Long long long
        Short Header
        Long long long
        Long long long
        Long long long long long

        1
        Longlonglong
        Long long long
        Short Header
        Long long long
        Long long long
        Short Header
        Long long long
        Long long long
        Short Header
        Long long long
        Long long long
        Long long long long long

        1
        Longlonglong
        Long long long
        Short Header
        Long long long
        Long long long
        Short Header
        Long long long
        Long long long
        Short Header
        Long long long
        Long long long
        Long long long long long

      this div should has own srollback (left-up) and (right-left) and should has 30% screen

Can you help me to divide these div to two parts (upper and down) ? I would like to divide in ration equals to 70%:30%.

Body:
.left{
  float:left;
  width:70%;
  overflow-x:auto;
  white-space: nowrap;
}
.right{
  float:left;
  width:30%;
  overflow-x:auto;
  white-space: nowrap;
}
.clearfix{
  clear:both;
}

<div class="left">
  <table>
    <tr>
      <td>...</td>
      <td>...</td>
    </tr>
    <tr>
      <td>...</td>
      <td>...</td>
    </tr>
    <tr>
      <td>...</td>
      <td>...</td>
    </tr>
  </table>
</div>
<div class="right">
  <p>....</p>
</div>
<div class="clearfix"></div>

Hope this will help you


问:
JWebBrowser not working on the other computers
I am trying to use JWebBrowser in my project. Everything works fine in my computer. But when I try to use the executive jar on other computers, nothing happens when I double click. Below is the example code, works fine on my computer but not working on other computers. How can I solve this proble?

Is there a way to get error messages for the executive jars, like I got from the eclipse console ?

```<code>import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import chrriis.common.UIUtils;
import chrriis.dj.nativeswing.swtimpl.NativeInterface;
import chrriis.dj.nativeswing.swtimpl.components.JWebBrowser;

/**
 * @author Christopher Deckers
 */
public class Main extends JPanel {

  public Main() {
    super(new BorderLayout());
    JPanel webBrowserPanel = new JPanel(new BorderLayout());
    webBrowserPanel.setBorder(BorderFactory.createTitledBorder("Native Web Browser component"));
    final JWebBrowser webBrowser = new JWebBrowser();
    webBrowser.navigate("http://www.google.com");
    webBrowserPanel.add(webBrowser, BorderLayout.CENTER);
    add(webBrowserPanel, BorderLayout.CENTER);

    JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 4, 4));
    JCheckBox menuBarCheckBox = new JCheckBox("Menu Bar", webBrowser.isMenuBarVisible());
    menuBarCheckBox.addItemListener(new ItemListener() {
      public void itemStateChanged(ItemEvent e) {
        webBrowser.setMenuBarVisible(e.getStateChange() == ItemEvent.SELECTED);
      }
    });
    buttonPanel.add(menuBarCheckBox);
    add(buttonPanel, BorderLayout.SOUTH);
  }

  public static void main(String[] args) {

    UIUtils.setPreferredLookAndFeel();
    NativeInterface.open();
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        JFrame frame = new JFrame("DJ Native Swing Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new Main(), BorderLayout.CENTER);
        frame.setSize(800, 600);
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
      }
    });
    NativeInterface.runEventPump();
  }

}
</code>```

答:
Try to change the default JRE version to 32bit in eclipse.
Or add -d32 to VM arguments in the "Edit launch configuration properties".</p>

Body:
I am trying to use JWebBrowser in my project. Everything works fine in my computer. But when I try to use the executive jar on other computers, nothing happens when I double click. Below is the example code, works fine on my computer but not working on other computers. How can I solve this proble?

Is there a way to get error messages for the executive jars, like I got from the eclipse console ?

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import chrriis.common.UIUtils;
import chrriis.dj.nativeswing.swtimpl.NativeInterface;
import chrriis.dj.nativeswing.swtimpl.components.JWebBrowser;

/**
 * @author Christopher Deckers
 */
public class Main extends JPanel {

  public Main() {
    super(new BorderLayout());
    JPanel webBrowserPanel = new JPanel(new BorderLayout());
    webBrowserPanel.setBorder(BorderFactory.createTitledBorder("Native Web Browser component"));
    final JWebBrowser webBrowser = new JWebBrowser();
    webBrowser.navigate("http://www.google.com");
    webBrowserPanel.add(webBrowser, BorderLayout.CENTER);
    add(webBrowserPanel, BorderLayout.CENTER);

    JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 4, 4));
    JCheckBox menuBarCheckBox = new JCheckBox("Menu Bar", webBrowser.isMenuBarVisible());
    menuBarCheckBox.addItemListener(new ItemListener() {
      public void itemStateChanged(ItemEvent e) {
        webBrowser.setMenuBarVisible(e.getStateChange() == ItemEvent.SELECTED);
      }
    });
    buttonPanel.add(menuBarCheckBox);
    add(buttonPanel, BorderLayout.SOUTH);
  }

  public static void main(String[] args) {

    UIUtils.setPreferredLookAndFeel();
    NativeInterface.open();
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        JFrame frame = new JFrame("DJ Native Swing Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new Main(), BorderLayout.CENTER);
        frame.setSize(800, 600);
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
      }
    });
    NativeInterface.runEventPump();
  }

}


问:
Getting "type or namespace name could not be found" but everything seems ok?
I'm getting a:

type or namespace name could not be found

error for a C# WPF app in VS2010. This area of code was compiling fine, but suddenly I'm getting this error. I've tried removing the Project Reference and the using statement, shutting VS2010 and restarting, but still I have this issue.

Any ideas why this might be occurring, where it seems like I'm doing the right thing re Reference & using statement?

I also noted in VS2010 that intellisense for that namespace is working ok, so it seems like VS2010 has the project reference and is seeing the namespace on one hand, but during compile doesn't see it?

答:
My case was same as discussed here but nothing solved it until I've removed the System.Core reference from the references list (Everything worked fine without it)

hope it will help someone because this issue is quite frustrating


问:
How to restrict sqlite only to execute SELECT statements, and not INSERT, UPDATE
I have a reports page where you can enter the query manually for a report. How can I block any INSERT, UPDATE or DELETE statements, and only run SELECT?

```<code>using (var connection = new SQLiteConnection(connectionString))
            {
                var da = new SQLiteDataAdapter
                {
                    SelectCommand = new SQLiteCommand(query, connection)
                };
                try
                {
                    da.Fill(table);
                }
</code>```

I could check if the query string contains "INSERT", "UPDATE" or "DELETE", but I don't think it's a good practice.

答:
A) Use a read-only connection - I think that would be almost the best solution

B) Use more than one TextBox as Input (but this would become more a solution like checking the String for Insert etc.)

For Example

Select |____| From |_________| Where |_______|

Edit: to answer your comment just have a look at http://www.sqlite.org/c3ref/open.html especially the topic "SQLITE_OPEN_READONLY" - I haven't done anything with sqlite now, but I think that should do the trick...

Body:
I have a reports page where you can enter the query manually for a report. How can I block any INSERT, UPDATE or DELETE statements, and only run SELECT?

using (var connection = new SQLiteConnection(connectionString))
            {
                var da = new SQLiteDataAdapter
                {
                    SelectCommand = new SQLiteCommand(query, connection)
                };
                try
                {
                    da.Fill(table);
                }

I could check if the query string contains "INSERT", "UPDATE" or "DELETE", but I don't think it's a good practice.


问:
How To improve a sql query performance
I Have a view that return to me the customers and sum of their payment and its work but it take 8 second and when i remove the computed column part from the query it didn't take any time, and i tried to solve this by creating a non-clustered index on tables but its also 8 second,  so I'm asking about if there is any method to improve the performance,  although i have to use this technique.

my code is

```<code>SELECT ID
    ,NAME
    ,Total = (
        SELECT Sum(Value)
        FROM TRANSACTION
        WHERE Employee.ID = employee_ID
        )
FROM Employee;
</code>```

Thanks in advance

答:
Try an indexed view on the total

```<code>CREATE VIEW totalView
WITH SCHEMABINDING
AS
    select employee_ID, sum(value) as total
      from TRANSACTION
      group by employee_ID

CREATE UNIQUE CLUSTERED INDEX PK_totalView ON totalView
(
    employee_id,total
);
</code>```

Then join to that

```<code>select employee.id, employee.name, coalesce(t.total,0)
 from employee
 left outer join totalView t where t.employee_ID = employee.id
</code>```

Adjust the join type according to your need.

Title: How To improve a sql query performance

Body:
I Have a view that return to me the customers and sum of their payment and its work but it take 8 second and when i remove the computed column part from the query it didn't take any time, and i tried to solve this by creating a non-clustered index on tables but its also 8 second,  so I'm asking about if there is any method to improve the performance,  although i have to use this technique.

my code is

SELECT ID
    ,NAME
    ,Total = (
        SELECT Sum(Value)
        FROM TRANSACTION
        WHERE Employee.ID = employee_ID
        )
FROM Employee;

Thanks in advance

Body:
Try an indexed view on the total

CREATE VIEW totalView
WITH SCHEMABINDING
AS
    select employee_ID, sum(value) as total
      from TRANSACTION
      group by employee_ID

CREATE UNIQUE CLUSTERED INDEX PK_totalView ON totalView
(
    employee_id,total
);

Then join to that

select employee.id, employee.name, coalesce(t.total,0)
 from employee
 left outer join totalView t where t.employee_ID = employee.id

Adjust the join type according to your need.


问:
What OAuth flow to use for IONIC2 app and Identity Server4
I've been researching oauth 2 and IdentityServer4 for the past day and a half and can say that I think the preferred method to use in this scenario would be hybrid flow. It seems that in the past it was implicit due to the fact that a mobile client can't protect a secret. Then it appeared to have changed to authorization flow without a secret... (no idea how that would work)

My understanding of IONIC and other cross platform frameworks is that they work by embedding the application inside of a web view and hence this is where my confusion sets in. Technically speaking, hybrid flow is recommended for native apps and IONIC is not something that allows you to build native apps.

If the recommended flow for native apps is hybrid, but you are using IONIC and hence not building a native app, then does the hybrid flow still apply?

Again, my guess is that it does, because since this is going to be an app running locally on an end user's machine then the secret is NOT safe there.

This also confuses me a bit more because there are other flows, for example: credential based flows where one must supply a username and password. This confuses me because this is generally how one would want users to authenticate in a mobile app. Hybrid flow seems to be a flow that does not require a username and password..

I am coming from an MVC4 owin background.

My basic architecture plan is like this

Auth server

API

IONIC app

答:
Ionic apps for mobile should be treated as native apps and the recommended flow by OIDC standards for mobile is to use Hybrid+PKCE.

Have a look here

If you want an idea of how to setup the Client for ionic on IdentityServer4 check the sample here. Don't mind xamarin just focus on the IdentityServer part.


问:
Firebase transactions in NodeJS always running 3 times?
Whenever I define a Firebase transaction in NodeJS I notice it always runs three times - the first two times with null data, then finally a third time with actually data. Is this normal/intended?

For example this code:

```<code>firebaseOOO.child('ref').transaction(function(data) {
    console.log(data);
    return data;
});
</code>```

outputs the following:

```<code>null
null
i1: { a1: true }
</code>```

I would have expected that it only print the last item.

To answer a question in the comments, here is the same with a callback:

```<code>firebaseOOO.child('ref').transaction(function(data) {
    console.log(data);
    return data;
}, function(error, committed, snapshot) {
    if (error)
        console.log('failed');
    else if (!committed)
        console.log('aborted');
    else
        console.log('committed');
    console.log('fin');
});
</code>```

Which yields the following output:

```<code>null
null
i1: { a1: true }
committed
fin
</code>```

I had read the details of how transactions work before posting the question, so I had tried setting applyLocally to false like this:

```<code>firebaseOOO.child('ref').transaction(function(data) {
    console.log('hit');
    return data;
}, function(){}, false);
</code>```

But it still hits 3 times (just double-checked) so I thought it was something different. Getting the 'value' before transacting does "work" as expected, in that it only hits once, and that's regardless of what applyLocally is set to, so I'm not sure what applyLocally does? This is what I mean by getting the value before transacting:

```<code>firebaseOOO.child('ref').once('value', function(data) {
    console.log('1');
    firebaseOOO.child('ref').transaction(function(data) {
        console.log('2');
        return data;
    });
});
</code>```

Outputs:

```<code>1
2
</code>```

@Michael: How can one make use of this behavior? Transactions are primarily for having data use itself to modify itself - the prototypical increment++ scenario. So if I need to add 1 to the existing value of 10, and continue working with the result of 11, the first two times the function hits I will have an erroneous result of 1 that I need to handle, and finally the correct result of 11 on the third hit. How can I make use of those two initial 1's? Another scenario (and maybe I shouldn't be using transactions for this, but if it worked like I expected it makes for cleaner code) is to insert a value if it does not yet exist. If transactions only hit once, a null value would mean the value does not exist, and so you could, for example, init the counter to 1 in that case, otherwise add 1 to whatever the value is. With the noisy nulls, this is not possible.

It seems the takeaway from all this is to simply use the 'once' pattern more often than not?

ONCE TRANSACTION PATTERN:

```<code>firebaseOOO.child('ref').once('value', function(data) {
    console.log('1');
    firebaseOOO.child('ref').transaction(function(data) {
        console.log('2');
        return data;
    });
});
</code>```

答:
transaction() will be called multiple times and must be able to handle  null data. Even if there is existing data in your database it may not be locally cached when the transaction function is run.</p>

```<code>firebaseOOO.child('ref').transaction(function(data) {

if(data!=null){
    console.log(data);
    return data;
}
else {
   return data;
 }
}, function(error, committed, snapshot) {
    if (error)
        console.log('failed');
    else if (!committed)
        console.log('aborted');
    else
        console.log('committed');
    console.log('fin');
});
</code>```

Body:
Whenever I define a Firebase transaction in NodeJS I notice it always runs three times - the first two times with null data, then finally a third time with actually data. Is this normal/intended?

For example this code:

firebaseOOO.child('ref').transaction(function(data) {
    console.log(data);
    return data;
});

outputs the following:

null
null
i1: { a1: true }

I would have expected that it only print the last item.

To answer a question in the comments, here is the same with a callback:

firebaseOOO.child('ref').transaction(function(data) {
    console.log(data);
    return data;
}, function(error, committed, snapshot) {
    if (error)
        console.log('failed');
    else if (!committed)
        console.log('aborted');
    else
        console.log('committed');
    console.log('fin');
});

Which yields the following output:

null
null
i1: { a1: true }
committed
fin

I had read the details of how transactions work before posting the question, so I had tried setting applyLocally to false like this:

firebaseOOO.child('ref').transaction(function(data) {
    console.log('hit');
    return data;
}, function(){}, false);

But it still hits 3 times (just double-checked) so I thought it was something different. Getting the 'value' before transacting does "work" as expected, in that it only hits once, and that's regardless of what applyLocally is set to, so I'm not sure what applyLocally does? This is what I mean by getting the value before transacting:

firebaseOOO.child('ref').once('value', function(data) {
    console.log('1');
    firebaseOOO.child('ref').transaction(function(data) {
        console.log('2');
        return data;
    });
});

Outputs:

1
2

@Michael: How can one make use of this behavior? Transactions are primarily for having data use itself to modify itself - the prototypical increment++ scenario. So if I need to add 1 to the existing value of 10, and continue working with the result of 11, the first two times the function hits I will have an erroneous result of 1 that I need to handle, and finally the correct result of 11 on the third hit. How can I make use of those two initial 1's? Another scenario (and maybe I shouldn't be using transactions for this, but if it worked like I expected it makes for cleaner code) is to insert a value if it does not yet exist. If transactions only hit once, a null value would mean the value does not exist, and so you could, for example, init the counter to 1 in that case, otherwise add 1 to whatever the value is. With the noisy nulls, this is not possible.

It seems the takeaway from all this is to simply use the 'once' pattern more often than not?

ONCE TRANSACTION PATTERN:

firebaseOOO.child('ref').once('value', function(data) {
    console.log('1');
    firebaseOOO.child('ref').transaction(function(data) {
        console.log('2');
        return data;
    });
});

Body:
transaction() will be called multiple times and must be able to handle  null data. Even if there is existing data in your database it may not be locally cached when the transaction function is run.

firebaseOOO.child('ref').transaction(function(data) {

if(data!=null){
    console.log(data);
    return data;
}
else {
   return data;
 }
}, function(error, committed, snapshot) {
    if (error)
        console.log('failed');
    else if (!committed)
        console.log('aborted');
    else
        console.log('committed');
    console.log('fin');
});