问:
Python Buildozer PyMySQL Cant Connect
I have created a application inside kivy using the pymysql module to create a simple log in system. The python file runs without errors on my desktop, but when I run the app on my Nexus tablet it crashes and throws following errors.

Can someone identify the cause of this issue and point me in the right direction? Thanks.

```<code>06-07 12:07:35.319 10766 10786 I python  :  Traceback (most recent call     last):
06-07 12:07:35.342 10766 10786 I python  :    File "/home/andrew/Desktop/Python/Kivy/1-application/.buildozer/android/app/main.py", line 83, in <module>
06-07 12:07:35.343 10766 10786 I python  :    File "/home/andrew/Desktop/Python/Kivy/1-application/.buildozer/android/platform/build/dists/myapp/private/lib/python2.7/site-packages/pymysql/__init__.py", line 90, in Connect
06-07 12:07:35.344 10766 10786 I python  :    File "/home/andrew/Desktop/Python/Kivy/1-application/.buildozer/android/platform/build/dists/myapp/private/lib/python2.7/site-packages/pymysql/connections.py", line 706, in __init__
06-07 12:07:35.345 10766 10786 I python  :    File "/home/andrew/Desktop/Python/Kivy/1-application/.buildozer/android/platform/build/dists/myapp/private/lib/python2.7/site-packages/pymysql/connections.py", line 963, in connect
06-07 12:07:35.346 10766 10786 I python  :  pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on '<IP ADDRESS>' ([Errno 13] Permission denied)")
06-07 12:07:35.402 10766 10786 I python  : Python for android ended.
</code>```

EDIT:
I went into the buildozer.spec file and uncommented the permission for internet access now im getting a timeout error.

```<code>pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on '<IP ADDRESS>' (timed out)")
</code>```

Here is a sample of how I am trying to connect to my db...

```<code>from kivy.app import App
from kivy.uix.gridlayout import GridLayout
import pymysql.cursors

class LoginScreen(GridLayout):
    #CONTENT HERE

class SimpleKivy(App):
    def build(self):
        return LoginScreen()

if __name__ == "__main__":
    #Error Happens Here
    connection = pymysql.connect(host="<IP ADDRESS>", user="usr", password="pswd", db="slogin")

    SimpleKivy().run()
</code>```

答: Fixed. Firewall was blocking access to MYSQL server and the error without exception handling caused the application to crash.</p>

Title: Python Buildozer PyMySQL Cant Connect

Body:
I have created a application inside kivy using the pymysql module to create a simple log in system. The python file runs without errors on my desktop, but when I run the app on my Nexus tablet it crashes and throws following errors.

Can someone identify the cause of this issue and point me in the right direction? Thanks.

06-07 12:07:35.319 10766 10786 I python  :  Traceback (most recent call     last):
06-07 12:07:35.342 10766 10786 I python  :    File "/home/andrew/Desktop/Python/Kivy/1-application/.buildozer/android/app/main.py", line 83, in <module>
06-07 12:07:35.343 10766 10786 I python  :    File "/home/andrew/Desktop/Python/Kivy/1-application/.buildozer/android/platform/build/dists/myapp/private/lib/python2.7/site-packages/pymysql/__init__.py", line 90, in Connect
06-07 12:07:35.344 10766 10786 I python  :    File "/home/andrew/Desktop/Python/Kivy/1-application/.buildozer/android/platform/build/dists/myapp/private/lib/python2.7/site-packages/pymysql/connections.py", line 706, in __init__
06-07 12:07:35.345 10766 10786 I python  :    File "/home/andrew/Desktop/Python/Kivy/1-application/.buildozer/android/platform/build/dists/myapp/private/lib/python2.7/site-packages/pymysql/connections.py", line 963, in connect
06-07 12:07:35.346 10766 10786 I python  :  pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on '<IP ADDRESS>' ([Errno 13] Permission denied)")
06-07 12:07:35.402 10766 10786 I python  : Python for android ended.

EDIT:
I went into the buildozer.spec file and uncommented the permission for internet access now im getting a timeout error.

pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on '<IP ADDRESS>' (timed out)")

Here is a sample of how I am trying to connect to my db...

from kivy.app import App
from kivy.uix.gridlayout import GridLayout
import pymysql.cursors

class LoginScreen(GridLayout):
    #CONTENT HERE

class SimpleKivy(App):
    def build(self):
        return LoginScreen()

if __name__ == "__main__":
    #Error Happens Here
    connection = pymysql.connect(host="<IP ADDRESS>", user="usr", password="pswd", db="slogin")

    SimpleKivy().run()


来源: stackexchange

问:
Maximum length of the text field increases automatically on Data import in CRM
I have an Excel file to import in MS Dynamics CRM 365.

In that file, there is a text field column that contains data of maximum 11 characters. In CRM, the maximum length of that field is 10 characters.

Instead of restricting such records from importing, CRM automatically increases the maximum length of the field in CRM to 11 characters.

So how can we set not to customize the field max length on data import in CRM?

答:
I guess I am not an expert on the CRM Data Import, but I reckon that now you have identified this problem it is easy to workaround using Excel

before you import the file, modify it in Excel to do what you want

2 possibilities
1) you want to import all the records, but just the first 10 characters of the text column:  create a new column, and fill it with the formula LEFT(C2,10)
(If the text is in column C).  And copy the result back to the text column with Paste Values.  Then delete the new column and save the Excel and import

2) you want to omit the rows with more than 10 characters long. Use Filter to choose just the shorter rows, copy them to a new spreadsheet, delete all the rows except the header from the original spreadsheet, and copy-and-paste all the filtered rows back.  Then import that spreadsheet.

ContentLicense: CC BY-SA 3.0


问:
Android animation imageview 1st rotate and then fadeout for splash
I am trying to make a splash screen for my Android app. I have found many answer related to this question. but none of those worked correctly. I just want to
1. first fade_in an imageView, then rotate and then  fade_out
or 2. all at the same time. I have tried these code

```<code>    final ImageView iv = (ImageView) findViewById(R.id.imageView);
    final Animation an = AnimationUtils.loadAnimation(getBaseContext(),R.anim.animate);

    iv.startAnimation(an);
    an.setAnimationListener(new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {}

        @Override
        public void onAnimationEnd(Animation animation) {
            finish();
            Intent i = new Intent(getBaseContext(),Welcome.class);
            startActivity(i);
        }

        @Override
        public void onAnimationRepeat(Animation animation) {}
    });
</code>```

and in animate xml

```<code>    <?xml version="1.0" encoding="utf-8"?>
    <set xmlns:android="http://schemas.android.com/apk/res/android" android:fillAfter="true">

<rotate
    android:duration="10000"
    android:fromDegrees="0"
    android:toDegrees="360"
    android:pivotX="50%"
    android:pivotY="50%"
    />

<alpha
    android:fromAlpha="1.0"
    android:toAlpha="0.0"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:duration="5000"/>
<alpha
    android:fromAlpha="0.0"
    android:toAlpha="1.0"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:duration="5000"/>

</set>
</code>```

答:
You have to specify startOffset. If not specified all elements in your animation sets will all start simultaneously. Try this:

```<code><?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" android:fillAfter="true">

    <alpha
        android:fromAlpha="1.0"
        android:toAlpha="0.0"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:duration="5000" />

    <rotate
        android:duration="10000"
        android:fromDegrees="0"
        android:toDegrees="360"
        android:pivotX="50%"
        android:pivotY="50%"
        android:startOffset="5000" />

    <alpha
        android:fromAlpha="0.0"
        android:toAlpha="1.0"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:duration="5000"
        android:startOffset="15000" />

</set>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to make a splash screen for my Android app. I have found many answer related to this question. but none of those worked correctly. I just want to
1. first fade_in an imageView, then rotate and then  fade_out
or 2. all at the same time. I have tried these code

    final ImageView iv = (ImageView) findViewById(R.id.imageView);
    final Animation an = AnimationUtils.loadAnimation(getBaseContext(),R.anim.animate);

    iv.startAnimation(an);
    an.setAnimationListener(new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {}

        @Override
        public void onAnimationEnd(Animation animation) {
            finish();
            Intent i = new Intent(getBaseContext(),Welcome.class);
            startActivity(i);
        }

        @Override
        public void onAnimationRepeat(Animation animation) {}
    });

and in animate xml

    <?xml version="1.0" encoding="utf-8"?>
    <set xmlns:android="http://schemas.android.com/apk/res/android" android:fillAfter="true">

<rotate
    android:duration="10000"
    android:fromDegrees="0"
    android:toDegrees="360"
    android:pivotX="50%"
    android:pivotY="50%"
    />

<alpha
    android:fromAlpha="1.0"
    android:toAlpha="0.0"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:duration="5000"/>
<alpha
    android:fromAlpha="0.0"
    android:toAlpha="1.0"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:duration="5000"/>

</set>

Body:
You have to specify startOffset. If not specified all elements in your animation sets will all start simultaneously. Try this:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" android:fillAfter="true">

    <alpha
        android:fromAlpha="1.0"
        android:toAlpha="0.0"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:duration="5000" />

    <rotate
        android:duration="10000"
        android:fromDegrees="0"
        android:toDegrees="360"
        android:pivotX="50%"
        android:pivotY="50%"
        android:startOffset="5000" />

    <alpha
        android:fromAlpha="0.0"
        android:toAlpha="1.0"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:duration="5000"
        android:startOffset="15000" />

</set>


问:
Image resizing service (for Rails, or anything really)
I'm looking for a (ideally self-hosted) service that lets me do something like

This service would:

download http://mydomain.com/path/to/image.jpg (if it hadn't before)

resize it to 150x100

strip / squash the thumbnail of metadata (and whatever else is good for thumbnails)

cache the thumbnail (to disk, or maybe to s3?)

serve it to the client

on subsequent requests for that URL, serve the same cached thumbnail

This would allow me

only have the original image on my site and outsource the thumbnail generation to another service

allow me to easily create new thumbnail sizes

should be efficient

Does something like that exist?  Would prefer open source, and hopefully either in Ruby or Node.js.

Bonus points for working on a limited amount of diskspace (i.e. so it would only cache, say, 5GB of images).

答: Image Science may fulfill your thumbnailing needs, although the whole caching, hosting and metadata stripping will require other tools.</p>

ContentLicense: CC BY-SA 2.5


问:
How do you lock a button's position in JavaFX?
In one of my javafx projects I have a button that triggers the program. Upon displaying new data sometimes the button is pushed downwards due to other components of the borderpane expanding. Any way I can lock the button to a specific position so that it does not move if that occurs?</p>

答:
You could try placing the button on a separate Pane outside of the BorderPane, then grouping both Panes on a root Pane/main Pane of some sort, like so:

Any layout changes to child components of the BorderPane will not affect the layout of any components outside of it.

As you can see though, this leaves empty space at the top of the application. You can overlap the StackPane with the Button on top of the BorderPane if you fiddle with its layout settings, but this does mean that any child components of the BorderPane can be hidden behind the StackPane. It's up to you to decide which way you prefer.


问:
How to resolve cannot import name pages (django/wagtail)
Recently I have been trying to get wagtail to work with my existing Django application. I was experiencing an error: -

```<code>ImportError: No module named wagtail
unable to load app 0 (mountpoint='') (callable not found or import error)
</code>```

After much troubleshooting I managed to fix this, by copying the folder wagtail from:

```<code>/usr/local/lib/python2.7/dist-packages/
</code>```

into here

```<code>/opt/django/src/
</code>```

Having resolved this error, I received another about a different module, and another... each time I copied the folder from   /usr/local/lib/python2.7/dist-packages/ into /opt/django/src/ and it eventually resolved the issues I was having and uWSGI started.

Now when I access the homepage of my app, I receive this error

```<code>ImportError at /

