问:
How can I get selector from jQuery object
```<code>$("*").click(function(){
    $(this); // how can I get selector from $(this) ?
});
</code>```

Is there an easy way to get selector from $(this)? There is a way to select an element by its selector, but what about getting the selector from element?

答:
Thank you p1nox!

My problem was to put focus back on an ajax call that was modifying part of the form.

```<code>$.ajax({  url : "ajax_invite_load.php",
        async : true,
         type : 'POST',
         data : ...
     dataType : 'html',
      success : function(html, statut) {
                    var focus = $(document.activeElement).getSelector();
                    $td_left.html(html);
                    $(focus).focus();
                }
});
</code>```

I just needed to encapsulate your function in a jQuery plugin:

```<code>    !(function ($, undefined) {

    $.fn.getSelector = function () {
      if (!this || !this.length) {
        return ;
      }

      function _getChildSelector(index) {
        if (typeof index === 'undefined') {
          return '';
        }

        index = index + 1;
        return ':nth-child(' + index + ')';
      }

      function _getIdAndClassNames($el) {
        var selector = '';

        // attach id if exists
        var elId = $el.attr('id');
        if(elId){
          selector += '#' + elId;
        }

        // attach class names if exists
        var classNames = $el.attr('class');
        if(classNames){
          selector += '.' + classNames.replace(/^\s+|\s+$/g, '').replace(/\s/gi, '.');
        }

        return selector;
      }

      // get all parents siblings index and element's tag name,
      // except html and body elements
      var selector = this.parents(':not(html,body)')
        .map(function() {
          var parentIndex = $(this).index();

          return this.tagName + _getChildSelector(parentIndex);
        })
        .get()
        .reverse()
        .join(' ');

      if (selector) {
        // get node name from the element itself
        selector += ' ' + this[0].nodeName +
          // get child selector from element ifself
          _getChildSelector(this.index());
      }

      selector += _getIdAndClassNames(this);

      return selector;
    }

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

Body:
$("*").click(function(){
    $(this); // how can I get selector from $(this) ?
});

Is there an easy way to get selector from $(this)? There is a way to select an element by its selector, but what about getting the selector from element?

Body:
Thank you p1nox!

My problem was to put focus back on an ajax call that was modifying part of the form.

$.ajax({  url : "ajax_invite_load.php",
        async : true,
         type : 'POST',
         data : ...
     dataType : 'html',
      success : function(html, statut) {
                    var focus = $(document.activeElement).getSelector();
                    $td_left.html(html);
                    $(focus).focus();
                }
});

I just needed to encapsulate your function in a jQuery plugin:

    !(function ($, undefined) {

    $.fn.getSelector = function () {
      if (!this || !this.length) {
        return ;
      }

      function _getChildSelector(index) {
        if (typeof index === 'undefined') {
          return '';
        }

        index = index + 1;
        return ':nth-child(' + index + ')';
      }

      function _getIdAndClassNames($el) {
        var selector = '';

        // attach id if exists
        var elId = $el.attr('id');
        if(elId){
          selector += '#' + elId;
        }

        // attach class names if exists
        var classNames = $el.attr('class');
        if(classNames){
          selector += '.' + classNames.replace(/^\s+|\s+$/g, '').replace(/\s/gi, '.');
        }

        return selector;
      }

      // get all parents siblings index and element's tag name,
      // except html and body elements
      var selector = this.parents(':not(html,body)')
        .map(function() {
          var parentIndex = $(this).index();

          return this.tagName + _getChildSelector(parentIndex);
        })
        .get()
        .reverse()
        .join(' ');

      if (selector) {
        // get node name from the element itself
        selector += ' ' + this[0].nodeName +
          // get child selector from element ifself
          _getChildSelector(this.index());
      }

      selector += _getIdAndClassNames(this);

      return selector;
    }

})(window.jQuery);


来源: stackexchange

问:
How to filter a search query on multiple fields?
I have a list of studies. And I want to search over them with a typeahead function in a front page.

For that I use Hibernate Search with Spring Boot (2.1.5).
I indexed my STUDY table and some fields are marked with @Field attribute to be indexed.

The search works well.

But now I want to add a filter to use the same typeahead function but searching of a subset of my studies.

For that I created a filter like the Hibernate Search documentation but I didn't found a way to filter on two field with a OR between them.

My actual filter but filtering only on one field (avisDefinitifCet):

```<code>/**
 * etudeFilter
 */
public class EtudeFilterFactory {
    private String clasCet1ErPassage;
    private String avisDefinitifCet;

    public void setClasCet1ErPassage(String clasCet1ErPassage) {
        this.clasCet1ErPassage = clasCet1ErPassage;
    }

    public void setAvisDefinitifCet(String avisDefinitifCet) {
        this.avisDefinitifCet = avisDefinitifCet;
    }

    @Factory
    public Query getFilter() {
        System.out.println("Filter avisDefinitifCet : " + this.avisDefinitifCet.toLowerCase());
        return new TermQuery(new Term("avisDefinitifCet", this.avisDefinitifCet.toLowerCase()));
    }
}
</code>```

How can I filter with a second field in my case clasCet1ErPassage?

At this end make a search on the standard search query and applying the filter like this

```<code>SELECT *
FROM STUDY
WHERE
A=t OR B=t OR C=t -- Normal search
AND (avisDefinitifCet='acceptation' OR clasCet1ErPassage='acceptation') -- Filter on two fields
</code>```

My search function:

```<code>public List<Etude> search(String text, Map<String, String> allParams) {
        text = stripAccents(text);
        // get the full text entity manager
        FullTextEntityManager fullTextEntityManager = getFullTextEntityManager(entityManager);

        // create the query using Hibernate Search query DSL
        QueryBuilder queryBuilder = fullTextEntityManager
                .getSearchFactory()
                .buildQueryBuilder()
                .forEntity(Etude.class)
                .get();

        // Simple Query String queries
        Query query = queryBuilder
                .simpleQueryString()
                .onFields("n0Cet")
                .andField("anneeCet")
                .andField("noDansAnneeCet")
                .andField("sigleEtude")
                .andField("titreEtude")
                .andField("traitement1")
                .andField("traitement2")
                .andField("traitement3")
                .andField("traitement4")
                .andField("traitement5")
                .andField("demandeurIgr.nomInvestigateurIgr")
                .andField("investigateurHorsIgr.nomInvestigateur")
                .andField("investigateurIgr.nomInvestigateurIgr")
                .andField("promoteur.nomPromoteur")
                .matching(text)
                .createQuery();

        // wrap Lucene query in an Hibernate Query object
        FullTextQuery fullTextQuery = fullTextEntityManager
                .createFullTextQuery(query, Etude.class)
                .setMaxResults(101);

        // Here allParams contains
        // avisDefinitifCet => 'acceptation',
        // clasCet1ErPassage => 'acceptation'
        allParams.forEach((key, value) -> {
            fullTextQuery.enableFullTextFilter("etudeFilter").setParameter(key, value);
        });

        return (List<Etude>) fullTextQuery.getResultList();
    }
</code>```

Am I thinking in the right way to implement it or I'm going wrong?

答:
EDIT: Appparently you're using full-text filters, where you indeed have to use Lucene APIs directly.

In this case, just use a boolean junction with "should" clauses. When there's only "should" clauses in a boolean junction, at least one of them has to match.

    @Factory
    public Query getFilter() {
        String valueToMatch = this.avisDefinitifCet.toLowerCase();
        return new BooleanQuery.Builder()
            .add(new TermQuery(new Term("avisDefinitifCet", valueToMatch)), Occur.SHOULD)
            .add(new TermQuery(new Term("clasCet1ErPassage", valueToMatch)), Occur.SHOULD)
            .build();
    }
```

<hr>

<p>Previous answer:</p>

<p>If you're new to Lucene, you really should give the Hibernate Search DSL a try.</p>

<p>In your case, you'll want a keyword query that targets two fields:</p>

```EntityManager em = ...;

FullTextEntityManager fullTextEntityManager =
    org.hibernate.search.jpa.Search.getFullTextEntityManager(em);

QueryBuilder queryBuilder = fullTextEntityManager.getSearchFactory()
    .buildQueryBuilder().forEntity( Etude.class ).get();

Query luceneQuery = queryBuilder.keyword()
    .onField("avisDefinitifCet").andField("clasCet1ErPassage")
    .matching("acceptation")
    .createQuery();
```

Note that, despite the method being called andField, it's actually an "OR": the query will match if any field matches.

For more advanced combination of queries, have a look at boolean junctions.

ContentLicense: CC BY-SA 4.0

Body:
I have a list of studies. And I want to search over them with a typeahead function in a front page.

For that I use Hibernate Search with Spring Boot (2.1.5).
I indexed my STUDY table and some fields are marked with @Field attribute to be indexed.

The search works well.

But now I want to add a filter to use the same typeahead function but searching of a subset of my studies.

For that I created a filter like the Hibernate Search documentation but I didn't found a way to filter on two field with a OR between them.

My actual filter but filtering only on one field (avisDefinitifCet):

/**
 * etudeFilter
 */
public class EtudeFilterFactory {
    private String clasCet1ErPassage;
    private String avisDefinitifCet;

    public void setClasCet1ErPassage(String clasCet1ErPassage) {
        this.clasCet1ErPassage = clasCet1ErPassage;
    }

    public void setAvisDefinitifCet(String avisDefinitifCet) {
        this.avisDefinitifCet = avisDefinitifCet;
    }

    @Factory
    public Query getFilter() {
        System.out.println("Filter avisDefinitifCet : " + this.avisDefinitifCet.toLowerCase());
        return new TermQuery(new Term("avisDefinitifCet", this.avisDefinitifCet.toLowerCase()));
    }
}

How can I filter with a second field in my case clasCet1ErPassage?

At this end make a search on the standard search query and applying the filter like this

SELECT *
FROM STUDY
WHERE
A=t OR B=t OR C=t -- Normal search
AND (avisDefinitifCet='acceptation' OR clasCet1ErPassage='acceptation') -- Filter on two fields

My search function:

public List<Etude> search(String text, Map<String, String> allParams) {
        text = stripAccents(text);
        // get the full text entity manager
        FullTextEntityManager fullTextEntityManager = getFullTextEntityManager(entityManager);

        // create the query using Hibernate Search query DSL
        QueryBuilder queryBuilder = fullTextEntityManager
                .getSearchFactory()
                .buildQueryBuilder()
                .forEntity(Etude.class)
                .get();

        // Simple Query String queries
        Query query = queryBuilder
                .simpleQueryString()
                .onFields("n0Cet")
                .andField("anneeCet")
                .andField("noDansAnneeCet")
                .andField("sigleEtude")
                .andField("titreEtude")
                .andField("traitement1")
                .andField("traitement2")
                .andField("traitement3")
                .andField("traitement4")
                .andField("traitement5")
                .andField("demandeurIgr.nomInvestigateurIgr")
                .andField("investigateurHorsIgr.nomInvestigateur")
                .andField("investigateurIgr.nomInvestigateurIgr")
                .andField("promoteur.nomPromoteur")
                .matching(text)
                .createQuery();

        // wrap Lucene query in an Hibernate Query object
        FullTextQuery fullTextQuery = fullTextEntityManager
                .createFullTextQuery(query, Etude.class)
                .setMaxResults(101);

        // Here allParams contains
        // avisDefinitifCet => 'acceptation',
        // clasCet1ErPassage => 'acceptation'
        allParams.forEach((key, value) -> {
            fullTextQuery.enableFullTextFilter("etudeFilter").setParameter(key, value);
        });

        return (List<Etude>) fullTextQuery.getResultList();
    }

