问:
toggle visibility of chain group in constraint layout
In previous xml layout, I have multiple view groups with few elements inside. Hide each view group will also hide all of its child elements. Since I wanted to have flat structure and tried ConstraintLayout. Cool I know how to chain element with spread to align properly. Since flat structure does not have wrapped LinearLayout, now i have 3 views to hide instead. I would like to know if there is alternative to achieve this.

Without constraint layout

```<code><RelativeLayout....
..........
..........
<LinearLayout
        android:visibility="gone"
        tools:visibility="visible"
        android:id="@+id/filter_area"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.AppCompatTextView
            android:id="@+id/lblTerminal"
            android:background="@color/lightGray"
            style="@style/PurpleSubtitle"
            android:drawableRight="@drawable/i_down_yellow"
            android:drawableEnd="@drawable/i_down_yellow"
            android:padding="10dp"
            android:text="@string/lblTerminal"
            android:layout_weight="5"
            android:layout_width="0dp"
            android:layout_height="wrap_content" />

        <View
            android:background="@android:color/black"
            android:layout_width="1dp"
            android:layout_height="match_parent"/>

        <android.support.v7.widget.AppCompatTextView
            android:id="@+id/lblCategory"
            android:background="@color/lightGray"
            android:padding="10dp"
            android:drawableRight="@drawable/i_down_yellow"
            android:drawableEnd="@drawable/i_down_yellow"
            style="@style/PurpleSubtitle"
            android:text="@string/lblCategory"
            android:layout_weight="5"
            android:layout_width="0dp"
            android:layout_height="wrap_content" />

    </LinearLayout>
  .......
  .......
  </RelativeLayout>
</code>```

With constraint layout

```<code>    <android.support.constraint.ConstraintLayout
    .....
    .....
    .....
       #happy that i no longer need LinearLayout for align properly
       <android.support.v7.widget.AppCompatTextView
            android:id="@+id/lblTerminal"
            android:background="@color/lightGray"
            style="@style/PurpleSubtitle"
            android:drawableRight="@drawable/i_down_yellow"
            android:drawableEnd="@drawable/i_down_yellow"
            android:padding="10dp"
            android:text="@string/lblTerminal"
            android:layout_weight="5"
            android:layout_width="0dp"
            android:layout_height="50dp"
            app:layout_constraintTop_toBottomOf="@+id/txt_search"
            app:layout_constraintRight_toLeftOf="@+id/view3"
            app:layout_constraintLeft_toLeftOf="@+id/guideline2"
            app:layout_constraintHorizontal_chainStyle="spread"/>

        <View
            android:background="@android:color/black"
            android:layout_width="1dp"
            android:layout_height="50dp"
            android:id="@+id/view3"
            app:layout_constraintTop_toBottomOf="@+id/txt_search"
            app:layout_constraintRight_toLeftOf="@+id/lblCategory"
            app:layout_constraintLeft_toRightOf="@+id/lblTerminal" />

        <android.support.v7.widget.AppCompatTextView
            android:id="@+id/lblCategory"
            android:background="@color/lightGray"
            android:padding="10dp"
            android:drawableRight="@drawable/i_down_yellow"
            android:drawableEnd="@drawable/i_down_yellow"
            style="@style/PurpleSubtitle"
            android:text="@string/lblCategory"
            android:layout_width="0dp"
            android:layout_height="50dp"
            app:layout_constraintTop_toTopOf="@+id/view3"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintLeft_toRightOf="@+id/view3" />

  ......
  ......
  ......

  </android.support.constraint.ConstraintLayout>
</code>```

答:
You can use that same Linear Layout as child of Constraint Layout too, OR you can also make all those 3 widgets as child of another Constraint Layout and make that layout as child of main Constraint Layout.

Then you can maintain the visibility and other stuff same as before.

Body:
In previous xml layout, I have multiple view groups with few elements inside. Hide each view group will also hide all of its child elements. Since I wanted to have flat structure and tried ConstraintLayout. Cool I know how to chain element with spread to align properly. Since flat structure does not have wrapped LinearLayout, now i have 3 views to hide instead. I would like to know if there is alternative to achieve this.

Without constraint layout

<RelativeLayout....
..........
..........
<LinearLayout
        android:visibility="gone"
        tools:visibility="visible"
        android:id="@+id/filter_area"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.AppCompatTextView
            android:id="@+id/lblTerminal"
            android:background="@color/lightGray"
            style="@style/PurpleSubtitle"
            android:drawableRight="@drawable/i_down_yellow"
            android:drawableEnd="@drawable/i_down_yellow"
            android:padding="10dp"
            android:text="@string/lblTerminal"
            android:layout_weight="5"
            android:layout_width="0dp"
            android:layout_height="wrap_content" />

        <View
            android:background="@android:color/black"
            android:layout_width="1dp"
            android:layout_height="match_parent"/>

        <android.support.v7.widget.AppCompatTextView
            android:id="@+id/lblCategory"
            android:background="@color/lightGray"
            android:padding="10dp"
            android:drawableRight="@drawable/i_down_yellow"
            android:drawableEnd="@drawable/i_down_yellow"
            style="@style/PurpleSubtitle"
            android:text="@string/lblCategory"
            android:layout_weight="5"
            android:layout_width="0dp"
            android:layout_height="wrap_content" />

    </LinearLayout>
  .......
  .......
  </RelativeLayout>

With constraint layout

    <android.support.constraint.ConstraintLayout
    .....
    .....
    .....
       #happy that i no longer need LinearLayout for align properly
       <android.support.v7.widget.AppCompatTextView
            android:id="@+id/lblTerminal"
            android:background="@color/lightGray"
            style="@style/PurpleSubtitle"
            android:drawableRight="@drawable/i_down_yellow"
            android:drawableEnd="@drawable/i_down_yellow"
            android:padding="10dp"
            android:text="@string/lblTerminal"
            android:layout_weight="5"
            android:layout_width="0dp"
            android:layout_height="50dp"
            app:layout_constraintTop_toBottomOf="@+id/txt_search"
            app:layout_constraintRight_toLeftOf="@+id/view3"
            app:layout_constraintLeft_toLeftOf="@+id/guideline2"
            app:layout_constraintHorizontal_chainStyle="spread"/>

        <View
            android:background="@android:color/black"
            android:layout_width="1dp"
            android:layout_height="50dp"
            android:id="@+id/view3"
            app:layout_constraintTop_toBottomOf="@+id/txt_search"
            app:layout_constraintRight_toLeftOf="@+id/lblCategory"
            app:layout_constraintLeft_toRightOf="@+id/lblTerminal" />

        <android.support.v7.widget.AppCompatTextView
            android:id="@+id/lblCategory"
            android:background="@color/lightGray"
            android:padding="10dp"
            android:drawableRight="@drawable/i_down_yellow"
            android:drawableEnd="@drawable/i_down_yellow"
            style="@style/PurpleSubtitle"
            android:text="@string/lblCategory"
            android:layout_width="0dp"
            android:layout_height="50dp"
            app:layout_constraintTop_toTopOf="@+id/view3"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintLeft_toRightOf="@+id/view3" />

  ......
  ......
  ......

  </android.support.constraint.ConstraintLayout>


来源: stackexchange

问:
How to json.dumps byte object in python3
In python2

```<code>import json
a = {"text": u"你好".encode("gbk")}
json.dumps(a, ensure_ascii=False)

>>> Out: '{"text": "\xc4\xe3\xba\xc3"}'
</code>```

I want to get same 'Out' in python3:

```<code>import codecs
byte_obj = "你好".encode("gbk")
x = byte_obj.decode("utf8", "backslashreplace") # ops, it become '\\xc4\\xe3\\xba\\xc3'
x = codecs.escape_encode(byte_obj)[0] # ops, it become b'\\xc4\\xe3\\xba\\xc3'

# fail, I have to concatenate them

b'{"text": "' + u"你好".encode("gbk") + b'"}'

>>> Out: b'{"text": "\xc4\xe3\xba\xc3"}'
</code>```

In Python3, If there is a way to convert

```<code>{"text": "你好"}  # first, encoding with gbk, then json.dumps
</code>```

to

```<code>b'{"text": "\xc4\xe3\xba\xc3"}'  # json serialized result
</code>```

答:
If you actually want GBK encoding in Python 3:

```<code>import json
a = {"text": u"你好"}
print(json.dumps(a, ensure_ascii=False).encode('gbk'))
</code>```

b'{"text": "\xc4\xe3\xba\xc3"}'

ContentLicense: CC BY-SA 3.0

Body:
In python2

import json
a = {"text": u"你好".encode("gbk")}
json.dumps(a, ensure_ascii=False)

>>> Out: '{"text": "\xc4\xe3\xba\xc3"}'

I want to get same 'Out' in python3:

import codecs
byte_obj = "你好".encode("gbk")
x = byte_obj.decode("utf8", "backslashreplace") # ops, it become '\\xc4\\xe3\\xba\\xc3'
x = codecs.escape_encode(byte_obj)[0] # ops, it become b'\\xc4\\xe3\\xba\\xc3'

# fail, I have to concatenate them

b'{"text": "' + u"你好".encode("gbk") + b'"}'

>>> Out: b'{"text": "\xc4\xe3\xba\xc3"}'

In Python3, If there is a way to convert

{"text": "你好"}  # first, encoding with gbk, then json.dumps

to

b'{"text": "\xc4\xe3\xba\xc3"}'  # json serialized result

Body:
If you actually want GBK encoding in Python 3:

import json
a = {"text": u"你好"}
print(json.dumps(a, ensure_ascii=False).encode('gbk'))

b'{"text": "\xc4\xe3\xba\xc3"}'


问:
Running Perl Script from Command Line?
I have perl express 2.5 loaded on my server.  I would like to be able to run my perl scripts using a command line so they can be scheduled rather than manually bringing up the script in Perl Express and clicking on the run command.  Is there a way to execute the script from a command line using this version of Perl or do I need to download a newer or more robust version of the Perl Engine.  </p>

答:
You just need to give perl command and the path of your perl script.
example :</p>

```<code>D:\Project\dir>perl <path_of_perl_script .pl>
</code>```

Title: Running Perl Script from Command Line?

Body:
You just need to give perl command and the path of your perl script.
example :

D:\Project\dir>perl <path_of_perl_script .pl>


问:
is_paginated not working properly for class based views in Django
book_list.html