cannot import name pages

    Request Method:     GET
Request URL:    http://example.com
Django Version:     1.9
Exception Type:     ImportError
Exception Value:

cannot import name pages

Exception Location:     ./wagtail/wagtailadmin/urls/__init__.py in <module>, line 4
Python Executable:  /usr/local/bin/uwsgi
Python Version:     2.7.3
Python Path:

['.',
 '',
 '/opt/django/src',
 '/root/.python',
 '/opt/django/env/lib/python2.7',
 '/opt/django/env/lib/python2.7/plat-linux2',
 '/opt/django/env/lib/python2.7/lib-tk',
 '/opt/django/env/lib/python2.7/lib-old',
 '/opt/django/env/lib/python2.7/lib-dynload',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-linux2',
 '/usr/lib/python2.7/lib-tk',
 '/opt/django/env/local/lib/python2.7/site-packages',
 '/opt/django/env/lib/python2.7/site-packages']
</code>```

I have checked the file referenced (./wagtail/wagtailadmin/urls/__init__.py) and it looks like this:

```<code>from django.conf.urls import url, include
from django.views.decorators.cache import cache_control

from wagtail.wagtailadmin.urls import pages as wagtailadmin_pages_urls
from wagtail.wagtailadmin.urls import collections as wagtailadmin_collections_urls
from wagtail.wagtailadmin.urls import password_reset as wagtailadmin_password_reset_urls
from wagtail.wagtailadmin.views import account, chooser, home, pages, tags, userbar
from wagtail.wagtailadmin.api import urls as api_urls
from wagtail.wagtailcore import hooks
from wagtail.utils.urlpatterns import decorate_urlpatterns
from wagtail.wagtailadmin.decorators import require_admin_access
</code>```

The offending line is the first wagtail 'from' ...

from wagtail.wagtailadmin.urls import pages as wagtailadmin_pages_urls

How can I resolve this error?

答:
I ran into the

cannot import name pages

error at:

from wagtail.wagtailadmin.urls import pages as wagtailadmin_pages_urls

while trying to deploy a wagtail app to Google App Engine and could not duplicate the problem on my local dev server.

A seemingly unrelated error that I saw only intermittently in GAE involved an import error in the PIL library. I was able to resolve BOTH errors by deleting PIL and pillow related folders from my vendored packages in my /lib directory. I had to import PIL through the app.yaml file instead due to the platform specific binary, but running pip install -t lib/ -r requirements-vendor.txt caused PIL to be installed into the lib folder as well (as a dependency of Wagtail)

Body:
Recently I have been trying to get wagtail to work with my existing Django application. I was experiencing an error: -

ImportError: No module named wagtail
unable to load app 0 (mountpoint='') (callable not found or import error)

After much troubleshooting I managed to fix this, by copying the folder wagtail from:

/usr/local/lib/python2.7/dist-packages/

into here

/opt/django/src/

Having resolved this error, I received another about a different module, and another... each time I copied the folder from   /usr/local/lib/python2.7/dist-packages/ into /opt/django/src/ and it eventually resolved the issues I was having and uWSGI started.

Now when I access the homepage of my app, I receive this error

ImportError at /

cannot import name pages

    Request Method:     GET
Request URL:    http://example.com
Django Version:     1.9
Exception Type:     ImportError
Exception Value:

cannot import name pages

Exception Location:     ./wagtail/wagtailadmin/urls/__init__.py in <module>, line 4
Python Executable:  /usr/local/bin/uwsgi
Python Version:     2.7.3
Python Path:

['.',
 '',
 '/opt/django/src',
 '/root/.python',
 '/opt/django/env/lib/python2.7',
 '/opt/django/env/lib/python2.7/plat-linux2',
 '/opt/django/env/lib/python2.7/lib-tk',
 '/opt/django/env/lib/python2.7/lib-old',
 '/opt/django/env/lib/python2.7/lib-dynload',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-linux2',
 '/usr/lib/python2.7/lib-tk',
 '/opt/django/env/local/lib/python2.7/site-packages',
 '/opt/django/env/lib/python2.7/site-packages']

I have checked the file referenced (./wagtail/wagtailadmin/urls/__init__.py) and it looks like this:

from django.conf.urls import url, include
from django.views.decorators.cache import cache_control

from wagtail.wagtailadmin.urls import pages as wagtailadmin_pages_urls
from wagtail.wagtailadmin.urls import collections as wagtailadmin_collections_urls
from wagtail.wagtailadmin.urls import password_reset as wagtailadmin_password_reset_urls
from wagtail.wagtailadmin.views import account, chooser, home, pages, tags, userbar
from wagtail.wagtailadmin.api import urls as api_urls
from wagtail.wagtailcore import hooks
from wagtail.utils.urlpatterns import decorate_urlpatterns
from wagtail.wagtailadmin.decorators import require_admin_access

The offending line is the first wagtail 'from' ...

from wagtail.wagtailadmin.urls import pages as wagtailadmin_pages_urls

How can I resolve this error?


问:
Show result of query with count
I'm making a query with a count statement and I wanna show the result
something like this

I have a file with name functions.php where I make the query in a (obviously) function.

those are my functions:

```<code>function conection($bd_config){
    try {
        $conection = new PDO('mysql:host=localhost;dbname='.$bd_config['database'], $bd_config['user'], $bd_config['pass']);
        return $conection;
    } catch (PDOException $e) {
        return false;
    }
}

function checksession(){
    if (!isset($_SESSION['user'])) {
        header('Location: ' .  ROUTE. '/login.php');
    }
}

@$us = $_SESSION['USER'][0];

    function notification_count($conexion, $us){
        $count = $conection->prepare('SELECT * FROM postulate WHERE du = $us AND seen = 0');
        $count->execute();
        $total = $count->rowCount();
        $total = $count->fetchColumn();
        return $total;
    }
</code>```

I have another file with name lateral.php where I "call" the function and the view of latera.view.php

lateral.php:

```<code><?php session_start();
require 'extras/config.php';
include 'functions.php';

checksession();

$conection = conection($bd_config);

$quantity = notification_count($conection, $us);

require "views/lateral.php";
</code>```

lateral.view.php:

```<code><div class="block-section text-center ">
  <img src="images/<?php echo($_SESSION['user'][14])  ?>" class="img-rounded" alt="">
  <div class="white-space-20"></div>
  <h4><a href="perfil.php"><?php echo($_SESSION['user'][3])  ?></a></h4>
  <div class="white-space-20"></div>
  <ul class="list-unstyled">
    <li><a href="mensajes.php"> Messages </a></li>
    <li><a href="notificaciones.php"> Notifications<?php here is where I want the total of the query ?></a></li>
    <li><a href="cambio.php"> Change password</a></li>

  </ul>
  <div class="white-space-20"></div>
</div>
</div>
<div class="col-md-9 col-sm-9">
<!-- Block side right -->
</code>```

答:
in the file of functions I need to make my query like this:

```<code>function notifications_count($conection, $us){
    $count= $conection->prepare("SELECT COUNT(*) FROM postul WHERE du = $us AND seen = 0");
    $count->execute();
    $number_notu = $count->fetchAll();
    return $number_notu;
}
</code>```

then in the file of notifications.php where onlye I print code and make a require of the view(HTML) I need to put something like this:

```<code><?php session_start();

require 'extra/config.php';
require 'functions.php';

$conection = conection($bd_config);
if (!$conection) {
    header('Location: error.php');
}

$postul= get_people($notu_config['post_notu'], $conection, $us);

if (!$postul) {
    $vacio = "<li>The aren't any notifications</li>";
}

$total_notu = notu_count($conection, $us);

require "views/notifications.php";
</code>```

and in the view of notifications where I print only HTML  I need to make a foreach:

```<code><div class="block-section text-center ">
  <img src="images/<?php echo($_SESSION['user'][14])  ?>" class="img-rounded" alt="">
  <div class="white-space-20"></div>
  <h4><a href="profile.php"><?php echo($_SESSION['user'][3])  ?></a></h4>
  <div class="white-space-20"></div>
  <ul class="list-unstyled">
    <li><a href="messages.php"> Messages</a></li>
    <?php foreach ($total_notu as $notu) : ?>
    <li><a href="notificaciones.php"> Notificaciones <span class="badge "><?php echo "$notu[0]"; ?></span></a></li>
  <?php endforeach; ?>
    <li><a href="change.php"> Change password</a></li>

  </ul>
  <div class="white-space-20"></div>