Am I thinking in the right way to implement it or I'm going wrong?

Body:
EDIT: Appparently you're using full-text filters, where you indeed have to use Lucene APIs directly.

In this case, just use a boolean junction with "should" clauses. When there's only "should" clauses in a boolean junction, at least one of them has to match.

    @Factory
    public Query getFilter() {
        String valueToMatch = this.avisDefinitifCet.toLowerCase();
        return new BooleanQuery.Builder()
            .add(new TermQuery(new Term("avisDefinitifCet", valueToMatch)), Occur.SHOULD)
            .add(new TermQuery(new Term("clasCet1ErPassage", valueToMatch)), Occur.SHOULD)
            .build();
    }

Previous answer:

If you're new to Lucene, you really should give the Hibernate Search DSL a try.

In your case, you'll want a keyword query that targets two fields:

EntityManager em = ...;

FullTextEntityManager fullTextEntityManager =
    org.hibernate.search.jpa.Search.getFullTextEntityManager(em);

QueryBuilder queryBuilder = fullTextEntityManager.getSearchFactory()
    .buildQueryBuilder().forEntity( Etude.class ).get();

Query luceneQuery = queryBuilder.keyword()
    .onField("avisDefinitifCet").andField("clasCet1ErPassage")
    .matching("acceptation")
    .createQuery();

Note that, despite the method being called andField, it's actually an "OR": the query will match if any field matches.

For more advanced combination of queries, have a look at boolean junctions.


问:
Align image in center and middle within div
I have following div

```<code><div id="over" style="position:absolute; width:100%; height:100%>
 <img src="img.png">
</div>
</code>```

How to align the image so as to be located in the middle and center of div ?

答:
The marked answer for this will not vertically align the image. A suitable solution for modern browsers is flexbox. A flex container can be configured to align its items both horizontally and vertically.</p>

```<code><div id="over" style="position:absolute; width:100%; height:100%; display: flex; align-items: center; justify-content: center;">
    <img src="img.png">
</div>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have following div

How to align the image so as to be located in the middle and center of div ?

Body:
The marked answer for this will not vertically align the image. A suitable solution for modern browsers is flexbox. A flex container can be configured to align its items both horizontally and vertically.

<div id="over" style="position:absolute; width:100%; height:100%; display: flex; align-items: center; justify-content: center;">
    <img src="img.png">
</div>


问:
XMLReader() in PHP - parsing attributes in multiple elements with the same name
Im using XMLReader to parse XML but i've come across a situation where two elements have the same name and not sure how to deal with it

the elements in question are

```<code><field name="latitude" value="51.4070767"/>
<field name="longitude" value="-0.6366062"/>
</code>```

I want to pull in the two value fields into seperate strings.

I can pull in the first one using this method

```<code>$bp = $product->fields->field["value"]; ###gives 51.4070767
</code>```

but how do i access the second? (-0.6366062)

Cheers

答:
You need to make field an array, so that you can do:

```<code>$product->fields->field[0]["value"];
$product->fields->field[1]["value"];
</code>```

Body:
Im using XMLReader to parse XML but i've come across a situation where two elements have the same name and not sure how to deal with it

the elements in question are

<field name="latitude" value="51.4070767"/>
<field name="longitude" value="-0.6366062"/>

I want to pull in the two value fields into seperate strings.

I can pull in the first one using this method

$bp = $product->fields->field["value"]; ###gives 51.4070767

but how do i access the second? (-0.6366062)

Cheers

Body:
You need to make field an array, so that you can do:

$product->fields->field[0]["value"];
$product->fields->field[1]["value"];


问:
Optimising code with a lot of "if" statements
I want to optimise this code to reduce the number of if statements. Maybe it'd be better to use a lot of classes, and let the classes handle each required action?

It could be fabric pattern? Or is it OK to use 30+ similar if statements?

I've tried to make a Dictionary with string and object class. But I couldn't get it to work (or my skills are not good enough)

```<code>if (node[DATA_CONNECTION_ELEMENT] != null)
{
    return new DataConnectionPropertyDataBinding(form, node[DATA_CONNECTION_ELEMENT], inputableEntity);
}
else if (node[FORM_PARAMETER_ELEMENT] != null)
{
    return new FormParameterDataBinding(form, node[FORM_PARAMETER_ELEMENT], inputableEntity);
}

// + 30 more else ifs

else if (node[COMMAND_ELEMENT] != null)
{
    return new CommandResultDataBinding(form, node[COMMAND_ELEMENT], inputableEntity);
}
else if (node[CONDITION_ELEMENT] != null)
{
    return new ConditionDataBinding(form, node[CONDITION_ELEMENT], inputableEntity);
}
else if (node[CLIPBOARD_ELEMENT] != null)
{
    return new ClipboardDataBinding(form, node[CLIPBOARD_ELEMENT], inputableEntity);
}
else
{
    return new ConstantDataBinding(form, node);
}
</code>```

Want to make it look something like

```<code>foreach (var item in allThatShareSomeInterface)
{
    if (item.CanHandle(node.Atributes[0]))
    {
        return item.neededObject();
    }
}
</code>```

Here is the answer. How it really works.

```<code>        Dictionary<string, Type> allObjects = new Dictionary<string, Type>();
        allObjects.Add(CONDITION_ELEMENT, typeof(ConditionDataBinding));
        allObjects.Add(DATA_TYPE_FORMAT_ELEMENT, typeof(DataTypeFormatDataBinding));
        allObjects.Add(DATA_TYPE_CONVERT_ELEMENT, typeof(DataTypeConvertDataBinding));
        allObjects.Add(FORM_PARAMETER_ELEMENT, typeof(FormParameterDataBinding));
        allObjects.Add(FORM_ELEMENT, typeof(FormPropertyDataBinding));
        allObjects.Add(STRING_ELEMENT, typeof(StringFormatDataBinding));
        allObjects.Add(FORMULA_ELEMENT, typeof(FormulaDataBinding));
        allObjects.Add(COMMAND_ELEMENT, typeof(CommandResultDataBinding));
        // + many

        foreach (var pair in allObjects)
        {
            if (node[pair.Key] != null)
            {
                ConstructorInfo ctor = pair.Value.GetConstructor(new[] { typeof(IWorkflowForm), typeof(XmlNode), typeof(IInputable) });
                return ctor.Invoke(new object[] { form, node[pair.Key], inputableEntity });
            }
        }
</code>```

答:
If you know what you are doing, and you indeed need that many binding classes, one way to solve that is custom attributes + reflection + runtime code generation. Here’s an example.</p>

```<code>// Enum for element type. The order matters, it's the order in which input dictionary is tested.
enum eElement
{
    DataConnection,
    FormParameter,
}
// Custom attribute to mark bindings classes with.
class DataBindingAttribute : Attribute
{
    public eElement element;
    public DataBindingAttribute( eElement e ) { element = e; }
}

// Base class for bindings
abstract class BindingBase { }

// Couple test binding classes
[DataBinding( eElement.DataConnection )]
class DataConnectionPropertyDataBinding: BindingBase
{
    public DataConnectionPropertyDataBinding( object data ) { }
}
[DataBinding( eElement.FormParameter )]
class FormParameterDataBinding: BindingBase
{
    public readonly object data;
    public FormParameterDataBinding( object data ) { this.data = data; }
}

// This static class does the magic.
static class BindingsFactory
{
    // Key = eElement from custom attribute, value = function that constructs the binding. This example uses the constructor with single object argument.
    // It's a good idea to use strong types for arguments instead.
    static readonly SortedDictionary<eElement, Func<object, BindingBase>> dictTypes = new SortedDictionary<eElement, Func<object, BindingBase>>();

    static BindingsFactory()
    {
        // Constructor argument types, just a single `object` in this example.
        Type[] constructorArgumentTypes = new Type[ 1 ]
        {
            typeof( object )
        };

        ParameterExpression[] constructorArgumentExpressions = constructorArgumentTypes
            .Select( tp => Expression.Parameter( tp ) )
            .ToArray();

        // Find all types in current assembly
        var ass = Assembly.GetExecutingAssembly();
        foreach( Type tp in ass.GetTypes() )
        {
            // Try to get the custom attribute
            var dba = tp.GetCustomAttribute<DataBindingAttribute>();
            if( null == dba )
                continue;

            // Ensure you don't have 2 classes with the same element ID value
            Debug.Assert( !dictTypes.ContainsKey( dba.element ) );
            // Ensure the found type inherits from BindingBase
            Debug.Assert( typeof( BindingBase ).IsAssignableFrom( tp ) );

            // Compile the function that constructs the new binding object
            ConstructorInfo ci = tp.GetConstructor( constructorArgumentTypes );
            Debug.Assert( null != ci );

            // new Binding(...)
            var expNew = Expression.New( ci, constructorArgumentExpressions );
            // (BindingBase)( new Binding( ... ) )
            var expCast = Expression.Convert( expNew, typeof( BindingBase ) );
            // Compile into lambda
            var lambda = Expression.Lambda<Func<object, BindingBase>>( expCast, constructorArgumentExpressions );
            // Compile the lambda, and save in the sorted dictionary
            var func = lambda.Compile();
            dictTypes.Add( dba.element, func );
        }
    }

    public static BindingBase tryConstruct( Dictionary<eElement, object> dict )
    {
        foreach( var kvp in dictTypes )
        {
            object arg;
            if( !dict.TryGetValue( kvp.Key, out arg ) )
                continue;
            return kvp.Value( arg );
        }
        return null;
    }
}

