问:
overload of template template function - explicit call
So, first consider the following where template parameters are known implicitly from the function arguments:

```<code>#include <iostream>
using namespace std;

class A {};
class B {};

template <class T1, class T2>
class C {
    T1 a;
    T2 b;
};

template <class T1>
class D {
    T1 a;
};

template <template<class, class> class TC, class TA, class TB>
void foo(TC<TA, TB> c) {
    std::cout << "T<T,T>" << std::endl;
};

template <template<class> class TD, class TA>
void foo(TD<TA> d){
    std::cout << "T<T>" << std::endl;
};

int main() {
    C<A,B> c;
    D<A> d;

    foo(c);
    foo(d);
}
</code>```

And output is as you'd expect:

```<code>T<T,T>
T<T>
</code>```

However, what if I don't have an instance of class C and D so I need to explicitly call the correct overload?  How would this be done?  i.e., have a main() that consists of:

```<code>int main() {
    foo<C<A,B> >();
    foo<D<A> >();
}
</code>```

I've experimented with a few overloads of foo() as shown below:

```<code>template <template<class, class> class TC>
void foo() {
    std::cout << "T<T,T>" << std::endl;
};

template <template<class> class TD>
void foo(){
    std::cout << "T<T>" << std::endl;
};

template <template<class, class> class TC, class TA, class TB>
void foo() {
    std::cout << "T<T,T>" << std::endl;
};

template <template<class> class TD, class TA>
void foo(){
    std::cout << "T<T>" << std::endl;
};
</code>```