</div>
</div>
<div class="col-md-9 col-sm-9">
<!-- Block side right -->
</code>```

I hope I can help someone ho are on the same troble like me :)

Title: Show result of query with count

Body:
I'm making a query with a count statement and I wanna show the result
something like this

I have a file with name functions.php where I make the query in a (obviously) function.

those are my functions:

function conection($bd_config){
    try {
        $conection = new PDO('mysql:host=localhost;dbname='.$bd_config['database'], $bd_config['user'], $bd_config['pass']);
        return $conection;
    } catch (PDOException $e) {
        return false;
    }
}

function checksession(){
    if (!isset($_SESSION['user'])) {
        header('Location: ' .  ROUTE. '/login.php');
    }
}

@$us = $_SESSION['USER'][0];

    function notification_count($conexion, $us){
        $count = $conection->prepare('SELECT * FROM postulate WHERE du = $us AND seen = 0');
        $count->execute();
        $total = $count->rowCount();
        $total = $count->fetchColumn();
        return $total;
    }

I have another file with name lateral.php where I "call" the function and the view of latera.view.php

lateral.php:

<?php session_start();
require 'extras/config.php';
include 'functions.php';

checksession();

$conection = conection($bd_config);

$quantity = notification_count($conection, $us);

require "views/lateral.php";

lateral.view.php:

  <img src="images/<?php echo($_SESSION['user'][14])  ?>" class="img-rounded" alt="">

<?php echo($_SESSION['user'][3])  ?>

 Messages

 Notifications<?php here is where I want the total of the query ?>

 Change password

Body:
in the file of functions I need to make my query like this:

function notifications_count($conection, $us){
    $count= $conection->prepare("SELECT COUNT(*) FROM postul WHERE du = $us AND seen = 0");
    $count->execute();
    $number_notu = $count->fetchAll();
    return $number_notu;
}

then in the file of notifications.php where onlye I print code and make a require of the view(HTML) I need to put something like this:

<?php session_start();

require 'extra/config.php';
require 'functions.php';

$conection = conection($bd_config);
if (!$conection) {
    header('Location: error.php');
}

$postul= get_people($notu_config['post_notu'], $conection, $us);

if (!$postul) {
    $vacio = "<li>The aren't any notifications</li>";
}

$total_notu = notu_count($conection, $us);

require "views/notifications.php";

and in the view of notifications where I print only HTML  I need to make a foreach:

<div class="block-section text-center ">
  <img src="images/<?php echo($_SESSION['user'][14])  ?>" class="img-rounded" alt="">
  <div class="white-space-20"></div>
  <h4><a href="profile.php"><?php echo($_SESSION['user'][3])  ?></a></h4>
  <div class="white-space-20"></div>
  <ul class="list-unstyled">
    <li><a href="messages.php"> Messages</a></li>
    <?php foreach ($total_notu as $notu) : ?>
    <li><a href="notificaciones.php"> Notificaciones <span class="badge "><?php echo "$notu[0]"; ?></span></a></li>
  <?php endforeach; ?>
    <li><a href="change.php"> Change password</a></li>

  </ul>
  <div class="white-space-20"></div>
</div>
</div>
<div class="col-md-9 col-sm-9">
<!-- Block side right -->

I hope I can help someone ho are on the same troble like me :)


问:
How stop service with Handler
How make Handler stop together Service

Service:

```<code>int delay = 10000;
new Handler().postDelayed(new Runnable() {
    public void run(){
        //Do Something every 10 seconds
        new Handler().postDelayed(this, delay);
    }
}, delay);

...

public void onDestroy() {
    // TODO: Implement this method
    super.onDestroy();
    stopSelf();
}
</code>```

In Activity on I call stopService this Handler keep running.

答:
Modify your handler in the following way: add a boolean flag which you would set to 'false' when you would need to stop the handler. Inside your runnable, add the following:

```<code>int delay = 10000;
static boolean running = true;
new Handler().postDelayed(new Runnable() {
    public void run(){
        if (running) {
            new Handler().postDelayed(this, delay);
        }
    }
}, delay);

public void onDestroy() {
    super.onDestroy();
    stopSelf();
    running = false;
}
</code>```

It will simply not start again.

Title: How stop service with Handler

Body:
How make Handler stop together Service

Service:

int delay = 10000;
new Handler().postDelayed(new Runnable() {
    public void run(){
        //Do Something every 10 seconds
        new Handler().postDelayed(this, delay);
    }
}, delay);

...

public void onDestroy() {
    // TODO: Implement this method
    super.onDestroy();
    stopSelf();
}

In Activity on I call stopService this Handler keep running.

Body:
Modify your handler in the following way: add a boolean flag which you would set to 'false' when you would need to stop the handler. Inside your runnable, add the following:

int delay = 10000;
static boolean running = true;
new Handler().postDelayed(new Runnable() {
    public void run(){
        if (running) {
            new Handler().postDelayed(this, delay);
        }
    }
}, delay);

public void onDestroy() {
    super.onDestroy();
    stopSelf();
    running = false;
}

It will simply not start again.


问:
PANDAS how to drop columns that have numbers and combine the rest of the columns
I have a DataFrame:

```<code>     A          B       C
  0 PQ          None    None
  1 Chieti      None    None
  2 Gainesville None    None
  3 Wenzhou     325027  None
  4 Boston      None    None
  5 D-53127     Bonn    None
  6 SE-11282    Stockholm None
  7 Birmingham  None    None
  8 Miami       None    None
  9 Los         Angeles None
</code>```

I want to combine the text in all columns  and create a new column which is column 'D' here .However I do not want to include the column if there are numbers or digits in that column . My final output should look like this:

```<code>     A          B       C       D
  0 PQ          None    None    PQ
  1 Chieti      None    None    Chieti
  2 Gainesville None    None    Gainesville
  3 Wenzhou     325027  None    Wenzhou
  4 Boston      None    None    Boston
  5 D-53127     Bonn    None    Bonn
  6 SE-11282    Stockholm None  Stockholm
  7 Birmingham  None    None    Birmingham
  8 Miami       None    None    Miami
  9 Los         Angeles None    LosAngeles
</code>```

Could the knowledgeable folks in Stackoverflow give me an insight into solving this using PANDAS/python

答:
You can mask the cells containing digits can then concat all columns"</p>

```<code>df['D'] = df[~df.fillna('').apply(lambda x: x.str.contains('\d'))]\
            .fillna('').apply(lambda x: ''.join(x), axis=1)
df
Out[810]:
             A          B     C            D
0           PQ       None  None           PQ
1       Chieti       None  None       Chieti
2  Gainesville       None  None  Gainesville
3      Wenzhou     325027  None      Wenzhou
4       Boston       None  None       Boston
5      D-53127       Bonn  None         Bonn
6     SE-11282  Stockholm  None    Stockholm
7   Birmingham       None  None   Birmingham
8        Miami       None  None        Miami
9          Los    Angeles  None   LosAngeles
</code>```

Body:
I have a DataFrame:

     A          B       C
  0 PQ          None    None
  1 Chieti      None    None
  2 Gainesville None    None
  3 Wenzhou     325027  None
  4 Boston      None    None
  5 D-53127     Bonn    None
  6 SE-11282    Stockholm None
  7 Birmingham  None    None
  8 Miami       None    None
  9 Los         Angeles None

I want to combine the text in all columns  and create a new column which is column 'D' here .However I do not want to include the column if there are numbers or digits in that column . My final output should look like this:

     A          B       C       D
  0 PQ          None    None    PQ
  1 Chieti      None    None    Chieti
  2 Gainesville None    None    Gainesville
  3 Wenzhou     325027  None    Wenzhou
  4 Boston      None    None    Boston
  5 D-53127     Bonn    None    Bonn
  6 SE-11282    Stockholm None  Stockholm
  7 Birmingham  None    None    Birmingham
  8 Miami       None    None    Miami
  9 Los         Angeles None    LosAngeles

Could the knowledgeable folks in Stackoverflow give me an insight into solving this using PANDAS/python

Body:
You can mask the cells containing digits can then concat all columns"

df['D'] = df[~df.fillna('').apply(lambda x: x.str.contains('\d'))]\
            .fillna('').apply(lambda x: ''.join(x), axis=1)
df
Out[810]:
             A          B     C            D
0           PQ       None  None           PQ
1       Chieti       None  None       Chieti
2  Gainesville       None  None  Gainesville
3      Wenzhou     325027  None      Wenzhou
4       Boston       None  None       Boston
5      D-53127       Bonn  None         Bonn
6     SE-11282  Stockholm  None    Stockholm
7   Birmingham       None  None   Birmingham
8        Miami       None  None        Miami
9          Los    Angeles  None   LosAngeles


问:
Append HTML Strings to DOMDocument at start and end of DOMXPath
Here is my block of html

```<code>$html = '<div class="importantnoticediv">
            <p class="important-notice-title important-notice-title-1">
                NOTICE:
            </p>
            <p class="important-notice-title important-notice-title-2">
                PROFESSIONAL INSTALLATION IS RECOMMENDED!
            </p>
        </div>';
</code>```

I'm able to initiate a new DOMDocument and target this specific DIV class using DOMXpath

```<code>$dom = new DOMDocument;
$dom->loadHTML($post_content);
$xpath = new DOMXpath($dom);
$importantnotice = $xpath->query('//div[contains(@class, "importantnoticediv")]');
$indiv = $importantnotice->item(0);
</code>```

I'm having a very hard time figuring out how to append the HTML I want to this class, though.

Here's what I'm trying to transform my block of html into:

```<code><div class="importantnoticediv">
    <div class="note-icon note-icon-important">
        <span><i class="fa fa-exclamation" aria-hidden="true"></i>
        </span>
    </div>
    <div class="note-text note-text-important">
        <p class="important-notice-title important-notice-title-1">
                NOTICE:
        </p>
        <p class="important-notice-title important-notice-title-2">
                PROFESSIONAL INSTALLATION IS RECOMMENDED!
        </p>
    </div>
</div>
</code>```

So, in other words,

```<code><div class="note-icon note-icon-important">
    <span><i class="fa fa-exclamation" aria-hidden="true"></i>
    </span>
</div>
<div class="note-text note-text-important">
</code>```

Immediately after my
 as well as add a closing
 at the very end of this div class.

Is this even possible with DOMDocument and DOMXpath? Given that what I am trying to add isn't "valid" html (even though it is, once I do the two steps..)
I understand I can create new elements, but how do I insert just a custom html string immediately after the start and end of my chosen DOMDocument/DOMXpath?

答:
Here's one way to do it. It makes use of DOMDocumentFragment. Admittedly, it's all a bit convoluted.

Furthermore, one problem with DOMDocumentFragment is that, besides appendXML(), it does not have a counterpart method appendHTML(), which means you can only append HTML to it if it validates as XML.

```<code>$html = '<div class="importantnoticediv">
            <p class="important-notice-title important-notice-title-1">
                NOTICE:
            </p>
            <p class="important-notice-title important-notice-title-2">
                PROFESSIONAL INSTALLATION IS RECOMMENDED!
            </p>
        </div>';

$dom = new DOMDocument;
// format our output to make it a tad bit easier on the eyes (doesn't help all that much, though)
$dom->formatOutput = true;
// this implicitly adds <html> and <body> tags
$dom->loadHTML( $html );

$xpath = new DOMXpath( $dom );