class Program
{
    static void Main( string[] args )
    {
        var dict = new Dictionary<eElement, object>();
        dict[ eElement.FormParameter ] = 12;
        // This line will construct an instance of FormParameterDataBinding
        var res = BindingsFactory.tryConstruct( dict );
    }
}
</code>```

Body:
I want to optimise this code to reduce the number of if statements. Maybe it'd be better to use a lot of classes, and let the classes handle each required action?

It could be fabric pattern? Or is it OK to use 30+ similar if statements?

I've tried to make a Dictionary with string and object class. But I couldn't get it to work (or my skills are not good enough)

if (node[DATA_CONNECTION_ELEMENT] != null)
{
    return new DataConnectionPropertyDataBinding(form, node[DATA_CONNECTION_ELEMENT], inputableEntity);
}
else if (node[FORM_PARAMETER_ELEMENT] != null)
{
    return new FormParameterDataBinding(form, node[FORM_PARAMETER_ELEMENT], inputableEntity);
}

// + 30 more else ifs

else if (node[COMMAND_ELEMENT] != null)
{
    return new CommandResultDataBinding(form, node[COMMAND_ELEMENT], inputableEntity);
}
else if (node[CONDITION_ELEMENT] != null)
{
    return new ConditionDataBinding(form, node[CONDITION_ELEMENT], inputableEntity);
}
else if (node[CLIPBOARD_ELEMENT] != null)
{
    return new ClipboardDataBinding(form, node[CLIPBOARD_ELEMENT], inputableEntity);
}
else
{
    return new ConstantDataBinding(form, node);
}

Want to make it look something like

foreach (var item in allThatShareSomeInterface)
{
    if (item.CanHandle(node.Atributes[0]))
    {
        return item.neededObject();
    }
}

Here is the answer. How it really works.

        Dictionary<string, Type> allObjects = new Dictionary<string, Type>();
        allObjects.Add(CONDITION_ELEMENT, typeof(ConditionDataBinding));
        allObjects.Add(DATA_TYPE_FORMAT_ELEMENT, typeof(DataTypeFormatDataBinding));
        allObjects.Add(DATA_TYPE_CONVERT_ELEMENT, typeof(DataTypeConvertDataBinding));
        allObjects.Add(FORM_PARAMETER_ELEMENT, typeof(FormParameterDataBinding));
        allObjects.Add(FORM_ELEMENT, typeof(FormPropertyDataBinding));
        allObjects.Add(STRING_ELEMENT, typeof(StringFormatDataBinding));
        allObjects.Add(FORMULA_ELEMENT, typeof(FormulaDataBinding));
        allObjects.Add(COMMAND_ELEMENT, typeof(CommandResultDataBinding));
        // + many

        foreach (var pair in allObjects)
        {
            if (node[pair.Key] != null)
            {
                ConstructorInfo ctor = pair.Value.GetConstructor(new[] { typeof(IWorkflowForm), typeof(XmlNode), typeof(IInputable) });
                return ctor.Invoke(new object[] { form, node[pair.Key], inputableEntity });
            }
        }

Body:
If you know what you are doing, and you indeed need that many binding classes, one way to solve that is custom attributes + reflection + runtime code generation. Here’s an example.

// Enum for element type. The order matters, it's the order in which input dictionary is tested.
enum eElement
{
    DataConnection,
    FormParameter,
}
// Custom attribute to mark bindings classes with.
class DataBindingAttribute : Attribute
{
    public eElement element;
    public DataBindingAttribute( eElement e ) { element = e; }
}

// Base class for bindings
abstract class BindingBase { }

// Couple test binding classes
[DataBinding( eElement.DataConnection )]
class DataConnectionPropertyDataBinding: BindingBase
{
    public DataConnectionPropertyDataBinding( object data ) { }
}
[DataBinding( eElement.FormParameter )]
class FormParameterDataBinding: BindingBase
{
    public readonly object data;
    public FormParameterDataBinding( object data ) { this.data = data; }
}

// This static class does the magic.
static class BindingsFactory
{
    // Key = eElement from custom attribute, value = function that constructs the binding. This example uses the constructor with single object argument.
    // It's a good idea to use strong types for arguments instead.
    static readonly SortedDictionary<eElement, Func<object, BindingBase>> dictTypes = new SortedDictionary<eElement, Func<object, BindingBase>>();

    static BindingsFactory()
    {
        // Constructor argument types, just a single `object` in this example.
        Type[] constructorArgumentTypes = new Type[ 1 ]
        {
            typeof( object )
        };

        ParameterExpression[] constructorArgumentExpressions = constructorArgumentTypes
            .Select( tp => Expression.Parameter( tp ) )
            .ToArray();

        // Find all types in current assembly
        var ass = Assembly.GetExecutingAssembly();
        foreach( Type tp in ass.GetTypes() )
        {
            // Try to get the custom attribute
            var dba = tp.GetCustomAttribute<DataBindingAttribute>();
            if( null == dba )
                continue;

            // Ensure you don't have 2 classes with the same element ID value
            Debug.Assert( !dictTypes.ContainsKey( dba.element ) );
            // Ensure the found type inherits from BindingBase
            Debug.Assert( typeof( BindingBase ).IsAssignableFrom( tp ) );

            // Compile the function that constructs the new binding object
            ConstructorInfo ci = tp.GetConstructor( constructorArgumentTypes );
            Debug.Assert( null != ci );

            // new Binding(...)
            var expNew = Expression.New( ci, constructorArgumentExpressions );
            // (BindingBase)( new Binding( ... ) )
            var expCast = Expression.Convert( expNew, typeof( BindingBase ) );
            // Compile into lambda
            var lambda = Expression.Lambda<Func<object, BindingBase>>( expCast, constructorArgumentExpressions );
            // Compile the lambda, and save in the sorted dictionary
            var func = lambda.Compile();
            dictTypes.Add( dba.element, func );
        }
    }

    public static BindingBase tryConstruct( Dictionary<eElement, object> dict )
    {
        foreach( var kvp in dictTypes )
        {
            object arg;
            if( !dict.TryGetValue( kvp.Key, out arg ) )
                continue;
            return kvp.Value( arg );
        }
        return null;
    }
}

class Program
{
    static void Main( string[] args )
    {
        var dict = new Dictionary<eElement, object>();
        dict[ eElement.FormParameter ] = 12;
        // This line will construct an instance of FormParameterDataBinding
        var res = BindingsFactory.tryConstruct( dict );
    }
}


问:
Azure Search Indexer fails to create when trying to index fields with special characters in the name
I am trying to create an Azure Search indexer and i am getting the following error message:

"Azure Search notification
Import configuration failed, error creating Index: "The request is invalid. Details: definition : Invalid field name: '@type'. Field names must begin with a letter and can contain only letters, digits, or underscore ('_').""

I have my data stored in a Cosmos DB using SQL API and the documents stored there contain data following the schema.org standard, so i have fields with name starting with @, such as @type.

I know there are some questions around this, but more related with the search capabilities for fields with special characters in the name. In this case, i am not able even to index them. And in theory i should be able to do it, right?

答:
You can use a field mapping to "rename" the problematic fields. See Field mappings in Azure Search indexers.
Note that because field mappings are not exposed in the portal, you will need to create the indexer programmatically using the Create Indexer REST API or corresponding .NET client SDK API.


问:
VueJS - vue.config.js proxy configuration for build
I'm currently using devServer{proxy:{...}} in vue.config.js to configure proxy for api calls for avoiding CORS problems in my application. It works fine when I run npm run serve in localhost.

Now I need to deploy my application to a host, so I run npm run build, change the url's of my Ajax calls and it's not running... So what I indeed need is to configure my proxy for deployment (build), not for devServer.

What is the correct way to do that?

I've already tried:
server{proxy:{...}} and build{proxy:{...}}, but none of them are allowed when running npm run build.

Thank you!

答:
You can try another approach which is adding API URL's to .env files

If you are using Vue CLI you can create .env.development and .env.production files and put API URL's for development and production like:

.env.development

VUE_APP_API_URL=http://localhost:8080/api
```

<p><strong>.env.production</strong></p>

<pre class="lang-js prettyprint-override"><code>VUE_APP_API_URL=http://myapp.com/api
</code>```

In your project files you can access the variables by putting VUE_APP_ keyword like;

Your file to make api requests

const url = process.env.VUE_APP_API_URL
const res = axios.get(url, config).then (...)
                                  .catch(...)
```

You can look for more from Vue's official docs

To handle the CORS issue, I can give you some tips.

Divide your app as packages named server and client

Move everything related to vuejs to client folder

Move server.js to server folder

Implement cardconnect inside server.js

Create an nodejs api via expressjs and move cardconnect logic to controllers(endpoints)

Consume nodejs api that makes cardconnect implementation via vue.js(this will resolve the cors issue since you dont make requests from vuejs, but triggering the cardconnect implementation via node.js)

Serve Vue app with your Node.js server

Body:
You can try another approach which is adding API URL's to .env files

If you are using Vue CLI you can create .env.development and .env.production files and put API URL's for development and production like:

.env.development

VUE_APP_API_URL=http://localhost:8080/api

.env.production

VUE_APP_API_URL=http://myapp.com/api

In your project files you can access the variables by putting VUE_APP_ keyword like;

Your file to make api requests

const url = process.env.VUE_APP_API_URL
const res = axios.get(url, config).then (...)
                                  .catch(...)

You can look for more from Vue's official docs

To handle the CORS issue, I can give you some tips.

Divide your app as packages named server and client

Move everything related to vuejs to client folder

Move server.js to server folder

Implement cardconnect inside server.js

Create an nodejs api via expressjs and move cardconnect logic to controllers(endpoints)

Consume nodejs api that makes cardconnect implementation via vue.js(this will resolve the cors issue since you dont make requests from vuejs, but triggering the cardconnect implementation via node.js)

Serve Vue app with your Node.js server


问:
Trying to convert XML values into map
I have seen a lot of similar problems that keep getting me partway there, but I end up starting to have to build recursive solutions on top which I'm trying to avoid.

I have an XML file I want to convert into a map.

The structure is unknown except for one thing

```<code><items>
<item>
{section to be converted to map}
</item>
<item>
{section to be converted to map}
</item>
</items>
</code>```

All the solutions I've seen seem to be converting the entire thing into map, or parse through each attribute/value manually.

I'm wondering if there's a method to say...

Jump into items, jump into each item, convert each item to map, then I can process each map individually.

I am streaming through a potentially large file, so don't want to hold the entire thing in memory, just one item at a time.

I have tried to use xmleventreader to do this, but get jammed up in a recursive nightmare. The item was for the event reader to find individual items, and them on those individual items to have them process, but not finding any documentation on how to capture what's between each value so it can be processed as an XML later.

```<code>private void parseItemList(MultipartFile file) {
    XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
    try {
        XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(file.getInputStream());
        processItems(xmlEventReader);
    } catch (FileNotFoundException | XMLStreamException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
</code>```

The idea would be to convert:

```<code><items>
<item>
<id>1</id>
<value>4</value>
</item>
<item>
<id>2</id>
<attributes>
<value>5</value>
</attributes>
</item>
</items>
</code>```

into

```<code>{id: 1, value: 4}
{id: 2, attributes{value: 5}}
</code>```

and so on, where I can process and push each map individually before moving onto the next. If there's a library that handles this easily, I'd love to be pointed in that direction.

答:
You can use Declarative Stream Mapping (DSM) stream parsing library to easily convert complex XML to java class. You can call custom functions to process partial data while you are reading the xml document.

First of all, you must define mappings between XML data and your class fields in yaml format.

Here are mapping definitions for your XML.

```<code>result:
   type: object                    # type is the object to consume low memory.
                                   #you will get an object(Map) as a result not List
   path: /items/item
   function: processFunction       # call registered ' processFunction' for every 'items/item'
   fields:
       value:          # not exist for second item it is skiped
       id:
       attributes:      # not exist for first item so it is skiped
         type: object
         fields:
           value:
</code>```

Create a process function:

```<code>FunctionExecutor processFunction=new FunctionExecutor() {
            @Override
            public void execute(Params params) {
                Node node = params.getCurrentNode();
                // deserialize to your class
                //YourClass.class=node.toObject(YourClass.class);
                //or
                // directly access data
                System.out.println(node.getData());

            }
        }
</code>```

Java Code to parse XML:

```<code> DSMBuilder builder = new DSMBuilder(new File("path/to/mapping.yaml")).setType(DSMBuilder.TYPE.XML);

 // register function
 builder.registerFunction("processFunction",processFunction);

 DSM dsm= builder.create();
 Object object =  dsm.toObject(xmlContent);
 // type of object varibale is a Map<String,Obejct>
</code>```

Output:

```<code>{id=1, value=4}
{id=2, attributes={value=5}}
</code>```

UPDATE:

If you want to value tag in "item" and "attributes" tag become in same level you can change your mapping definition as follows

```<code>result:
   type: object                    # it is defiden as object for low memory.
                                   #you will get an object(Map) as a result not List
   path: /items/item
   function: processFunction       # call registered '' processFunction for every 'items/item'
   fields:
       id:
       value:
          path: .*value   # path is regex.   take both value tag in item and attributes tags
</code>```

Output:

```<code>{id=1, value=4}
{id=2, value=5}
</code>```

Title: Trying to convert XML values into map

Body:
I have seen a lot of similar problems that keep getting me partway there, but I end up starting to have to build recursive solutions on top which I'm trying to avoid.

I have an XML file I want to convert into a map.

The structure is unknown except for one thing

<items>
<item>
{section to be converted to map}
</item>
<item>
{section to be converted to map}
</item>
</items>

All the solutions I've seen seem to be converting the entire thing into map, or parse through each attribute/value manually.

I'm wondering if there's a method to say...

Jump into items, jump into each item, convert each item to map, then I can process each map individually.

I am streaming through a potentially large file, so don't want to hold the entire thing in memory, just one item at a time.

I have tried to use xmleventreader to do this, but get jammed up in a recursive nightmare. The item was for the event reader to find individual items, and them on those individual items to have them process, but not finding any documentation on how to capture what's between each value so it can be processed as an XML later.

private void parseItemList(MultipartFile file) {
    XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
    try {
        XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(file.getInputStream());
        processItems(xmlEventReader);
    } catch (FileNotFoundException | XMLStreamException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

The idea would be to convert:

<items>
<item>
<id>1</id>
<value>4</value>
</item>
<item>
<id>2</id>
<attributes>
<value>5</value>
</attributes>
</item>
</items>

into

{id: 1, value: 4}
{id: 2, attributes{value: 5}}

and so on, where I can process and push each map individually before moving onto the next. If there's a library that handles this easily, I'd love to be pointed in that direction.

Body:
You can use Declarative Stream Mapping (DSM) stream parsing library to easily convert complex XML to java class. You can call custom functions to process partial data while you are reading the xml document.

First of all, you must define mappings between XML data and your class fields in yaml format.

Here are mapping definitions for your XML.

result:
   type: object                    # type is the object to consume low memory.
                                   #you will get an object(Map) as a result not List
   path: /items/item
   function: processFunction       # call registered ' processFunction' for every 'items/item'
   fields:
       value:          # not exist for second item it is skiped
       id:
       attributes:      # not exist for first item so it is skiped
         type: object
         fields:
           value:

Create a process function:

FunctionExecutor processFunction=new FunctionExecutor() {
            @Override
            public void execute(Params params) {
                Node node = params.getCurrentNode();
                // deserialize to your class
                //YourClass.class=node.toObject(YourClass.class);
                //or
                // directly access data
                System.out.println(node.getData());

            }
        }

Java Code to parse XML:

 DSMBuilder builder = new DSMBuilder(new File("path/to/mapping.yaml")).setType(DSMBuilder.TYPE.XML);

 // register function
 builder.registerFunction("processFunction",processFunction);

 DSM dsm= builder.create();
 Object object =  dsm.toObject(xmlContent);
 // type of object varibale is a Map<String,Obejct>

Output:

{id=1, value=4}
{id=2, attributes={value=5}}

UPDATE:

If you want to value tag in "item" and "attributes" tag become in same level you can change your mapping definition as follows

result:
   type: object                    # it is defiden as object for low memory.
                                   #you will get an object(Map) as a result not List
   path: /items/item
   function: processFunction       # call registered '' processFunction for every 'items/item'
   fields:
       id:
       value:
          path: .*value   # path is regex.   take both value tag in item and attributes tags

Output:

{id=1, value=4}
{id=2, value=5}


问:
how to handle xml data in javascript
I am newbie in javascript xml data handling. Currently, my ajax call to a server, and the server returns xml data, I don't know how to parse the xml data to get some values.

My ajax call:

```<code>$.ajax({
            url: 'http://localhost:8080/someinterface/the-id',
            type: 'GET',
            async: false,
            dataType: 'application/xml',
            data: {id: 43},
            success: function(data) {

                //handle the data

            },
            error: function(xhr, status, error){
                alert('error happens');
            }
         })
</code>```

the returned xml data looks like:

```<code><DOCUMENT>
  <AGE>16</AGE>
  <USERNAME>default user</USERNAME>
  <SECURITYID>1111</SECURITYID>
...
</code>```

how to parse the xml data to get for example "USERNAME" in my javascript ??

------------EDIT------------

I tried to use your proposed ways, but now I got error message:

XML Parsing Error: no element found Location: moz-nullprincipal:{120e8c1d-5174-4e94-9ebb-2bffda80b170} Line Number 1, Column 1:
^

and the ajax call result to the error function

-------------------PARTLY SOLVED------------------------

Finally, I found the reason is that my application is running on jetty server on localhost:8080, while my ajax is requesting xml data on tomcat server which is running on localhost:8085. Because of the domain port are different, I got the weired problem. Now, after I move my application to tomcat server and request tomcat server, I got the xml response successfully.

The ajax call goes to the success function, and I use

```<code>success: function(data){
           xmlDoc = $.parseXML(data);
            $xml = $(xmlDoc);
            $userName = $xml.find('USERNAME');
            var userName = $userName.text();
            alert('1');
            alert(userName);
}
</code>```

I got alert('1') in my browser, BUT I do not get alert(userName) , I don't know why... So I put here "PARTLY SOLVED", so...why I do not get my userName alert..

答:
Use Json data type instead, it's designed to be used with javascript.

Example:

```<code>$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback
});
</code>```

Title: how to handle xml data in javascript

Body:
I am newbie in javascript xml data handling. Currently, my ajax call to a server, and the server returns xml data, I don't know how to parse the xml data to get some values.

My ajax call:

$.ajax({
            url: 'http://localhost:8080/someinterface/the-id',
            type: 'GET',
            async: false,
            dataType: 'application/xml',
            data: {id: 43},
            success: function(data) {

                //handle the data

            },
            error: function(xhr, status, error){
                alert('error happens');
            }
         })

the returned xml data looks like:

<DOCUMENT>
  <AGE>16</AGE>
  <USERNAME>default user</USERNAME>
  <SECURITYID>1111</SECURITYID>
...

how to parse the xml data to get for example "USERNAME" in my javascript ??

------------EDIT------------

I tried to use your proposed ways, but now I got error message:

XML Parsing Error: no element found Location: moz-nullprincipal:{120e8c1d-5174-4e94-9ebb-2bffda80b170} Line Number 1, Column 1:
^

and the ajax call result to the error function

-------------------PARTLY SOLVED------------------------

Finally, I found the reason is that my application is running on jetty server on localhost:8080, while my ajax is requesting xml data on tomcat server which is running on localhost:8085. Because of the domain port are different, I got the weired problem. Now, after I move my application to tomcat server and request tomcat server, I got the xml response successfully.

The ajax call goes to the success function, and I use

success: function(data){
           xmlDoc = $.parseXML(data);
            $xml = $(xmlDoc);
            $userName = $xml.find('USERNAME');
            var userName = $userName.text();
            alert('1');
            alert(userName);
}

I got alert('1') in my browser, BUT I do not get alert(userName) , I don't know why... So I put here "PARTLY SOLVED", so...why I do not get my userName alert..

Body:
Use Json data type instead, it's designed to be used with javascript.

Example:

$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback
});


问:
docker ps Invalid bind address format:
When I execute the command I get:

```<code>$ docker ps
Invalid bind address format: "tcp://192.168.99.100:2376"

$docker-machine rm -f default
$ docker-machine create -d virtualbox default
$ (docker-machine env default)
</code>```

And now I can't list my docker images and containers.
What I can do to fix it?

答:
Another possible solution which worked for me:

DELETE the DOCKER_HOST environment variable and reboot.

Refer to: Docker Issue - Invalid bind address format Windows

Title: docker ps Invalid bind address format:

Body:
When I execute the command I get:

$ docker ps
Invalid bind address format: "tcp://192.168.99.100:2376"

$docker-machine rm -f default
$ docker-machine create -d virtualbox default
$ (docker-machine env default)

And now I can't list my docker images and containers.
What I can do to fix it?


问:
Create directory without compile error message
Please help. I am pretty new. I am trying to create a folder using dates and got a compile error message "wrong number of arguments or invalid property assignments". The code worked perfectly for a month but not anymore. </p>

```<code>Sub Test()

MkDir "\\AD.TEST.COM\nas\Team-AB-TEST\TEST FOLDER\TEST FOLDER \" & Format(Date, "yyyy") & " Email Tracking\" & Format(Date, "mm.dd.yy") & "\Attach\"

End Sub
</code>```

答:
Your code is compiling perfectly.

But when you add this next to your code:

```<code>Function Format(s As String)
Format = "tralala"
End Function
</code>```

Then, it does not work anymore.

Can you verify you don't have some Format() function defined somewhere?

Body:
Please help. I am pretty new. I am trying to create a folder using dates and got a compile error message "wrong number of arguments or invalid property assignments". The code worked perfectly for a month but not anymore.

Sub Test()

MkDir "\\AD.TEST.COM\nas\Team-AB-TEST\TEST FOLDER\TEST FOLDER \" & Format(Date, "yyyy") & " Email Tracking\" & Format(Date, "mm.dd.yy") & "\Attach\"

End Sub

Body:
Your code is compiling perfectly.

But when you add this next to your code:

Function Format(s As String)
Format = "tralala"
End Function

Then, it does not work anymore.

Can you verify you don't have some Format() function defined somewhere?


问:
My container with max-width: 960px doesn't seem to work
I want to make a navbar with the following code:

```<code><nav>
  <ul class ="container">
   <li class = "ul--wrap"><a class = "p p__li" href="index.php?page=home">Home</a></li>
   <li class = "ul--wrap"><a class = "p p__li" href="index.php?page=activities">Activities</a></li>
   <li class = "ul--wrap"><a class = "p p__li" href="index.php?page=locations">Locations</a></li>
   <li class = "ul--wrap"><a class = "p p__li"href="index.php?page=register">Register</a></li>
   <li class = "ul--wrap"><button class = "btn"><a class = "p p__li p__li--light" href="index.php?page=tickets">Tickets</a></button></li>
         </ul>
</nav>
</code>```

I want to have a container so the navbar doesn't extend the width of 960px.
I have this container code:

```<code>.container{
    max-width: 96rem;
    vertical-align: center;
    margin: 0 auto;
 }
</code>```

When I want to change the space between the
 items, the
 items extend the 960px centered container.

答:
I believe your problem lies with the max-width property in the .container CSS property you have created.

As pointed out in the comments by @Jones - 1rem = 16px

Change your CSS to:

```<code>.container{
    max-width: 60rem;
    vertical-align: center;
    margin: 0 auto;
}
</code>```

Body:
I want to make a navbar with the following code:

Home

Activities

Locations

Register

<button class = "btn">Tickets</button>

I want to have a container so the navbar doesn't extend the width of 960px.
I have this container code:

.container{
    max-width: 96rem;
    vertical-align: center;
    margin: 0 auto;
 }

When I want to change the space between the
 items, the
 items extend the 960px centered container.

Body:
I believe your problem lies with the max-width property in the .container CSS property you have created.

As pointed out in the comments by @Jones - 1rem = 16px

Change your CSS to:

.container{
    max-width: 60rem;
    vertical-align: center;
    margin: 0 auto;
}


问:
Connect to Kubernetes mongo db in different namespace
Can anyone point out how to connect to the mongo db instance using mongo client using either command line client or from .net core programs with connection strings?

We have created a sample cluster in digitalocean with a namespace, let's say mongodatabase.

We installed the mongo statefulset with 3 replicas. We are able to successfully connect with the below command
 kubectl --kubeconfig=configfile.yaml -n mongodatabase exec -ti mongo-0 mongo
But when we connect from a different namespace or from default namespace with the pod names in the below format, it doesn't work.

```<code> kubectl --kubeconfig=configfile.yaml  exec -ti mongo-0.mongo.mongodatabase.cluster.svc.local mongo
</code>```

where mongo-0.mongo.mongodatabase.cluster.svc.local is in pod-0.service_name.namespace.cluster.svc.local (also tried pod-0.statfulset_name.namespace.cluster.svc.local and pod-0.service_name.statefulsetname.namespace.cluster.svc.local) etc.,

Can any one help with the correct dns name/connection string to be used while connecting with mongo client in command line and also from the programs like java/.net core etc.,?

Also should we use kubernetes deployment instead of statefulsets here?

答:
You need to reference the mongo service by namespaced dns.  So if your mongo service is mymongoapp and it is deployed in mymongonamespace, you should be able to access it as mymongoapp.mymongonamespace.

To test, I used the bitnami/mongodb docker client.  As follows:

From within mymongonamespace, this command works

```<code>$ kubectl config set-context --current --namespace=mymongonamespace
$ kubectl run mongodbclient --rm --tty -i --image bitnami/mongodb --command -- mongo --host mymongoapp
</code>```

But when I switched to namespace default it didn't work

```<code>$ kubectl config set-context --current --namespace=default
$ kubectl run mongodbclient --rm --tty -i --image bitnami/mongodb --command -- mongo --host mymongoapp
</code>```

Qualifying the host with the namespace then works

```<code>$ kubectl run mongodbclient --rm --tty -i --image bitnami/mongodb --command -- mongo --host mymongoapp.mymongonamespace
</code>```

Body:
Can anyone point out how to connect to the mongo db instance using mongo client using either command line client or from .net core programs with connection strings?

We have created a sample cluster in digitalocean with a namespace, let's say mongodatabase.

We installed the mongo statefulset with 3 replicas. We are able to successfully connect with the below command
 kubectl --kubeconfig=configfile.yaml -n mongodatabase exec -ti mongo-0 mongo
But when we connect from a different namespace or from default namespace with the pod names in the below format, it doesn't work.

 kubectl --kubeconfig=configfile.yaml  exec -ti mongo-0.mongo.mongodatabase.cluster.svc.local mongo

where mongo-0.mongo.mongodatabase.cluster.svc.local is in pod-0.service_name.namespace.cluster.svc.local (also tried pod-0.statfulset_name.namespace.cluster.svc.local and pod-0.service_name.statefulsetname.namespace.cluster.svc.local) etc.,

Can any one help with the correct dns name/connection string to be used while connecting with mongo client in command line and also from the programs like java/.net core etc.,?

Also should we use kubernetes deployment instead of statefulsets here?

Body:
You need to reference the mongo service by namespaced dns.  So if your mongo service is mymongoapp and it is deployed in mymongonamespace, you should be able to access it as mymongoapp.mymongonamespace.

To test, I used the bitnami/mongodb docker client.  As follows:

From within mymongonamespace, this command works

$ kubectl config set-context --current --namespace=mymongonamespace
$ kubectl run mongodbclient --rm --tty -i --image bitnami/mongodb --command -- mongo --host mymongoapp

But when I switched to namespace default it didn't work

$ kubectl config set-context --current --namespace=default
$ kubectl run mongodbclient --rm --tty -i --image bitnami/mongodb --command -- mongo --host mymongoapp

Qualifying the host with the namespace then works

$ kubectl run mongodbclient --rm --tty -i --image bitnami/mongodb --command -- mongo --host mymongoapp.mymongonamespace