```<code>{% extends "base.html" %}
{% block content %}
<h3> Available books </h3>
{% if book_list %}
<ul>
    {% for book in book_list %}
     <li> <a href = "{{ book.get_absolute_url }}">{{book.title }}</a>    <small> by {{book.author }}</small></li>
     <p>{{ book.summary }}
    {% endfor %}
<ul>
{% endif %}
{% if is_paginated %}
  <div class="pagination">
      <span class="page-links">
          {% if page_obj.has_previous %}
              <a href="{{ request.path }}?page={{ page_obj.previous_page_number }}">previous</a>
          {% endif %}
          <span class="page-current">
              Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
          </span>
          {% if page_obj.has_next %}
              <a href="{{ request.path }}?page={{ page_obj.next_page_number }}">next</a>
          {% endif %}
      </span>
  </div>
{% else %}
      <h4> pagination not working</h4>
{% endif %}
{% endblock %}
</code>```

class in views.py :

```<code>class BookListView(generic.ListView):
  model = Book
  paginate_by = 2
  queryset =Book.objects.all()
</code>```

urls.py :

```<code> urlpatterns =[
 url('^$',views.index, name ='index'),  # matching with an empty string
 url('^books/$',views.BookListView.as_view(),name ='books'), #the one to which I am adding the paginator
 url('^book/(?P<pk>\d+)/$',views.BookDetailView.as_view(),name='book-detail'),

]
</code>```

Book model :

```<code>class Book(models.Model):
  title=models.CharField(max_length=100)
  author = models.ForeignKey('Author',on_delete=models.SET_NULL,null = True)
  summary = models.TextField(max_length=200,help_text="Enter the description")
  isbn = models.CharField('ISBN',max_length=13 ,help_text='13 Character <a href="https://www.isbn-international.org/content/what-isbn">ISBN number</a>' )
  genre = models.ManyToManyField(Genre,help_text = 'selct a genre for this book')

  class Meta:
     ordering =["title"]
  def __str__(self):
     return self.title

  def get_absolute_url(self):
     return reverse('book-detail',args=[str(self.id)] )
</code>```

The book_list gets rendered perfectly, the problem is with the paginator, the is_paginated condition is not working and it executes the else statement, I have been trying for more than 3 hours, but couldn't find a solution, What Am I missing here ?

Django version : 1.11.2
Python : 3.5

Edit :
 update 1: The problem was the paginate_by value was two, and the total items to display was also two hence it didn't initiate the is_paginated tag,It worked fine when I added one item more than paginate_by value.

答:
use this, you had some problem with the if condition</p>

```<code>{% extends "base.html" %}
{% block content %}
<h3> Available books </h3>
{% if object_list %}
    <ul>
        {% for book in object_list %}
         <li> <a href = "{{ book.get_absolute_url }}">{{book.title }}</a>    <small> by {{book.author }}</small></li>
         <p>{{ book.summary }}
        {% endfor %}
    <ul>

    {% if is_paginated %}
      <div class="pagination">
          <span class="page-links">
              {% if page_obj.has_previous %}
                  <a href="{{ request.path }}?page={{ page_obj.previous_page_number }}">previous</a>
              {% endif %}
              <span class="page-current">
                  Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
              </span>
              {% if page_obj.has_next %}
                  <a href="{{ request.path }}?page={{ page_obj.next_page_number }}">next</a>
              {% endif %}
          </span>
      </div>
    {% else %}
          <h4> pagination not working</h4>
    {% endif %}
        {% else %}
        <h4> No book</h4>
{% endif %}
{% endblock %}
</code>```

Body:
book_list.html

{% extends "base.html" %}
{% block content %}

 Available books

{% if book_list %}

    {% for book in book_list %}

 {{book.title }}     by {{book.author }}

{{ book.summary }}
    {% endfor %}

{% endif %}
{% if is_paginated %}

          {% if page_obj.has_previous %}
              previous
          {% endif %}

              Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.

          {% if page_obj.has_next %}
              next
          {% endif %}

{% else %}

 pagination not working

{% endif %}
{% endblock %}

class in views.py :

class BookListView(generic.ListView):
  model = Book
  paginate_by = 2
  queryset =Book.objects.all()

urls.py :

 urlpatterns =[
 url('^$',views.index, name ='index'),  # matching with an empty string
 url('^books/$',views.BookListView.as_view(),name ='books'), #the one to which I am adding the paginator
 url('^book/(?P<pk>\d+)/$',views.BookDetailView.as_view(),name='book-detail'),

]

Book model :

class Book(models.Model):
  title=models.CharField(max_length=100)
  author = models.ForeignKey('Author',on_delete=models.SET_NULL,null = True)
  summary = models.TextField(max_length=200,help_text="Enter the description")
  isbn = models.CharField('ISBN',max_length=13 ,help_text='13 Character ISBN number' )
  genre = models.ManyToManyField(Genre,help_text = 'selct a genre for this book')

  class Meta:
     ordering =["title"]
  def __str__(self):
     return self.title

  def get_absolute_url(self):
     return reverse('book-detail',args=[str(self.id)] )

The book_list gets rendered perfectly, the problem is with the paginator, the is_paginated condition is not working and it executes the else statement, I have been trying for more than 3 hours, but couldn't find a solution, What Am I missing here ?

Django version : 1.11.2
Python : 3.5

Edit :
 update 1: The problem was the paginate_by value was two, and the total items to display was also two hence it didn't initiate the is_paginated tag,It worked fine when I added one item more than paginate_by value.

Body:
use this, you had some problem with the if condition

{% extends "base.html" %}
{% block content %}
<h3> Available books </h3>
{% if object_list %}
    <ul>
        {% for book in object_list %}
         <li> <a href = "{{ book.get_absolute_url }}">{{book.title }}</a>    <small> by {{book.author }}</small></li>
         <p>{{ book.summary }}
        {% endfor %}
    <ul>

    {% if is_paginated %}
      <div class="pagination">
          <span class="page-links">
              {% if page_obj.has_previous %}
                  <a href="{{ request.path }}?page={{ page_obj.previous_page_number }}">previous</a>
              {% endif %}
              <span class="page-current">
                  Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
              </span>
              {% if page_obj.has_next %}
                  <a href="{{ request.path }}?page={{ page_obj.next_page_number }}">next</a>
              {% endif %}
          </span>
      </div>
    {% else %}
          <h4> pagination not working</h4>
    {% endif %}
        {% else %}
        <h4> No book</h4>
{% endif %}
{% endblock %}


问:
Delete similar record in table with custom condition
I have a table in sql server and in my table is a field like name.
I need to delete records from my table with this condition.
All characters are similar except for the last character, and last character is "a" or "b"

For example table records are name1a,name2a,name1b,....
and need delete name1a and name1b

答:
If you are asking how to delete any rows that have duplicates in the table (matching all but the last character) rather than how to use a wildcard, here is how:

```<code>declare @names table (keycol int, namecol varchar(10))

insert into @names (keycol, namecol) values (1, 'name1a')
insert into @names (keycol, namecol) values (2, 'name1b')
insert into @names (keycol, namecol) values (3, 'name2a')
insert into @names (keycol, namecol) values (4, 'name2b')
insert into @names (keycol, namecol) values (5, 'name3a')
insert into @names (keycol, namecol) values (6, 'name4b')

;with dupenames as
(
    select LEFT(namecol,LEN(namecol)-1) as NameMinusOne
    from @names
    group by LEFT(namecol,LEN(namecol)-1)
    having count(*) > 1
)
delete from @names
from @names n
inner join dupenames dn on dn.NameMinusOne = LEFT(n.namecol,LEN(n.namecol)-1)
</code>```

OUTPUT:

```<code>keycol      namecol
----------- ----------
5           name3a
6           name4b
</code>```

Body:
If you are asking how to delete any rows that have duplicates in the table (matching all but the last character) rather than how to use a wildcard, here is how:

declare @names table (keycol int, namecol varchar(10))

insert into @names (keycol, namecol) values (1, 'name1a')
insert into @names (keycol, namecol) values (2, 'name1b')
insert into @names (keycol, namecol) values (3, 'name2a')
insert into @names (keycol, namecol) values (4, 'name2b')
insert into @names (keycol, namecol) values (5, 'name3a')
insert into @names (keycol, namecol) values (6, 'name4b')

;with dupenames as
(
    select LEFT(namecol,LEN(namecol)-1) as NameMinusOne
    from @names
    group by LEFT(namecol,LEN(namecol)-1)
    having count(*) > 1
)
delete from @names
from @names n
inner join dupenames dn on dn.NameMinusOne = LEFT(n.namecol,LEN(n.namecol)-1)

OUTPUT:

keycol      namecol
----------- ----------
5           name3a
6           name4b

ContentLicense: CC BY-SA 2.5


问:
Visual Studio 2010 shortcut to find classes and methods?
Is there any shortcut in Visual studio 2010 to find classes/interfaces?

I was using Resharper few years back to do that. Here now, I don't have the Resharper and looking something similar in Visual studio 2010 which can help me do that.

Right now, I have to use find all "s classname" that's closest I can get.

答: Ctrl+T in Visual Studio 2017.

Body: Ctrl+T in Visual Studio 2017.


问:
How to highlight the day in datepicker on click of text box
Here is my code

```<code> <input type="text" name="date" class="datepicker" value="20-Jun-2017" readonly="">

$(".datepicker").each(function() {

    var date_val = $(this).val();

    $(this).datepicker({

        'setDate':  date_val,

        'pickDate': true,

        'dateFormat': 'd-M-y'
    });
});
</code>```

datepicker is highlighting only today's date, but not default textbox value.

Thanks in advance :)

答:
Hi date picker will automatically highlights selected dates, but you can highlight dates manually as well, please refer below link

Datepicker for highlighting specific dates

Body:
Here is my code

 <input type="text" name="date" class="datepicker" value="20-Jun-2017" readonly="">

$(".datepicker").each(function() {

    var date_val = $(this).val();

    $(this).datepicker({

        'setDate':  date_val,

        'pickDate': true,

        'dateFormat': 'd-M-y'
    });
});

datepicker is highlighting only today's date, but not default textbox value.

Thanks in advance :)


问:
HWIOAuthBundle facebook 443 Bad Access
I'm building a symfony REST Api in which I'm trying to get HWIOAuthBundle, FOSUserBundle and LexikJWTBundle working all together.

I followed this gist for the HWIOAuthBundle/FOSUserBundle integration.

Now I'm getting the facebook login form when hitting the /login route. But after submition I get this error :