// notice I appended /p to your original query, so that we get the list of <p> elements inside the "importantnoticediv"
$nodes = $xpath->query('//div[contains(@class, "importantnoticediv")]/p');
// the first <p>
$p1 = $nodes->item( 0 );
// the second <p>
$p2 = $nodes->item( 1 );

// we create a DOMDocumentFragment that is associated with our DOMDocument
$frag = $dom->createDocumentFragment();

// I append your first HTML fragment (must be valid XML)
$frag->appendXML( '<div class="note-icon note-icon-important">
    <span><i class="fa fa-exclamation" aria-hidden="true"></i>
    </span>
</div>' );
// ... and insert it before our first <p> (parentNode is the "importantnoticediv")
$p1->parentNode->insertBefore( $frag, $p1 );

// frag is now empty again, because we just inserted it(s contents) into the DOMDocument

// we create our second fragment
$frag->appendXML( '<div class="note-text note-text-important"></div>' );

// this time we append it to "importantnoticediv" (i.e. as last child)
// and get the reference to this newly inserted <div>
$insertedNode = $p1->parentNode->appendChild( $frag );

// now we can append (i.e. move) the <p> elements to the newly inserted <div>
$insertedNode->appendChild( $p1 );
$insertedNode->appendChild( $p2 );

// the HTML should now be as desired
echo $dom->saveHTML();
</code>```

Body:
Here is my block of html

$html = '

                NOTICE:

                PROFESSIONAL INSTALLATION IS RECOMMENDED!

';

I'm able to initiate a new DOMDocument and target this specific DIV class using DOMXpath

$dom = new DOMDocument;
$dom->loadHTML($post_content);
$xpath = new DOMXpath($dom);
$importantnotice = $xpath->query('//div[contains(@class, "importantnoticediv")]');
$indiv = $importantnotice->item(0);

I'm having a very hard time figuring out how to append the HTML I want to this class, though.

Here's what I'm trying to transform my block of html into:

                NOTICE:

                PROFESSIONAL INSTALLATION IS RECOMMENDED!

So, in other words,

Immediately after my
 as well as add a closing
 at the very end of this div class.

Is this even possible with DOMDocument and DOMXpath? Given that what I am trying to add isn't "valid" html (even though it is, once I do the two steps..)
I understand I can create new elements, but how do I insert just a custom html string immediately after the start and end of my chosen DOMDocument/DOMXpath?

Body:
Here's one way to do it. It makes use of DOMDocumentFragment. Admittedly, it's all a bit convoluted.

Furthermore, one problem with DOMDocumentFragment is that, besides appendXML(), it does not have a counterpart method appendHTML(), which means you can only append HTML to it if it validates as XML.

$html = '<div class="importantnoticediv">
            <p class="important-notice-title important-notice-title-1">
                NOTICE:
            </p>
            <p class="important-notice-title important-notice-title-2">
                PROFESSIONAL INSTALLATION IS RECOMMENDED!
            </p>
        </div>';

$dom = new DOMDocument;
// format our output to make it a tad bit easier on the eyes (doesn't help all that much, though)
$dom->formatOutput = true;
// this implicitly adds <html> and <body> tags
$dom->loadHTML( $html );

$xpath = new DOMXpath( $dom );

// notice I appended /p to your original query, so that we get the list of <p> elements inside the "importantnoticediv"
$nodes = $xpath->query('//div[contains(@class, "importantnoticediv")]/p');
// the first <p>
$p1 = $nodes->item( 0 );
// the second <p>
$p2 = $nodes->item( 1 );

// we create a DOMDocumentFragment that is associated with our DOMDocument
$frag = $dom->createDocumentFragment();

// I append your first HTML fragment (must be valid XML)
$frag->appendXML( '<div class="note-icon note-icon-important">
    <span><i class="fa fa-exclamation" aria-hidden="true"></i>
    </span>
</div>' );
// ... and insert it before our first <p> (parentNode is the "importantnoticediv")
$p1->parentNode->insertBefore( $frag, $p1 );

// frag is now empty again, because we just inserted it(s contents) into the DOMDocument

// we create our second fragment
$frag->appendXML( '<div class="note-text note-text-important"></div>' );

// this time we append it to "importantnoticediv" (i.e. as last child)
// and get the reference to this newly inserted <div>
$insertedNode = $p1->parentNode->appendChild( $frag );

// now we can append (i.e. move) the <p> elements to the newly inserted <div>
$insertedNode->appendChild( $p1 );
$insertedNode->appendChild( $p2 );

// the HTML should now be as desired
echo $dom->saveHTML();


问:
What is a good name for this state-like monad
This is something of a combination of State and Writer.  I have checked the monad laws.

```<code>newtype M s a = M { runM :: s -> (s,a) }

instance (Monoid s) => Monad (M s) where
    return = M . const . (mempty,)
    m >>= f = M $ \s ->
        let (s' ,x) = runM m s
            (s'',y) = runM (f x) (s `mappend` s')
        in (s' `mappend` s'', y)
</code>```

StateWriter seems kinda lame.

答: Monoidal State. MonoState.MState. AccumState.

Body:
This is something of a combination of State and Writer.  I have checked the monad laws.

newtype M s a = M { runM :: s -> (s,a) }

instance (Monoid s) => Monad (M s) where
    return = M . const . (mempty,)
    m >>= f = M $ \s ->
        let (s' ,x) = runM m s
            (s'',y) = runM (f x) (s `mappend` s')
        in (s' `mappend` s'', y)

StateWriter seems kinda lame.


问:
Reading data from text file to linked list, error handling
I'm currently working on a program that's supposed to read data from a text file, and place said data in a linked list. I've got a pretty good idea of what I'm doing, but the thing is I'm supposed to include error handling that jumps to the next line if there is any errors in the data format in the file.

The file contains information about a number of terminators in the form of their model and their serial number.

An example of the data that can be read is:

```<code>TERMINATOR T-800 1

TERMINATOR T-1000 2

TERMINATOR T-800 3

TERMINATOR T-800 4
</code>```

In the first row above, T-800 is the model, and 1 is the serial number. The four rows above are all valid, but if the fifth row would look something like this:

```<code>TORMONUTTUR T-800 1h6
</code>```

or:

```<code>abc 2
</code>```

, the data should be discarded and the program should continue reading the next row.

I'm currently lost on this, and would appreciate just a nod in the right direction, since I'm not sure how I should even begin with this problem.

答:
You could read try to read every part of the line as a string (because if serial number was an int for example, 1h6 would be truncated, and you would fail to check if it's valid). For the serial number string, you should check if it's really an integer, and if so convert to a number with std::stoi.

From my answer and How do I check if a C++ string is an int?, I got this:

```<code>#include <fstream>
#include <iostream>
#include <string>

inline bool isInteger(const std::string & s)
{
   if(s.empty() || ((!isdigit(s[0])) && (s[0] != '-') && (s[0] != '+'))) return false ;

   char * p ;
   strtol(s.c_str(), &p, 10) ;

   return (*p == 0) ;
}

int main(void)
{

    std::ifstream infile("thefile.txt");
    if (infile.is_open()) {
        int serial_number;
        std::string model, terminator, serial_number_str;
        while (infile >> terminator >> model >> serial_number_str)
        {
            if(terminator == "TERMINATOR" && isInteger(serial_number_str))
            {
                serial_number = std::stoi(serial_number_str);
                std::cout << terminator << " " << model << " " << serial_number << "\n";
            }
        }
    }
    infile.close();
    return 0;
}
</code>```

which for a file of:

Georgioss-MacBook-Pro:~ gsamaras$ cat thefile.txt

```<code>TERMINATOR T-800 1

TERMINATOR T-1000 2

TERMINATOR T-800 3

TERMINATOR T-800 4

TORMONUTTUR T-800 1h6

abc 2
</code>```

gives:

```<code>Georgioss-MacBook-Pro:~ gsamaras$ g++ main.cpp
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out
TERMINATOR T-800 1
TERMINATOR T-1000 2
TERMINATOR T-800 3
TERMINATOR T-800 4
</code>```

You can improve it further by using std::regex to check the format of model.

Body:
I'm currently working on a program that's supposed to read data from a text file, and place said data in a linked list. I've got a pretty good idea of what I'm doing, but the thing is I'm supposed to include error handling that jumps to the next line if there is any errors in the data format in the file.

The file contains information about a number of terminators in the form of their model and their serial number.

An example of the data that can be read is:

TERMINATOR T-800 1

TERMINATOR T-1000 2

TERMINATOR T-800 3

TERMINATOR T-800 4

In the first row above, T-800 is the model, and 1 is the serial number. The four rows above are all valid, but if the fifth row would look something like this:

TORMONUTTUR T-800 1h6

or:

abc 2

, the data should be discarded and the program should continue reading the next row.

I'm currently lost on this, and would appreciate just a nod in the right direction, since I'm not sure how I should even begin with this problem.

Body:
You could read try to read every part of the line as a string (because if serial number was an int for example, 1h6 would be truncated, and you would fail to check if it's valid). For the serial number string, you should check if it's really an integer, and if so convert to a number with std::stoi.

From my answer and How do I check if a C++ string is an int?, I got this:

#include <fstream>
#include <iostream>
#include <string>

inline bool isInteger(const std::string & s)
{
   if(s.empty() || ((!isdigit(s[0])) && (s[0] != '-') && (s[0] != '+'))) return false ;

   char * p ;
   strtol(s.c_str(), &p, 10) ;

   return (*p == 0) ;
}

int main(void)
{

    std::ifstream infile("thefile.txt");
    if (infile.is_open()) {
        int serial_number;
        std::string model, terminator, serial_number_str;
        while (infile >> terminator >> model >> serial_number_str)
        {
            if(terminator == "TERMINATOR" && isInteger(serial_number_str))
            {
                serial_number = std::stoi(serial_number_str);
                std::cout << terminator << " " << model << " " << serial_number << "\n";
            }
        }
    }
    infile.close();
    return 0;
}

which for a file of:

Georgioss-MacBook-Pro:~ gsamaras$ cat thefile.txt

TERMINATOR T-800 1

TERMINATOR T-1000 2

TERMINATOR T-800 3

TERMINATOR T-800 4

TORMONUTTUR T-800 1h6

abc 2

gives:

Georgioss-MacBook-Pro:~ gsamaras$ g++ main.cpp
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out
TERMINATOR T-800 1
TERMINATOR T-1000 2
TERMINATOR T-800 3
TERMINATOR T-800 4

You can improve it further by using std::regex to check the format of model.


问:
iOS @2x elongated images
I have a set of images with @2x for retina display detection. This works fine on most images, however 1 image is elongated. This image was added to an UIImageView in Interface Builder.

I know the names are the same (aside from the @2x part) and the files are both the same type (PNG). What else could be causing this issue?

答: You will need to manually set the frame of the UIImageView.</p>

Title: iOS @2x elongated images


答:
One way to not overwhelm yourself is to delegate different actions to different functions so you don't have to worry about everything at once.  I would recommend opening the file and reading one line at a time.  For each line, you can validate the format, then append the data to your linked list, otherwise do nothing and continue to the next line.  That might look something like this.

```<code>char line[128];
while(fgets(line, 128, (FILE*)fh) != NULL) {
    if(isValidLine(line)) {
        // add data to linked list
    }
}
</code>```

The logic is easy to understand there.  You just have to define your function isValidLine to read the line to make sure it has valid data in it, and return the corresponding boolean value.  To validate this, you might use sscanf or some other string tokenizer to parse the line, or do it yourself manually.  For instance, check that it starts with the string "TERMINATOR " and proceed from there.  One everything checks out, return true, but at any time the string fails your format requirements, return false right away.

Title: Reading data from text file to linked list, error handling

Body:
One way to not overwhelm yourself is to delegate different actions to different functions so you don't have to worry about everything at once.  I would recommend opening the file and reading one line at a time.  For each line, you can validate the format, then append the data to your linked list, otherwise do nothing and continue to the next line.  That might look something like this.

char line[128];
while(fgets(line, 128, (FILE*)fh) != NULL) {
    if(isValidLine(line)) {
        // add data to linked list
    }
}

The logic is easy to understand there.  You just have to define your function isValidLine to read the line to make sure it has valid data in it, and return the corresponding boolean value.  To validate this, you might use sscanf or some other string tokenizer to parse the line, or do it yourself manually.  For instance, check that it starts with the string "TERMINATOR " and proceed from there.  One everything checks out, return true, but at any time the string fails your format requirements, return false right away.


问:
Load MainActivity during Splash Screen
I currently have a splashScreenActivity that requires the User the press on a button to go to the MainActivity.

Would it be possible to load all the contents of MainActivity WITHOUT MainActivity's UI APPEARING ON TOP OF splashScreenActivity's UI so that when he does presses the button, he is redirected to the MainActivity and all the data is 100% loaded?

Thanks in advance

答:
enter code here1) Use AsyncTask<> to load all your MainActivity contents in the background while the user is in the SplashScreenActivity. This will help you avoid the extra step of clicking on a button to take you from the SplashScreenActivity to the MainActivity, and this will be handled through the use of Intents. (Refer to working example below)

SplashScreenActivity.java

```<code>        package foo.foo.load.mainactivity

        import android.app.Activity;
        import android.content.Context;
        import android.content.Intent;
        import android.content.pm.ActivityInfo;
        import android.content.res.AssetManager;
        import android.content.res.Configuration;
        import android.os.AsyncTask;
        import android.os.Bundle;
        import android.util.Log;
        import java.util.ArrayList;
        import java.util.List;

        public class SplashScreenActivity extends Activity {
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_splash);

                // Make call to execute AsycTasks<> here
                // This helps avoid the extra step of clicking on a button
                // to take you to the MainActivity
                new StartMainActivity().execute(this);

                Thread timerThread = new Thread() {
                    public void run() {
                        try {
                            sleep(2000);
                        } catch(InterruptedException e) {
                            e.printStackTrace();
                        } finally {
                            // After 2 seconds the Splashscreen will disappear and user is taken to MainActivity
                            Intent splashScreenIntent = new Intent(SplashScreenActivity.this, MainActivity.class);
                            startActivity(splashScreenIntent);
                        }
                    }
                };

                timerThread.start();
            }

            @Override
            protected void onPause() {
                super.onPause();
                finish();
            }

            private class StartMainActivity extends AsyncTask<Context, Void, Intent> {

                Context ctx;

                @Override
                protected Intent doInBackground(Context... params) {
                    ctx = params[0];
                    AssetManager assetManager = ctx.getAssets();
                    final CBLite cblite = new CBLite(new AndroidContext(ctx), assetManager);

                    // Handle all your MainActivity Contents call here
                    // Begin MainActivity Content Calls
                    Image.getImages();
                    Navigation.getMainNavigation();
                    // End MainActivity Content Calls

                    Intent in = new Intent();
                    in.setClass(ctx, MainActivity.class);

                    return in;
                }

                @Override
                protected void onPostExecute(Intent intent) {
                    ctx.startActivity(intent);
                    super.onPostExecute(intent);
                }

            }
        }

</code>```

activity_splash.xml

```<code>    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:background="@drawable/splashscreen_background_image"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/splashScreenMainTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="150dp"
            android:gravity="center"
            android:text="Header Title"
            android:visibility="visible"/>

        <TextView
            android:id="@+id/splashScreenSubTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/splashScreenMainTitle"
            android:layout_marginBottom="40dp"
            android:gravity="center"
            android:text="Sub Header Title"
            android:visibility="visible"/>

        <ImageView
            android:id="@+id/splashScreenLogo"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/splashScreenSubTitle"
            android:src="@drawable/logo"
            android:layout_gravity="center_horizontal"
            android:background="@android:color/transparent"/>

    </RelativeLayout>
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_menu_search" />
   </android.support.design.widget.CoordinatorLayout>
</code>```

Title: Load MainActivity during Splash Screen

Body:
enter code here1) Use AsyncTask<> to load all your MainActivity contents in the background while the user is in the SplashScreenActivity. This will help you avoid the extra step of clicking on a button to take you from the SplashScreenActivity to the MainActivity, and this will be handled through the use of Intents. (Refer to working example below)

SplashScreenActivity.java

        package foo.foo.load.mainactivity

        import android.app.Activity;
        import android.content.Context;
        import android.content.Intent;
        import android.content.pm.ActivityInfo;
        import android.content.res.AssetManager;
        import android.content.res.Configuration;
        import android.os.AsyncTask;
        import android.os.Bundle;
        import android.util.Log;
        import java.util.ArrayList;
        import java.util.List;

        public class SplashScreenActivity extends Activity {
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_splash);

                // Make call to execute AsycTasks<> here
                // This helps avoid the extra step of clicking on a button
                // to take you to the MainActivity
                new StartMainActivity().execute(this);

                Thread timerThread = new Thread() {
                    public void run() {
                        try {
                            sleep(2000);
                        } catch(InterruptedException e) {
                            e.printStackTrace();
                        } finally {
                            // After 2 seconds the Splashscreen will disappear and user is taken to MainActivity
                            Intent splashScreenIntent = new Intent(SplashScreenActivity.this, MainActivity.class);
                            startActivity(splashScreenIntent);
                        }
                    }
                };

                timerThread.start();
            }

            @Override
            protected void onPause() {
                super.onPause();
                finish();
            }

            private class StartMainActivity extends AsyncTask<Context, Void, Intent> {

                Context ctx;

                @Override
                protected Intent doInBackground(Context... params) {
                    ctx = params[0];
                    AssetManager assetManager = ctx.getAssets();
                    final CBLite cblite = new CBLite(new AndroidContext(ctx), assetManager);

                    // Handle all your MainActivity Contents call here
                    // Begin MainActivity Content Calls
                    Image.getImages();
                    Navigation.getMainNavigation();
                    // End MainActivity Content Calls

                    Intent in = new Intent();
                    in.setClass(ctx, MainActivity.class);

                    return in;
                }

                @Override
                protected void onPostExecute(Intent intent) {
                    ctx.startActivity(intent);
                    super.onPostExecute(intent);
                }

            }
        }

activity_splash.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:background="@drawable/splashscreen_background_image"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/splashScreenMainTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="150dp"
            android:gravity="center"
            android:text="Header Title"
            android:visibility="visible"/>

        <TextView
            android:id="@+id/splashScreenSubTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/splashScreenMainTitle"
            android:layout_marginBottom="40dp"
            android:gravity="center"
            android:text="Sub Header Title"
            android:visibility="visible"/>

        <ImageView
            android:id="@+id/splashScreenLogo"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/splashScreenSubTitle"
            android:src="@drawable/logo"
            android:layout_gravity="center_horizontal"
            android:background="@android:color/transparent"/>

    </RelativeLayout>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_menu_search" />
   </android.support.design.widget.CoordinatorLayout>


问:
Stagefright vs Gstreamer
What are the advantages of using gstreamer over stagefright? Could anyone please point out the difference. </p>

答:
I'm not familiar with StageFright, but I would point out that GStreamer offers some very mature debugging capabilities, including dumping GraphViz ("dot") data that can be used to construct literal, visual graphs of your figurative playback graphs, including during construction, even after certain kinds of partial failure.  Multiple debug levels are available, along with certain kinds of filtering.

I would definitely recommend anyone choosing between these two libraries for development purposes compare their debugging and troubleshooting capabilities, especially with respect to troubleshooting pipeline starvation and synchronization.

(Oh, and by the way-- the best format to convert those dot dumps to is SVG.  I usually open them in Firefox.)

Title: Stagefright vs Gstreamer


问:
PageSettings keep getting modifed unexpectedly
It seems that you can persist in a settings file PrinterSettings and also PageSettings, they are Serializable etc.  Great!  Everything was going OK until I tried to persist my PageSettings and the margins.  Everytime I change the margins, save the settings and then reload them back into the PageSetupDialog.PageSettings - they have been modified.  Does anyone know why this happens? Is it something that the driver or Windows is doing ?  Its bizarre, see below:

Here I show the dialog:

```<code>PageSetupDialog psd = new PageSetupDialog();
psd.PageSettings = MySettings.Default.pageSettings;

    if (psd.ShowDialog() == DialogResult.OK)
</code>```

I manually change the values to 5.

Then I save the changes:

```<code>MySettings.Default.pageSettings = psd.PageSettings;
</code>```

When I reload the dialog and load in the settings from the settings file the values have changed to 2!?

UPDATE:

So just to try and expand on the problem - if we show the PageSetupDialog for the first time with default settings values which are 10 for all margins.  If we inspect the values during debug then we see them represented like this:

So they are all 100, strange but I expected them to be 10 i.e. like 10mm like the dialog says, so I don't know what unit of measure 100 is pertaining to be but anyway lets assume that it correlates with 10 in the dialog.

We then edit them all to 5 in the dialog and press OK - so we get past this code:

```<code>if (psd.ShowDialog() == DialogResult.OK)
</code>```

so we would expect to see on inspection of the pageSettingDialog object to see some values for the margins to be all 5 (or 50, as seems to be the case in the 10 vs 100 confusion, see above).  Let's have a look at the object then:

Low and behold it's not what we were expecting, it's 20 for some bizarre reason.  That's where I get stuck, I just can't work out whats going on behind the seens here.  Why is it changing from 50 to 20?, why won't it keep the value I set?
Hope that explains it a little bit better.

答:
Since we don't have any more code to look at, I'm going to give it my "best guess".

My thought is that your code is setting the value of 2 when the dialog is opening.  The settings are saved as 5 but dialog is displaying 2 because of a hardcoded setting.  Make sure that there is nothing overriding the reading of the setting in the dialog display.

Alternatively, upon saving the form, there is something overriding the value.

Look in your settings read code and your settings write code to see if there is a "2" anywhere hardcoded in your code.

Body:
It seems that you can persist in a settings file PrinterSettings and also PageSettings, they are Serializable etc.  Great!  Everything was going OK until I tried to persist my PageSettings and the margins.  Everytime I change the margins, save the settings and then reload them back into the PageSetupDialog.PageSettings - they have been modified.  Does anyone know why this happens? Is it something that the driver or Windows is doing ?  Its bizarre, see below:

Here I show the dialog:

PageSetupDialog psd = new PageSetupDialog();
psd.PageSettings = MySettings.Default.pageSettings;

    if (psd.ShowDialog() == DialogResult.OK)

I manually change the values to 5.

Then I save the changes:

MySettings.Default.pageSettings = psd.PageSettings;

When I reload the dialog and load in the settings from the settings file the values have changed to 2!?

UPDATE:

So just to try and expand on the problem - if we show the PageSetupDialog for the first time with default settings values which are 10 for all margins.  If we inspect the values during debug then we see them represented like this:

So they are all 100, strange but I expected them to be 10 i.e. like 10mm like the dialog says, so I don't know what unit of measure 100 is pertaining to be but anyway lets assume that it correlates with 10 in the dialog.

We then edit them all to 5 in the dialog and press OK - so we get past this code:

if (psd.ShowDialog() == DialogResult.OK)

so we would expect to see on inspection of the pageSettingDialog object to see some values for the margins to be all 5 (or 50, as seems to be the case in the 10 vs 100 confusion, see above).  Let's have a look at the object then:

Low and behold it's not what we were expecting, it's 20 for some bizarre reason.  That's where I get stuck, I just can't work out whats going on behind the seens here.  Why is it changing from 50 to 20?, why won't it keep the value I set?
Hope that explains it a little bit better.


问:
Merge the values from two Collections using Java
I have two Collections with values such as the following:

Collection 1 =[Balance, OrigYear, OrigRate]

Collection 2 =[Sum, Count, Avg]

I want to merge the values from two Collections into a single Collection or ArrayList, which will have a output like [Balance Sum, OrigYear Count, OrigRate Avg].

Could some one please suggest something using Java, as I'm naive user in writing code using Java?

答:
If your lists have different size then result will gather only paired (between two lists) values. However you can modify below code to align lists size by adding empty strings in smaller list.</p>

```<code>List<String> list1 = Arrays.asList("Balance", "OrigYear", "OrigRate");
List<String> list2 = Arrays.asList("Sum", "Count", "Avg");
List<String> resultList = new ArrayList<String>();

for (int i = 0; i < Math.min(list1.size(), list2.size()); i++) {
    resultList.add(String.join(" ", list1.get(i), list2.get(i)));
}
</code>```

Body:
If your lists have different size then result will gather only paired (between two lists) values. However you can modify below code to align lists size by adding empty strings in smaller list.

List<String> list1 = Arrays.asList("Balance", "OrigYear", "OrigRate");
List<String> list2 = Arrays.asList("Sum", "Count", "Avg");
List<String> resultList = new ArrayList<String>();

for (int i = 0; i < Math.min(list1.size(), list2.size()); i++) {
    resultList.add(String.join(" ", list1.get(i), list2.get(i)));
}


问:
Is ASP.NET MVC's Checkbox Implementation Accessible / Screen Reader-Friendly?
If you've ever looked at what ASP.NET MVC actually renders when you use @Html.CheckBoxFor, then you've seen that each checkbox you request to be rendered actually results in the emission of not one but two input tags. One is the "true" value checkbox, and the other is for "false." The latter input is of type "hidden".

Generally this doesn't cause problems if you're using ASP.NET MVC correctly. You wouldn't notice the input doubling unless you tried to, for example, do something directly with Request.Form(e.g. Why does ASP.NET MVC Html.CheckBox output two INPUTs with the same name?)

My question, though, is how screen readers deal with this. For example, can they be relied upon to correctly report only the visible checkbox to the site user?

答:
Given the example you cite in your comment, it returns this code:

```<code><div class="col pure-u-xl-1-3 pure-u-lg-1-3 pure-u-md-1 pure-u-sm-1 pure-u-xs-1">
  <label>Home Club Newsletter</label>
  <input checked="checked" … id="newsletter" name="JoinHomeClub" type="checkbox" value="true">
  <input name="JoinHomeClub" type="hidden" value="false">
  <span class="checkbox-label">Yes, please sign me Up!</span>
</div>
</code>```

Right off the bat there is a problem here because the  is not associated with the control, and the visible text that is next to the checkbox is not associated with the field.

When I access the field in NVDA, all it says is "checkbox checked". There is no accessible name at all.

But to your question…

Your question was related to the <input type="hidden">. As @SLaks said, screen readers ignore <input type="hidden">. The fact that they have the same name value is no problem. If they had the same id value, then you would have a problem (how it would manifest in a screen reader depends on things and stuff).

Body:
Given the example you cite in your comment, it returns this code:

<div class="col pure-u-xl-1-3 pure-u-lg-1-3 pure-u-md-1 pure-u-sm-1 pure-u-xs-1">
  <label>Home Club Newsletter</label>
  <input checked="checked" … id="newsletter" name="JoinHomeClub" type="checkbox" value="true">
  <input name="JoinHomeClub" type="hidden" value="false">
  <span class="checkbox-label">Yes, please sign me Up!</span>
</div>

Right off the bat there is a problem here because the <label> is not associated with the control, and the visible text that is next to the checkbox is not associated with the field.

When I access the field in NVDA, all it says is "checkbox checked". There is no accessible name at all.

But to your question…

Your question was related to the <input type="hidden">. As @SLaks said, screen readers ignore <input type="hidden">. The fact that they have the same name value is no problem. If they had the same id value, then you would have a problem (how it would manifest in a screen reader depends on things and stuff).


问:
How do I extract the HTTP error code sent from Azure AD using ADAL Objective-C
I'm trying to write an error handler for an iOS app and want to handle errors differently based on HTTP error codes from the Azure AD token service (STS).  For instance, if I get an HTTP 429, I know not to retry the request or if I get an HTTP 500 I may choose to do a retry.

How can I extract this information out of the AD Error provided in ADAL Objective C?

答:
We do not recommend you use the HTTP error codes directly when using our libraries. We provide ADAL error codes that you should use in order to determine the next steps in your application. These wrap both HTTP errors and other errors the library could throw in to one NSError object you can use.

You should check the error domain for ADAuthenticationErrorDomain and then match on the error code such as AD_ERROR_USER_INPUT_NEEDED

We maintain this error code list in the ADErrorCodes.h header file of the SDK along with the description of how the error can occur: https://github.com/AzureAD/azure-activedirectory-library-for-objc/blob/dev/ADAL/src/public/ADErrorCodes.h

To catch these errors in your code, use the following pattern:

```<code>[authContext acquireTokenSilentWithResource:...
          completionBlock:^(ADAuthenticationResult *result) {

if (!result.error) {

// normal program flow

} else {

   if ([result.error.domain isEqual:ADAuthenticationErrorDomain] && result.error.code == AD_ERROR_USER_INPUT_NEEDED) {

            // Handle user input needed error

       }

   else if ([result.error.domain isEqual:ADAuthenticationErrorDomain] && result.error.code == AD_ERROR_SERVER_WRONG_USER) {

           // Handle user returned by the server
           //does not match the the user identifier error

          }
}];
</code>```

Body:
We do not recommend you use the HTTP error codes directly when using our libraries. We provide ADAL error codes that you should use in order to determine the next steps in your application. These wrap both HTTP errors and other errors the library could throw in to one NSError object you can use.

You should check the error domain for ADAuthenticationErrorDomain and then match on the error code such as AD_ERROR_USER_INPUT_NEEDED

We maintain this error code list in the ADErrorCodes.h header file of the SDK along with the description of how the error can occur: https://github.com/AzureAD/azure-activedirectory-library-for-objc/blob/dev/ADAL/src/public/ADErrorCodes.h

To catch these errors in your code, use the following pattern:

[authContext acquireTokenSilentWithResource:...
          completionBlock:^(ADAuthenticationResult *result) {

if (!result.error) {

// normal program flow

} else {

   if ([result.error.domain isEqual:ADAuthenticationErrorDomain] && result.error.code == AD_ERROR_USER_INPUT_NEEDED) {

            // Handle user input needed error

       }

   else if ([result.error.domain isEqual:ADAuthenticationErrorDomain] && result.error.code == AD_ERROR_SERVER_WRONG_USER) {

           // Handle user returned by the server
           //does not match the the user identifier error

          }
}];


问:
Need help in latent semantic indexing
I am sorry, if my question sounds stupid :)
Can you please recommend me any pseudo code or good algo for LSI implementation in java?
I am not math expert. I tried to read some articles on wikipedia and other websites about
LSI ( latent semantic indexing ) they were full of math.
I know LSI is full of math. But if i see some source code or algo. I understand things more
easily. That's why i asked here, because so many GURU are here !
Thanks in advance </p>

答:
An idea of LSA is based on one assumption: the more two words occur in same documents, the more similar they are. Indeed, we can expect that words "programming" and "algorithm" will occur in same documents much more often then, say, "programming" and "dog-breeding".

Same for documents: the more common/similar words two documents have, the more similar themselves they are. So, you can express similarity of documents by frequencies of words and vice versa.

Knowing this, we can construct a co-occurrence matrix, where column names represent documents, row names - words and each cells[i][j] represents frequency of word words[i] in document documents[j]. Frequency may be computed in many ways, IIRC, original LSA uses tf-idf index.

Having such matrix, you can find similarity of two documents by comparing corresponding columns. How to compare them? Again, there are several ways. The most popular is a cosine distance. You must remember from school maths, that matrix may be treated as a bunch of vectors, so each column is just a vector in some multidimensional space. That's why this model is called "Vector Space Model". More on VSM and cosine distance here.

But we have one problem with such matrix: it is big. Very very big. Working with it is too computationally expensive, so we have to reduce it somehow. LSA uses SVD technique to keep the most "important" vectors. After reduction matrix is ready to use.

So, algorithm for LSA will look something like this:

Collect all documents and all unique words from them.

Extract frequency information and build co-occurrence matrix.

Reduce matrix with SVD.

If you're going to write LSA library by yourself, the good point to start is Lucene search engine, which will make much easier steps 1 and 2, and some implementation of high-dimensional matrices with SVD capability like Parallel Colt or UJMP.

Also pay attention to other techinques, which grown up from LSA, like Random Indexing. RI uses same idea and shows approximately same results, but doesn't use full matrix stage and is completely incremental, which makes it much more computationally efficient.

Title: Need help in latent semantic indexing


问:
Adding flags using argparse to provide a list of options
I have written this program to provide a list of options using the flag --list. So, I want to use --list to provide all the options whereas when I am using --list --ex, I just want to provide a part of the list of options.

Here is the program -

```<code>import argparse
import sys
options = {
    'external': {
        },
    'internal': {
        }
}

def print_list(value):
    l1 = []
    l2 = []

    for k, v in options.iteritems():
        if k == "external":
            for opt, val in options["external"].iteritems():
                l1.append(opt)
        elif k == "internal":
            for opt,val in options["internal"].iteritems():
                l2.append(opt)
    if value == "external":
        return l1

    elif value == "internal":
        return l2
    elif value == "all":
        return l1 + l2

parser = argparse.ArgumentParser(
    description="Testing argparse"
    )

parser.add_argument("--list", action = "store_true")
parser.add_argument("--ex", action = "store_true")
parser.add_argument("--in", action = "store_true")
args = parser.parse_args(sys.argv[1:])

if args.list:
    val = print_list("all")
    for items in val:
        print items

if  not args.list and args.ex:
    parser.error("You need to provide list option")

if args.ex:
    val = print_list("external")
    for items in val:
        print items
</code>```

So when I do, --list --ex I get all the options, plus the external options. Whereas when I type --list --ex, I just want the external options.

Thanks in advance for any help.

答:
```<code>if args.list and args.external:
    val = print_list("external")
    for items in val:
        print items

elif args.list:
    val = print_list("all")
    for items in val:
        print items
</code>```

I just made a small change in the code, and was able to achieve what I wanted, thanks.

Body:
I have written this program to provide a list of options using the flag --list. So, I want to use --list to provide all the options whereas when I am using --list --ex, I just want to provide a part of the list of options.

Here is the program -

import argparse
import sys
options = {
    'external': {
        },
    'internal': {
        }
}

def print_list(value):
    l1 = []
    l2 = []

    for k, v in options.iteritems():
        if k == "external":
            for opt, val in options["external"].iteritems():
                l1.append(opt)
        elif k == "internal":
            for opt,val in options["internal"].iteritems():
                l2.append(opt)
    if value == "external":
        return l1

    elif value == "internal":
        return l2
    elif value == "all":
        return l1 + l2

parser = argparse.ArgumentParser(
    description="Testing argparse"
    )

parser.add_argument("--list", action = "store_true")
parser.add_argument("--ex", action = "store_true")
parser.add_argument("--in", action = "store_true")
args = parser.parse_args(sys.argv[1:])

if args.list:
    val = print_list("all")
    for items in val:
        print items

if  not args.list and args.ex:
    parser.error("You need to provide list option")

if args.ex:
    val = print_list("external")
    for items in val:
        print items

So when I do, --list --ex I get all the options, plus the external options. Whereas when I type --list --ex, I just want the external options.

Thanks in advance for any help.

Body:
if args.list and args.external:
    val = print_list("external")
    for items in val:
        print items

elif args.list:
    val = print_list("all")
    for items in val:
        print items

I just made a small change in the code, and was able to achieve what I wanted, thanks.


问:
Linking Types in Scala
I have a class of objects which either have one type of ID or another:

```<code>sealed trait ItemId
case class NumericId(id: Int) extends ItemId
case class StringId(id: String) extends ItemId

sealed trait Item {
  def id: ItemId
}

case class ItemWithNumericId(id: NumericId) extends Item
case class ItemWithStringId(id: StringId) extends Item
</code>```

I'd like to create an interface for some sort of service which retrieves items:

```<code>trait ItemService[IdType <: ItemId, ItemType <: Item] {
  def get(id: IdType): ItemType
}
</code>```

How do I link the ItemId type with the Item type to put a constraint on ItemServices to not allow something like:

```<code>class SillyItemService extends ItemService[NumericId, ItemWithStringId] {
  def get(id: NumericId): ItemWithStringId = ???
}
</code>```

I've realised I can add generic types to the Item class:

```<code>sealed trait ItemId
case class NumericId(id: Int) extends ItemId
case class StringId(id: String) extends ItemId

sealed trait Item[Id <: ItemId] {
  def id: Id
}

case class ItemWithNumericId(id: NumericId) extends Item[NumericId]
case class ItemWithStringId(id: StringId) extends Item[StringId]

trait ItemService[IdType <: ItemId, ItemType <: Item[IdType]] {
  def get(id: IdType): ItemType
}
</code>```

which is OK but It's super verbose. Ideally, the service would only have a single generic type.

Thanks very much for any answers/input.

答:
This would be my approach:

```<code>sealed trait ItemId
case class NumericId(id: Int) extends ItemId
case class StringId(id: String) extends ItemId

trait Item[A <: ItemId] {
  def id: A
}

trait ItemService[A <: ItemId, B <: Item[A]] {
  def get(id: A): B
}
</code>```

It's honestly not much different from what you had done, I just think there's not much need to make the Item trait sealed and introduce two implementations right there.

If you have no use for narrowing the return type of the get method of a specific ItemService, you could even leave off the B type parameter to make things one step simpler:

```<code>trait ItemService[A <: ItemId] {
  def get(id: A): Item[A]
}
</code>```

Title: Linking Types in Scala

Body:
I have a class of objects which either have one type of ID or another:

sealed trait ItemId
case class NumericId(id: Int) extends ItemId
case class StringId(id: String) extends ItemId

sealed trait Item {
  def id: ItemId
}

case class ItemWithNumericId(id: NumericId) extends Item
case class ItemWithStringId(id: StringId) extends Item

I'd like to create an interface for some sort of service which retrieves items:

trait ItemService[IdType <: ItemId, ItemType <: Item] {
  def get(id: IdType): ItemType
}

How do I link the ItemId type with the Item type to put a constraint on ItemServices to not allow something like:

class SillyItemService extends ItemService[NumericId, ItemWithStringId] {
  def get(id: NumericId): ItemWithStringId = ???
}

I've realised I can add generic types to the Item class:

sealed trait ItemId
case class NumericId(id: Int) extends ItemId
case class StringId(id: String) extends ItemId

sealed trait Item[Id <: ItemId] {
  def id: Id
}

case class ItemWithNumericId(id: NumericId) extends Item[NumericId]
case class ItemWithStringId(id: StringId) extends Item[StringId]

trait ItemService[IdType <: ItemId, ItemType <: Item[IdType]] {
  def get(id: IdType): ItemType
}

which is OK but It's super verbose. Ideally, the service would only have a single generic type.

Thanks very much for any answers/input.

Body:
This would be my approach:

sealed trait ItemId
case class NumericId(id: Int) extends ItemId
case class StringId(id: String) extends ItemId

trait Item[A <: ItemId] {
  def id: A
}

trait ItemService[A <: ItemId, B <: Item[A]] {
  def get(id: A): B
}

It's honestly not much different from what you had done, I just think there's not much need to make the Item trait sealed and introduce two implementations right there.

If you have no use for narrowing the return type of the get method of a specific ItemService, you could even leave off the B type parameter to make things one step simpler:

trait ItemService[A <: ItemId] {
  def get(id: A): Item[A]
}


问:
Automatically sync a local folder to a remote one via FTP using a crontab bash script without sending local open files
I'm trying to sync a local folder to a remote one using some FTP client parallel sessions (LFTP) started from a linux crontab script.
Some computational jobs produce (and save in the local dir) the files that will be sent to the FTP server.
I need to verify that the new files saved in the local directory are not still open by the previously mentioned saving processes in order to send only the closed files.
Is there a way to do it? Do you think that the "mirror" option of LFTP command already do this kind of check?

Thank you in advance,
Mauro

答:
Need to see what you're doing before I can help you fix it, but you could do something like this:</p>

```<code># Start of loop over filenames
   # get inode of file
   inode=$( ls -i $file | cut -d' ' -f1 )

   # If file inode does not show up in lsof, run the ftp command in the background
   lsof | grep "$inode" || ftp $file <destination> &

# End of loop
</code>```

Body:
Need to see what you're doing before I can help you fix it, but you could do something like this:

# Start of loop over filenames
   # get inode of file
   inode=$( ls -i $file | cut -d' ' -f1 )

   # If file inode does not show up in lsof, run the ftp command in the background
   lsof | grep "$inode" || ftp $file <destination> &

# End of loop


问:
Auto Increment non-pk field starting at 1000
I have been working in Django for about a week now so I don't have much idea on the following. I need to create a sequence for a field in my model and postgres database that auto increments starting at 1000. So it would list like:
1000, 1001, 1002, etc....

From what I have researched so far I would need to extend the save function and check the previous value in the db.

The end result is to be able to post to an API using this model and this field increments like above.

```<code>class MyModel(AuditMixin, models.Model):
    order_number = models.IntegerField(blank=False)

    def get_number(self):
        return ???

    def save(self):
        ??? .save()
</code>```

答:
From what I have researched so far I would need to extend the save function and check the previous value in the db.

Generally doing a SELECT followed by an insert or update based on that SELECT is a bad idea for any RDBMS. Because this can lead to race conditions and databases have built in mechanisms that avoid this race condition and are usually faster.

Postgresql has a Serial type. It will be included in the django.contrib.posgres from the next major release of Django but for now. Create a custom migration like this:

```<code>CREATE SEQUENCE my_serial START 1000;
ALTER TABLE myapp_mymodel ALTER COLUMN order_number SET DEFAULT nextval('my_serial');
</code>```

If you have never created a custom migration before, look up RunPython

Body:
I have been working in Django for about a week now so I don't have much idea on the following. I need to create a sequence for a field in my model and postgres database that auto increments starting at 1000. So it would list like:
1000, 1001, 1002, etc....

From what I have researched so far I would need to extend the save function and check the previous value in the db.

The end result is to be able to post to an API using this model and this field increments like above.

class MyModel(AuditMixin, models.Model):
    order_number = models.IntegerField(blank=False)

    def get_number(self):
        return ???

    def save(self):
        ??? .save()

Body:
From what I have researched so far I would need to extend the save function and check the previous value in the db.

Generally doing a SELECT followed by an insert or update based on that SELECT is a bad idea for any RDBMS. Because this can lead to race conditions and databases have built in mechanisms that avoid this race condition and are usually faster.

Postgresql has a Serial type. It will be included in the django.contrib.posgres from the next major release of Django but for now. Create a custom migration like this:

CREATE SEQUENCE my_serial START 1000;
ALTER TABLE myapp_mymodel ALTER COLUMN order_number SET DEFAULT nextval('my_serial');

If you have never created a custom migration before, look up RunPython


问:
xcode - MPNowPlayingInfoCenter info is not displayed on iOS 8
I'm developing a music application, which should play music in the background.

I use the MPMoviePlayerController to play the music. My code to initiate the MPMoviePlayerController:

```<code>NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
resourcePath = [resourcePath stringByAppendingString:@"/music.m4a"];
NSError* err;
self.player = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:resourcePath]];
if (err) {
    NSLog(@"ERROR: %@", err.localizedDescription);
}
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];
[session setActive:YES error:nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self.player setShouldAutoplay:NO];
[self.player setControlStyle: MPMovieControlStyleEmbedded];
self.player.view.hidden = YES;
[self.player prepareToPlay];
</code>```

When I execute [self.player play]; the music starts.
But I also want to display the name of the song, the name of the album and the album artwork in the LockScreen and the ControlCenter. I'm using the following code:

```<code>Class playingInfoCenter = NSClassFromString(@"MPNowPlayingInfoCenter");
    if (playingInfoCenter) {
        NSMutableDictionary *songInfo = [[NSMutableDictionary alloc] init];
        MPMediaItemArtwork *albumArt = [[MPMediaItemArtwork alloc] initWithImage: [UIImage imageNamed:@"artwork.png"]];
        [songInfo setObject:@"SongName" forKey:MPMediaItemPropertyTitle];
        [songInfo setObject:@"ArtistName" forKey:MPMediaItemPropertyArtist];
        [songInfo setObject:@"AlbumTitle" forKey:MPMediaItemPropertyAlbumTitle];
        [songInfo setObject:albumArt forKey:MPMediaItemPropertyArtwork];
        [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songInfo];
    }