问:
How to get the ValueItem value of ListBox item by its index
I have a listbox that has a description and a value stored in it (the description is a customer name and the valueitem is that customer's ID in the database) On my form I have two listboxes the one on the left has a full list of customer names and the user then selects from that list and adds the ones they want to associate a user with to the right hand listbox. When I come to save the record I want to store the list of customerIDs in a table so that I can identify which customers this record relates to.

My code loops through the list using a For .. Next loop:

```<code>For n = 0 To lbxCustomerList.Items.Count - 1
  U.CustomersLinkedTo += lbxCustomerList.Items(n).Value.ToString() & ","
Next
</code>```

U is a User record class and the field CustomersLinkedTo is an NVarchar(255) field that I will build a comma separated list to of the CustomerIDs that the user has allocated this user to.

The issue is that lbxCustomerList.Items(n).Value is not allowed. I am using VB.NET and Dot Net Framework V4.

I have tried loading the ListBox into a ListBox.ObjectCollection variable and then seeing if that allows me to access the ValuItems but that doesn't allow it either.  How do I get the values as opposed to the description text??

EDIT ****
In order to aid those good people who are trying to help me I am adding below the code I use to populate the Customer list and then the code I use to populate the lbxCustomersLinkedTo that contains the customers they have selected:

Populate the list on the left that the user picks Customer names from and adds them to the list on the right that contains the subset the user wants to allocate to to a user.

```<code>    Private Sub PopulateCustomerList()
    Dim c As New Customer()
    Dim cc As New ArrayList()

    Try
        'Clear list
        lbxCustomerList.Items.Clear()
        lbxCustomerList.DataSource = Nothing

        'Populate from DB.
        cc = c.GetCustomersForDropLists(customerTypeEnum.Active)
        lbxCustomerList.DataSource = cc
        lbxCustomerList.DisplayMember = "DisplayedText"
        lbxCustomerList.ValueMember = "ReturnedID"
        lbxCustomerList.Refresh()

    Catch ex As Exception
        PEH("PopulateCustomerList", "frmUserSetup", ex.Message)
    End Try
End Sub
</code>```

Code that adds the items the user selects from the Customers list to the one I am interested in that I use to derive teh Customer ID list I want to add to my user's record.

```<code>   Private Sub AddToList()
    Dim SelItems As New ListBox.SelectedObjectCollection(lbxCustomerList)
    SelItems = lbxCustomerList.SelectedItems

    Try

        If lbxCustomerList.SelectedItems.Count > 0 Then
            For n = 0 To SelItems.Count - 1
                lbxCustomersLinkedTo.Items.Add(SelItems(n))
            Next
            lbxCustomerList.ClearSelected()
        End If

    Catch ex As Exception
        PEH("AddToList", "frmUserSetup", ex.Message)
    End Try
End Sub
</code>```

This is an image of the part of the user form I am talking about:

@ThePeter - Thanks your routine with a slight modification did the trick.

This is my code in the save routine now:

```<code>           'Get the Customers an officer works for into a comma separated list.
        'First remove any existing items.
        U.CustomersLinkedTo = ""

        If (lbxCustomersLinkedTo.Items.Count > 0) Then
            For n = 0 To lbxCustomersLinkedTo.Items.Count - 1
                If n = lbxCustomersLinkedTo.Items.Count - 1 Then
                    U.CustomersLinkedTo += WhatValueIsSelectedInListBoxForIndex(lbxCustomersLinkedTo, n) 'Don't add comma to last item.
                Else
                    U.CustomersLinkedTo += WhatValueIsSelectedInListBoxForIndex(lbxCustomersLinkedTo, n) & ","
                End If
            Next
        End If
</code>```

This is your routine modified slightly as it gave an error initially:

```<code>   ''' <summary>
''' Use this function to get the values of an item in the list box. It works with list boxes that are bound to a DataSet, and those that have been populated via code, or manually populated via the GUI.
''' </summary>
''' <param name="lstBox">The list box you want to find the selected value in.</param>
''' <param name="iIndex">The number of the item in the ListBox that you want the value for.</param>
''' <param name="DesiredReturnValue">By default it returns the hidden return value, but you can ask for the display value if desired.</param>
''' <returns>This function returns a String value.</returns>
Public Function WhatValueIsSelectedInListBoxForIndex(ByVal lstBox As ListBox, ByVal iIndex As Integer, Optional ByVal DesiredReturnValue As SelectByMode = SelectByMode.ByReturnValue) As String
    Dim sReturn As String = ""

    Try
        If DesiredReturnValue = SelectByMode.ByReturnValue Then
            'Returns the value that is not visible, but stored in the "ValueMember" field of the bound ComboBox
            If lstBox.ValueMember.Length > 0 And lstBox.DisplayMember.Length > 0 Then
                'This is a bound listbox.
                Dim drSelectedItem As DataRowView = lstBox.Items(iIndex)
                sReturn = drSelectedItem.Item(0).ToString
            Else
                Try
                    'This listbox was populated in code with display values and return values.
                    sReturn = lstBox.Items(iIndex).ReturnedID
                Catch ex As Exception
                    PEH("WhatValueIsSelectedInListBoxForIndex - Populated Code section", "frmUserSetup", ex.Message)
                End Try
            End If
        ElseIf DesiredReturnValue = SelectByMode.ByDisplayName Then
            'Return the selected TEXT (visible in the control)
            If lstBox.ValueMember.Length > 0 And lstBox.DisplayMember.Length > 0 Then
                'This is a bound listbox.
                Dim drSelectedItem As DataRowView = lstBox.Items(iIndex)
                sReturn = drSelectedItem.Item(1).ToString
            Else
                sReturn = lstBox.Items(iIndex).ToString
            End If
        Else
            sReturn = ""
        End If
    Catch Ex As Exception

        PEH("WhatValueIsSelectedInListBoxForIndex", "frmUserSetup", Ex.Message)
        sReturn = ""
    End Try

    If sReturn Is Nothing Then sReturn = ""
    Return sReturn

End Function
</code>```

The bit I had to modify to suit my listbox was the line:

```<code>                       'This listbox was populated in code with display values and return values.
                    sReturn = lstBox.Items(iIndex).ReturnedID
</code>```

With your help, this now works and populates the database field directly.

Siv

答:
Remove the .Value part or Use this code instead

```<code>For n = 0 To lbxCustomerList.Items.Count - 1
  U.CustomersLinkedTo += lbxCustomerList.Items(n).ToString() & ","
Next
</code>```

Even easier you can use what @LarsTech Said
This will not require the loop

```<code>U.CustomersLinkedTo = String.Join(", ", lbxCustomerList.Items)
</code>```

Body:
I have a listbox that has a description and a value stored in it (the description is a customer name and the valueitem is that customer's ID in the database) On my form I have two listboxes the one on the left has a full list of customer names and the user then selects from that list and adds the ones they want to associate a user with to the right hand listbox. When I come to save the record I want to store the list of customerIDs in a table so that I can identify which customers this record relates to.

My code loops through the list using a For .. Next loop:

For n = 0 To lbxCustomerList.Items.Count - 1
  U.CustomersLinkedTo += lbxCustomerList.Items(n).Value.ToString() & ","
Next

U is a User record class and the field CustomersLinkedTo is an NVarchar(255) field that I will build a comma separated list to of the CustomerIDs that the user has allocated this user to.

The issue is that lbxCustomerList.Items(n).Value is not allowed. I am using VB.NET and Dot Net Framework V4.

I have tried loading the ListBox into a ListBox.ObjectCollection variable and then seeing if that allows me to access the ValuItems but that doesn't allow it either.  How do I get the values as opposed to the description text??

EDIT ****
In order to aid those good people who are trying to help me I am adding below the code I use to populate the Customer list and then the code I use to populate the lbxCustomersLinkedTo that contains the customers they have selected:

Populate the list on the left that the user picks Customer names from and adds them to the list on the right that contains the subset the user wants to allocate to to a user.

    Private Sub PopulateCustomerList()
    Dim c As New Customer()
    Dim cc As New ArrayList()

    Try
        'Clear list
        lbxCustomerList.Items.Clear()
        lbxCustomerList.DataSource = Nothing

        'Populate from DB.
        cc = c.GetCustomersForDropLists(customerTypeEnum.Active)
        lbxCustomerList.DataSource = cc
        lbxCustomerList.DisplayMember = "DisplayedText"
        lbxCustomerList.ValueMember = "ReturnedID"
        lbxCustomerList.Refresh()

    Catch ex As Exception
        PEH("PopulateCustomerList", "frmUserSetup", ex.Message)
    End Try
End Sub

Code that adds the items the user selects from the Customers list to the one I am interested in that I use to derive teh Customer ID list I want to add to my user's record.

   Private Sub AddToList()
    Dim SelItems As New ListBox.SelectedObjectCollection(lbxCustomerList)
    SelItems = lbxCustomerList.SelectedItems

    Try

        If lbxCustomerList.SelectedItems.Count > 0 Then
            For n = 0 To SelItems.Count - 1
                lbxCustomersLinkedTo.Items.Add(SelItems(n))
            Next
            lbxCustomerList.ClearSelected()
        End If

    Catch ex As Exception
        PEH("AddToList", "frmUserSetup", ex.Message)
    End Try
End Sub

This is an image of the part of the user form I am talking about:

@ThePeter - Thanks your routine with a slight modification did the trick.

This is my code in the save routine now:

           'Get the Customers an officer works for into a comma separated list.
        'First remove any existing items.
        U.CustomersLinkedTo = ""

        If (lbxCustomersLinkedTo.Items.Count > 0) Then
            For n = 0 To lbxCustomersLinkedTo.Items.Count - 1
                If n = lbxCustomersLinkedTo.Items.Count - 1 Then
                    U.CustomersLinkedTo += WhatValueIsSelectedInListBoxForIndex(lbxCustomersLinkedTo, n) 'Don't add comma to last item.
                Else
                    U.CustomersLinkedTo += WhatValueIsSelectedInListBoxForIndex(lbxCustomersLinkedTo, n) & ","
                End If
            Next
        End If

This is your routine modified slightly as it gave an error initially:

   '''
''' Use this function to get the values of an item in the list box. It works with list boxes that are bound to a DataSet, and those that have been populated via code, or manually populated via the GUI.
'''
''' <param name="lstBox">The list box you want to find the selected value in.</param>
''' <param name="iIndex">The number of the item in the ListBox that you want the value for.</param>
''' <param name="DesiredReturnValue">By default it returns the hidden return value, but you can ask for the display value if desired.</param>
''' <returns>This function returns a String value.</returns>
Public Function WhatValueIsSelectedInListBoxForIndex(ByVal lstBox As ListBox, ByVal iIndex As Integer, Optional ByVal DesiredReturnValue As SelectByMode = SelectByMode.ByReturnValue) As String
    Dim sReturn As String = ""

    Try
        If DesiredReturnValue = SelectByMode.ByReturnValue Then
            'Returns the value that is not visible, but stored in the "ValueMember" field of the bound ComboBox
            If lstBox.ValueMember.Length > 0 And lstBox.DisplayMember.Length > 0 Then
                'This is a bound listbox.
                Dim drSelectedItem As DataRowView = lstBox.Items(iIndex)
                sReturn = drSelectedItem.Item(0).ToString
            Else
                Try
                    'This listbox was populated in code with display values and return values.
                    sReturn = lstBox.Items(iIndex).ReturnedID
                Catch ex As Exception
                    PEH("WhatValueIsSelectedInListBoxForIndex - Populated Code section", "frmUserSetup", ex.Message)
                End Try
            End If
        ElseIf DesiredReturnValue = SelectByMode.ByDisplayName Then
            'Return the selected TEXT (visible in the control)
            If lstBox.ValueMember.Length > 0 And lstBox.DisplayMember.Length > 0 Then
                'This is a bound listbox.
                Dim drSelectedItem As DataRowView = lstBox.Items(iIndex)
                sReturn = drSelectedItem.Item(1).ToString
            Else
                sReturn = lstBox.Items(iIndex).ToString
            End If
        Else
            sReturn = ""
        End If
    Catch Ex As Exception

        PEH("WhatValueIsSelectedInListBoxForIndex", "frmUserSetup", Ex.Message)
        sReturn = ""
    End Try

    If sReturn Is Nothing Then sReturn = ""
    Return sReturn

End Function

The bit I had to modify to suit my listbox was the line:

                       'This listbox was populated in code with display values and return values.
                    sReturn = lstBox.Items(iIndex).ReturnedID

With your help, this now works and populates the database field directly.

Siv

Body:
Remove the .Value part or Use this code instead

For n = 0 To lbxCustomerList.Items.Count - 1
  U.CustomersLinkedTo += lbxCustomerList.Items(n).ToString() & ","
Next

Even easier you can use what @LarsTech Said
This will not require the loop

U.CustomersLinkedTo = String.Join(", ", lbxCustomerList.Items)


问:
How to Convince management to upgrade to .Net 4.0
We developed an application using .net 2.0.
We license our software which means whenever we release a new version, we have to push out the change to all our existing clients.

No one in my group has the slightest motivation to upgrade to a newer version of .net. They simple see it as more work for our support team to deploy and argue that clients will be resistant to any change.

Can anyone point me in the direction of some argument i could present to Non programmers that might sway them.

If noting else, some argument that it is safe, and will not cause our clients any harm who already have the .net 2.0 framework on their machines?

I figure it's hopeless. I'm gonna be stuck using the .net 2.0 framework until for another 4 or 5 years i bet... perhaps longer :( help!

I really want to be able to use WCF, LINQ, WPF (possible), and the option to use the Entity Framework 4.0.!

thanks

jonathan

答:
Think software development as a business like any other business. No factory changes its perfectly running machines just because a new model of that machine has 10 more buttons to perform 10 new actions which are not required by that factory.
Software houses are there to generate profit not to educate developer; University will be a better place for education.</p>


问:
How do I search a list of characters in a text
I have to search the non-English text in a text fields in Power Query. Several language has special characters which might be searchable in the text field and if found then is obvious those text field is Non-English text.

I've tried and works to find specific language characters like "é" or "ä" etc. But I know to use only the Conditional Column function search each character and if found it then gives "0" as value than later I am multiplying all conditional column and if it is 0 then is Non-English text if it is "1" then is English.

```<code>= Table.AddColumn(#"Added Conditional Column13", "Custom É", each if Text.Contains([Text 1], "É") then 0 else if Text.Contains([Text 2], "É") then 0 else if Text.Contains([Text 3], "É") then 0 else 1)
</code>```

Is there a solution to search a list of special characters in the text fields (e.g. "ÁáÉéÖöÜüäß") -> search > results "0" if found anyone in the text otherwise gives as output "1".

答: I would look at the Range,find() command on how to search for characters in Excel. I would also use it on combination with VBA Strings and ASCII which is all the ASCII characters recognised by Excel</p>

Body:
I have to search the non-English text in a text fields in Power Query. Several language has special characters which might be searchable in the text field and if found then is obvious those text field is Non-English text.

I've tried and works to find specific language characters like "é" or "ä" etc. But I know to use only the Conditional Column function search each character and if found it then gives "0" as value than later I am multiplying all conditional column and if it is 0 then is Non-English text if it is "1" then is English.

= Table.AddColumn(#"Added Conditional Column13", "Custom É", each if Text.Contains([Text 1], "É") then 0 else if Text.Contains([Text 2], "É") then 0 else if Text.Contains([Text 3], "É") then 0 else 1)

Is there a solution to search a list of special characters in the text fields (e.g. "ÁáÉéÖöÜüäß") -> search > results "0" if found anyone in the text otherwise gives as output "1".


问:
ASP.NET Core API oData and API layer model
I need to use OData for my API endpoints in ASP.NET Core application, but all examples are about working directly with Data Model classes. In my application architecture I has service layer, methods of this service return DTO classes and then map to API view classes.

My data class (infrastructure layer):

```<code>public partial class Carrier : BaseEntity
{
    public string Name { get; set; }
    public string Code { get; set; }
    public string UsDotNumber { get; set; }
    public string McNumber { get; set; }
</code>```

My DTO class:

```<code>public class CarrierBaseDto
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Code { get; set; }
    public string Fein { get; set; }
    public string McNumber { get; set; }
</code>```

My presentation (API) class:

```<code>public class CarrierAPI
{
    [JsonProperty(PropertyName = "name")]
    public string Name { get; set; }
    [JsonProperty(PropertyName = "code")]
    public string Code { get; set; }
    [JsonProperty(PropertyName = "fein")]
    public string Fein { get; set; }
    [JsonProperty(PropertyName = "mcNumber")]
    public string McNumber { get; set; }
</code>```

my service method:

```<code>    public List<CarrierBaseDto> SearchCarriersDto()
    {
        var query = _context.Carriers
            .Where(c => !c.Deleted);

        IQueryable<CarrierBaseDto> queryDto = query.ProjectTo<CarrierBaseDto>(_mapperConfig);
        return queryDto.ToList();
    }
</code>```

My controller method:

```<code>    [HttpGet]
    [Route("GetAll")]
    public IActionResult GetAll()
    {
        var carriers = _carrierService.SearchCarriersDto();
        var carriersApi = _mapper.Map<List<CarrierElementAPI>>(carriers);
        return new OkObjectResult(carriersApi);
    }
</code>```

I want to add abilities to use $orderBy, $filter, $fields params. How to add it to my current architecture?

答:
I think it was when they originally designed OData it was not intended to be used without DDD, because the metadata was suppose to allow you to handle the filter etc, which is now creating somewhat of a limitation on using it.

There's some hacky workarounds but they only partially work.  The closest thing that I can think of that you can do is generically take in query options and apply them, Then use automapper to project to your queryable,

The only issue is the mappings from Entity to DTO in your automapper setup cannot be complex and must be setup through expression mapping

```<code>public Object[] Get(ODataQueryOptions<ProductDTO> options)
{
    ODataQuerySettings settings = new ODataQuerySettings()
    {
        PageSize = 5
    };

    IQueryable results = options.ApplyTo(_products.AsQueryable().ProjectTo<ProductDTO>(), settings);

    results.ToArray()
}
</code>```

Body:
I need to use OData for my API endpoints in ASP.NET Core application, but all examples are about working directly with Data Model classes. In my application architecture I has service layer, methods of this service return DTO classes and then map to API view classes.

My data class (infrastructure layer):

public partial class Carrier : BaseEntity
{
    public string Name { get; set; }
    public string Code { get; set; }
    public string UsDotNumber { get; set; }
    public string McNumber { get; set; }

My DTO class:

public class CarrierBaseDto
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Code { get; set; }
    public string Fein { get; set; }
    public string McNumber { get; set; }

My presentation (API) class:

public class CarrierAPI
{
    [JsonProperty(PropertyName = "name")]
    public string Name { get; set; }
    [JsonProperty(PropertyName = "code")]
    public string Code { get; set; }
    [JsonProperty(PropertyName = "fein")]
    public string Fein { get; set; }
    [JsonProperty(PropertyName = "mcNumber")]
    public string McNumber { get; set; }

my service method:

    public List<CarrierBaseDto> SearchCarriersDto()
    {
        var query = _context.Carriers
            .Where(c => !c.Deleted);

        IQueryable<CarrierBaseDto> queryDto = query.ProjectTo<CarrierBaseDto>(_mapperConfig);
        return queryDto.ToList();
    }

My controller method:

    [HttpGet]
    [Route("GetAll")]
    public IActionResult GetAll()
    {
        var carriers = _carrierService.SearchCarriersDto();
        var carriersApi = _mapper.Map<List<CarrierElementAPI>>(carriers);
        return new OkObjectResult(carriersApi);
    }

I want to add abilities to use $orderBy, $filter, $fields params. How to add it to my current architecture?

Body:
I think it was when they originally designed OData it was not intended to be used without DDD, because the metadata was suppose to allow you to handle the filter etc, which is now creating somewhat of a limitation on using it.

There's some hacky workarounds but they only partially work.  The closest thing that I can think of that you can do is generically take in query options and apply them, Then use automapper to project to your queryable,

The only issue is the mappings from Entity to DTO in your automapper setup cannot be complex and must be setup through expression mapping

public Object[] Get(ODataQueryOptions<ProductDTO> options)
{
    ODataQuerySettings settings = new ODataQuerySettings()
    {
        PageSize = 5
    };

    IQueryable results = options.ApplyTo(_products.AsQueryable().ProjectTo<ProductDTO>(), settings);

    results.ToArray()
}


问:
Assign Value from Query with sum to Textbox
I am trying to assign the value from a SQL Query to a text box.

I have the function tied to a ComboBox After update.

I tested the SQL by running it.

How do I assign the result to the Txtbox named prepoffEIC?

Dim MyVar2 As Integer
MyVar2 = Me.SelectedExam.Column(0)
ExamViewQry = "SELECT Sum(tblentrys.entryhours) AS TotalHoursPerFunction FROM tBleExams INNER JOIN (tBlBankList INNER JOIN (tBlExaminers INNER JOIN (tBlEntrys INNER JOIN tBlActivity ON tBlEntrys.EntryActivityID = tBlActivity.FunctionKey) ON tBlExaminers.ExaminersKey = tBlEntrys.EntryExaminerID) ON tBlBankList.BankID = tBlEntrys.EntryInstitutionID) ON (tBlBankList.BankID = tBleExams.ExamBankID) AND (tBleExams.ExamID = tBlEntrys.EntryExamID) WHERE tBlEntrys.EntryActivityID=1 AND tblEntrys.EntryExamStageID=1 AND tBleExams.ExamID=" & MyVar2

Me.prepoffEIC.ControlSource = "ExamViewQry"
Me.prepoffEIC.Requery
```

答:
Create a query using the sql you have, but slightly modded paste it here:

```<code>PARAMETERS eid long;
SELECT Sum(tblentrys.entryhours) AS TotalHoursPerFunction
FROM tBleExams
INNER JOIN (
    tBlBankList INNER JOIN (
        tBlExaminers INNER JOIN (
            tBlEntrys INNER JOIN tBlActivity ON tBlEntrys.EntryActivityID = tBlActivity.FunctionKey
            ) ON tBlExaminers.ExaminersKey = tBlEntrys.EntryExaminerID
        ) ON tBlBankList.BankID = tBlEntrys.EntryInstitutionID
    ) ON (tBlBankList.BankID = tBleExams.ExamBankID)
    AND (tBleExams.ExamID = tBlEntrys.EntryExamID)
WHERE tBlEntrys.EntryActivityID = 1
    AND tblEntrys.EntryExamStageID = 1
    AND tBleExams.ExamID = [eid]
</code>```

lets call it qryGetHours (since i dont know what you need it for.)
in the after update event (also use better naming, this is quick and dirty)

```<code>dim db as DAO.Database
dim qry as QueryDef
dim rs as DAO.Recordset

set db = currentdb
set qry = db.querydefs("qryGetHours")
'this is the name of the query you made above
qry.parameters("eid").value = me.SelectedExam.Column(0)
set rs = qry.openrecordset(dbopendynaset,dbseechanges)
'dbseechanges is more for if you have a sql server backend, but i usually do
if not ( rs.eof and rs.bof) then
    rs.movefirst
    me.prepoffEIC = rs.fields("TotalHoursPerFunction").value
    'This portion assumes that you only get one record back,
    'or if you do end up with more than one, it only goes
    'after the first one.
else
    msgbox "Errors... Errors everywhere."
    'You will definitely want to put something meaningful
    'here relating to it not being able to find the data you
    'were looking for.
end if
if not rs is nothing then
    rs.close
    set rs = nothing
end if
set qry = nothing
set db = nothing
'you will always want to do this portion where you properly
'check if a recordset exists and then close it when you are
'done, along with closing out the querydef and database variables.
</code>```

Body:
Create a query using the sql you have, but slightly modded paste it here:

PARAMETERS eid long;
SELECT Sum(tblentrys.entryhours) AS TotalHoursPerFunction
FROM tBleExams
INNER JOIN (
    tBlBankList INNER JOIN (
        tBlExaminers INNER JOIN (
            tBlEntrys INNER JOIN tBlActivity ON tBlEntrys.EntryActivityID = tBlActivity.FunctionKey
            ) ON tBlExaminers.ExaminersKey = tBlEntrys.EntryExaminerID
        ) ON tBlBankList.BankID = tBlEntrys.EntryInstitutionID
    ) ON (tBlBankList.BankID = tBleExams.ExamBankID)
    AND (tBleExams.ExamID = tBlEntrys.EntryExamID)
WHERE tBlEntrys.EntryActivityID = 1
    AND tblEntrys.EntryExamStageID = 1
    AND tBleExams.ExamID = [eid]

lets call it qryGetHours (since i dont know what you need it for.)
in the after update event (also use better naming, this is quick and dirty)

dim db as DAO.Database
dim qry as QueryDef
dim rs as DAO.Recordset

set db = currentdb
set qry = db.querydefs("qryGetHours")
'this is the name of the query you made above
qry.parameters("eid").value = me.SelectedExam.Column(0)
set rs = qry.openrecordset(dbopendynaset,dbseechanges)
'dbseechanges is more for if you have a sql server backend, but i usually do
if not ( rs.eof and rs.bof) then
    rs.movefirst
    me.prepoffEIC = rs.fields("TotalHoursPerFunction").value
    'This portion assumes that you only get one record back,
    'or if you do end up with more than one, it only goes
    'after the first one.
else
    msgbox "Errors... Errors everywhere."
    'You will definitely want to put something meaningful
    'here relating to it not being able to find the data you
    'were looking for.
end if
if not rs is nothing then
    rs.close
    set rs = nothing
end if
set qry = nothing
set db = nothing
'you will always want to do this portion where you properly
'check if a recordset exists and then close it when you are
'done, along with closing out the querydef and database variables.


问:
Javascript background color transition and reset on HTTP response
I am making a POST request to a server using ajax from Firefox. The input is just some text entry in a box contained within a div:

```<code><div id="mydiv">
    ...stuff...
</div>
</code>```

If the request is successful, I call a handler to reflect that status. If the request is in error, I call a different handler.

```<code>$.ajax({
    type: 'POST',
    data: my_json,
    dataType: "json",
    url: "/my/url",
    success: function(result, status, xhr) {
        success_callback();
    },
    error: function(xhr) {
        error_callback();
    }

});
</code>```

The success callback doesn't do much. In the error callback, I want to change the background color attribute to red to give a visual indication of the error, and then fade back to the original background color (say, white).

Doing an instantaneous color change is easy:

```<code>function success_callback() {

    var element = document.getElementById('mydiv');
    element.style.backgroundColor = "white";

}

function error_callback() {

    var element = document.getElementById('mydiv');
    element.style.backgroundColor = "red";

}
</code>```

I've tried doing the fade using a css animation such as

CSS

```<code>.div.error {
     -webkit-animation-duration: 3s;
     -webkit-animation-name: error;
     animation-duration: 3s;
     animation-name: error;
}
@-webkit-keyframes error {
    from {
        background-color: red;
    }
    to {
        background-color: white;
    }
}
</code>```

and then adding the error class in the JavaScript:

JS

```<code>function error_callback() {

    if ($('.div').hasClass('error')) {
        $('.div').removeClass('error');
    else {
        $('.div').addClass('error');
    }
}
</code>```

This works the first time I send a bad POST request, but doesn't on subsequent bad POSTs because I don't think removeClass is working correctly (or rather I'm not using it correctly).

I've also tried using jquery-ui following this post CSS transition: fade background color, resetting after but that doesn't seem to work for me. Perhaps it something to do with executing an animation in the context of a button click rather than an HTTP response?

Am I heading in the right direction for using this? I'd like to keep within the boundaries of standard jQuery if possible (i.e. stay away from jQuery UI).

答:
The issue is because on each successive request you toggle the background colour instead of setting it to a state which reflects the status of the last request.

To fix this you could instead set the error class on the element, then use a timeout to remove that class after an arbitrary time, 10 seconds for example:

```<code>function error_callback() {
  var $div = $('.div').addClass('error');
  setTimeout(function() {
    $div.removeClass('error');
  }, 10000);
}
</code>```

Note that, as @Taplar mentioned in the comment below, you would also need to remember to remove the error class when a second successful request is made shortly after an initial failure.

Body:
I am making a POST request to a server using ajax from Firefox. The input is just some text entry in a box contained within a div:

    ...stuff...

If the request is successful, I call a handler to reflect that status. If the request is in error, I call a different handler.

$.ajax({
    type: 'POST',
    data: my_json,
    dataType: "json",
    url: "/my/url",
    success: function(result, status, xhr) {
        success_callback();
    },
    error: function(xhr) {
        error_callback();
    }

});

The success callback doesn't do much. In the error callback, I want to change the background color attribute to red to give a visual indication of the error, and then fade back to the original background color (say, white).

Doing an instantaneous color change is easy:

function success_callback() {

    var element = document.getElementById('mydiv');
    element.style.backgroundColor = "white";

}

function error_callback() {

    var element = document.getElementById('mydiv');
    element.style.backgroundColor = "red";

}

I've tried doing the fade using a css animation such as

CSS

.div.error {
     -webkit-animation-duration: 3s;
     -webkit-animation-name: error;
     animation-duration: 3s;
     animation-name: error;
}
@-webkit-keyframes error {
    from {
        background-color: red;
    }
    to {
        background-color: white;
    }
}

and then adding the error class in the JavaScript:

JS

function error_callback() {

    if ($('.div').hasClass('error')) {
        $('.div').removeClass('error');
    else {
        $('.div').addClass('error');
    }
}

This works the first time I send a bad POST request, but doesn't on subsequent bad POSTs because I don't think removeClass is working correctly (or rather I'm not using it correctly).

I've also tried using jquery-ui following this post CSS transition: fade background color, resetting after but that doesn't seem to work for me. Perhaps it something to do with executing an animation in the context of a button click rather than an HTTP response?

Am I heading in the right direction for using this? I'd like to keep within the boundaries of standard jQuery if possible (i.e. stay away from jQuery UI).

Body:
The issue is because on each successive request you toggle the background colour instead of setting it to a state which reflects the status of the last request.

To fix this you could instead set the error class on the element, then use a timeout to remove that class after an arbitrary time, 10 seconds for example:

function error_callback() {
  var $div = $('.div').addClass('error');
  setTimeout(function() {
    $div.removeClass('error');
  }, 10000);
}

Note that, as @Taplar mentioned in the comment below, you would also need to remember to remove the error class when a second successful request is made shortly after an initial failure.


问:
Is there a (repeat-last-command) in Emacs?
Frequently, I've dug into apropos and docs looking for something like the following only to give up to get back to the task at hand:

(repeat-last-command)

do the last C- or M- command I just executed (to be rebound to a fn key)

or sometimes the related:

(describe-last-function)

what keystroke did I just mistakenly issue, the effect of which I'd like to add to my bag of tricks. describe-key is close, but requires knowing what I typed.

Am I simply asking too much from my trusty sidekick?

答: This is old, but Google pops post this up first when I was looking to retrieve the last command I typed at the Emacs prompt.  None of these answers worked for me so I decided to put in my two cents for those who might stumble upon this later on as I did.  I'm using Portacle, but I found what I was looking for in here so I'm hoping it's generic enough to work with different setups.  Anyway, what worked for me is using C-↑ and C-↓ to cycle through the history.  Using M-p and M-n worked as well, but I prefer using the arrows since I use Bash quite a bit.

OwnerDisplayName: ack

LastEditorDisplayName: Paul Dixon


问:
Silverlight, "The type or namespace name 'CookieContainer' does not exist in the namespace 'System.Net'"
I'm running VS2010 pro, and I downloaded a sample Silverlight app written in an older version.  I did the conversion but now when I go to run it, I get this error.  I searched the net, the only recommendation I found was to add a reference to "System.Net" (which didn't make sense, but I did anyway), but this didn't help.  The offending code:</p>

```<code>public System.Net.CookieContainer CookieContainer {...
</code>```

答:
CookieContainer Class Namespace:
  System.Net Assembly:  System (in
  System.dll) Supported in: 4, 3.5 SP1

CookieContainer still exists.

Try deleting the reference in your project then add System.net again.

Body:
I'm running VS2010 pro, and I downloaded a sample Silverlight app written in an older version.  I did the conversion but now when I go to run it, I get this error.  I searched the net, the only recommendation I found was to add a reference to "System.Net" (which didn't make sense, but I did anyway), but this didn't help.  The offending code:

public System.Net.CookieContainer CookieContainer {...


问:
resizing Flex dashboard gauge within a shiny app
Is there a way that i can make a flexdashboard gauge bigger in my shiny app?

I have tried to change the width and height in the UI but that just moves it around on the dashboard. It doesn't make it bigger.

library(shiny)
library(flexdashboard)

fluidRow(column(
         width =  12,
           gaugeOutput('Scale', width = "800px", height = "400px")
       )
)
```

答:
Do you mean something like this?

Just using some simple css.

```<code>library(shiny)
library(flexdashboard)

css <- HTML("
.html-widget.gauge svg {
  height: 400px;
  width: 800px;
}")

ui <- fluidPage(
  tags$head(tags$style(css)),
  fluidRow(column(
    width =  12,
    gaugeOutput('Scale')
  )
  )
)

server <- function(input, output, session) {
  output$Scale <- renderGauge({
    gauge(56, min = 0, max = 100, symbol = '%', label = paste("Test Label"),gaugeSectors(
      success = c(100, 6), warning = c(5,1), danger = c(0, 1), colors = c("#CC6699")
    ))
  })
}

shinyApp(ui, server)
</code>```

Body:
Do you mean something like this?

Just using some simple css.

library(shiny)
library(flexdashboard)

css <- HTML("
.html-widget.gauge svg {
  height: 400px;
  width: 800px;
}")

ui <- fluidPage(
  tags$head(tags$style(css)),
  fluidRow(column(
    width =  12,
    gaugeOutput('Scale')
  )
  )
)

server <- function(input, output, session) {
  output$Scale <- renderGauge({
    gauge(56, min = 0, max = 100, symbol = '%', label = paste("Test Label"),gaugeSectors(
      success = c(100, 6), warning = c(5,1), danger = c(0, 1), colors = c("#CC6699")
    ))
  })
}

shinyApp(ui, server)


问:
How can i see active threads over time from jtl file
When i am executing my test in non-gui mode and trying to see active threads over time from jtl file.It does not show any data.I tried to make changes in properties file but no result.</p>

答: Set "jmeter.save.saveservice.thread_counts" to TRUE in jmeter.properties file</p>


问:
how to access the class variable by string in Python?
The codes are like this:

```<code>class Test:
    a = 1
    def __init__(self):
        self.b=2
</code>```

When I make an instance of Test, I can access its instance variable b like this(using the string "b"):

```<code>test = Test()
a_string = "b"
print test.__dict__[a_string]
</code>```

But it doesn't work for a as self.__dict__ doesn't contain a key named a. Then how can I accessa if I only have a string a?

Thanks!

答:
Since the variable is a class variable one can use the below code:-</p>

```<code>class Test:
    a = 1
    def __init__(self):
        self.b=2

print Test.__dict__["a"]
</code>```

Body:
The codes are like this:

class Test:
    a = 1
    def __init__(self):
        self.b=2

When I make an instance of Test, I can access its instance variable b like this(using the string "b"):

test = Test()
a_string = "b"
print test.__dict__[a_string]

But it doesn't work for a as self.__dict__ doesn't contain a key named a. Then how can I accessa if I only have a string a?

Thanks!

Body:
Since the variable is a class variable one can use the below code:-

class Test:
    a = 1
    def __init__(self):
        self.b=2

print Test.__dict__["a"]


问:
Not able to locate web element on chrome browser's settings popup
I am trying to clear browser cache, for which i need to click on clear data button of browser setting popup, but, i am not able to write xpath for the button on chrome browser

i have tried inspecting the element to find out if the button is on a iframe but its not in iframe, so i have decided to try it with an with out iframe snippet, either of ways the element is not traces out in dom

```<code>    public void clearBrowserCache() throws InterruptedException{
    driver.get("chrome://settings/clearBrowserData");
    Thread.sleep(2000);
    System.out.println(driver.getWindowHandles());
    String windowIds=driver.getWindowHandle();

   // driver.switchTo().frame(windowIds);
      driver.findElement(By.cssSelector(
      [id=clearBrowsingDataConfirm]")).click();

    }
</code>```

Expected is that i should be able to click on the clear data button
Actual is that i am not able to find out the xpath for of the emlement

答:
Depending on which version of chrome you are using, this could work:

```<code>driver.findElement(By.cssSelector("* /deep/ #clearBrowsingDataConfirm")).click();
</code>```

However the /deep/ combinator is deprecated, so it may not work on newer Chrome's versions.

Body:
I am trying to clear browser cache, for which i need to click on clear data button of browser setting popup, but, i am not able to write xpath for the button on chrome browser

i have tried inspecting the element to find out if the button is on a iframe but its not in iframe, so i have decided to try it with an with out iframe snippet, either of ways the element is not traces out in dom

    public void clearBrowserCache() throws InterruptedException{
    driver.get("chrome://settings/clearBrowserData");
    Thread.sleep(2000);
    System.out.println(driver.getWindowHandles());
    String windowIds=driver.getWindowHandle();

   // driver.switchTo().frame(windowIds);
      driver.findElement(By.cssSelector(
      [id=clearBrowsingDataConfirm]")).click();

    }

Expected is that i should be able to click on the clear data button
Actual is that i am not able to find out the xpath for of the emlement

Body:
Depending on which version of chrome you are using, this could work:

driver.findElement(By.cssSelector("* /deep/ #clearBrowsingDataConfirm")).click();

However the /deep/ combinator is deprecated, so it may not work on newer Chrome's versions.


问:
Using Core Data with many images per entity?
I'm new to Core Data and I'm working on my first personal iOS app.

I have an entity, lets call it Car, which has a thumbail as well as a gallery of other images associated with it. The data is synced to an online service using ASIHTTPRequest and JSONKit. The app doesn't need to create new Car's, just display them.

The thumbnail could be around 100kB so I may store that as blob data within the Car entity.

However I'm not sure how I should store the other multiple images?

The images would be around 800kB to 1MB each using so storing them in the Core Data store doesn't seem to be recommended.

The only options I can think of are:

Store the url of each photo within another entity CarImage and rely on ASIHTTPRequest's cache.

Create a folder structure and save each image into it's corresponding Car's folder and keep references to the file path in the CarImage entity

Because the data is synced, there is the potential for Car's to be deleted, so images in folders would have to be deleted as well. I can see this getting out of hand pretty quickly.

I would appreciate any advice. Thanks.

答:
I'd take your first option.

Regarding the images that would have to be deleted: isn't that taken care of automatically by ASIHTTPRequest's cache, once they expire? At least that's what I'd expect from a cache...


问:
How to assign a return value from a SQL Server Function to a Variable
I have function that returns a Date value. I need to assign that return value to a declared variable.

```<code>Declare @Duedate Date
Set @Duedate = SELECT dbo.TATDueDateCaluator('2019-05-10',2)
Select @Duedate
</code>```

Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'SELECT'.

答:
You can simply define it in one line:</p>

```Declare @Duedate Date = dbo.TATDueDateCaluator('2019-05-10',2)

Select Duedate```

Body:
I have function that returns a Date value. I need to assign that return value to a declared variable.

Declare @Duedate Date
Set @Duedate = SELECT dbo.TATDueDateCaluator('2019-05-10',2)
Select @Duedate

Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'SELECT'.

Body:
You can simply define it in one line:

Declare @Duedate Date = dbo.TATDueDateCaluator('2019-05-10',2)

Select Duedate