```<code>[2/2] HttpTransportException: Error while sending HTTP request
[1/2] RequestException: Failed to connect to graph.facebook.com port 443: Bad access

INFO - Matched route "hwi_oauth_service_redirect".

CRITICAL -
Uncaught PHP Exception HWI\Bundle\OAuthBundle\OAuth\Exception\HttpTransportException:
"Error while sending HTTP request"
at C:\myProject\vendor\hwi\oauth-bundle\OAuth\ResourceOwner\AbstractResourceOwner.php
line 257

DEBUG -
Notified event "kernel.request" to listener
"Symfony\Component\EventDispatcher\Debug\WrappedListener::__invoke".
</code>```

...

I'm now looking for help about this. Or any other way to get those bundles to work together.

config.yml :

```<code>hwi_oauth:
# list of names of the firewalls in which this bundle is active, this setting MUST be set
firewall_names: [auth]

http_client:
    timeout:       10000
    verify_peer: false
    max_redirects: 1000
    ignore_errors: false

fosub:
    username_iterations: 300
    properties:
        # these properties will be used/redefined later in the custom FOSUBUserProvider service.
        facebook: facebook_id
# an optional setting to configure a query string parameter which can be used to redirect
# the user after authentication, e.g. /connect/facebook?_destination=/my/destination will
# redirect the user to /my/destination after facebook authenticates them.  If this is not
# set then the user will be redirected to the original resource that they requested, or
# the base address if no resource was requested.  This is similar to the behaviour of
# [target_path_parameter for form login](http://symfony.com/doc/2.0/cookbook/security/form_login.html).
# target_path_parameter: _destination

# an optional setting to use the HTTP REFERER header to be used in case no
# previous URL was stored in the session (i.e. no resource was requested).
# This is similar to the behaviour of
# [using the referring URL for form login](http://symfony.com/doc/2.0/cookbook/security/form_login.html#using-the-referring-url).
# use_referer: true

# here you will add one (or more) configurations for resource owners
resource_owners:
    facebook:
        type:                facebook
        client_id:           {id}
        client_secret:       {secret}
        scope:         ""
        infos_url:           "https://graph.facebook.com/me?fields=name,email,picture.type(square)"
        options:
            display: popup
</code>```

security.yml :

```<code>firewalls:
     auth:
        pattern: ^/api/minisite/user/auth
        anonymous: true
        stateless: true
        form_login:
            check_path: /api/minisite/user/auth/login_check
            success_handler: lexik_jwt_authentication.handler.authentication_success
            failure_handler: lexik_jwt_authentication.handler.authentication_failure
            username_parameter: username
            password_parameter: password
            require_previous_session: false
        oauth:
            resource_owners:
                facebook:      "/api/minisite/user/auth/facebook/login/check-facebook"
            login_path:        /api/minisite/user/auth/facebook/login
            check_path: /api/minisite/user/auth/login_check
            failure_path:      /api/minisite/user/auth/facebook/login
            oauth_user_provider:
                #this is my custom user provider, created from FOSUBUserProvider - will manage the
                #automatic user registration on your site, with data from the provider (facebook. google, etc.)
                service: my_user_provider
        logout:       true
        anonymous:    true

access_control:
    - { path: ^/api/minisite/user/auth, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/api/minisite, roles: IS_AUTHENTICATED_FULLY }
</code>```

答:
Configure this in your config.yml file.

```<code>    hwi_oauth:
        http_client:
            verify_peer: false
</code>```

Setting this allows you to turn off SSL verification.

Title: HWIOAuthBundle facebook 443 Bad Access

Body:
I'm building a symfony REST Api in which I'm trying to get HWIOAuthBundle, FOSUserBundle and LexikJWTBundle working all together.

I followed this gist for the HWIOAuthBundle/FOSUserBundle integration.

Now I'm getting the facebook login form when hitting the /login route. But after submition I get this error :

[2/2] HttpTransportException: Error while sending HTTP request
[1/2] RequestException: Failed to connect to graph.facebook.com port 443: Bad access

INFO - Matched route "hwi_oauth_service_redirect".

CRITICAL -
Uncaught PHP Exception HWI\Bundle\OAuthBundle\OAuth\Exception\HttpTransportException:
"Error while sending HTTP request"
at C:\myProject\vendor\hwi\oauth-bundle\OAuth\ResourceOwner\AbstractResourceOwner.php
line 257

DEBUG -
Notified event "kernel.request" to listener
"Symfony\Component\EventDispatcher\Debug\WrappedListener::__invoke".

...

I'm now looking for help about this. Or any other way to get those bundles to work together.

config.yml :

hwi_oauth:
# list of names of the firewalls in which this bundle is active, this setting MUST be set
firewall_names: [auth]

http_client:
    timeout:       10000
    verify_peer: false
    max_redirects: 1000
    ignore_errors: false

fosub:
    username_iterations: 300
    properties:
        # these properties will be used/redefined later in the custom FOSUBUserProvider service.
        facebook: facebook_id
# an optional setting to configure a query string parameter which can be used to redirect
# the user after authentication, e.g. /connect/facebook?_destination=/my/destination will
# redirect the user to /my/destination after facebook authenticates them.  If this is not
# set then the user will be redirected to the original resource that they requested, or
# the base address if no resource was requested.  This is similar to the behaviour of
# [target_path_parameter for form login](http://symfony.com/doc/2.0/cookbook/security/form_login.html).
# target_path_parameter: _destination

# an optional setting to use the HTTP REFERER header to be used in case no
# previous URL was stored in the session (i.e. no resource was requested).
# This is similar to the behaviour of
# [using the referring URL for form login](http://symfony.com/doc/2.0/cookbook/security/form_login.html#using-the-referring-url).
# use_referer: true

# here you will add one (or more) configurations for resource owners
resource_owners:
    facebook:
        type:                facebook
        client_id:           {id}
        client_secret:       {secret}
        scope:         ""
        infos_url:           "https://graph.facebook.com/me?fields=name,email,picture.type(square)"
        options:
            display: popup

security.yml :

firewalls:
     auth:
        pattern: ^/api/minisite/user/auth
        anonymous: true
        stateless: true
        form_login:
            check_path: /api/minisite/user/auth/login_check
            success_handler: lexik_jwt_authentication.handler.authentication_success
            failure_handler: lexik_jwt_authentication.handler.authentication_failure
            username_parameter: username
            password_parameter: password
            require_previous_session: false
        oauth:
            resource_owners:
                facebook:      "/api/minisite/user/auth/facebook/login/check-facebook"
            login_path:        /api/minisite/user/auth/facebook/login
            check_path: /api/minisite/user/auth/login_check
            failure_path:      /api/minisite/user/auth/facebook/login
            oauth_user_provider:
                #this is my custom user provider, created from FOSUBUserProvider - will manage the
                #automatic user registration on your site, with data from the provider (facebook. google, etc.)
                service: my_user_provider
        logout:       true
        anonymous:    true

access_control:
    - { path: ^/api/minisite/user/auth, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/api/minisite, roles: IS_AUTHENTICATED_FULLY }

Body:
Configure this in your config.yml file.

    hwi_oauth:
        http_client:
            verify_peer: false

Setting this allows you to turn off SSL verification.


问:
Android design game card UI
I need help with the design of my card game.

I having a Vector of cards (player cards), each item appers in ImageView (Already done and working).

```<code>private Vector<Card> myCards;
</code>```

I having a LinearLayout that holding 5 imageView's.

```<code><LinearLayout
android:id="@+id/myCardsLayout"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:layout_alignParentBottom="true"
android:orientation="horizontal"
android:paddingBottom="10dip">

<ImageView
    android:id="@+id/my_card_1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:onClick="goToMainMenu"
    />

<ImageView
    android:id="@+id/my_card_2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
        android:onClick="goToMainMenu"
      />

    <ImageView
        android:id="@+id/my_card_3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:onClick="goToMainMenu"
     />

    <ImageView
        android:id="@+id/my_card_4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:onClick="goToMainMenu"
    />

    <ImageView
        android:id="@+id/my_card_5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:onClick="goToMainMenu"
   />
</LinearLayout>
</code>```

I want to choose the cards that i want to drop by click on the card, And that the player will see this by jumping the card slightly up (or another recommended way).

I will implement that on android:onClick function (goToMainMenu is a temporary statement).

Any idea ? Thanks!

UPDATE1

```<code>  public void myCard1OnClick(View view) {
    view.setSelected(true);
    if(view.isSelected()) {
        int y = view.getTop();
        view.setTop(y - 30);
    }
    else{
        int y = view.getTop();
        view.setTop(y + 30);
    }
}
</code>```

答:
try to use setX() and setY() view properties to move across a space.
And about the issue of moving the card and after that it get back to its original position, maybe its because the set selected its not working, and then enters to the else statement.

Title: Android design game card UI

Body:
I need help with the design of my card game.

I having a Vector of cards (player cards), each item appers in ImageView (Already done and working).

private Vector<Card> myCards;

I having a LinearLayout that holding 5 imageView's.

<LinearLayout
android:id="@+id/myCardsLayout"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:layout_alignParentBottom="true"
android:orientation="horizontal"
android:paddingBottom="10dip">

<ImageView
    android:id="@+id/my_card_1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:onClick="goToMainMenu"
    />

<ImageView
    android:id="@+id/my_card_2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
        android:onClick="goToMainMenu"
      />

    <ImageView
        android:id="@+id/my_card_3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:onClick="goToMainMenu"
     />

    <ImageView
        android:id="@+id/my_card_4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:onClick="goToMainMenu"
    />

    <ImageView
        android:id="@+id/my_card_5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:onClick="goToMainMenu"
   />
</LinearLayout>

I want to choose the cards that i want to drop by click on the card, And that the player will see this by jumping the card slightly up (or another recommended way).

I will implement that on android:onClick function (goToMainMenu is a temporary statement).

Any idea ? Thanks!

UPDATE1

  public void myCard1OnClick(View view) {
    view.setSelected(true);
    if(view.isSelected()) {
        int y = view.getTop();
        view.setTop(y - 30);
    }
    else{
        int y = view.getTop();
        view.setTop(y + 30);
    }
}


问:
Is GIT a good solution for large projects like Laravel?
When a team work on a Laravel project, they usually edit route file, the same controllers and views. Resulting in thousands of merging conflicts. And resolving them is time consuming. Is there a way of preventing these conflicts?.

答:
It happens in almost every project when using git , we all face these situations like working on same files which result in merge conflicts but on the other hand we all team members have a synced code at the end of the day. Also as an alternative to avoid multiple merge conflicts in each pull , you can make your branches and then push your code to your respective branches. In this way there will be merge conflict only when you merge these branches to your main branch. This is just my opinion that GIT is the best tool when it comes to project management.
You could also try adding comments section in your file if you don't want to create that many branches.</p>

ContentLicense: CC BY-SA 4.0