</code>```

But nothing gets displayed in the LockScreen. It doesn't get displayed in the ControlCenter either.

How can I solve my problem? I didn't find anything on the internet.

Thanks in advance, Fabian.

答: Expanding further on @matt's answer, it's required that you call endReceivingRemoteControlEvents and resignFirstResponder when the app comes back into the foreground (applicationDidBecomeActive).  Otherwise the OS assumes you are a bad actor (or forgot to turn them off) and turns off your ability to show the sleep controls entirely, even after you call beginReceivingRemoteControlEvents again.  I added these calls and now the Sleep Controls always show when they should.

Body:
I'm developing a music application, which should play music in the background.

I use the MPMoviePlayerController to play the music. My code to initiate the MPMoviePlayerController:

NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
resourcePath = [resourcePath stringByAppendingString:@"/music.m4a"];
NSError* err;
self.player = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:resourcePath]];
if (err) {
    NSLog(@"ERROR: %@", err.localizedDescription);
}
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];
[session setActive:YES error:nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self.player setShouldAutoplay:NO];
[self.player setControlStyle: MPMovieControlStyleEmbedded];
self.player.view.hidden = YES;
[self.player prepareToPlay];

When I execute [self.player play]; the music starts.
But I also want to display the name of the song, the name of the album and the album artwork in the LockScreen and the ControlCenter. I'm using the following code:

Class playingInfoCenter = NSClassFromString(@"MPNowPlayingInfoCenter");
    if (playingInfoCenter) {
        NSMutableDictionary *songInfo = [[NSMutableDictionary alloc] init];
        MPMediaItemArtwork *albumArt = [[MPMediaItemArtwork alloc] initWithImage: [UIImage imageNamed:@"artwork.png"]];
        [songInfo setObject:@"SongName" forKey:MPMediaItemPropertyTitle];
        [songInfo setObject:@"ArtistName" forKey:MPMediaItemPropertyArtist];
        [songInfo setObject:@"AlbumTitle" forKey:MPMediaItemPropertyAlbumTitle];
        [songInfo setObject:albumArt forKey:MPMediaItemPropertyArtwork];
        [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songInfo];
    }

But nothing gets displayed in the LockScreen. It doesn't get displayed in the ControlCenter either.

How can I solve my problem? I didn't find anything on the internet.

Thanks in advance, Fabian.


问:
Reading c++ 2d array in python swig
C++ part
I have a class a with a public variable 2d int array b that I want to print out in python.(The way I want to access it is a.b)

I have been able to wrap the most part of the code and I can call most of the functions in class a in python now.

So how can I read b in python? How to read it into an numpy array with numpy.i(I find some solution on how to work with a function not variable)? Is there a way I can read any array in the c++ library? Or I have to deal with each of the variables in the interface file.

for now b is <Swig Object of type 'int (*)[24]' at 0x02F65158> when I try to use it in python

ps:
1. If possible I don't want to modify the cpp part.

I'm trying to access a variable, not a function.

So don't refer me to links that doesn't really answer my question, thanks.

答:
Your question would be easier to answer if you could add a code snippet of your C++ definition (or C if you use int**). When you say "2d int array", do you mean a general int**? Is the array size known in advance?

At any rate, you could probably use numpy.i but it depends on the fine details of your array.

See this somewhat related question:
Swig and multidimensional arrays

Title: Reading c++ 2d array in python swig


问:
Slider with Prototype javascript
I am creating a slider using prototype javascrtipt

My problem is when slider goes to 5 th slide it again slides back to 1 st slide in sequence(5,4,3,2,1) and it is starting from 1 slide

Can any one explain how should i over come this thank you very much..

```<code>var slider;
Event.observe(window, 'load', function() {
    slider = new MOSS('moss_panel', '', 'moss_panel', null, 1, true, false, 1);
    m_TimeOutSlider = setTimeout("MOSSSlideShow('1')", 1000);
});