However, this (and all permutations I've been able to think of) simply results in a series of errors along the lines of the (abbreviated) output shown below

```<code>prog.cpp: In function 'int main()':
prog.cpp:44:18: error: no matching function for call to 'foo()'
     foo<C<A,B> >();
                  ^
prog.cpp:44:18: note: candidates are:
prog.cpp:19:6: note: template<template<class, class> class TC> void foo()
 void foo() {
      ^
prog.cpp:19:6: note:   template argument deduction/substitution failed:
prog.cpp:24:6: note: template<template<class> class TD> void foo()
 void foo(){
      ^
prog.cpp:24:6: note:   template argument deduction/substitution failed:
</code>```

Is what I'm looking to do even allowable?  If so, where am I messing up?

---- EDIT ----

So as apple apple pointed out if my main() is as follows:

```<code>int main() {
    foo<C, A, B>();
    foo<D, A>();
}
</code>```

I get the output as expected.

However, my real-world case winds up being more complex.  I'll expand a bit here.  The legacy code has (hundreds) of typedefs defined in headers elsewhere along the lines of:

```<code>typedef C<A, B> type_117;
typedef D<A>    type_252;
</code>```

The class I'm working on is templated and is instantiated with one of those typedefs as the templating argument.  So something along the lines of:

```<code>template <class Type>
class Test
{
public:
   Test();
   SomeClass mSC;
}
Test::Test()
  : mSC(foo<Type>())
{
};
</code>```

where Test was instantiated as

```<code>Test<type_117> aTest;
</code>```

So I've been trying to figure out how to write foo() for this context.  At the point I call foo() within my Test's initializer am I able to "decompose" it to produce the <C,A,B> form?  Or have I hit a roadblock and need to rework some of the existing framework?

答:
You may use partial specialization (and variadic template):</p>

```<code>template <class Type>
class Test;

template <template <typename ...> class C, typename ... Ts>
class Test<C<Ts...>>
{
public:
   Test() : mSC(foo<C, Ts...>()) {}
   SomeClass mSC;
};
</code>```

Body:
So, first consider the following where template parameters are known implicitly from the function arguments:

#include <iostream>
using namespace std;

class A {};
class B {};

template <class T1, class T2>
class C {
    T1 a;
    T2 b;
};

template <class T1>
class D {
    T1 a;
};

template <template<class, class> class TC, class TA, class TB>
void foo(TC<TA, TB> c) {
    std::cout << "T<T,T>" << std::endl;
};

template <template<class> class TD, class TA>
void foo(TD<TA> d){
    std::cout << "T<T>" << std::endl;
};

int main() {
    C c;
    D d;

    foo(c);
    foo(d);
}

And output is as you'd expect:

T<T,T>
T<T>

However, what if I don't have an instance of class C and D so I need to explicitly call the correct overload?  How would this be done?  i.e., have a main() that consists of:

int main() {
    foo<C >();
    foo<D >();
}

I've experimented with a few overloads of foo() as shown below:

template <template<class, class> class TC>
void foo() {
    std::cout << "T<T,T>" << std::endl;
};

template <template<class> class TD>
void foo(){
    std::cout << "T<T>" << std::endl;
};

template <template<class, class> class TC, class TA, class TB>
void foo() {
    std::cout << "T<T,T>" << std::endl;
};

template <template<class> class TD, class TA>
void foo(){
    std::cout << "T<T>" << std::endl;
};

However, this (and all permutations I've been able to think of) simply results in a series of errors along the lines of the (abbreviated) output shown below

prog.cpp: In function 'int main()':
prog.cpp:44:18: error: no matching function for call to 'foo()'
     foo<C >();
                  ^
prog.cpp:44:18: note: candidates are:
prog.cpp:19:6: note: template<template<class, class> class TC> void foo()
 void foo() {
      ^
prog.cpp:19:6: note:   template argument deduction/substitution failed:
prog.cpp:24:6: note: template<template<class> class TD> void foo()
 void foo(){
      ^
prog.cpp:24:6: note:   template argument deduction/substitution failed:

Is what I'm looking to do even allowable?  If so, where am I messing up?

---- EDIT ----

So as apple apple pointed out if my main() is as follows:

int main() {
    foo<C, A, B>();
    foo<D, A>();
}

I get the output as expected.

However, my real-world case winds up being more complex.  I'll expand a bit here.  The legacy code has (hundreds) of typedefs defined in headers elsewhere along the lines of:

typedef C type_117;
typedef D    type_252;

The class I'm working on is templated and is instantiated with one of those typedefs as the templating argument.  So something along the lines of:

template <class Type>
class Test
{
public:
   Test();
   SomeClass mSC;
}
Test::Test()
  : mSC(foo<Type>())
{
};

where Test was instantiated as

Test<type_117> aTest;

So I've been trying to figure out how to write foo() for this context.  At the point I call foo() within my Test's initializer am I able to "decompose" it to produce the <C,A,B> form?  Or have I hit a roadblock and need to rework some of the existing framework?

Body:
You may use partial specialization (and variadic template):

template <class Type>
class Test;

template <template <typename ...> class C, typename ... Ts>
class Test<C<Ts...>>
{
public:
   Test() : mSC(foo<C, Ts...>()) {}
   SomeClass mSC;
};


来源: stackexchange

问:
How to print an equation in Ruby
I've got a question.

```<code>1.0X + 1.0Y + -7.0 = 0
</code>```

How can I print an equation better?

For example, instead of +- 7.0 I'd like to print -7.0; or in a case with zero coefficients.

Thanks

答:
Prints an equation with full control of formating

```<code>a = b = 1
c = -7
puts "%0.1fX + %0.1fY %s %0.1f = %d"%[ a, b, c < 0 ? '-' : '+', c.abs, 0 ]
</code>```

output:

```<code>1.0X + 1.0Y - 7.0 = 0
</code>```

Documentation: Ruby's % string operator / sprintf

ContentLicense: CC BY-SA 3.0

Title: How to print an equation in Ruby

Body:
I've got a question.

1.0X + 1.0Y + -7.0 = 0

How can I print an equation better?

For example, instead of +- 7.0 I'd like to print -7.0; or in a case with zero coefficients.

Thanks

Body:
Prints an equation with full control of formating

a = b = 1
c = -7
puts "%0.1fX + %0.1fY %s %0.1f = %d"%[ a, b, c < 0 ? '-' : '+', c.abs, 0 ]

output:

1.0X + 1.0Y - 7.0 = 0

Documentation: Ruby's % string operator / sprintf


问:
How to Create Object Copy
Right now I'm working with two functions across two .cpp files. Let's say I'm working with a struct called someStruct:

```<code>struct someStruct {
  int num;
}
</code>```

A.cpp:

```<code>int main() {
  someStruct *a = NULL;
  bool ret;
  ret = foo(a);
  std::cout << a->num; // should print 5
}
</code>```

B.cpp:

```<code>bool foo(someStruct *a) {
  someStruct *b = someFunction(); // points to an instance of someStruct on the stack
  // note that b->num should hold 5

  // need something here
  // ATTEMPT 1:
  a = new someStruct(*b);
  // ATTEMPT 2
  a = (someStruct *)malloc(sizeof(someStruct));
  a = memcpy(a, b, sizeof(someStruct));
}
</code>```

What I want to accomplish is for a in the main function to end up pointing to an instance of someStruct that has the same values as the struct pointer b in foo().

Neither of the attempts I listed worked.

答:
Terms: HEAP vs STACK

Your question should be named "how to create object copy". One reason is that original object location doesn't matter, creating copy from object on stack and from object on heap are pretty much the same. The second reason is that your current code tries copying object pointed by someFunction() return value which may have sense only if someFucntion() creted object on heap. Otherwise, if someFunction() created object on stack like this:

```<code>someStruct tmp;
tmp.num = 5;
return &tmp;
</code>```

then once someFunction() finishes execution, its stack frame is freed and might be reused for other functions stacks. Thus 'tmp' structure is located in memory, which can be overwritten any moment, so you can't rely on its data. Never use pointer to local variables after local variable goes out of scope.

Copying object

Well, your ATTEMPT 1 is fine. Using new for creating class or structure calls constructor to build object. You passed another object as parameter, so copy constructor is called. You didn't write copy constructor, but compiler created trivial one automatically, so it correctly copied all fields from original object to newly created.

However, cout didn't show expected output due to bug in another part of the program. Calling foo(a); means passing copy of a as a parameter to foo. So you don't change main's a value within foo, but change value of foo's copy of a. On return to main, a is still NULL and can't be dereferenced. As minimal fix, you need to pass a (which is already pointer, so it's a bit confusing) by pointer or by reference instead of passing it by value. Example:

```<code>int main() {
  someStruct *a = NULL;
  bool ret;
  ret = foo(&a);
  std::cout << a->num; // should print 5
  delete a;
  return ret;
}

bool foo(someStruct **x) {
  someStruct *b = someFunction(); // points to an instance of someStruct on the heap
  *x = new someStruct(*b);
  delete b;
  return true;
};
</code>```

Make a good habit of calling delete eventually for each dynamically allocated buffer, memory leakages may become quite painful on larger programs.

Title: How to Create Object Copy

Body:
Right now I'm working with two functions across two .cpp files. Let's say I'm working with a struct called someStruct:

struct someStruct {
  int num;
}

A.cpp:

int main() {
  someStruct *a = NULL;
  bool ret;
  ret = foo(a);
  std::cout <num; // should print 5
}

B.cpp:

bool foo(someStruct *a) {
  someStruct *b = someFunction(); // points to an instance of someStruct on the stack
  // note that b->num should hold 5

  // need something here
  // ATTEMPT 1:
  a = new someStruct(*b);
  // ATTEMPT 2
  a = (someStruct *)malloc(sizeof(someStruct));
  a = memcpy(a, b, sizeof(someStruct));
}

What I want to accomplish is for a in the main function to end up pointing to an instance of someStruct that has the same values as the struct pointer b in foo().

Neither of the attempts I listed worked.

Body:
Terms: HEAP vs STACK

Your question should be named "how to create object copy". One reason is that original object location doesn't matter, creating copy from object on stack and from object on heap are pretty much the same. The second reason is that your current code tries copying object pointed by someFunction() return value which may have sense only if someFucntion() creted object on heap. Otherwise, if someFunction() created object on stack like this:

someStruct tmp;
tmp.num = 5;
return &tmp;

then once someFunction() finishes execution, its stack frame is freed and might be reused for other functions stacks. Thus 'tmp' structure is located in memory, which can be overwritten any moment, so you can't rely on its data. Never use pointer to local variables after local variable goes out of scope.

Copying object

Well, your ATTEMPT 1 is fine. Using new for creating class or structure calls constructor to build object. You passed another object as parameter, so copy constructor is called. You didn't write copy constructor, but compiler created trivial one automatically, so it correctly copied all fields from original object to newly created.

However, cout didn't show expected output due to bug in another part of the program. Calling foo(a); means passing copy of a as a parameter to foo. So you don't change main's a value within foo, but change value of foo's copy of a. On return to main, a is still NULL and can't be dereferenced. As minimal fix, you need to pass a (which is already pointer, so it's a bit confusing) by pointer or by reference instead of passing it by value. Example:

int main() {
  someStruct *a = NULL;
  bool ret;
  ret = foo(&a);
  std::cout << a->num; // should print 5
  delete a;
  return ret;
}

bool foo(someStruct **x) {
  someStruct *b = someFunction(); // points to an instance of someStruct on the heap
  *x = new someStruct(*b);
  delete b;
  return true;
};

Make a good habit of calling delete eventually for each dynamically allocated buffer, memory leakages may become quite painful on larger programs.


问:
Reserved SQL keyword 'User' is not permitted as simple type name
When I gave the roo command

```<code>entity --class  ~.domain.User
</code>```

in the roo shell, I got

```<code>Reserved SQL keyword 'User' is not permitted as simple type name
</code>```

What I want to know is that, is there a way to gave alias name to the entity ? Because I do have a couple of entities which name are not permitted as above. Or is there a way to overcome this kind of problem ?

Any help will be greatly appreciated. Thank you very much.

答:
You could try to add the  --permitReservedWords option to the entity command.

https://jira.springsource.org/browse/ROO-1502

ContentLicense: CC BY-SA 2.5

Body:
When I gave the roo command

entity --class  ~.domain.User

in the roo shell, I got

Reserved SQL keyword 'User' is not permitted as simple type name

What I want to know is that, is there a way to gave alias name to the entity ? Because I do have a couple of entities which name are not permitted as above. Or is there a way to overcome this kind of problem ?

Any help will be greatly appreciated. Thank you very much.


问:
Text wont center on phone
I have a weird problem here, the text and images aren't aligning to the center, I've been coding this site from scratch and it works pretty well when I test it on the computer, but when I try it on the phone it doesn't work. Here are the pictures (From the computer and the phone)

---------COMPUTER
Computer's resized Firefox windows 1

---------PHONE
Phone's screenshot 1 - Chrome

Here's my code, I've been using bootstrap and normal HTML, CSS and basic PHP and JavaScript

```<code><nav class="navbar navbar-default nav_menu_head">
<div class="container-fluid">
<div class="row">
    <nav class="navbar navbar-default nav_menu_head">
  <div class="container-fluid">
<div class="row">
   <div class="navbar-header">

      <div class="col-md-6 col-xs-10">
       <a href="index.php" class="navbar-brand" rel="home">
        <img class="img-responsive logo" src="img/logo2.png"></a>

      </div>
      <div class="col-xs-2">
  <button type="button" class="navbar-toggle navbar_colapse" data-toggle="collapse" data-target="#myNavbar">
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
  </button>
     </div>

      <div class="collapse navbar-collapse col-md-6 text-justify-xs" id="myNavbar">
     <ul class="nav navbar-nav navbar-right nav_menu_head" >
  <li ><a href="index.php#empresa" >EMPRESA</a></li>
  <li ><a href="productos.php">PRODUCTO</a></li>
  <li><a href="index.php#contacto">CONTACTO</a></li>
<!--  <li ><a href="#">SOPORTE TÉCNICO</a></li -->
</ul>
</div>
</div>
 </nav>
</code>```

And here´s the CSS

```<code>.text_box{width: 100%;
height: 200px;}
.navbar-header{float: none;}

.text-justify-xs {
text-align: center;
}

.img-responsive.menu_image{margin: 0 auto;}
.collapse.navbar-collapse.col-md-6.text-justify-xs {border-width: 0px;}
</code>```

答: This looks like a mismatch between the display property values on your ul. It's not uncommon for browsers to have different default values. Try setting display: block on your .nav_menu_head.

Title: Text wont center on phone

Body:
I have a weird problem here, the text and images aren't aligning to the center, I've been coding this site from scratch and it works pretty well when I test it on the computer, but when I try it on the phone it doesn't work. Here are the pictures (From the computer and the phone)

---------COMPUTER
Computer's resized Firefox windows 1

---------PHONE
Phone's screenshot 1 - Chrome

Here's my code, I've been using bootstrap and normal HTML, CSS and basic PHP and JavaScript

  <button type="button" class="navbar-toggle navbar_colapse" data-toggle="collapse" data-target="#myNavbar">

  </button>

EMPRESA

PRODUCTO

CONTACTO

And here´s the CSS

.text_box{width: 100%;
height: 200px;}
.navbar-header{float: none;}

.text-justify-xs {
text-align: center;
}

.img-responsive.menu_image{margin: 0 auto;}
.collapse.navbar-collapse.col-md-6.text-justify-xs {border-width: 0px;}


问:
function type with ternary operator
I try this code:

```<code>    int a=1;
    std::function<int (int, int)> getM = a?
    [](int x, int y) {
        return (x+y);
    } :
    [](int x, int y) {
        return (x*y);
    };

    cout<<getM(1,2);
</code>```

In visual studio it gives an error:
error C2446: ':' : no conversion from 'wmain::' to 'wmain::'
1>          No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

In GCC it's compiled.  I suppose that GCC is the correct behaviour, but I'm not sure. What are other options to make this on VS2013?

答:
I can confirm it also doesn't build with VS 2015 update 3.

What are other options?

Well, a standard if/else is always the alternative for any ternary operation:

```<code>std::function<int (int, int)> getM;;

if (a)
    getM = [](int x, int y) { return (x + y); };
else
    getM = [](int x, int y) { return (x * y); };
</code>```

Title: function type with ternary operator

Body:
I try this code:

    int a=1;
    std::function<int (int, int)> getM = a?
    [](int x, int y) {
        return (x+y);
    } :
    [](int x, int y) {
        return (x*y);
    };

    cout<<getM(1,2);

In visual studio it gives an error:
error C2446: ':' : no conversion from 'wmain::' to 'wmain::'
1>          No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

In GCC it's compiled.  I suppose that GCC is the correct behaviour, but I'm not sure. What are other options to make this on VS2013?

Body:
I can confirm it also doesn't build with VS 2015 update 3.

What are other options?

Well, a standard if/else is always the alternative for any ternary operation:

std::function<int (int, int)> getM;;

if (a)
    getM = [](int x, int y) { return (x + y); };
else
    getM = [](int x, int y) { return (x * y); };


问:
Small JavaScript/jQuery mouseleave question
I got this small JavaScript using jQuery that slides down a ul when an image is clicked:

```<code>$(document).ready(function () {
$('img.menu_class').click(function() {
$('ul.the_menu').slideToggle('medium');
});

});
</code>```

I was wondering if I could modify it to recognize when the mouse leaves the ul/image and make it slide back instead of having the user click on the image again. If I use something else than click() it would (naturally) only apply to the image and won't recognize the ul as an object. Any suggestions?

答:
Try this

$('img.menu_class').bind('mouseleave',function() {
$('ul.the_menu').slideToggle('medium');
});

or

$('img.menu_class').bind('hover',function() {
$('ul.the_menu').slideToggle('medium');
});

Use this code.

This is my updated code

Use this code to slidedown ur list once mouse hover on image and remains open

```
$(document).ready(function () {

$('img.menu_class').bind('hover mouseleave',function() {
 $('ul.the_menu').slideDown('medium');
});

//to close ul

$('#id_of_close_element').bind('click',function() {
 $('ul.the_menu').slideUp('medium');
});

});
```

Body:
I got this small JavaScript using jQuery that slides down a ul when an image is clicked:

$(document).ready(function () {
$('img.menu_class').click(function() {
$('ul.the_menu').slideToggle('medium');
});

});

I was wondering if I could modify it to recognize when the mouse leaves the ul/image and make it slide back instead of having the user click on the image again. If I use something else than click() it would (naturally) only apply to the image and won't recognize the ul as an object. Any suggestions?

Body:
Try this

$('img.menu_class').bind('mouseleave',function() {
$('ul.the_menu').slideToggle('medium');
});

or

$('img.menu_class').bind('hover',function() {
$('ul.the_menu').slideToggle('medium');
});

Use this code.

This is my updated code

Use this code to slidedown ur list once mouse hover on image and remains open

$(document).ready(function () {

$('img.menu_class').bind('hover mouseleave',function() {
 $('ul.the_menu').slideDown('medium');
});

//to close ul

$('#id_of_close_element').bind('click',function() {
 $('ul.the_menu').slideUp('medium');
});

});


问:
Update buffer and reset the locking-mode back to original one
Lets say we have a procedure which takes in a buffer-parameter:

myprocedure.p:

```<code>DEF PARAM BUFFER bufferParameter FOR DatabaseTable.

/* Get the same buffer in EXCLUSIVE-LOCK for updating */
FIND CURRENT bufferParameter EXCLUSIVE-LOCK.

/* Update the value */
ASSIGN bufferParameter.MyField = "new value".

/* Reset the locking mode back to the original one? */
FIND CURRENT bufferParameter NO-LOCK.
</code>```

The problem with this approach is that it is possibly changing the original locking-mode of the passed buffer parameter. It is possible that the buffer was in EXCLUSIVE-LOCK or f.ex in NO-LOCK. By changing the locking-mode, this procedure could invoke updating errors in some other programs using this same buffer.

Another solution would be to create a new temporary buffer for the same table, and then update the database thru that buffer (without touching the passed parameter buffer). The con of this approach is that the original passed buffer parameter will become 'out-of-date'. It would require a new database query to update it's 'MyField' value to match the one in the database.

How I could reset the buffer's locking-mode back to the original one after updating it's fields?

答:
This thread might be useful background - it talks about how to figure out the current lock status.

```<code>http://stackoverflow.com/questions/26136842/progress-4gl-display-buffer-lock-type?rq=1
</code>```

Ultimately I think this  is what you really need:

```<code>    /* lightly tested psuedo code...
     */

    procedure updateMyField:

      define input parameter myRowid  as rowid.

      define buffer updMyTable for myTable.  /* this limits the scope of the buffer to this procedure */

      do for updMyTable transaction:  /* FOR "strong scopes" the buffer to this block */
        find updMyTable exclusive-lock where rowid( updMyTable ) = myRowid no-error.  /* the EXCLUSIVE-LOCK is scoped the FOR block -- when we leave the block it is released */
        if available updMyTable then
          assign
            updMyTable.myField = "new value"
          .
         else
          do:
            message "could not get an exclusive-lock on myTable".
            /* or whatever error handling you need... */
          end.
      end.  /* the transaction is committed and the lock is released -- no need to change its status */

      return.

    end.

    /* main block
     */

    find first myTable no-lock.
    display myTable.myField.
    pause.

    run updateMyField ( rowid( myTable )).

    find first myTable no-lock.
    display myTable.myField.
    pause.
</code>```

Body:
Lets say we have a procedure which takes in a buffer-parameter:

myprocedure.p:

DEF PARAM BUFFER bufferParameter FOR DatabaseTable.

/* Get the same buffer in EXCLUSIVE-LOCK for updating */
FIND CURRENT bufferParameter EXCLUSIVE-LOCK.

/* Update the value */
ASSIGN bufferParameter.MyField = "new value".

/* Reset the locking mode back to the original one? */
FIND CURRENT bufferParameter NO-LOCK.

The problem with this approach is that it is possibly changing the original locking-mode of the passed buffer parameter. It is possible that the buffer was in EXCLUSIVE-LOCK or f.ex in NO-LOCK. By changing the locking-mode, this procedure could invoke updating errors in some other programs using this same buffer.

Another solution would be to create a new temporary buffer for the same table, and then update the database thru that buffer (without touching the passed parameter buffer). The con of this approach is that the original passed buffer parameter will become 'out-of-date'. It would require a new database query to update it's 'MyField' value to match the one in the database.

How I could reset the buffer's locking-mode back to the original one after updating it's fields?

Body:
This thread might be useful background - it talks about how to figure out the current lock status.

http://stackoverflow.com/questions/26136842/progress-4gl-display-buffer-lock-type?rq=1

Ultimately I think this  is what you really need:

    /* lightly tested psuedo code...
     */

    procedure updateMyField:

      define input parameter myRowid  as rowid.

      define buffer updMyTable for myTable.  /* this limits the scope of the buffer to this procedure */

      do for updMyTable transaction:  /* FOR "strong scopes" the buffer to this block */
        find updMyTable exclusive-lock where rowid( updMyTable ) = myRowid no-error.  /* the EXCLUSIVE-LOCK is scoped the FOR block -- when we leave the block it is released */
        if available updMyTable then
          assign
            updMyTable.myField = "new value"
          .
         else
          do:
            message "could not get an exclusive-lock on myTable".
            /* or whatever error handling you need... */
          end.
      end.  /* the transaction is committed and the lock is released -- no need to change its status */

      return.

    end.

    /* main block
     */

    find first myTable no-lock.
    display myTable.myField.
    pause.

    run updateMyField ( rowid( myTable )).

    find first myTable no-lock.
    display myTable.myField.
    pause.


问:
C++ - segmentation fault on second binary search
I have a class ledger, whose instances are supposed to store instances of a member class company in two vectors combyID and combyname, sorted by two different criteria - ID and name (both are strings). The vectors start out empty, so instead of sorting them after each new addition of an instance of the member class, a customized binary search methods binsID and binsName search the vectors for the element to be added and if the element isn't found, it is inserted in the vectors. The insert() position is defined by the idx value, modified by the binary search method.

The problem lies within the method NewCo, which calls both binary search methods and eventually inserts the element to the vectors. When the program is run with more than just one NewCo call in the main function, Segmentation fault (core dumped) error is given. The error doesn't appear either if the binsID method isn't called or the insert() isn't called on combyID (omitting the insertion to that vector). I am posting both the code and the valgrind analysis.

The code:

```<code>#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <string>
#include <vector>
using namespace std;

class ledger
{
  public:
    bool NewCo (string name, string ID)
    {
        unsigned int idx_id = 0, idx_name = 0;
        bool found1 = binsID(combyID, idx_id, ID);  //line 14
        bool found2 = binsName(combyname, idx_name, name);
        if (found1 == false && found2 == false)
        {
            company co;
            co.co_name = name;
            co.co_id = ID;
            combyID.insert(combyID.begin() + idx_id, co);
            combyname.insert(combyname.begin() + idx_name, co);
            return 1;
        }
        return 0;
    }
  private:
      class company
      {
      public:
          string co_name;
          string co_id;
      };
      vector <company> combyID;
      vector <company> combyname;
      bool binsName(vector <company> vek, unsigned int & idx, string val)
      {
          if (vek.size() == 0) return false;
          unsigned int begin = 0, end = vek.size() - 1, mid;
          while(begin <= end)
          {
              mid = (begin + end) / 2;
              idx = mid;
              if (vek[mid].co_name == val)
              {
                  idx = mid;
                  return true;
              }
              else if (val < vek[mid].co_name)
                  end = mid - 1;
              else
                  begin = mid + 1;
          }
        if (vek[idx].co_name < val) idx++;
        return false;
      }
    bool binsID(vector <company> vek, unsigned int & idx, string val)
      {
        if (vek.size() == 0) return false;
          unsigned int begin = 0, end = vek.size() - 1, mid;
          while(begin <= end)
          {
              mid = (begin + end) / 2;
              idx = mid;
              if (vek[mid].co_id == val)  //line 66
              {
                  idx = mid;
                  return true;
              }
              else if (val < vek[mid].co_id)
                  end = mid - 1;
              else
                  begin = mid + 1;
          }
        if (vek[idx].co_id < val) idx++;
        return false;
      }
};

int main ( void )
{
  ledger b1;
  b1.NewCo( "ABC", "123.456.789" );
  b1.NewCo( "DEF", "123.456" );  //line 85

  return 0;
}
</code>```

Valgrind:

```<code>==6775== Command: ./a.out -g
==6775==
==6775== Invalid read of size 8
==6775==    at 0x4F597B0: std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::size() const (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21)
==6775==    by 0x401C2A: __gnu_cxx::__enable_if<std::__is_char<char>::__value, bool>::__type std::operator==<char>(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) (basic_string.h:4913)
==6775==    by 0x40177B: ledger::binsID(std::vector<ledger::company, std::allocator<ledger::company> >, unsigned int&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >) (main.cpp:66)
==6775==    by 0x40138B: ledger::NewCo(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >) (main.cpp:14)
==6775==    by 0x40109E: main (main.cpp:85)
==6775==  Address 0x2005ab5d68 is not stack'd, malloc'd or (recently) free'd
==6775==
==6775==
==6775== Process terminating with default action of signal 11 (SIGSEGV)
==6775==  Access not within mapped region at address 0x2005AB5D68
==6775==    at 0x4F597B0: std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::size() const (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21)
==6775==    by 0x401C2A: __gnu_cxx::__enable_if<std::__is_char<char>::__value, bool>::__type std::operator==<char>(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) (basic_string.h:4913)
==6775==    by 0x40177B: ledger::binsID(std::vector<ledger::company, std::allocator<ledger::company> >, unsigned int&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >) (main.cpp:66)
==6775==    by 0x40138B: ledger::NewCo(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >) (main.cpp:14)
==6775==    by 0x40109E: main (main.cpp:85)
==6775==  If you believe this happened as a result of a stack
==6775==  overflow in your program's main thread (unlikely but
==6775==  possible), you can try to increase the size of the
==6775==  main thread stack using the --main-stacksize= flag.
==6775==  The main thread stack size used in this run was 8388608.
==6775==
==6775== HEAP SUMMARY:
==6775==     in use at exit: 72,896 bytes in 4 blocks
==6775==   total heap usage: 4 allocs, 0 frees, 72,896 bytes allocated
==6775==
==6775== LEAK SUMMARY:
==6775==    definitely lost: 0 bytes in 0 blocks
==6775==    indirectly lost: 0 bytes in 0 blocks
==6775==      possibly lost: 0 bytes in 0 blocks
==6775==    still reachable: 72,896 bytes in 4 blocks
==6775==         suppressed: 0 bytes in 0 blocks
==6775== Rerun with --leak-check=full to see details of leaked memory
==6775==
==6775== For counts of detected and suppressed errors, rerun with: -v
==6775== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
Segmentation fault (core dumped)
</code>```

答:
You'll want to review your algorithms in both binsName() and binsID() methods.

For your second pass, the statement:

```<code>end = mid - 1;
</code>```

is producing an end value of -1 (or in this case, UINT_MAX since you're using unsigned integers) as the value of mid is 0.

Body:
I have a class ledger, whose instances are supposed to store instances of a member class company in two vectors combyID and combyname, sorted by two different criteria - ID and name (both are strings). The vectors start out empty, so instead of sorting them after each new addition of an instance of the member class, a customized binary search methods binsID and binsName search the vectors for the element to be added and if the element isn't found, it is inserted in the vectors. The insert() position is defined by the idx value, modified by the binary search method.

The problem lies within the method NewCo, which calls both binary search methods and eventually inserts the element to the vectors. When the program is run with more than just one NewCo call in the main function, Segmentation fault (core dumped) error is given. The error doesn't appear either if the binsID method isn't called or the insert() isn't called on combyID (omitting the insertion to that vector). I am posting both the code and the valgrind analysis.

The code:

#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <string>
#include <vector>
using namespace std;

class ledger
{
  public:
    bool NewCo (string name, string ID)
    {
        unsigned int idx_id = 0, idx_name = 0;
        bool found1 = binsID(combyID, idx_id, ID);  //line 14
        bool found2 = binsName(combyname, idx_name, name);
        if (found1 == false && found2 == false)
        {
            company co;
            co.co_name = name;
            co.co_id = ID;
            combyID.insert(combyID.begin() + idx_id, co);
            combyname.insert(combyname.begin() + idx_name, co);
            return 1;
        }
        return 0;
    }
  private:
      class company
      {
      public:
          string co_name;
          string co_id;
      };
      vector <company> combyID;
      vector <company> combyname;
      bool binsName(vector <company> vek, unsigned int & idx, string val)
      {
          if (vek.size() == 0) return false;
          unsigned int begin = 0, end = vek.size() - 1, mid;
          while(begin <= end)
          {
              mid = (begin + end) / 2;
              idx = mid;
              if (vek[mid].co_name == val)
              {
                  idx = mid;
                  return true;
              }
              else if (val < vek[mid].co_name)
                  end = mid - 1;
              else
                  begin = mid + 1;
          }
        if (vek[idx].co_name < val) idx++;
        return false;
      }
    bool binsID(vector <company> vek, unsigned int & idx, string val)
      {
        if (vek.size() == 0) return false;
          unsigned int begin = 0, end = vek.size() - 1, mid;
          while(begin <= end)
          {
              mid = (begin + end) / 2;
              idx = mid;
              if (vek[mid].co_id == val)  //line 66
              {
                  idx = mid;
                  return true;
              }
              else if (val < vek[mid].co_id)
                  end = mid - 1;
              else
                  begin = mid + 1;
          }
        if (vek[idx].co_id < val) idx++;
        return false;
      }
};

int main ( void )
{
  ledger b1;
  b1.NewCo( "ABC", "123.456.789" );
  b1.NewCo( "DEF", "123.456" );  //line 85

  return 0;
}

Valgrind:

==6775== Command: ./a.out -g
==6775==
==6775== Invalid read of size 8
==6775==    at 0x4F597B0: std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::size() const (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21)
==6775==    by 0x401C2A: __gnu_cxx::__enable_if<std::__is_char<char>::__value, bool>::__type std::operator==<char>(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) (basic_string.h:4913)
==6775==    by 0x40177B: ledger::binsID(std::vector<ledger::company, std::allocator<ledger::company> >, unsigned int&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >) (main.cpp:66)
==6775==    by 0x40138B: ledger::NewCo(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >) (main.cpp:14)
==6775==    by 0x40109E: main (main.cpp:85)
==6775==  Address 0x2005ab5d68 is not stack'd, malloc'd or (recently) free'd
==6775==
==6775==
==6775== Process terminating with default action of signal 11 (SIGSEGV)
==6775==  Access not within mapped region at address 0x2005AB5D68
==6775==    at 0x4F597B0: std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::size() const (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21)
==6775==    by 0x401C2A: __gnu_cxx::__enable_if<std::__is_char<char>::__value, bool>::__type std::operator==<char>(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) (basic_string.h:4913)
==6775==    by 0x40177B: ledger::binsID(std::vector<ledger::company, std::allocator<ledger::company> >, unsigned int&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >) (main.cpp:66)
==6775==    by 0x40138B: ledger::NewCo(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >) (main.cpp:14)
==6775==    by 0x40109E: main (main.cpp:85)
==6775==  If you believe this happened as a result of a stack
==6775==  overflow in your program's main thread (unlikely but
==6775==  possible), you can try to increase the size of the
==6775==  main thread stack using the --main-stacksize= flag.
==6775==  The main thread stack size used in this run was 8388608.
==6775==
==6775== HEAP SUMMARY:
==6775==     in use at exit: 72,896 bytes in 4 blocks
==6775==   total heap usage: 4 allocs, 0 frees, 72,896 bytes allocated
==6775==
==6775== LEAK SUMMARY:
==6775==    definitely lost: 0 bytes in 0 blocks
==6775==    indirectly lost: 0 bytes in 0 blocks
==6775==      possibly lost: 0 bytes in 0 blocks
==6775==    still reachable: 72,896 bytes in 4 blocks
==6775==         suppressed: 0 bytes in 0 blocks
==6775== Rerun with --leak-check=full to see details of leaked memory
==6775==
==6775== For counts of detected and suppressed errors, rerun with: -v
==6775== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
Segmentation fault (core dumped)

Body:
You'll want to review your algorithms in both binsName() and binsID() methods.

For your second pass, the statement:

end = mid - 1;

is producing an end value of -1 (or in this case, UINT_MAX since you're using unsigned integers) as the value of mid is 0.


问:
Substring between 2 indexes using recursion
I started learning Java, currently I'm playing around with recursion.

I wanted to try and make a substring method which will substring from both sides by 1 character until we get the desired string.

I managed to do the first part but I'm having problem figuring out how to substring from the back.

n and m should be the indexes between which we want to substring (inclusive).

In this example result of method should be "bstri"

Here is my code:

```<code>public static void main(String[] args) {
    String s = "substringme";

    System.out.println(rec(s,2,6));
}

public static String rec(String s, int n, int m) {
    if(n == 0 /* && missing 2nd part of condition */){
        return s;
    } else {
        if(n>0){
            s = s.substring(1);
            n--;
        }
        if(/* missing condition */){
            s= s.substring(0, s.length()-1);
        }
        return rec(s,n,m);
    }
}
</code>```

I would appreciate any help I can get.

答:
I propose that you do m-- in the first loop because the definition of m as an index changes when you shorten s from the front.

```<code> public static String rec(String s, int n, int m) {
         if(n == 0 && m == s.length() - 1){
             return s;
         } else {
             if (n > 0) {
                 s = s.substring(1);
                 n--;
                 m--;
             }
             if (m < s.length() - 1) {
                 s = s.substring(0, s.length() - 1);
             }
             return rec(s, n, m);
         }
     }
</code>```

Body:
I started learning Java, currently I'm playing around with recursion.

I wanted to try and make a substring method which will substring from both sides by 1 character until we get the desired string.

I managed to do the first part but I'm having problem figuring out how to substring from the back.

n and m should be the indexes between which we want to substring (inclusive).

In this example result of method should be "bstri"

Here is my code:

public static void main(String[] args) {
    String s = "substringme";

    System.out.println(rec(s,2,6));
}

public static String rec(String s, int n, int m) {
    if(n == 0 /* && missing 2nd part of condition */){
        return s;
    } else {
        if(n>0){
            s = s.substring(1);
            n--;
        }
        if(/* missing condition */){
            s= s.substring(0, s.length()-1);
        }
        return rec(s,n,m);
    }
}

I would appreciate any help I can get.

Body:
I propose that you do m-- in the first loop because the definition of m as an index changes when you shorten s from the front.

 public static String rec(String s, int n, int m) {
         if(n == 0 && m == s.length() - 1){
             return s;
         } else {
             if (n > 0) {
                 s = s.substring(1);
                 n--;
                 m--;
             }
             if (m < s.length() - 1) {
                 s = s.substring(0, s.length() - 1);
             }
             return rec(s, n, m);
         }
     }


问:
Query a model through a User model django in template
I have this scenario:

```<code>class Package(models.Model):
    title = models.CharField(max_length=200)
    createdBy = models.ForeignKey(User)

class UserProfile(models.Model):
    website = models.URLField()
    user = models.OneToOneField(User)
</code>```

In my template, I have the object object, and I can do this: {{ object.createdBy }}

Can I do something like {{ object.createdBy.userprofile.website }} in my template?

答:
You should add related_name to your ForeignKey.

```<code>class Package(models.Model):
    title = models.CharField(max_length=200)
    createdBy = models.ForeignKey(User)

class UserProfile(models.Model):
    website = models.URLField()
    user = models.OneToOneField(User, related_name='userprofile')
</code>```

After that you can retrieve user profile for user using name specified in related_name parameter.

```<code>user = User.objects.select_related('userprofile').first()
profile = user.userprofile
</code>```

In your template it will look like:

```<code>{{ object.createdBy.userprofile.website }}
</code>```

As mentioned in comments related_name not needed in your situation because it has same name as related model name. From docs:

If you do not specify the related_name argument for the OneToOneField, Django will use the lower-case name of the current model as default value.

Body:
I have this scenario:

class Package(models.Model):
    title = models.CharField(max_length=200)
    createdBy = models.ForeignKey(User)

class UserProfile(models.Model):
    website = models.URLField()
    user = models.OneToOneField(User)

In my template, I have the object object, and I can do this: {{ object.createdBy }}

Can I do something like {{ object.createdBy.userprofile.website }} in my template?

Body:
You should add related_name to your ForeignKey.

class Package(models.Model):
    title = models.CharField(max_length=200)
    createdBy = models.ForeignKey(User)

class UserProfile(models.Model):
    website = models.URLField()
    user = models.OneToOneField(User, related_name='userprofile')

After that you can retrieve user profile for user using name specified in related_name parameter.

user = User.objects.select_related('userprofile').first()
profile = user.userprofile

In your template it will look like:

{{ object.createdBy.userprofile.website }}

As mentioned in comments related_name not needed in your situation because it has same name as related model name. From docs:

If you do not specify the related_name argument for the OneToOneField, Django will use the lower-case name of the current model as default value.


问:
why didRegisterForRemoteNotificationsWithDeviceToken is not called
I am making an application in which I want to implement apple push notification  service.  I am following the step-by-step instructions given in this tutorial.

But still, the methods are not called. I don't know what is causing the problem. Can anyone help me?

```<code>    - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
        //NSString * token = [[NSString alloc] initWithData:deviceTokenencoding:NSUTF8StringEncoding];
        NSString *str = [NSString stringWithFormat:@"Device Token=%@",deviceToken];
        NSLog(@"Device Token:%@",str);

        //NSLog(@"Device token is called");
        //const void *devTokenBytes = [deviceToken bytes];
        //NSLog(@"Device Token");
    }

    - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
        NSString *str = [NSString stringWithFormat: @"Error: %@", err];
        NSLog(@"Error:%@",str);
    }
</code>```

答:
You need to call registerForNotifications method from didFinishLaunchingWithOptions.</p>

```<code> func registerForNotifications(){

        if #available(iOS 10.0, *) {

            let center = UNUserNotificationCenter.current()
            center.delegate = self
            center.requestAuthorization(options:[.alert,.sound,.badge]) { (granted, error) in
                if granted{
                    UIApplication.shared.registerForRemoteNotifications()
                }else{

                    print("Notification permission denied.")

                }
            }

        } else {

            // For iOS 9 and Below
            let type: UIUserNotificationType = [.alert,.sound,.badge];
            let setting = UIUserNotificationSettings(types: type, categories: nil);
            UIApplication.shared.registerUserNotificationSettings(setting);
            UIApplication.shared.registerForRemoteNotifications()
        }
    }

 func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

        let token = String(format: "%@", deviceToken as CVarArg).trimmingCharacters(in: CharacterSet(charactersIn: "<>")).replacingOccurrences(of: " ", with: "")
        print(token)

    }

extension AppDelegate : UNUserNotificationCenterDelegate{

    @available(iOS 10.0, *)

    func userNotificationCenter(_ center: UNUserNotificationCenter,  willPresent notification: UNNotification, withCompletionHandler   completionHandler: @escaping (_ options:   UNNotificationPresentationOptions) -> Void) {
        print("Handle push from foreground”)

        let info = ((notification.request.content.userInfo as NSDictionary).value(forKey: "aps") as! NSDictionary)
        if let type = info.value(forKey: "type") as? Int{
            if type == 0 {

         // notification received ,Handle your notification here

            }
        }
    }

    @available(iOS 10.0, *)

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

        print("Handle push from background or closed")

        let info = ((response.notification.request.content.userInfo as NSDictionary).value(forKey: "aps") as! NSDictionary)
        if let type = info.value(forKey: "type") as? Int{
            if type == 0 {

            // notification received ,Handle your notification here
            }
        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am making an application in which I want to implement apple push notification  service.  I am following the step-by-step instructions given in this tutorial.

But still, the methods are not called. I don't know what is causing the problem. Can anyone help me?

    - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
        //NSString * token = [[NSString alloc] initWithData:deviceTokenencoding:NSUTF8StringEncoding];
        NSString *str = [NSString stringWithFormat:@"Device Token=%@",deviceToken];
        NSLog(@"Device Token:%@",str);

        //NSLog(@"Device token is called");
        //const void *devTokenBytes = [deviceToken bytes];
        //NSLog(@"Device Token");
    }

    - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
        NSString *str = [NSString stringWithFormat: @"Error: %@", err];
        NSLog(@"Error:%@",str);
    }

Body:
You need to call registerForNotifications method from didFinishLaunchingWithOptions.

 func registerForNotifications(){

        if #available(iOS 10.0, *) {

            let center = UNUserNotificationCenter.current()
            center.delegate = self
            center.requestAuthorization(options:[.alert,.sound,.badge]) { (granted, error) in
                if granted{
                    UIApplication.shared.registerForRemoteNotifications()
                }else{

                    print("Notification permission denied.")

                }
            }

        } else {

            // For iOS 9 and Below
            let type: UIUserNotificationType = [.alert,.sound,.badge];
            let setting = UIUserNotificationSettings(types: type, categories: nil);
            UIApplication.shared.registerUserNotificationSettings(setting);
            UIApplication.shared.registerForRemoteNotifications()
        }
    }

 func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

        let token = String(format: "%@", deviceToken as CVarArg).trimmingCharacters(in: CharacterSet(charactersIn: "<>")).replacingOccurrences(of: " ", with: "")
        print(token)

    }

extension AppDelegate : UNUserNotificationCenterDelegate{

    @available(iOS 10.0, *)

    func userNotificationCenter(_ center: UNUserNotificationCenter,  willPresent notification: UNNotification, withCompletionHandler   completionHandler: @escaping (_ options:   UNNotificationPresentationOptions) -> Void) {
        print("Handle push from foreground”)

        let info = ((notification.request.content.userInfo as NSDictionary).value(forKey: "aps") as! NSDictionary)
        if let type = info.value(forKey: "type") as? Int{
            if type == 0 {

         // notification received ,Handle your notification here

            }
        }
    }

    @available(iOS 10.0, *)

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

        print("Handle push from background or closed")

        let info = ((response.notification.request.content.userInfo as NSDictionary).value(forKey: "aps") as! NSDictionary)
        if let type = info.value(forKey: "type") as? Int{
            if type == 0 {

            // notification received ,Handle your notification here
            }
        }
    }
}


问:
How to call angular service from SlickGrid custom editor
How to call angular service from slickgrid custom cell editor.
Below link is mentioned that describes the slickgrid custom cell editor.

https://github.com/mleibman/SlickGrid/wiki/Writing-custom-cell-editors

```<code>function IEditor(args) {
    this.applyValue = function(item,state) {

    // Unable to get the service in the editor context.
    // this.testService is undefined.
    this.testService.getDetails(itemId).get(result =>{
       console.log(result );
    });
  };
}
</code>```

I am facing an issue to get the service in the editor context. I tried with this and self but no success.

答:
the second .this doesn't have the same context of the wrapper function. You should write it like this:

```<code> function IEditor(args) {

  var that = this;
  this.applyValue = function(item,state) {

  // Unable to get the service in the editor context.
  // this.testService is undefined.
  that.testService.getDetails(itemId).get(result =>{
     console.log(result );
  });
 };
}
</code>```

or if you are using ES6:

```<code> function IEditor(args) {

  this.applyValue = (item,state) => {

  // Unable to get the service in the editor context.
  // this.testService is undefined.
  this.testService.getDetails(itemId).get(result =>{
     console.log(result );
  });
 };
}
</code>```

Body:
How to call angular service from slickgrid custom cell editor.
Below link is mentioned that describes the slickgrid custom cell editor.

https://github.com/mleibman/SlickGrid/wiki/Writing-custom-cell-editors

function IEditor(args) {
    this.applyValue = function(item,state) {

    // Unable to get the service in the editor context.
    // this.testService is undefined.
    this.testService.getDetails(itemId).get(result =>{
       console.log(result );
    });
  };
}

I am facing an issue to get the service in the editor context. I tried with this and self but no success.

Body:
the second .this doesn't have the same context of the wrapper function. You should write it like this:

 function IEditor(args) {

  var that = this;
  this.applyValue = function(item,state) {

  // Unable to get the service in the editor context.
  // this.testService is undefined.
  that.testService.getDetails(itemId).get(result =>{
     console.log(result );
  });
 };
}

or if you are using ES6:

 function IEditor(args) {

  this.applyValue = (item,state) => {

  // Unable to get the service in the editor context.
  // this.testService is undefined.
  this.testService.getDetails(itemId).get(result =>{
     console.log(result );
  });
 };
}


问:
in SSMS, is there any way to preview table contents without writing a query?
Browsing table contents in SQL Server Management Studio (SSMS) doesn't seem as easy as it should be. In contrast to other client software I have used, I can't find a way to simply click on a table and view its top rows (i.e. preview it).

The closest is to right click and "SELECT Top 1000 Rows" but not only is that two clicks, more importantly it opens a new query tab. If I'm browsing a lot of tables, I end up needing to juggle a lot of unnecessary tabs.

Is there a better way?

答: What you can do is to select on the table in the query tab and right-click and then "design query in the editor"</p>


问:
Is it best practise to give the top level App component state?
I'm new to react/redux and am wondering how to architecture my first app. It will have a currentUser along with other bits of App level state.

Would it be wise to connect() my App component and pass this information down or just directly connect the components that need access to this information (e.g NavBar)?

答:
Per the Redux FAQ entry at http://redux.js.org/docs/faq/ReactRedux.html#react-multiple-components :

Early Redux documentation advised that you should only have a few connected components near the top of your component tree. However, time and experience has shown that that generally requires a few components to know too much about the data requirements of all their descendants, and forces them to pass down a confusing number of props.

The current suggested best practice is to categorize your components as “presentational” or “container” components, and extract a connected container component wherever it makes sense:

Emphasizing “one container component at the top” in Redux examples was a mistake. Don't take this as a maxim. Try to keep your presentation components separate. Create container components by connecting them when it's convenient. Whenever you feel like you're duplicating code in parent components to provide data for same kinds of children, time to extract a container. Generally as soon as you feel a parent knows too much about “personal” data or actions of its children, time to extract a container.

In general, try to find a balance between understandable data flow and areas of responsibility with your components.


问:
Parse XML files in folder and rename them with values from three nodes
I'm new to winbatch scripting. I would like to pares XML files in folder and rename them with values from three nodes.
    Ex: in C drive I have three files:

```<code>1.xml
2.xml
3.xml
</code>```

Batch script should rename files as follows:

```<code>1.xml = AB_D_HR.xml
2.xml = ZZ_PK_IT.xml
3.xml = TS_MR_IT.xml
</code>```

I reached till the point where i can get the values of two nodes however not sure about further steps. please suggest:

XML1:
<company name="AAA">
    <department>
        <depname>HR</depname>
    </department>
    <Employee>
        <lastname>D</lastname>
        <firstname>AB</firstname>
    </Employee>
</company>

XML2:
<company name="AAA">
    <department>
        <depname>IT</depname>
    </department>
    <Employee>
        <lastname>PK</lastname>
        <firstname>ZZ</firstname>
    </Employee>
</company>

XML3:
<company name="AAA">
    <department>
        <depname>IT</depname>
    </department>
    <Employee>
        <lastname>MR</lastname>
        <firstname>TS</firstname>
    </Employee>
</company>
```

<pre class="lang-bat prettyprint-override"><code>@echo off

for /f "delims=" %%T in ('dir /b *.xml') do (
   for /f "tokens=3 delims=<>" %%A in (
     'find /i "<lastname>" ^< "%%T"'
    )do set K=%%A

for /f "tokens=3 delims=<>" %%B in (
     'find /i "<firstname>" ^< "%%T"'
    )do set L=%%B

)

echo %K%_%L%

pause
</code>```

答:
Depending upon your filenames, and potentially their contents, the following may be a possibility.

@Echo Off
SetLocal EnableDelayedExpansion
Set "i=0"
For /F "Tokens=1,4 Delims=:<>" %%A In (
    'Findstr/IC:"<depname>" /C:"<lastname>" /C:"<firstname>" "*.xml"') Do (
    Set/A "i+=1"
    If !i! Equ 1 (Set "_=%%B%%~xA") Else (If !i!==2 (Set "_=%%B_!_!"
        ) Else (Ren "%%A" "%%B_!_!"
            Set "i=0")))
Timeout -1
GoTo :EOF
```

Body:
I'm new to winbatch scripting. I would like to pares XML files in folder and rename them with values from three nodes.
    Ex: in C drive I have three files:

1.xml
2.xml
3.xml

Batch script should rename files as follows:

1.xml = AB_D_HR.xml
2.xml = ZZ_PK_IT.xml
3.xml = TS_MR_IT.xml

I reached till the point where i can get the values of two nodes however not sure about further steps. please suggest:

XML1:
<company name="AAA">
    <department>
        <depname>HR</depname>
    </department>
    <Employee>
        <lastname>D</lastname>
        <firstname>AB</firstname>
    </Employee>
</company>

XML2:
<company name="AAA">
    <department>
        <depname>IT</depname>
    </department>
    <Employee>
        <lastname>PK</lastname>
        <firstname>ZZ</firstname>
    </Employee>
</company>

XML3:
<company name="AAA">
    <department>
        <depname>IT</depname>
    </department>
    <Employee>
        <lastname>MR</lastname>
        <firstname>TS</firstname>
    </Employee>
</company>

@echo off

for /f "delims=" %%T in ('dir /b *.xml') do (
   for /f "tokens=3 delims=<>" %%A in (
     'find /i "<lastname>" ^< "%%T"'
    )do set K=%%A

for /f "tokens=3 delims=<>" %%B in (
     'find /i "<firstname>" ^< "%%T"'
    )do set L=%%B

)

echo %K%_%L%

pause


问:
Adobe Air native installer Linux - Dependency is not satisfiable

I created native installers for my air application successfully under MacOS and Windows.

With Ubuntu 10 I am able to create a .deb package, but when I launch it opens the Ubuntu software center showing error:

Dependency is not satisfiable: adobeair (>= 2.5.0.0)

I thought native installer should be able to download the proper adobe air version if available (2.5.1 seems available as deb package). If I install air for linux 2.5.1 from adobe website my application launches fine.

Did anyone experience the same issue?

Thanks in advance for any help

Paolo

答:
Unfortunately, many years late "Adobe AIR for Linux is no longer supported." following what adobe page says. Using the "AIR archive" is possible to get unsupported versions, the 2.6.0 version is the most recent available. If you need to install a program that require a newer version of it, you might go to Virtual box with a Windows guest.

For version 2.6.0 the recommend steps for Ubuntu 16.10 are:

for 32bit machine

```<code>wget -O adobe-air_i386.deb http://drive.noobslab.com/data/apps/AdobeAir/adobeair_2.6.0.2_i386.deb
sudo dpkg -i adobe-air_i386.deb
sudo apt-get install -f && rm adobe-air_i386.deb
</code>```

for 64bit machine

```<code>wget -O adobe-air_amd64.deb http://drive.noobslab.com/data/apps/AdobeAir/adobeair_2.6.0.2_amd64.deb
sudo dpkg -i adobe-air_amd64.deb
sudo apt-get install -f && rm adobe-air_amd64.deb
</code>```

The recommend steps for Ubuntu 16.04/14.04/12.04/Linux Mint 18/17/13 (both extracted from here):

```<code>wget -O adobe-air.sh http://drive.noobslab.com/data/apps/AdobeAir/adobe-air.sh
chmod +x adobe-air.sh;sudo ./adobe-air.sh
</code>```

Body:
Unfortunately, many years late "Adobe AIR for Linux is no longer supported." following what adobe page says. Using the "AIR archive" is possible to get unsupported versions, the 2.6.0 version is the most recent available. If you need to install a program that require a newer version of it, you might go to Virtual box with a Windows guest.

For version 2.6.0 the recommend steps for Ubuntu 16.10 are:

for 32bit machine

wget -O adobe-air_i386.deb http://drive.noobslab.com/data/apps/AdobeAir/adobeair_2.6.0.2_i386.deb
sudo dpkg -i adobe-air_i386.deb
sudo apt-get install -f && rm adobe-air_i386.deb

for 64bit machine

wget -O adobe-air_amd64.deb http://drive.noobslab.com/data/apps/AdobeAir/adobeair_2.6.0.2_amd64.deb
sudo dpkg -i adobe-air_amd64.deb
sudo apt-get install -f && rm adobe-air_amd64.deb

The recommend steps for Ubuntu 16.04/14.04/12.04/Linux Mint 18/17/13 (both extracted from here):

wget -O adobe-air.sh http://drive.noobslab.com/data/apps/AdobeAir/adobe-air.sh
chmod +x adobe-air.sh;sudo ./adobe-air.sh


问:
Vagrant Windows 10 'hangs" on vagrant up
I've been having a problem with Vagrant (1.8.1, using VirtualBox 5.0.20) on Windows 10.

When I follow the getting started tutorial https://www.vagrantup.com/docs/getting-started/ after I have typed vagrant up, my console is stuck on:

```<code>==> default: Waiting for machine to boot. This may take a few minutes...
default: SSH address: 127.0.0.1:2200
default: SSH username: vagrant
default: SSH auth method: private key
</code>```

It does not continue, i can see the VM boot inside of VirtualBox, and i can use the VirtualBox GUI to log in with the default credentials, so the VM itself is working.

According to https://www.vagrantup.com/docs/virtualbox/common-issues.html
I should run VirtualBox as admin and do vagrant up from a cmd.exe with admin rights, but when i do that i get the message:

```<code>There was an error while executing `VBoxManage`, a CLI used by Vagrant
for controlling VirtualBox. The command and stderr is shown below.
Command: ["modifyvm", "1b9d4f9b-04d8-48bf-8d16-d3aed99d341b", "--natpf1", "delete", "ssh"]
Stderr: VBoxManage.exe: error: Code E_FAIL (0x80004005) - Unspecified error (extended info not available)
VBoxManage.exe: error: Context: "LockMachine(a->session, LockType_Write)" at line 493 of file VBoxManageModifyVM.cpp
</code>```

This seems different from the 100's of posts all around the net like these:
https://github.com/Varying-Vagrant-Vagrants/VVV/issues/375
since I am not getting antying after the output listed above, it just sits there and after alike 10 minutes it comes up with the message:

```<code>Timed out while waiting for the machine to boot. This means that
Vagrant was unable to communicate with the guest machine within
the configured ("config.vm.boot_timeout" value) time period.
If you look above, you should be able to see the error(s) that
Vagrant had when attempting to connect to the machine. These errors
are usually good hints as to what may be wrong.
If you're using a custom box, make sure that networking is properly
working and you're able to connect to the machine. It is a common
problem that networking isn't setup properly in these boxes.
Verify that authentication configurations are also setup properly,
as well.
If the box appears to be booting properly, you may want to increase
the timeout ("config.vm.boot_timeout") value.
</code>```

I've also read Vagrant stuck in "Waiting for VM to Boot" but it did not help me.

Is there anything else I am missing here?

答:
In my case, vagrant up was hanging on 'Syncing VM folder' , on Windows 7 with Vagrant 1.9.3 and VBox 5.1.18 . It turned out that it requires Powershell >= 3.0.
I downloaded it from https://www.google.ca/search?q=powershell+3.0+download&ie=utf-8&oe=utf-8&client=firefox-b&gfe_rd=cr&ei=x0fdWLfsBubQXu2OorAD, and worked fine afterwards.</p>

Body:
I've been having a problem with Vagrant (1.8.1, using VirtualBox 5.0.20) on Windows 10.

When I follow the getting started tutorial https://www.vagrantup.com/docs/getting-started/ after I have typed vagrant up, my console is stuck on:

==> default: Waiting for machine to boot. This may take a few minutes...
default: SSH address: 127.0.0.1:2200
default: SSH username: vagrant
default: SSH auth method: private key

It does not continue, i can see the VM boot inside of VirtualBox, and i can use the VirtualBox GUI to log in with the default credentials, so the VM itself is working.

According to https://www.vagrantup.com/docs/virtualbox/common-issues.html
I should run VirtualBox as admin and do vagrant up from a cmd.exe with admin rights, but when i do that i get the message:

There was an error while executing `VBoxManage`, a CLI used by Vagrant
for controlling VirtualBox. The command and stderr is shown below.
Command: ["modifyvm", "1b9d4f9b-04d8-48bf-8d16-d3aed99d341b", "--natpf1", "delete", "ssh"]
Stderr: VBoxManage.exe: error: Code E_FAIL (0x80004005) - Unspecified error (extended info not available)
VBoxManage.exe: error: Context: "LockMachine(a->session, LockType_Write)" at line 493 of file VBoxManageModifyVM.cpp

This seems different from the 100's of posts all around the net like these:
https://github.com/Varying-Vagrant-Vagrants/VVV/issues/375
since I am not getting antying after the output listed above, it just sits there and after alike 10 minutes it comes up with the message:

Timed out while waiting for the machine to boot. This means that
Vagrant was unable to communicate with the guest machine within
the configured ("config.vm.boot_timeout" value) time period.
If you look above, you should be able to see the error(s) that
Vagrant had when attempting to connect to the machine. These errors
are usually good hints as to what may be wrong.
If you're using a custom box, make sure that networking is properly
working and you're able to connect to the machine. It is a common
problem that networking isn't setup properly in these boxes.
Verify that authentication configurations are also setup properly,
as well.
If the box appears to be booting properly, you may want to increase
the timeout ("config.vm.boot_timeout") value.

I've also read Vagrant stuck in "Waiting for VM to Boot" but it did not help me.

Is there anything else I am missing here?


问:
Using XML-RPC in iPhone apps
Is it possible to use XML-RPC calls in iPhone application (what approaches are the best)?
Are there any constraints with XML-RPC?

Thank you,
Paul

答:
You might be interested in the WordPress for iOS app. It's completely open source and uses an XML-RPC library.

http://ios.wordpress.org/

Title: Using XML-RPC in iPhone apps


问:
How would I declare a global variable in Visual Basic?
I want to create a variable that can be used across multiple forms.

It's going to be a temporary storage place for integers.

答:
You can just add it as PUBLIC to ANY Module

Example:

Module Module1
    'Global variables
    Public glbtxtTemplateName As String     'GLOBAL VARIABLE FOR TEMPLATE

VB loads the Modals first as a class and all PUBLIC items therein are shared directly. Think about it this way.

Lets say we have a MODULE called "MY_PROCESSES"

When you declare a SUB or a FUNCTION in "MY_PROCESSES" if you want it to be used OUTSIDE of "MY_PROCESSES" you declare as PUBLIC like this

PUBLIC SUB LOAD_TEMPLATE()
....

To get to LOAD_TEMPLATE you just call it in your code from anywhere:

LOAD_TEMPLATE

So if I need to set or use the global variable that I made public in my module I just refer to it by name:

glbtxtTemplateName="TEMPLATE_NAME"

IF glbtxtTemplateName="" then LoadTemplate

I do like building the class as above because you can reference it faster without remembering the variable but if you only need 1 or 2 global variables you can name them like we used to with Hungarian Notation style name.
This method is really quite simple and elegant. Old is new and New is Old.


问:
Pattern for parsing date with two timezone format in Joda-Time
I've a scenario where I'm getting date strings in various different patterns (from a third-party email server) (for example):

Mon, 13 Mar 2017 19:00:10 +0530 (IST)

Tue, 21 Mar 2017 09:23:00 -0700 (PDT)

Sun, 12 Mar 2017 14:31:13 +0000 (UTC)

That means, only the time-zones are being changed. I can easily parse this using Java's SimpleDateFormat, for example:

```<code>String pattern = "EEE, dd MMM yyyy HH:mm:ss Z '('z')'"
SimpleDateFormat df = new SimpleDateFormat(pattern);
df.parse("Fri, 31 Mar 2017 13:31:14 +0530 (IST)");
</code>```

But when using DateTimeFormat from Joda-Time library, I'm not able to use the same pattern.

```<code>String pattern = "EEE, dd MMM yyyy HH:mm:ss Z '('z')'"
DateTimeFormat parser = DateTimeFormat.forPattern(pattern)
parser.parseDateTime("Fri, 31 Mar 2017 13:31:14 +0530 (IST)")
</code>```

What I'm missing here?

答:
tl;dr

```<code>String input = "Mon, 13 Mar 2017 19:00:10 +0530 (IST)";
int index = input.indexOf ( " (" ); // Searching for SPACE + LEFT PARENTHESIS.
String inputModified = input.substring ( 0 , index ); // "Mon, 13 Mar 2017 19:00:10 +0530"

Instant instant =
    OffsetDateTime.parse (
        inputModified ,
        DateTimeFormatter.ofPattern( "EEE, d MMM uuuu HH:mm:ss Z" )
    ).toInstant()
;
</code>```

See similar code run live at IdeOne.com.

Using java.time

FYI: The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

two timezone format in Joda-Time

Mon, 13 Mar 2017 19:00:10 +0530 (IST)

No, that is a zero time zone format.

The +0530 is an offset-from-UTC, a number of hours and minutes away from UTC.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

Since the 3-4 letter abbreviations cannot be reliably parsed, Joda-Time has a policy of refusing to try (as noted in comment by Hugo above). I suspect this is a wise policy, given what we see next.

The java.time classes will make an attempt to guess at parsing such pseudo-time-zone names but may not be your intended value. Indeed, it interprets inappropriately your first example, interpreting IST apparently as Israel Standard Time out of the choices that include India Standard Time, Ireland Standard Time, and possibly more.

```<code>String input = "Mon, 13 Mar 2017 19:00:10 +0530 (IST)";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE, d MMM uuuu HH:mm:ss Z '('z')'") ;
ZonedDateTime zdt = ZonedDateTime.parse ( input , f );
</code>```

zdt.toString(): 2017-03-13T19:00:10+02:00[Asia/Jerusalem]

So I suggest you lop off the bogus abbreviation chunk at the end. Parse the remaining text as an OffsetDateTime which at least gives you an exact moment on the timeline. Adjust into UTC as an Instant, as most of your work should generally be done in UTC including your logging.

Lop off the abbreviation using String::substring. Note we are including the SPACE before the LEFT PARENTHESIS in our substring search as we want to delete both characters and everything after that.

```<code>String input = "Mon, 13 Mar 2017 19:00:10 +0530 (IST)";
int index = input.indexOf ( " (" ); // Searching for SPACE + LEFT PARENTHESIS.
String inputModified = input.substring ( 0 , index );
</code>```

inputModified: Mon, 13 Mar 2017 19:00:10 +0530

Parse as an OffsetDateTime object using the numerical offset at the end to guide us as to the exact moment of this value.

```<code>DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE, d MMM uuuu HH:mm:ss Z" );
OffsetDateTime odt = OffsetDateTime.parse ( inputModified , f );
</code>```

odt.toString(): 2017-03-13T19:00:10+05:30

Extract an Instant object to give us the same moment in UTC.

```<code>Instant instant = odt.toInstant ();
</code>```

instant.toString(): 2017-03-13T13:30:10Z

You can adjust into your own particular time zone if you insist. But I advise learning to think in UTC when wearing your Programmer hat. Think of UTC as “The One True Time” and all other zones are mere variations on that theme.

```<code>ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
</code>```

ISO 8601

The kind of pattern shown in your examples was common in protocols of yesteryear such as RFC 1123 / RFC 822.

Nowadays, the approach is to always use ISO 8601. In this modern standard, the formats are easy to read across various human cultures, have less reliance on the English language, are easy for machines to parse, and are designed to be unambiguous.

The java.time classes use ISO 8601 by default when generating/parsing strings. You can see their generated output in my examples above. Note that ZonedDateTime extends the standard by appending the name of the time zone in square brackets.

By the way, if you have similar inputs that comply exactly with RFC 1123, know that java.time provides a predefined formatter object, DateTimeFormatter.RFC_1123_DATE_TIME.

Body:
I've a scenario where I'm getting date strings in various different patterns (from a third-party email server) (for example):

Mon, 13 Mar 2017 19:00:10 +0530 (IST)

Tue, 21 Mar 2017 09:23:00 -0700 (PDT)

Sun, 12 Mar 2017 14:31:13 +0000 (UTC)

That means, only the time-zones are being changed. I can easily parse this using Java's SimpleDateFormat, for example:

String pattern = "EEE, dd MMM yyyy HH:mm:ss Z '('z')'"
SimpleDateFormat df = new SimpleDateFormat(pattern);
df.parse("Fri, 31 Mar 2017 13:31:14 +0530 (IST)");

But when using DateTimeFormat from Joda-Time library, I'm not able to use the same pattern.

String pattern = "EEE, dd MMM yyyy HH:mm:ss Z '('z')'"
DateTimeFormat parser = DateTimeFormat.forPattern(pattern)
parser.parseDateTime("Fri, 31 Mar 2017 13:31:14 +0530 (IST)")

What I'm missing here?

Body:
tl;dr

String input = "Mon, 13 Mar 2017 19:00:10 +0530 (IST)";
int index = input.indexOf ( " (" ); // Searching for SPACE + LEFT PARENTHESIS.
String inputModified = input.substring ( 0 , index ); // "Mon, 13 Mar 2017 19:00:10 +0530"

Instant instant =
    OffsetDateTime.parse (
        inputModified ,
        DateTimeFormatter.ofPattern( "EEE, d MMM uuuu HH:mm:ss Z" )
    ).toInstant()
;

See similar code run live at IdeOne.com.

Using java.time

FYI: The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

two timezone format in Joda-Time

Mon, 13 Mar 2017 19:00:10 +0530 (IST)

No, that is a zero time zone format.

The +0530 is an offset-from-UTC, a number of hours and minutes away from UTC.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

Since the 3-4 letter abbreviations cannot be reliably parsed, Joda-Time has a policy of refusing to try (as noted in comment by Hugo above). I suspect this is a wise policy, given what we see next.

The java.time classes will make an attempt to guess at parsing such pseudo-time-zone names but may not be your intended value. Indeed, it interprets inappropriately your first example, interpreting IST apparently as Israel Standard Time out of the choices that include India Standard Time, Ireland Standard Time, and possibly more.

String input = "Mon, 13 Mar 2017 19:00:10 +0530 (IST)";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE, d MMM uuuu HH:mm:ss Z '('z')'") ;
ZonedDateTime zdt = ZonedDateTime.parse ( input , f );

zdt.toString(): 2017-03-13T19:00:10+02:00[Asia/Jerusalem]

So I suggest you lop off the bogus abbreviation chunk at the end. Parse the remaining text as an OffsetDateTime which at least gives you an exact moment on the timeline. Adjust into UTC as an Instant, as most of your work should generally be done in UTC including your logging.

Lop off the abbreviation using String::substring. Note we are including the SPACE before the LEFT PARENTHESIS in our substring search as we want to delete both characters and everything after that.

String input = "Mon, 13 Mar 2017 19:00:10 +0530 (IST)";
int index = input.indexOf ( " (" ); // Searching for SPACE + LEFT PARENTHESIS.
String inputModified = input.substring ( 0 , index );

inputModified: Mon, 13 Mar 2017 19:00:10 +0530

Parse as an OffsetDateTime object using the numerical offset at the end to guide us as to the exact moment of this value.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE, d MMM uuuu HH:mm:ss Z" );
OffsetDateTime odt = OffsetDateTime.parse ( inputModified , f );

odt.toString(): 2017-03-13T19:00:10+05:30

Extract an Instant object to give us the same moment in UTC.

Instant instant = odt.toInstant ();

instant.toString(): 2017-03-13T13:30:10Z

You can adjust into your own particular time zone if you insist. But I advise learning to think in UTC when wearing your Programmer hat. Think of UTC as “The One True Time” and all other zones are mere variations on that theme.

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );

ISO 8601

The kind of pattern shown in your examples was common in protocols of yesteryear such as RFC 1123 / RFC 822.

Nowadays, the approach is to always use ISO 8601. In this modern standard, the formats are easy to read across various human cultures, have less reliance on the English language, are easy for machines to parse, and are designed to be unambiguous.

The java.time classes use ISO 8601 by default when generating/parsing strings. You can see their generated output in my examples above. Note that ZonedDateTime extends the standard by appending the name of the time zone in square brackets.

By the way, if you have similar inputs that comply exactly with RFC 1123, know that java.time provides a predefined formatter object, DateTimeFormatter.RFC_1123_DATE_TIME.


问:
Code Signing error in XCode 8.2.1
I have an app that builds on my Mac (running El Capitan) but when I copy the app project folder onto another Mac (running Sierra if that may be the problem) and run the project I get the code signing error:

```<code>CodeSign /Users/.../Library/Developer/Xcode/DerivedData/appname-fgarszmikfuloefrynwpohxkvgav/Build/Products/Debug-iphonesimulator/appname.app
    cd "/Users/... app path"
    export CODESIGN_ALLOCATE=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate
    export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"

Signing Identity:     "-"

    /usr/bin/codesign --force --sign - --timestamp=none /Users/.../Library/Developer/Xcode/DerivedData/appname-fgarszmikfuloefrynwpohxkvgav/Build/Products/Debug-iphonesimulator/appname.app

/Users/.../Library/Developer/Xcode/DerivedData/appname-fgarszmikfuloefrynwpohxkvgav/Build/Products/Debug-iphonesimulator/appname.app: resource fork, Finder information, or similar detritus not allowed
Command /usr/bin/codesign failed with exit code 1
</code>```

New certs and provisioning profiles etc but all that should be fine.

Followed every suggestion I can find on here (specifically Code Sign Error in macOS Sierra Xcode 8 : resource fork, Finder information, or similar detritus not allowed), cleaned, alt-cleaned. Auto manage signing doesn't fix it.

I have paid developer account.

Can anyone suggest what might be causing the problem?

答:
It seems like this error is caused by extended attributes on files in your project.

You can find out which files are causing this failure by running the following command: xattr -lr <path_to_app_bundle>

You can remove the extended attributes using this command: xattr -cr <path_to_app_bundle>

More info here.

Title: Code Signing error in XCode 8.2.1

Body:
I have an app that builds on my Mac (running El Capitan) but when I copy the app project folder onto another Mac (running Sierra if that may be the problem) and run the project I get the code signing error:

CodeSign /Users/.../Library/Developer/Xcode/DerivedData/appname-fgarszmikfuloefrynwpohxkvgav/Build/Products/Debug-iphonesimulator/appname.app
    cd "/Users/... app path"
    export CODESIGN_ALLOCATE=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate
    export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"

Signing Identity:     "-"

    /usr/bin/codesign --force --sign - --timestamp=none /Users/.../Library/Developer/Xcode/DerivedData/appname-fgarszmikfuloefrynwpohxkvgav/Build/Products/Debug-iphonesimulator/appname.app

/Users/.../Library/Developer/Xcode/DerivedData/appname-fgarszmikfuloefrynwpohxkvgav/Build/Products/Debug-iphonesimulator/appname.app: resource fork, Finder information, or similar detritus not allowed
Command /usr/bin/codesign failed with exit code 1

New certs and provisioning profiles etc but all that should be fine.

Followed every suggestion I can find on here (specifically Code Sign Error in macOS Sierra Xcode 8 : resource fork, Finder information, or similar detritus not allowed), cleaned, alt-cleaned. Auto manage signing doesn't fix it.

I have paid developer account.

Can anyone suggest what might be causing the problem?


问:
What is the best way to include custom font using CSS to make it compatible with maximum browsers?
I have tried various codes to embed custom font and finally following seems to work in FF & IE8 above. But it does not support in IE7.

```<code>@font-face {
font-family: 'xyzfont';
src: url('fonts/abc-font.eot?') format('eot'),
     url('fonts/abc-font.woff') format('woff'),
     url('fonts/abc-font.ttf') format('truetype');
}

h1, h2, h3, div span { font-family: 'xyzfont', Georgia, Arial; }
</code>```

Any suggestion to make it more compatible (such as IE7) most welcome.

答:
i use this code ;)

```<code>@font-face {
  font-family: 'BBadr';
    src: url('fonts/BBadr/BBadr.eot'); /* IE9 Compat Modes */
    src: url('fonts/BBadr/BBadr.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
      url("fonts/BBadr/BBadr.otf") format("opentype"), /* Open Type Font */
      url('fonts/BBadr/BBadr.woff') format('woff'),/* Pretty Modern Browsers */
      url('fonts/BBadr/BBadr.woff2') format('woff2'), /* Super Modern Browsers */
      url('fonts/BBadr/BBadr.ttf')  format('truetype'),/* Safari, Android, iOS */
      url('fonts/BBadr/BBadr.svg#BBadr') format('svg'); /* Legacy iOS */
}
</code>```

you can convert Online youre font ( ttf ( with this website :
Simple Online Web Font Converter: ttf otf woff woff2 eot svg otf with css stylesheet

Convert font and use my css code  ( not use the sample css of site )

Body:
I have tried various codes to embed custom font and finally following seems to work in FF & IE8 above. But it does not support in IE7.

@font-face {
font-family: 'xyzfont';
src: url('fonts/abc-font.eot?') format('eot'),
     url('fonts/abc-font.woff') format('woff'),
     url('fonts/abc-font.ttf') format('truetype');
}

h1, h2, h3, div span { font-family: 'xyzfont', Georgia, Arial; }

Any suggestion to make it more compatible (such as IE7) most welcome.

Body:
i use this code ;)

@font-face {
  font-family: 'BBadr';
    src: url('fonts/BBadr/BBadr.eot'); /* IE9 Compat Modes */
    src: url('fonts/BBadr/BBadr.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
      url("fonts/BBadr/BBadr.otf") format("opentype"), /* Open Type Font */
      url('fonts/BBadr/BBadr.woff') format('woff'),/* Pretty Modern Browsers */
      url('fonts/BBadr/BBadr.woff2') format('woff2'), /* Super Modern Browsers */
      url('fonts/BBadr/BBadr.ttf')  format('truetype'),/* Safari, Android, iOS */
      url('fonts/BBadr/BBadr.svg#BBadr') format('svg'); /* Legacy iOS */
}

you can convert Online youre font ( ttf ( with this website :
Simple Online Web Font Converter: ttf otf woff woff2 eot svg otf with css stylesheet

Convert font and use my css code  ( not use the sample css of site )


问:
dynamic textbox jquery focus
i am creating a dynamic text box of input type with the help of following
code
i am not able to set the focus on the input type.

```<code>var elem = document.createElement("input");
elem.type = "text";
elem.id = "txtParent";
elem.setAttribute('onblur', 'SetSpanValueForParent("' + spnText.id + '")');
$(elem).focus();
$(spnText).append(elem);
</code>```

i have also tried doing this
elem.focus();

can u provide that one line statement how can i achieve this

答:
You first need to append the input, before setting the focus().

Elements  can have focus only if they are visible.

Example:

```<code>function fx(spnText)
{
  var elem = document.createElement("input");
  elem.type = "text";
  elem.id = "txtParent";
  elem.setAttribute('onblur', 'SetSpanValueForParent("' + spnText.id + '")');
  $(spnText).append(elem);
  //a little delay before setting the focus
  setTimeout(function(){elem.focus()},50);
}
</code>```

Title: dynamic textbox jquery focus

Body:
i am creating a dynamic text box of input type with the help of following
code
i am not able to set the focus on the input type.

var elem = document.createElement("input");
elem.type = "text";
elem.id = "txtParent";
elem.setAttribute('onblur', 'SetSpanValueForParent("' + spnText.id + '")');
$(elem).focus();
$(spnText).append(elem);

i have also tried doing this
elem.focus();

can u provide that one line statement how can i achieve this

Body:
You first need to append the input, before setting the focus().

Elements  can have focus only if they are visible.

Example:

function fx(spnText)
{
  var elem = document.createElement("input");
  elem.type = "text";
  elem.id = "txtParent";
  elem.setAttribute('onblur', 'SetSpanValueForParent("' + spnText.id + '")');
  $(spnText).append(elem);
  //a little delay before setting the focus
  setTimeout(function(){elem.focus()},50);
}