问:
TYPO3 set fe_user group
I have TYPO3 version 7.6.18. I trying create user by code. How to add user group? I see it need create user group object.

```<code>$this->objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
            $newUser = $this->objectManager->get('Fhk\\Feusersplus\\Domain\\Repository\\UserRepository');

$userModel = $this->objectManager>get('Fhk\\Feusersplus\\Domain\\Model\\User');

$userGroup = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage();

$userModel->setUsername("sdfdsfdsfs");
$userModel->setEmail($user_data['email']);
$gender = 0;
$password = rand(99999999,9999999999999);
$userModel->setPassword($password);

$userModel->setUsergroup($userGroup);
$newUser->add($userModel);
</code>```

I think the user did't add to database because I did't set user group. Help me please)

I have corrected my code but it does't add user to database:

```<code> $this->objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
            $newUser = $this->objectManager->get('Fhk\\Feusersplus\\Domain\\Repository\\UserRepository');

                $userModel = $this->objectManager->get('Fhk\\Feusersplus\\Domain\\Model\\User');
                $userGroup = $this->objectManager->get('TYPO3\\CMS\\Extbase\\Domain\\Repository\\FrontendUserGroupRepository');

                $userGroup = $userGroup->findByUid(1);
                $newUserGroup = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage();
                $newUserGroup->attach($userGroup);

            $userModel->setUsername("sdfdsfdsfs");
                $userModel->setEmail($user_data['email']);
                $gender = 0;
                $password = rand(99999999,9999999999999);
                $userModel->setPassword($password);
                $userModel->setPid(3);
                $userModel->setUsergroup($newUserGroup);

                $newUser->add($userModel);
</code>```

答:
try something like below.</p>

```<code>$this->objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
$newUser = $this->objectManager->get('Fhk\\Feusersplus\\Domain\\Repository\\UserRepository');

$userModel = $this->objectManager->get('Fhk\\Feusersplus\\Domain\\Model\\User');
$userGroup = $this->objectManager->get('TYPO3\\CMS\\Extbase\\Domain\\Repository\\FrontendUserGroupRepository');

$userGroup = $this->FrontendUserGroupRepository->findByUid(1);

$userModel = new \Typo3\CMS\Extbase\Domain\Model\FrontendUser();

$userModel->setUsername("sdfdsfdsfs");
$userModel->setEmail($user_data['email']);
$gender = 0;
$password = rand(99999999,9999999999999);
$userModel->setPassword($password);
$userModel->setPid(3);
$userModel->addUsergroup($userGroup);

$this->FrontendUserRepository->add($userModel);
</code>```

Title: TYPO3 set fe_user group

Body:
I have TYPO3 version 7.6.18. I trying create user by code. How to add user group? I see it need create user group object.

$this->objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
            $newUser = $this->objectManager->get('Fhk\\Feusersplus\\Domain\\Repository\\UserRepository');

$userModel = $this->objectManager>get('Fhk\\Feusersplus\\Domain\\Model\\User');

$userGroup = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage();

$userModel->setUsername("sdfdsfdsfs");
$userModel->setEmail($user_data['email']);
$gender = 0;
$password = rand(99999999,9999999999999);
$userModel->setPassword($password);

$userModel->setUsergroup($userGroup);
$newUser->add($userModel);

I think the user did't add to database because I did't set user group. Help me please)

I have corrected my code but it does't add user to database:

 $this->objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
            $newUser = $this->objectManager->get('Fhk\\Feusersplus\\Domain\\Repository\\UserRepository');

                $userModel = $this->objectManager->get('Fhk\\Feusersplus\\Domain\\Model\\User');
                $userGroup = $this->objectManager->get('TYPO3\\CMS\\Extbase\\Domain\\Repository\\FrontendUserGroupRepository');

                $userGroup = $userGroup->findByUid(1);
                $newUserGroup = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage();
                $newUserGroup->attach($userGroup);

            $userModel->setUsername("sdfdsfdsfs");
                $userModel->setEmail($user_data['email']);
                $gender = 0;
                $password = rand(99999999,9999999999999);
                $userModel->setPassword($password);
                $userModel->setPid(3);
                $userModel->setUsergroup($newUserGroup);

                $newUser->add($userModel);

Body:
try something like below.

$this->objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
$newUser = $this->objectManager->get('Fhk\\Feusersplus\\Domain\\Repository\\UserRepository');

$userModel = $this->objectManager->get('Fhk\\Feusersplus\\Domain\\Model\\User');
$userGroup = $this->objectManager->get('TYPO3\\CMS\\Extbase\\Domain\\Repository\\FrontendUserGroupRepository');

$userGroup = $this->FrontendUserGroupRepository->findByUid(1);

$userModel = new \Typo3\CMS\Extbase\Domain\Model\FrontendUser();

$userModel->setUsername("sdfdsfdsfs");
$userModel->setEmail($user_data['email']);
$gender = 0;
$password = rand(99999999,9999999999999);
$userModel->setPassword($password);
$userModel->setPid(3);
$userModel->addUsergroup($userGroup);

$this->FrontendUserRepository->add($userModel);


问:
How to generate 504 gateway timeout error
I am testing a web application, which was sometimes generating 504, gateway timeout error. I want to check whether it is still generating the same or not.Is there any way by which I can generate the 504 error again?</p>

答:
Try after blocking using the firewall service or by disconnecting the server.
You may refer more here : https://www.keycdn.com/support/504-gateway-timeout/</p>


问:
Azure B2C MFA at User level and Sign-In Policy level
I have a web application that authenticates with my B2C tenant with MFA turned on at the Sign-In Policy level [at this point MFA is disabled at User Level] and the policy is configured to use "username" to login.  The application works fine and the user is able to login ... What I am trying to accomplish is to have MFA at user level meaning only certain users will be able to use MFA while others will be able to login without MFA.

The problem that I am facing is, when I turn on MFA at User Level and turn off MFA at Sign-In Policy level

mfa at user level

after the first password authentication screen the redirect to multi factor authentication screen where it asks the user to send code to is failing.  Instead it is going back to the first password authentication screen and seems to be in a loop.  When both MFAs are turned off, it works fine with the password authentication and user is able to login to the application.  When both are turned on, it’s the same behavior where it goes back to the first password screen in a loop.  Am I missing something here, or is it even possible to do this

答:
Azure AD B2C does not have out-of-the-box support for user-level MFA.

The UI you referenced is from enterprise Azure AD, and while it shows up for Azure AD B2C as well, as you've noticed, won't work.

The best approximation to what you are looking for is having two policies, one with MFA and one without MFA. You would have to implement your own mapping table and for users through the appropriate policy.


问:
How to launch the activity for user to key in information once only in android?
This is my login activity code. I just want to launch my user information for user to key in their information once only after that next time when user login will straight open to main activity. Can anyone help me or teach me?

```<code>public class LoginActivity extends AppCompatActivity implements View.OnClickListener{

private Button buttonSignIn;
private EditText editTextEmail;
private EditText editTextPassword;
private TextView textViewSignup;
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;

private SharedPreferences prefs;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    Boolean session_tag = prefs.getBoolean("session", false);
    if(session_tag)
    {
        startActivity(new Intent(getApplicationContext(),MainActivity.class));

    }

    firebaseAuth = FirebaseAuth.getInstance();

    if(firebaseAuth.getCurrentUser() !=null){
        //profile activity here
    }

    editTextEmail = (EditText) findViewById(R.id.editTextEmail);
    editTextPassword = (EditText) findViewById(R.id.editTextPassword);
    textViewSignup = (TextView) findViewById(R.id.textViewSignUp);
    buttonSignIn = (Button) findViewById(R.id.buttonSignin);

    progressDialog = new ProgressDialog(this);
    buttonSignIn.setOnClickListener(this);
    textViewSignup.setOnClickListener(this);

    prefs = PreferenceManager.getDefaultSharedPreferences(this);
}

private void userLogin(){
    String email = editTextEmail.getText().toString().trim();
    String password = editTextPassword.getText().toString().trim();

    if(TextUtils.isEmpty(email)){
        //email is empty
        Toast.makeText(this,"Please enter email", Toast.LENGTH_SHORT).show();
        //stopping the function execction further
        return;
    }

    if(TextUtils.isEmpty(password)){
        //password is empty
        Toast.makeText(this,"Please enter password",Toast.LENGTH_SHORT).show();
        //stopping the function execution further
        return;
    }
    //if validations are ok

    progressDialog.setMessage("Logging In...");
    progressDialog.show();

    firebaseAuth.signInWithEmailAndPassword(email,password)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    progressDialog.dismiss();

                    if(task.isSuccessful()){

                        //start the profle activity
                        finish();
                        startActivity(new Intent(getApplicationContext(),MainActivity.class));
                    }else{
                        Toast.makeText(getApplicationContext(),"Wrong email or password",Toast.LENGTH_SHORT).show();
                    }
                }

            });
}

@Override
public void onClick(View view) {
    if(view == buttonSignIn){
        userLogin();

    }
    if (view == textViewSignup){
        finish();
        startActivity(new Intent(this,RegisterActivity.class));

    }
}
</code>```

}

答:
@Bleach If You want to Send some Value in one activity to another activity You have three way to do this action in android studio
1. You use Intent . Help of Intent You send value one activity to another.
2. Shared Preferences .Help of Shared Preferences You Make a Session and send Value one Activity to another .
3. Bundle . Help Of Bundle You share a Data One activity to another when You Send data one Activity to another You have compress data in Bundle and send Into another activity.
Thank You .
If This Post Help You Please Tell me. I am waiting Your Reply.</p>

Body:
This is my login activity code. I just want to launch my user information for user to key in their information once only after that next time when user login will straight open to main activity. Can anyone help me or teach me?

public class LoginActivity extends AppCompatActivity implements View.OnClickListener{

private Button buttonSignIn;
private EditText editTextEmail;
private EditText editTextPassword;
private TextView textViewSignup;
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;

private SharedPreferences prefs;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    Boolean session_tag = prefs.getBoolean("session", false);
    if(session_tag)
    {
        startActivity(new Intent(getApplicationContext(),MainActivity.class));

    }

    firebaseAuth = FirebaseAuth.getInstance();

    if(firebaseAuth.getCurrentUser() !=null){
        //profile activity here
    }

    editTextEmail = (EditText) findViewById(R.id.editTextEmail);
    editTextPassword = (EditText) findViewById(R.id.editTextPassword);
    textViewSignup = (TextView) findViewById(R.id.textViewSignUp);
    buttonSignIn = (Button) findViewById(R.id.buttonSignin);