function MOSSSlideShow() {

    clearTimeout(m_TimeOutSlider);
    slider.next();
    if (slider.offset == 5) {
        slider.offset = -1;
    }
    m_TimeOutSlider = setTimeout("MOSSSlideShow()",5000);
}
</code>```

this is my code in javascript

答:
Instead of messing about with timers and intervals, and since you have Prototype, use the PeriodicalExecuter.

```<code>document.observe('dom:loaded', function() {
    var slider = new MOSS('moss_panel', '', 'moss_panel', null, 1, true, false, 1);
    new PeriodicalExecuter(slider.next, 5);
});
</code>```

(This is a simplistic example, it doesn't rotate from "5" to "1", it would be neatest if you wrote that into slider.next())

Title: Slider with Prototype javascript

Body:
I am creating a slider using prototype javascrtipt

My problem is when slider goes to 5 th slide it again slides back to 1 st slide in sequence(5,4,3,2,1) and it is starting from 1 slide

Can any one explain how should i over come this thank you very much..

var slider;
Event.observe(window, 'load', function() {
    slider = new MOSS('moss_panel', '', 'moss_panel', null, 1, true, false, 1);
    m_TimeOutSlider = setTimeout("MOSSSlideShow('1')", 1000);
});

function MOSSSlideShow() {

    clearTimeout(m_TimeOutSlider);
    slider.next();
    if (slider.offset == 5) {
        slider.offset = -1;
    }
    m_TimeOutSlider = setTimeout("MOSSSlideShow()",5000);
}

this is my code in javascript

Body:
Instead of messing about with timers and intervals, and since you have Prototype, use the PeriodicalExecuter.

document.observe('dom:loaded', function() {
    var slider = new MOSS('moss_panel', '', 'moss_panel', null, 1, true, false, 1);
    new PeriodicalExecuter(slider.next, 5);
});

(This is a simplistic example, it doesn't rotate from "5" to "1", it would be neatest if you wrote that into slider.next())


问:
Android studio can't be Updated , Ubuntu 16.04
i'm trying to Update My android studio for the latest version stable that recently released 2.2 Stable from my Current version 2.1.3 at Ubuntu this shows above android studio

after this finished it just close the android studio and when open it again no change it still version 2.1.3

it happen twice ?
how to solve this as this is the first time update from Ubuntu ?

答:
I sorted it out by changing the folder permission of

/android-studio


问:
Add Table Column Names from MS SQL in PHP
I am trying to add column names from MS SQL using a DNS - Less Connection; I have used the dns-less code to successfully connect but I need the column names to print also.

```<code>echo "<table>";
while (!$rs->EOF)  //carry on looping through while there are records
{
echo "<tr>";
for ($i=0; $i < $num_columns; $i++) {
echo "<td>" . $fld[$i]->value . "</td>";
}
echo "</tr>";
 $rs->MoveNext(); //move on to the next record
  }