    progressDialog = new ProgressDialog(this);
    buttonSignIn.setOnClickListener(this);
    textViewSignup.setOnClickListener(this);

    prefs = PreferenceManager.getDefaultSharedPreferences(this);
}

private void userLogin(){
    String email = editTextEmail.getText().toString().trim();
    String password = editTextPassword.getText().toString().trim();

    if(TextUtils.isEmpty(email)){
        //email is empty
        Toast.makeText(this,"Please enter email", Toast.LENGTH_SHORT).show();
        //stopping the function execction further
        return;
    }

    if(TextUtils.isEmpty(password)){
        //password is empty
        Toast.makeText(this,"Please enter password",Toast.LENGTH_SHORT).show();
        //stopping the function execution further
        return;
    }
    //if validations are ok

    progressDialog.setMessage("Logging In...");
    progressDialog.show();

    firebaseAuth.signInWithEmailAndPassword(email,password)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    progressDialog.dismiss();

                    if(task.isSuccessful()){

                        //start the profle activity
                        finish();
                        startActivity(new Intent(getApplicationContext(),MainActivity.class));
                    }else{
                        Toast.makeText(getApplicationContext(),"Wrong email or password",Toast.LENGTH_SHORT).show();
                    }
                }

            });
}

@Override
public void onClick(View view) {
    if(view == buttonSignIn){
        userLogin();

    }
    if (view == textViewSignup){
        finish();
        startActivity(new Intent(this,RegisterActivity.class));

    }
}

}


问:
How to check if an array doesn't contain a string and use it as condition
```<code>var name = document.getElementById("namebox").value;

if (array.includes(name) == false) {
   alert(name + " is not in record.")
}
</code>```

that didn't work and will always return false, how to express the check in other ways? please enlighten, thank you very much

答:
because your array is like

```<code>[ "name1,score1", "name2,score2"]
</code>```

searching for "name1" using includes wont work

you'll want something like

```<code>if (!array.some(item => item.split(',')[0] === name)) {
    alert(name + " is not in record.")
}
</code>```

or in pre ES2015

```<code>if (!array.some(function (item) {
    return item.split(',')[0] === name;
})) {
    alert(name + " is not in record.");
}
</code>```

or if your browser doesn't have Array.prototype.some

```<code>if (array.filter(function (item) {
    return item.split(',')[0] === name;
}).length === 0) {
    alert(name + " is not in record.");
}
</code>```

Body:
var name = document.getElementById("namebox").value;

if (array.includes(name) == false) {
   alert(name + " is not in record.")
}

that didn't work and will always return false, how to express the check in other ways? please enlighten, thank you very much

Body:
because your array is like

[ "name1,score1", "name2,score2"]

searching for "name1" using includes wont work

you'll want something like

if (!array.some(item => item.split(',')[0] === name)) {
    alert(name + " is not in record.")
}

or in pre ES2015

if (!array.some(function (item) {
    return item.split(',')[0] === name;
})) {
    alert(name + " is not in record.");
}

or if your browser doesn't have Array.prototype.some

if (array.filter(function (item) {
    return item.split(',')[0] === name;
}).length === 0) {
    alert(name + " is not in record.");
}


问:
How to use octave for data from c++ in c++
I have a c++ file which reads in some data as Float_t-arrays. On these I want to apply some octave functions (e.q. fft). How do I do that? Do I firstly have to convert Float_t into an octave variable?
Thanks!

I have:

```<code>int main()
{
Float values[10];

//do magic with octave, e.q. fft

// store the data back into values or keep them (?)
}
</code>```

I know I can do the following:

```<code>int main()
{
Float values[10]={0,1,2,3,4,5,6,7,8,9};

Matrix a_matrix = Matrix (2,2);
a_matrix(0,0) = values[0];

cout << "Matrix: " << a_matrix << endl;
}
</code>```

How do I do this with fft on the values-array?

答:
Pantxo gave you the correct answer on the help mailinglist. I add it here for completeness:

Since fft and related function are builtin you probably can include
   and call Ffft directly (without the
  need for feval) in your code. As an example the following code can be
  compiled with mkocfile and works for me:

```<code>//////////////////////////testfft.cc//////////////////
#include <octave/oct.h>
#include <octave/builtin-defun-decls.h>

DEFUN_DLD(testfft, args, nargout, "\
testfft\n\
")
{
  octave_value_list retval;
  int nargin = args.length ();

  retval = Ffft (args);
  return retval;
}
/////////////////////////////////////////////////////

Compile and test in Octave:

mkoctfile testfft.cc
x = 1:10;
all (testfft (x) == fft (x))
</code>```

EDIT

Since you have problems adapting this as standalone, I'll create another example:

```<code>// file main.cc
// compile and link with mkoctfile --link-stand-alone main.cc -o bentest
#include <iostream>
#include <octave/oct.h>
#include <octave/builtin-defun-decls.h>

int main ()
{
  Matrix a = Matrix (1,4);
  for (int k = 0; k < a.columns (); ++k)
    a(0, k) = k % 2;

  std::cout << "in:" << a << std::endl;

  octave_value_list in;
  in(0) = a;

  octave_value_list out = Ffft (in, 1);
  ComplexMatrix o = out(0).complex_matrix_value ();
  std::cout << "out:" << o << std::endl;

  return 0;
}
</code>```

which outputs.

```<code>in: 0 1 0 1

out: (2,0) (0,0) (-2,0) (0,0)
</code>```

Body:
I have a c++ file which reads in some data as Float_t-arrays. On these I want to apply some octave functions (e.q. fft). How do I do that? Do I firstly have to convert Float_t into an octave variable?
Thanks!

I have:

int main()
{
Float values[10];

//do magic with octave, e.q. fft

// store the data back into values or keep them (?)
}

I know I can do the following:

int main()
{
Float values[10]={0,1,2,3,4,5,6,7,8,9};

Matrix a_matrix = Matrix (2,2);
a_matrix(0,0) = values[0];

cout << "Matrix: " << a_matrix << endl;
}

How do I do this with fft on the values-array?

Body:
Pantxo gave you the correct answer on the help mailinglist. I add it here for completeness:

Since fft and related function are builtin you probably can include
   and call Ffft directly (without the
  need for feval) in your code. As an example the following code can be
  compiled with mkocfile and works for me:

//////////////////////////testfft.cc//////////////////
#include <octave/oct.h>
#include <octave/builtin-defun-decls.h>

DEFUN_DLD(testfft, args, nargout, "\
testfft\n\
")
{
  octave_value_list retval;
  int nargin = args.length ();

  retval = Ffft (args);
  return retval;
}
/////////////////////////////////////////////////////

Compile and test in Octave:

mkoctfile testfft.cc
x = 1:10;
all (testfft (x) == fft (x))

EDIT

Since you have problems adapting this as standalone, I'll create another example:

// file main.cc
// compile and link with mkoctfile --link-stand-alone main.cc -o bentest
#include <iostream>
#include <octave/oct.h>
#include <octave/builtin-defun-decls.h>

int main ()
{
  Matrix a = Matrix (1,4);
  for (int k = 0; k < a.columns (); ++k)
    a(0, k) = k % 2;

  std::cout << "in:" << a << std::endl;

  octave_value_list in;
  in(0) = a;

  octave_value_list out = Ffft (in, 1);
  ComplexMatrix o = out(0).complex_matrix_value ();
  std::cout << "out:" << o << std::endl;

  return 0;
}

which outputs.

in: 0 1 0 1

out: (2,0) (0,0) (-2,0) (0,0)


问:
How to replace GLSurfaceView with TextureView in Android Ice Cream Sandwich?
The TextureView documentation states that it can be used to render OpenGL content.

In the blog post announcing TextureView, it states:

A TextureView can just as easily be used to embed an OpenGL scene in your application. As of Android 4.0, eglCreateWindowSurface() can be used to render into a SurfaceTexture object.

Which seems to imply that to use TextureView instead of GLSurfaceView, one would have to do all the EGL setup themselves and manage the EGLContext and the threading (since GLSurfaceView maintains a GLThread). There doesn't seem to be any sample code in the Android 4.0 SDK that demonstrates how the "TextureView can just as easily be used to embed an OpenGL scene". TextureView seems to plug in more cleanly to the Camera preview (setPreviewTexture) and MediaPlayer (setSurface).

Is it possible to use GLSurfaceView in conjunction with TextureView by using GLSurfaceView.setEGLWindowSurfaceFactory to make it render to the TextureView's SurfaceTexture?

Again, it would be nice if there were some sample code.

答:
A moderator deleted this answer so adding it back for posterity:

See Romain Guy's answer (Nov 23rd 2011) from the android-dev google group:

http://groups.google.com/group/android-developers/browse_thread/thread/539457146a401cf1 (mirrored: http://grokbase.com/t/gg/android-developers/11bqmgb7sw/how-to-replace-glsurfaceview-with-textureview-in-android-ice-cream-sandwich)

GLSurfaceView handles GL setup for you, which TextureView will not do.
  A TextureView can be used as the native window when you create an EGL
  surface. Here is an example (the interesting part is the call to
  eglCreateWindowSurface()):