echo "</table>"; //close the connection and recordset objects freeing up resources
</code>```

I know how to modify the table but how do I add the table names?

答:
By your code, it's difficult to know how are you filling the variable $fld.

I would recommend to see the different ways you can fetch the values for MS SQL here.

If you can use mssql_fetch_assoc the the key of the array is the field (column) name.

Body:
I am trying to add column names from MS SQL using a DNS - Less Connection; I have used the dns-less code to successfully connect but I need the column names to print also.

echo "
";
while (!$rs->EOF)  //carry on looping through while there are records
{
echo "
";
for ($i=0; $i < $num_columns; $i++) {
echo "" . $fld[$i]->value . "	";
}
echo "
";
 $rs->MoveNext(); //move on to the next record
  }

echo "
"; //close the connection and recordset objects freeing up resources

I know how to modify the table but how do I add the table names?


问:
retrieving instagram stories data using instagram api
I want to access and retrieve a user's Stories post from Instagram using their Dev API.

I tested after posting a story myself by using https://api.instagram.com/v1/users/self/media/recent/?access_token=ACCESS-TOKEN.

However, that returns an empty object unless I post a regular post.

答:
As far as I am aware the Instagram API does not currently return Stories.

The example response in the documentation for the media endpoint, for example, shows responses for Images, Videos and Carousel items only.  The recent media end point documentation doesn't go into much detail on responses.

Media End Point Documentation