```<code> @Override
 public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
     mRenderThread = new RenderThread(getResources(), surface);
     mRenderThread.start();
 }

 private static class RenderThread extends Thread {
     private static final String LOG_TAG = "GLTextureView";

     static final int EGL_CONTEXT_CLIENT_VERSION = 0x3098;
     static final int EGL_OPENGL_ES2_BIT = 4;

     private volatile boolean mFinished;

     private final Resources mResources;
     private final SurfaceTexture mSurface;

     private EGL10 mEgl;
     private EGLDisplay mEglDisplay;
     private EGLConfig mEglConfig;
     private EGLContext mEglContext;
     private EGLSurface mEglSurface;
     private GL mGL;

     RenderThread(Resources resources, SurfaceTexture surface) {
         mResources = resources;
         mSurface = surface;
     }

     private static final String sSimpleVS =
             "attribute vec4 position;\n" +
             "attribute vec2 texCoords;\n" +
             "varying vec2 outTexCoords;\n" +
             "\nvoid main(void) {\n" +
             " outTexCoords = texCoords;\n" +
             " gl_Position = position;\n" +
             "}\n\n";
     private static final String sSimpleFS =
             "precision mediump float;\n\n" +
             "varying vec2 outTexCoords;\n" +
             "uniform sampler2D texture;\n" +
             "\nvoid main(void) {\n" +
             " gl_FragColor = texture2D(texture, outTexCoords);\n" +
             "}\n\n";

     private static final int FLOAT_SIZE_BYTES = 4;
     private static final int TRIANGLE_VERTICES_DATA_STRIDE_BYTES = 5 * FLOAT_SIZE_BYTES;
     private static final int TRIANGLE_VERTICES_DATA_POS_OFFSET = 0;
     private static final int TRIANGLE_VERTICES_DATA_UV_OFFSET = 3;
     private final float[] mTriangleVerticesData = {
             // X, Y, Z, U, V
             -1.0f, -1.0f, 0.0f, 0.0f, 0.0f,
              1.0f, -1.0f, 0.0f, 1.0f, 0.0f,
             -1.0f, 1.0f, 0.0f, 0.0f, 1.0f,
              1.0f, 1.0f, 0.0f, 1.0f, 1.0f,
     };

     @Override
     public void run() {
         initGL();

         FloatBuffer triangleVertices = ByteBuffer.allocateDirect(mTriangleVerticesData.length * FLOAT_SIZE_BYTES).order(ByteOrder.nativeOrder()).asFloatBuffer();
         triangleVertices.put(mTriangleVerticesData).position(0);

         int texture = loadTexture(R.drawable.large_photo);
         int program = buildProgram(sSimpleVS, sSimpleFS);

         int attribPosition = glGetAttribLocation(program, "position");
         checkGlError();

         int attribTexCoords = glGetAttribLocation(program, "texCoords");
         checkGlError();

         int uniformTexture = glGetUniformLocation(program, "texture");
         checkGlError();

         glBindTexture(GL_TEXTURE_2D, texture);
         checkGlError();

         glUseProgram(program);
         checkGlError();

         glEnableVertexAttribArray(attribPosition);
         checkGlError();

         glEnableVertexAttribArray(attribTexCoords);
         checkGlError();

         glUniform1i(uniformTexture, texture);
         checkGlError();

         while (!mFinished) {
             checkCurrent();

             glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
             checkGlError();

             glClear(GL_COLOR_BUFFER_BIT);
             checkGlError();

             // drawQuad

             triangleVertices.position(TRIANGLE_VERTICES_DATA_POS_OFFSET);
             glVertexAttribPointer(attribPosition, 3, GL_FLOAT, false,
                     TRIANGLE_VERTICES_DATA_STRIDE_BYTES, triangleVertices);

             triangleVertices.position(TRIANGLE_VERTICES_DATA_UV_OFFSET);
             glVertexAttribPointer(attribTexCoords, 3, GL_FLOAT, false,
                     TRIANGLE_VERTICES_DATA_STRIDE_BYTES, triangleVertices);

             glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

             if (!mEgl.eglSwapBuffers(mEglDisplay, mEglSurface)) {
                 throw new RuntimeException("Cannot swap buffers");
             }
             checkEglError();

             try {
                 Thread.sleep(2000);
             } catch (InterruptedException e) {
                 // Ignore
             }
         }

         finishGL();
     }

     private int loadTexture(int resource) {
         int[] textures = new int[1];

         glActiveTexture(GL_TEXTURE0);
         glGenTextures(1, textures, 0);
         checkGlError();

         int texture = textures[0];
         glBindTexture(GL_TEXTURE_2D, texture);
         checkGlError();

         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

         Bitmap bitmap = BitmapFactory.decodeResource(mResources, resource);

         GLUtils.texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bitmap, GL_UNSIGNED_BYTE, 0);
         checkGlError();

         bitmap.recycle();

         return texture;
     }

     private int buildProgram(String vertex, String fragment) {
         int vertexShader = buildShader(vertex, GL_VERTEX_SHADER);
         if (vertexShader == 0) return 0;

         int fragmentShader = buildShader(fragment, GL_FRAGMENT_SHADER);
         if (fragmentShader == 0) return 0;

         int program = glCreateProgram();
         glAttachShader(program, vertexShader);
         checkGlError();

         glAttachShader(program, fragmentShader);
         checkGlError();

         glLinkProgram(program);
         checkGlError();

         int[] status = new int[1];
         glGetProgramiv(program, GL_LINK_STATUS, status, 0);
         if (status[0] != GL_TRUE) {
             String error = glGetProgramInfoLog(program);
             Log.d(LOG_TAG, "Error while linking program:\n" + error);
             glDeleteShader(vertexShader);
             glDeleteShader(fragmentShader);
             glDeleteProgram(program);
             return 0;
         }

         return program;
     }

     private int buildShader(String source, int type) {
         int shader = glCreateShader(type);

         glShaderSource(shader, source);
         checkGlError();

         glCompileShader(shader);
         checkGlError();

         int[] status = new int[1];
         glGetShaderiv(shader, GL_COMPILE_STATUS, status, 0);
         if (status[0] != GL_TRUE) {
             String error = glGetShaderInfoLog(shader);
             Log.d(LOG_TAG, "Error while compiling shader:\n" + error);
             glDeleteShader(shader);
             return 0;
         }

         return shader;
     }

     private void checkEglError() {
         int error = mEgl.eglGetError();
         if (error != EGL10.EGL_SUCCESS) {
             Log.w(LOG_TAG, "EGL error = 0x" + Integer.toHexString(error));
         }
     }

     private void checkGlError() {
         int error = glGetError();
         if (error != GL_NO_ERROR) {
             Log.w(LOG_TAG, "GL error = 0x" + Integer.toHexString(error));
         }
     }

     private void finishGL() {
         mEgl.eglDestroyContext(mEglDisplay, mEglContext);
         mEgl.eglDestroySurface(mEglDisplay, mEglSurface);
     }

     private void checkCurrent() {
         if (!mEglContext.equals(mEgl.eglGetCurrentContext()) ||

         !mEglSurface.equals(mEgl.eglGetCurrentSurface(EGL10.EGL_DRAW))) {
             if (!mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext)) {
                 throw new RuntimeException("eglMakeCurrent failed " + GLUtils.getEGLErrorString(mEgl.eglGetError()));
             }
         }
     }

     private void initGL() {
         mEgl = (EGL10) EGLContext.getEGL();

         mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
         if (mEglDisplay == EGL10.EGL_NO_DISPLAY) {
             throw new RuntimeException("eglGetDisplay failed "
                     + GLUtils.getEGLErrorString(mEgl.eglGetError()));
         }

         int[] version = new int[2];
         if (!mEgl.eglInitialize(mEglDisplay, version)) {
             throw new RuntimeException("eglInitialize failed " +
                     GLUtils.getEGLErrorString(mEgl.eglGetError()));
         }

         mEglConfig = chooseEglConfig();
         if (mEglConfig == null) {
             throw new RuntimeException("eglConfig not initialized");
         }

         mEglContext = createContext(mEgl, mEglDisplay, mEglConfig);

         mEglSurface = mEgl.eglCreateWindowSurface(mEglDisplay, mEglConfig, mSurface, null);

         if (mEglSurface == null || mEglSurface == EGL10.EGL_NO_SURFACE)
         {
             int error = mEgl.eglGetError();
             if (error == EGL10.EGL_BAD_NATIVE_WINDOW) {
                 Log.e(LOG_TAG, "createWindowSurface returned EGL_BAD_NATIVE_WINDOW.");
                 return;
             }
             throw new RuntimeException("createWindowSurface failed "
                     + GLUtils.getEGLErrorString(error));
         }

         if (!mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext)) {
             throw new RuntimeException("eglMakeCurrent failed "
                     + GLUtils.getEGLErrorString(mEgl.eglGetError()));
         }

         mGL = mEglContext.getGL();
     }

     EGLContext createContext(EGL10 egl, EGLDisplay eglDisplay, EGLConfig eglConfig) {
         int[] attrib_list = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL10.EGL_NONE };
         return egl.eglCreateContext(eglDisplay, eglConfig, EGL10.EGL_NO_CONTEXT, attrib_list);
     }

     private EGLConfig chooseEglConfig() {
         int[] configsCount = new int[1];
         EGLConfig[] configs = new EGLConfig[1];
         int[] configSpec = getConfig();
         if (!mEgl.eglChooseConfig(mEglDisplay, configSpec, configs, 1, configsCount)) {
             throw new IllegalArgumentException("eglChooseConfig failed " +
                     GLUtils.getEGLErrorString(mEgl.eglGetError()));
         } else if (configsCount[0] > 0) {
             return configs[0];
         }
         return null;
     }

     private int[] getConfig() {
         return new int[] {
                 EGL10.EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
                 EGL10.EGL_RED_SIZE, 8,
                 EGL10.EGL_GREEN_SIZE, 8,
                 EGL10.EGL_BLUE_SIZE, 8,
                 EGL10.EGL_ALPHA_SIZE, 8,
                 EGL10.EGL_DEPTH_SIZE, 0,
                 EGL10.EGL_STENCIL_SIZE, 0,
                 EGL10.EGL_NONE
         };
     }

     void finish() {
         mFinished = true;
     }
 }
</code>```

Body:
A moderator deleted this answer so adding it back for posterity:

See Romain Guy's answer (Nov 23rd 2011) from the android-dev google group:

http://groups.google.com/group/android-developers/browse_thread/thread/539457146a401cf1 (mirrored: http://grokbase.com/t/gg/android-developers/11bqmgb7sw/how-to-replace-glsurfaceview-with-textureview-in-android-ice-cream-sandwich)

GLSurfaceView handles GL setup for you, which TextureView will not do.
  A TextureView can be used as the native window when you create an EGL
  surface. Here is an example (the interesting part is the call to
  eglCreateWindowSurface()):

 @Override
 public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
     mRenderThread = new RenderThread(getResources(), surface);
     mRenderThread.start();
 }

 private static class RenderThread extends Thread {
     private static final String LOG_TAG = "GLTextureView";

     static final int EGL_CONTEXT_CLIENT_VERSION = 0x3098;
     static final int EGL_OPENGL_ES2_BIT = 4;

     private volatile boolean mFinished;

     private final Resources mResources;
     private final SurfaceTexture mSurface;

     private EGL10 mEgl;
     private EGLDisplay mEglDisplay;
     private EGLConfig mEglConfig;
     private EGLContext mEglContext;
     private EGLSurface mEglSurface;
     private GL mGL;

     RenderThread(Resources resources, SurfaceTexture surface) {
         mResources = resources;
         mSurface = surface;
     }

     private static final String sSimpleVS =
             "attribute vec4 position;\n" +
             "attribute vec2 texCoords;\n" +
             "varying vec2 outTexCoords;\n" +
             "\nvoid main(void) {\n" +
             " outTexCoords = texCoords;\n" +
             " gl_Position = position;\n" +
             "}\n\n";
     private static final String sSimpleFS =
             "precision mediump float;\n\n" +
             "varying vec2 outTexCoords;\n" +
             "uniform sampler2D texture;\n" +
             "\nvoid main(void) {\n" +
             " gl_FragColor = texture2D(texture, outTexCoords);\n" +
             "}\n\n";

     private static final int FLOAT_SIZE_BYTES = 4;
     private static final int TRIANGLE_VERTICES_DATA_STRIDE_BYTES = 5 * FLOAT_SIZE_BYTES;
     private static final int TRIANGLE_VERTICES_DATA_POS_OFFSET = 0;
     private static final int TRIANGLE_VERTICES_DATA_UV_OFFSET = 3;
     private final float[] mTriangleVerticesData = {
             // X, Y, Z, U, V
             -1.0f, -1.0f, 0.0f, 0.0f, 0.0f,
              1.0f, -1.0f, 0.0f, 1.0f, 0.0f,
             -1.0f, 1.0f, 0.0f, 0.0f, 1.0f,
              1.0f, 1.0f, 0.0f, 1.0f, 1.0f,
     };

     @Override
     public void run() {
         initGL();

         FloatBuffer triangleVertices = ByteBuffer.allocateDirect(mTriangleVerticesData.length * FLOAT_SIZE_BYTES).order(ByteOrder.nativeOrder()).asFloatBuffer();
         triangleVertices.put(mTriangleVerticesData).position(0);

         int texture = loadTexture(R.drawable.large_photo);
         int program = buildProgram(sSimpleVS, sSimpleFS);

         int attribPosition = glGetAttribLocation(program, "position");
         checkGlError();

         int attribTexCoords = glGetAttribLocation(program, "texCoords");
         checkGlError();

         int uniformTexture = glGetUniformLocation(program, "texture");
         checkGlError();

         glBindTexture(GL_TEXTURE_2D, texture);
         checkGlError();

         glUseProgram(program);
         checkGlError();

         glEnableVertexAttribArray(attribPosition);
         checkGlError();

         glEnableVertexAttribArray(attribTexCoords);
         checkGlError();

         glUniform1i(uniformTexture, texture);
         checkGlError();

         while (!mFinished) {
             checkCurrent();

             glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
             checkGlError();

             glClear(GL_COLOR_BUFFER_BIT);
             checkGlError();

             // drawQuad

             triangleVertices.position(TRIANGLE_VERTICES_DATA_POS_OFFSET);
             glVertexAttribPointer(attribPosition, 3, GL_FLOAT, false,
                     TRIANGLE_VERTICES_DATA_STRIDE_BYTES, triangleVertices);

             triangleVertices.position(TRIANGLE_VERTICES_DATA_UV_OFFSET);
             glVertexAttribPointer(attribTexCoords, 3, GL_FLOAT, false,
                     TRIANGLE_VERTICES_DATA_STRIDE_BYTES, triangleVertices);

             glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

             if (!mEgl.eglSwapBuffers(mEglDisplay, mEglSurface)) {
                 throw new RuntimeException("Cannot swap buffers");
             }
             checkEglError();

             try {
                 Thread.sleep(2000);
             } catch (InterruptedException e) {
                 // Ignore
             }
         }

         finishGL();
     }

     private int loadTexture(int resource) {
         int[] textures = new int[1];

         glActiveTexture(GL_TEXTURE0);
         glGenTextures(1, textures, 0);
         checkGlError();

         int texture = textures[0];
         glBindTexture(GL_TEXTURE_2D, texture);
         checkGlError();

         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

         Bitmap bitmap = BitmapFactory.decodeResource(mResources, resource);

         GLUtils.texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bitmap, GL_UNSIGNED_BYTE, 0);
         checkGlError();

         bitmap.recycle();

         return texture;
     }

     private int buildProgram(String vertex, String fragment) {
         int vertexShader = buildShader(vertex, GL_VERTEX_SHADER);
         if (vertexShader == 0) return 0;

         int fragmentShader = buildShader(fragment, GL_FRAGMENT_SHADER);
         if (fragmentShader == 0) return 0;

         int program = glCreateProgram();
         glAttachShader(program, vertexShader);
         checkGlError();

         glAttachShader(program, fragmentShader);
         checkGlError();

         glLinkProgram(program);
         checkGlError();

         int[] status = new int[1];
         glGetProgramiv(program, GL_LINK_STATUS, status, 0);
         if (status[0] != GL_TRUE) {
             String error = glGetProgramInfoLog(program);
             Log.d(LOG_TAG, "Error while linking program:\n" + error);
             glDeleteShader(vertexShader);
             glDeleteShader(fragmentShader);
             glDeleteProgram(program);
             return 0;
         }

         return program;
     }

     private int buildShader(String source, int type) {
         int shader = glCreateShader(type);

         glShaderSource(shader, source);
         checkGlError();

         glCompileShader(shader);
         checkGlError();

         int[] status = new int[1];
         glGetShaderiv(shader, GL_COMPILE_STATUS, status, 0);
         if (status[0] != GL_TRUE) {
             String error = glGetShaderInfoLog(shader);
             Log.d(LOG_TAG, "Error while compiling shader:\n" + error);
             glDeleteShader(shader);
             return 0;
         }

         return shader;
     }

     private void checkEglError() {
         int error = mEgl.eglGetError();
         if (error != EGL10.EGL_SUCCESS) {
             Log.w(LOG_TAG, "EGL error = 0x" + Integer.toHexString(error));
         }
     }

     private void checkGlError() {
         int error = glGetError();
         if (error != GL_NO_ERROR) {
             Log.w(LOG_TAG, "GL error = 0x" + Integer.toHexString(error));
         }
     }

     private void finishGL() {
         mEgl.eglDestroyContext(mEglDisplay, mEglContext);
         mEgl.eglDestroySurface(mEglDisplay, mEglSurface);
     }

     private void checkCurrent() {
         if (!mEglContext.equals(mEgl.eglGetCurrentContext()) ||

         !mEglSurface.equals(mEgl.eglGetCurrentSurface(EGL10.EGL_DRAW))) {
             if (!mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext)) {
                 throw new RuntimeException("eglMakeCurrent failed " + GLUtils.getEGLErrorString(mEgl.eglGetError()));
             }
         }
     }

     private void initGL() {
         mEgl = (EGL10) EGLContext.getEGL();

         mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
         if (mEglDisplay == EGL10.EGL_NO_DISPLAY) {
             throw new RuntimeException("eglGetDisplay failed "
                     + GLUtils.getEGLErrorString(mEgl.eglGetError()));
         }

         int[] version = new int[2];
         if (!mEgl.eglInitialize(mEglDisplay, version)) {
             throw new RuntimeException("eglInitialize failed " +
                     GLUtils.getEGLErrorString(mEgl.eglGetError()));
         }

         mEglConfig = chooseEglConfig();
         if (mEglConfig == null) {
             throw new RuntimeException("eglConfig not initialized");
         }

         mEglContext = createContext(mEgl, mEglDisplay, mEglConfig);

         mEglSurface = mEgl.eglCreateWindowSurface(mEglDisplay, mEglConfig, mSurface, null);

         if (mEglSurface == null || mEglSurface == EGL10.EGL_NO_SURFACE)
         {
             int error = mEgl.eglGetError();
             if (error == EGL10.EGL_BAD_NATIVE_WINDOW) {
                 Log.e(LOG_TAG, "createWindowSurface returned EGL_BAD_NATIVE_WINDOW.");
                 return;
             }
             throw new RuntimeException("createWindowSurface failed "
                     + GLUtils.getEGLErrorString(error));
         }

         if (!mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext)) {
             throw new RuntimeException("eglMakeCurrent failed "
                     + GLUtils.getEGLErrorString(mEgl.eglGetError()));
         }

         mGL = mEglContext.getGL();
     }

     EGLContext createContext(EGL10 egl, EGLDisplay eglDisplay, EGLConfig eglConfig) {
         int[] attrib_list = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL10.EGL_NONE };
         return egl.eglCreateContext(eglDisplay, eglConfig, EGL10.EGL_NO_CONTEXT, attrib_list);
     }

     private EGLConfig chooseEglConfig() {
         int[] configsCount = new int[1];
         EGLConfig[] configs = new EGLConfig[1];
         int[] configSpec = getConfig();
         if (!mEgl.eglChooseConfig(mEglDisplay, configSpec, configs, 1, configsCount)) {
             throw new IllegalArgumentException("eglChooseConfig failed " +
                     GLUtils.getEGLErrorString(mEgl.eglGetError()));
         } else if (configsCount[0] > 0) {
             return configs[0];
         }
         return null;
     }

     private int[] getConfig() {
         return new int[] {
                 EGL10.EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
                 EGL10.EGL_RED_SIZE, 8,
                 EGL10.EGL_GREEN_SIZE, 8,
                 EGL10.EGL_BLUE_SIZE, 8,
                 EGL10.EGL_ALPHA_SIZE, 8,
                 EGL10.EGL_DEPTH_SIZE, 0,
                 EGL10.EGL_STENCIL_SIZE, 0,
                 EGL10.EGL_NONE
         };
     }

     void finish() {
         mFinished = true;
     }
 }


问:
Swift: Expandable Static TableView
Before I post this, I have read some article like this or this , but all of that example always using dynamic data. I want to know how implement expandable tableview in static data. I think this is more simple but I don't have any idea. My snippet code : </p>

```<code>override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if (indexPath.section == 1) {
        if indexPath.row == self.department {
            cell.accessoryType = .checkmark
        } else {
            cell.accessoryType = .none
        }
    }

    if indexPath.section == 0 {
        if indexPath.row == 2 {
            datePickerFrom.isHidden = true
        }
        else if indexPath.row == 4 {
            datePickerUntil.isHidden = true
        }
    }

}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: false)

    if indexPath.section == 1 {
        let lastDepartment = self.department
        self.department = indexPath.row

        tableView.reloadRows(at: [indexPath, IndexPath.init(row: lastDepartment, section: 1)], with: .none)
    }

    if indexPath.section == 0 {
        if indexPath.row == 2 {
            datePickerFrom.isHidden = false
        }
        else if indexPath.row == 4 {
            datePickerUntil.isHidden = false
        }

        tableView.reloadData()
    }
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    var count = 0
    if section == 0 {

    } else if section == 1 {
        count = 2
    } else if section == 2 || section == 3 {
        count = 1
    }

    return count
}
</code>```

<p>Let's say I have 4 section. I want make first section be expandable but with static table, cell and static data. </p>

答:
From Apple's developer site:

Static cells: Use static content to design the overall layout of the
table, including the total number of cells. A table view with static
content has a fixed set of cells that you can configure at design
time. You can also configure other static data elements such as
section headers. Use static cells when a table does not change its
layout, regardless of the specific information it displays

In your scenario, since you are using a dynamic data source, you'll have to make your table view dynamic

Title: Swift: Expandable Static TableView

Body:
Before I post this, I have read some article like this or this , but all of that example always using dynamic data. I want to know how implement expandable tableview in static data. I think this is more simple but I don't have any idea. My snippet code :

override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if (indexPath.section == 1) {
        if indexPath.row == self.department {
            cell.accessoryType = .checkmark
        } else {
            cell.accessoryType = .none
        }
    }

    if indexPath.section == 0 {
        if indexPath.row == 2 {
            datePickerFrom.isHidden = true
        }
        else if indexPath.row == 4 {
            datePickerUntil.isHidden = true
        }
    }

}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: false)

    if indexPath.section == 1 {
        let lastDepartment = self.department
        self.department = indexPath.row

        tableView.reloadRows(at: [indexPath, IndexPath.init(row: lastDepartment, section: 1)], with: .none)
    }

    if indexPath.section == 0 {
        if indexPath.row == 2 {
            datePickerFrom.isHidden = false
        }
        else if indexPath.row == 4 {
            datePickerUntil.isHidden = false
        }

        tableView.reloadData()
    }
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    var count = 0
    if section == 0 {

    } else if section == 1 {
        count = 2
    } else if section == 2 || section == 3 {
        count = 1
    }

    return count
}

Let's say I have 4 section. I want make first section be expandable but with static table, cell and static data.


答:
Yes GIT is a good solution for a large project. But you have to deal the route or any common file on which more than one person is working so that the merge conflict are minimum. On any common file make different code block like:

```<code>/* Block 1 Start */

/* Block 1 End */

/* Block 2 Start */

/* Block 2 End */
</code>```

and put all the related functionality inside these blocks, so that the conflict are minimum and when it occurs, it is easy to resolve the conflict as the blocks are divided.

Title: Is GIT a good solution for large projects like Laravel?

Body: When a team work on a Laravel project, they usually edit route file, the same controllers and views. Resulting in thousands of merging conflicts. And resolving them is time consuming. Is there a way of preventing these conflicts?.

Body:
Yes GIT is a good solution for a large project. But you have to deal the route or any common file on which more than one person is working so that the merge conflict are minimum. On any common file make different code block like:

/* Block 1 Start */

/* Block 1 End */

/* Block 2 Start */

/* Block 2 End */

and put all the related functionality inside these blocks, so that the conflict are minimum and when it occurs, it is easy to resolve the conflict as the blocks are divided.


问:
Cassandra Snapshot and Restart
Being a level 1 novice in Linux (Ubuntu 9), shell and cron, I've had some difficulty figuring this out. Each night, I'd like to take a snapshot of our Cassandra nodes and restart the process.

Why? Because our team is hunting down a memory leak that requires a process restart every 3 weeks or so. The root cause has been difficult to track down. In the meantime, I'd like to put these cron jobs in place to reduce service interruption.

Thanks in advance for anyone who has some of these already figured out!

答:
The general procedure is:

Run nodetool drain (http://www.riptano.com/docs/0.6/utilities/nodetool#nodetool-drain) on the node

Run nodetool snapshot

Kill the cassandra process

Start the cassandra process

When running nodetool snapshot, it is very important that you have JNA set up and working. This includes:

Having jna.jar in Cassandra's lib directory and either:

Running Cassandra as root, or

Increasing the memory locking limit using 'ulimit -l' or something like /etc/security/limits.conf

If this is all correct, you should see a message about "mlockall" succeeding in the logs on startup.

The other thing to keep an eye on is your disk space usage; this will grow as compactions occur and the old SSTables are replaced (but their snapshots remain).

Title: Cassandra Snapshot and Restart


问:
Building shared library with ffmpeg results in relocation error
I need to create a custom shared library that internally uses ffmpeg functions. The idea is to create one fat shared library, say, myffmpeg.so.

I first build ffmpeg code (3.3.1 as of this post). During configuration, I specify -fPIC via --extra-cflags and --extra-cxxflags. I also specify -enable-pic during the configuration. After running configure and make,  various archive files such as libswscale.a, libavformat.a, etc. are successfully created.

Next, I try to build my shared library:

```<code>gcc -fPIC -Ixxx  mywrapper.cpp
gcc -shared -o myffmpeg.so mywrapper.o -Lxxx -lswscale -lavformat...
</code>```

However, this results in an error:

```<code>Relocation R_X86_64_PC32 against symbol ff_M24A can not be
used when making a shared object;
</code>```

Looks like I am missing some compiler/linker setting. Can someone please point me in the right direction? Regards.

答: Here is how I solved the problem. You need to add "-Wl,-Bsymbolic" to ldflags during configuration. Also, when you create the shared library, you need to pass the same parameter to the linker. Regards.</p>

Body:
I need to create a custom shared library that internally uses ffmpeg functions. The idea is to create one fat shared library, say, myffmpeg.so.

I first build ffmpeg code (3.3.1 as of this post). During configuration, I specify -fPIC via --extra-cflags and --extra-cxxflags. I also specify -enable-pic during the configuration. After running configure and make,  various archive files such as libswscale.a, libavformat.a, etc. are successfully created.

Next, I try to build my shared library:

gcc -fPIC -Ixxx  mywrapper.cpp
gcc -shared -o myffmpeg.so mywrapper.o -Lxxx -lswscale -lavformat...

However, this results in an error:

Relocation R_X86_64_PC32 against symbol ff_M24A can not be
used when making a shared object;

Looks like I am missing some compiler/linker setting. Can someone please point me in the right direction? Regards.


问:
How remove \n from lines
```<code>file, _ := os.Open("x.txt")
    f := bufio.NewReader(file)

    for {
        read_line, _ := ReadString('\n')
        fmt.Print(read_line)

        // other code what work with parsed line...
        }
</code>```

end it add \n on every line , end program to work , only work with last line...

Please put example, i try anything end any solution what i find here not work for me.

答:
If you want to read a file line-by-line, using bufio.Scanner will be easier. Scanner won't includes endline (\n or \r\n) into the line.

```<code>file, err := os.Open("yourfile.txt")
if err != nil {
    //handle error
    return
}
defer file.Close()

s := bufio.NewScanner(file)
for s.Scan() {
    read_line := s.Text()

    // other code what work with parsed line...
}
</code>```

If you want to remove endline, I suggest you to use TrimRightFunc, i.e.

```<code>read_line = strings.TrimRightFunc(read_line, func(c rune) bool {
    //In windows newline is \r\n
    return c == '\r' || c == '\n'
})
</code>```

Update:

As pointed by @GwynethLlewelyn, using TrimRight will be simpler (cleaner), i.e.

```<code> read_line = strings.TrimRight(read_line, "\r\n")
</code>```

Internally, TrimRight function call TrimRightFunc, and will remove the character if it match any character given as the second argument of TrimRight.

Title: How remove \n from lines

Body:
file, _ := os.Open("x.txt")
    f := bufio.NewReader(file)

    for {
        read_line, _ := ReadString('\n')
        fmt.Print(read_line)

        // other code what work with parsed line...
        }

end it add \n on every line , end program to work , only work with last line...

Please put example, i try anything end any solution what i find here not work for me.

Body:
If you want to read a file line-by-line, using bufio.Scanner will be easier. Scanner won't includes endline (\n or \r\n) into the line.

file, err := os.Open("yourfile.txt")
if err != nil {
    //handle error
    return
}
defer file.Close()

s := bufio.NewScanner(file)
for s.Scan() {
    read_line := s.Text()

    // other code what work with parsed line...
}

If you want to remove endline, I suggest you to use TrimRightFunc, i.e.

read_line = strings.TrimRightFunc(read_line, func(c rune) bool {
    //In windows newline is \r\n
    return c == '\r' || c == '\n'
})

Update:

As pointed by @GwynethLlewelyn, using TrimRight will be simpler (cleaner), i.e.

 read_line = strings.TrimRight(read_line, "\r\n")

Internally, TrimRight function call TrimRightFunc, and will remove the character if it match any character given as the second argument of TrimRight.


问:
What does "Host key did not appear in manually configured list" mean?
I'm trying to set up an SSH key pair. I have so far I have

Generated the pair with PuTTYGen

Saved the private key to the client machine

Added the public key to server. I put it in the ~/.ssh/authorized_keys file for the user that I will be using to connect

Added the fingerprint from PuTTYGen to the Connection > SSH > Host Keys menu in PuTTY

Added the path of the private key to the Connection > SSH > Auth menu in PuTTY

But when I try to connect I get the error "Host key did not appear in manually configured list".

答:
The step 4 is wrong:

Added the fingerprint from PuTTYGen to the Connection > SSH > Host Keys menu in PuTTY

The "Host keys" box is for public key of the server (host key). While you have added there your public key.

In general, you do not need to add anything there. Just verify the host key on the prompt, that you will get on the first connection. What you have probably done already anyway. If not, see my article Where do I get SSH host key fingerprint to authorize the server? – You can also check another article Understanding SSH Key Pairs.


问:
In Eiffel, what is the difference between entities, variables, fields and arguments?
I've seen the terms entity, variable, and argument used to describe things about Eiffel, that look quite similar to me, and I wanted to understand what is the intention behind using either term instead of the other.

Arguments — Some routines require some data in order to run. Imagine a fictitious feature foo (x, y: INTEGER; z: BOOLEAN). This routine takes 3 arguments: x, y, and z. When you call the routine, you must give it three valid arguments, for instance foo(6, 92, False). These values we passed to the routine are called actual arguments, while the placeholders defined in the definition are called formal arguments.

I've read of object fields, which specify the place inside the object structure where values are stored (either references or expanded objects).

I think the only time I saw the term variables was for local variables, inside features.

And entity seems to be a generic term for denoting a data-container with a name, so local variables, arguments, and querys (features that return some data) are all examples of entities.

And in what category would Current and Result fall? Local variables?

Could someone help me with the terminology?

答:
You will see clear definitions for those terms in the ECMA Eiffel specification (Standard ECMA-367, section 8: Language specification).

To summarize:

An entity is either: argument, local, attribute (including constant attribute), Current or Result.

A variable is a local or an attribute (not including constant attribute). However, we often count Result as if it was a pseudo locals so it would be ok to call it also a variable, but the standard doesn't.

Note that none of the above includes routines (i.e. procedures or functions, also known as commands and queries in the Eiffel terminology).