问:
htaccess redirection of multiple URLs
I usually use this site to solve my problems, but for the first time I couldn't find a proper question, so forgive me if it actually exists!

Currently, I have valid URLs in such format:

```<code>http://www.example.com/index/modules/news/article.php?storyid=15807
</code>```

That the number at the end is generated dynamically by CMS and therefore changes for any new content published.

In order to use shorter URLs, I want these pages to be accessible by subdomain in such format:

```<code>http://news.example.com/n15807
</code>```

Please help me and let me know if there is a better option rather than using htaccess.

答:
After hours of searches I finally got it!

```<code>RewriteEngine on
RewriteCond %{HTTP_HOST} ^news.example.com$
RewriteRule ^news/(.*)$ http://www.example.com/index/modules/news/article.php?storyid=$1\#siteBody [R=301,L,NE]
</code>```

Thought it might help someone someday not to spend as much time as I did!

Title: htaccess redirection of multiple URLs

Body:
I usually use this site to solve my problems, but for the first time I couldn't find a proper question, so forgive me if it actually exists!

Currently, I have valid URLs in such format:

http://www.example.com/index/modules/news/article.php?storyid=15807

That the number at the end is generated dynamically by CMS and therefore changes for any new content published.

In order to use shorter URLs, I want these pages to be accessible by subdomain in such format:

http://news.example.com/n15807

Please help me and let me know if there is a better option rather than using htaccess.

Body:
After hours of searches I finally got it!

RewriteEngine on
RewriteCond %{HTTP_HOST} ^news.example.com$
RewriteRule ^news/(.*)$ http://www.example.com/index/modules/news/article.php?storyid=$1\#siteBody [R=301,L,NE]

Thought it might help someone someday not to spend as much time as I did!


来源: stackexchange

问:
Calling UWP OCR sample from WPF Application with UWPDesktop nuget package
I am calling Windows 10 API from my WPF application. I have installed "UWPDesktop" Nuget package also.
I have called UWP OCR API from WPF application, After running code, I am getting an
Exception.

System.InvalidOperationException: 'The process has no package identity.
  (Exception from HRESULT: 0x80073D54)'

I have just written this code in my wpf application.
And also added UWPDesktop nugget package to access UWP API.

var ocrEngine = Windows.Media.Ocr.OcrEngine.TryCreateFromLanguage(new Windows.Globalization.Language("en"));

```<code>        var file = await Package.Current.InstalledLocation.GetFileAsync(@"Assets\test.png");

        using (var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
        {
            // Create image decoder.
            var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream);

            // Load bitmap.
            var bitmap = await decoder.GetSoftwareBitmapAsync();

            // Extract text from image.
            OcrResult result = await ocrEngine.RecognizeAsync(bitmap);

            // Return recognized text.
            Trace.WriteLine(result);
        }
</code>```

I am getting exception at first line.

What is this exception and why it occurs?

答:
That error says that OcrEngine.TryCreateFromLanguage can be called only from a UWP app (which runs in an app container) and not in a desktop app (which doesn't run in a container). If you look at god API document you'll find a DualApiPartition attribute on Windows Runtime methods API that can be called in both UWP and desktop contexts. The OcrEngine methods don't have this attribute so can't be called from desktop apps.

Your options will be to use a different OCR package or to call it from inside an app context. For the latter look into packaging the WPF app as a UWP app with the Windows Desktop Bridge

ContentLicense: CC BY-SA 3.0

Body:
I am calling Windows 10 API from my WPF application. I have installed "UWPDesktop" Nuget package also.
I have called UWP OCR API from WPF application, After running code, I am getting an
Exception.

System.InvalidOperationException: 'The process has no package identity.
  (Exception from HRESULT: 0x80073D54)'

I have just written this code in my wpf application.
And also added UWPDesktop nugget package to access UWP API.

var ocrEngine = Windows.Media.Ocr.OcrEngine.TryCreateFromLanguage(new Windows.Globalization.Language("en"));

        var file = await Package.Current.InstalledLocation.GetFileAsync(@"Assets\test.png");

        using (var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
        {
            // Create image decoder.
            var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream);

            // Load bitmap.
            var bitmap = await decoder.GetSoftwareBitmapAsync();

            // Extract text from image.
            OcrResult result = await ocrEngine.RecognizeAsync(bitmap);

            // Return recognized text.
            Trace.WriteLine(result);
        }

I am getting exception at first line.

What is this exception and why it occurs?


问:
Determine 'this week' in T-SQL
This is locale specific to the US wherein it considered that the start of a week is Sunday; I want to be able to ask SQL to give me the date of the next Sunday relative to today [getDate()]. If today is Jan 15 it should return Jan 18; if today were Sunday it should return the following Sunday which is the 25th. This would be trivial to write a UDF for but I was curious if anyone had other tricks/ideas?</p>

答:
```<code>DECLARE @d AS datetime
SET @d = '1/15/2009'
PRINT @d
PRINT DATEADD(day, 8 - DATEPART(weekday, @d), @d)
SET @d = '1/18/2009'
PRINT @d
PRINT DATEADD(day, 8 - DATEPART(weekday, @d), @d)

-- So it should be able to be used inline pretty efficiently:
DATEADD(day, 8 - DATEPART(weekday, datecolumn), datecolumn)

-- If you want to change the first day for a different convention, simply use SET DATEFIRST before performing the operation
-- e.g. for Monday: SET DATEFIRST 1
-- e.g. for Saturday: SET DATEFIRST 6

DECLARE @restore AS int
SET @restore = @@DATEFIRST
SET DATEFIRST 1

DECLARE @d AS datetime
SET @d = '1/15/2009'
PRINT @d
PRINT DATEADD(day, 8 - DATEPART(weekday, @d), @d)
SET @d = '1/19/2009'
PRINT @d

PRINT DATEADD(day, 8 - DATEPART(weekday, @d), @d)
SET DATEFIRST @restore
</code>```

ContentLicense: CC BY-SA 2.5

Title: Determine 'this week' in T-SQL

LastEditorDisplayName: Cade Roux

OwnerDisplayName: Cade Roux


问:
Using resources with the same name in Xcode
Is there a way to add multiple resources with the same name to an Xcode project and have 1 of them take priority over the others?

Example:
I added 2 files, both called icon.png, to an Xcode project. They are on different folders in the file system (Folder1/icon.png and Folder2/icon.png) and on different groups in Xcode. Is there a way to tell Xcode to have Folder2/icon.png take priority over Folder1/icon.png? And if only 1 icon.png exists, then use that one.

Thanks.

EDIT (2010-12-23):

You can have multiple files with the same name in an Xcode project even if they are not in separate folder references, but they are in separate groups. Once compiled, the app bundle (which will be flat with no folders in it), will only have one copy of the file (icon.png). How do you pick which copy of the file to use?

I was told that you can do this for BlackBerry. It works something like this: The compiler will go down the list of files in the project and start adding them to the app bundle. If it sees a duplicate, it will overwrite it (or not), so the files at the bottom (or at the top) will have higher precedence and will be the final bundle.

答: This can better easily be solved by using folders within a resource bundle in your Xcode project.  Take a look here: http://developer.apple.com/library/mac/#documentation/CoreFoundation/Conceptual/CFBundles/Introduction/Introduction.html</p>


问:
XPages CSS and id-attributes
Normally I can get around the fact xpages hijacks the id-attribute on fields etc by using the x$ jQuery selector...

However, I'm building a sylesheet using the @print media query to make a normal form into a pretty version when printed. I have a scenario, where I have a custom control, have given it an ID of GuidanceArea, and under normal circumstances would be able to reference it in my style sheet with #GuidanceArea, just to simply hide it for example for this scenario.

However this isn't working, I assume because of the ID hijacking? It's not too much of a big deal, as I have workaround where for all elements I don't want to print I just append no-print to the elements styleClass and have .no-print set to display:none in my @media print within the style sheet.

However out of curiosity more than anything, I wondered if there's an easy way to get a hold of an elements ID for use in CSS?

答:
The short answer: don't

The longs answer: JSF and XPages manage the id attribute to ensure it is unique on a page. So you don't have actual knowledge what it will be.

The easiest way is to use the class attribute to mark the element of interest, so your selector would be .someclass instead of #someid

But if you absolutely have to: use  an XPages output element to send a piece of computed inline css where you use expression language to obtain the actual id. Browsers or libraries might cough on the : in the id, so your result requires lots of testing. VanillaJS should work.

Title: XPages CSS and id-attributes


问:
Add index position Value of an array of array using Linq
We can do sum using arr.Sum() function. But if it is an array of arrays. How will we add all values.
suppose data is
Array/List is  [[1,2,3],[3,4,5],[5,4,3]]
how will you get s1 , sum of all first index value, s2 , sum of second index value and so on using LINQ.

答:
If you want to sum up columns' values with a help of Linq:

```<code>int[][] source = new int[][] {
  new int[] { 1, 2, 3},
  new int[] { 3, 4, 5},
  new int[] { 5, 4, 3},
};

int maxCol = source.Max(item => item.Length);

var colsSum = Enumerable
  .Range(0, maxCol)
  .Select(index => source.Sum(item => item.Length > index ? item[index] : 0))
  .ToArray(); // let's meaterialize into an array
</code>```

Test:

```<code>Console.Write(string.Join(", ", colsSum));
</code>```

Outcome:

```<code> 9, 10, 11
</code>```

Summing up lines' values is easier:

```<code>// [6, 12, 12]
var linesSum = source
  .Select(item => item.Sum())
  .ToArray();
</code>```

If you want total sum:

```<code>// 30
var total = source
  .Select(item => item.Sum())
  .Sum();
</code>```

or

```<code>// 30
var total = source
  .SelectMany(item => item)
  .Sum();
</code>```

Body:
If you want to sum up columns' values with a help of Linq:

int[][] source = new int[][] {
  new int[] { 1, 2, 3},
  new int[] { 3, 4, 5},
  new int[] { 5, 4, 3},
};

int maxCol = source.Max(item => item.Length);

var colsSum = Enumerable
  .Range(0, maxCol)
  .Select(index => source.Sum(item => item.Length > index ? item[index] : 0))
  .ToArray(); // let's meaterialize into an array

Test:

Console.Write(string.Join(", ", colsSum));

Outcome:

 9, 10, 11

Summing up lines' values is easier:

// [6, 12, 12]
var linesSum = source
  .Select(item => item.Sum())
  .ToArray();

If you want total sum:

// 30
var total = source
  .Select(item => item.Sum())
  .Sum();

or

// 30
var total = source
  .SelectMany(item => item)
  .Sum();


问:
The server responded with a status of 500 AJAX Post
I have this javascript function which should redirect me to

http://localhost:8888/ID OF A PRODUCT/add-to-cart".

But instead I got this:

http://localhost:8888/undefined/add-to-cart".

```<code>$('.add-to-cart').on('click', function () {
        var productId = $(this).find('.indexImg').attr('id');

        $.ajax(productId+"/add-to-cart",
        {

        });
    });
</code>```

image}}" id="{{$product->id}}">

Can someone help me to get ID of a product ?

HTML:

```<code> @foreach($products as $product)
  <div class="col-md-3">
        <div class="box-product">
            <div class="img-wrapper item">
                <a href="/product/{{$product->id}}/{{$product->slug}}">
                    <a class="thumbnail" href="/product/{{$product->id}}/{{$product->slug}}" style="margin-bottom: 0px; border: none;">
                    <img class="indexImg" src="{{$product->image}}" id="{{$product->id}}">
                    </a>
                </a>
            <div class="tags">
            @if($product->discount > 0)
                <span class="label-tags"><span class="label label-danger">Išpardavimas</span></span>
            @endif
                <span class="label-tags"><span class="label label-info">Nauja</span></span>
            </div>
            <div class="option">
                <i class="fa fa-shopping-cart add-to-cart" aria-hidden="true" style="color: white"></i>
            </div>
        </div>
</code>```

答:
The way you are trying to get product ID based on DOM is incorrect. The jQuery .find() method looks for specified elements within the elements, i.e. its descendants. If you look at the HTML, you'll see that the div elements containing the add-to-cart button and the image whose id attribute you are trying to fetch are on the same level.

So you've got to change the way you are traversing to reach the id attribute of the  tag.

var productId = $(this).closest('.box-product').find('.indexImg').attr('id');

Body:
I have this javascript function which should redirect me to

http://localhost:8888/ID OF A PRODUCT/add-to-cart".

But instead I got this:

http://localhost:8888/undefined/add-to-cart".

$('.add-to-cart').on('click', function () {
        var productId = $(this).find('.indexImg').attr('id');

        $.ajax(productId+"/add-to-cart",
        {

        });
    });

image}}" id="{{$product->id}}">

Can someone help me to get ID of a product ?

HTML:

 @foreach($products as $product)

                id}}/{{$product->slug}}">
                    id}}/{{$product->slug}}" style="margin-bottom: 0px; border: none;">
                    image}}" id="{{$product->id}}">

            @if($product->discount > 0)
                Išpardavimas
            @endif
                Nauja

Body:
The way you are trying to get product ID based on DOM is incorrect. The jQuery .find() method looks for specified elements within the elements, i.e. its descendants. If you look at the HTML, you'll see that the div elements containing the add-to-cart button and the image whose id attribute you are trying to fetch are on the same level.

So you've got to change the way you are traversing to reach the id attribute of the <img> tag.

var productId = $(this).closest('.box-product').find('.indexImg').attr('id');


问:
android - Format Double and put it in TextView without comma (if needed)
I get the "price" value from the server in Double and I need to put it in TextView in my application. The problem is: when price = 500 I get 500.0 because it's Double. I want it to look like 500.55 or 500.50 or just 500 - how do I format these numbers in the right way?

答:
You need to explicitly get the int value using method intValue() like this:

Double d = 5.25;
Integer i = d.intValue();

OR
double d = 5.25;
int i = (int) d;

ContentLicense: CC BY-SA 4.0


问:
IOS11 Beta ARKit can't scale Scene object
I created a basic scene, and added an dae file.
First every time i run or save the project i get the popup:
The document “billboard.dae” could not be saved.

It still runs though but is annoying.

But the issue is I can't scale the object.
I have tried different values 0.5s and also > 1 but nothing seems to work. Here is my code

```<code>  override func viewDidLoad()
    {
        super.viewDidLoad()

        sceneView.delegate = self
        sceneView.showsStatistics = true

        let scene = SCNScene(named: "art.scnassets/billboard.dae")!
        let billboardNode = scene.rootNode.childNode(withName: "billboard", recursively: true)

        //  billboardNode?.position = SCNVector3Make(0, 0, 1)
        billboardNode?.position.z = 10
        billboardNode?.scale.z = 0.5
        //  billboardNode?.scale = SCNVector3Make(0.4,0.4, 0.4)

        sceneView.scene = scene
    }
</code>```

Any ideas?

Thanks

答:
Have you verified billboardNode is not nil? You're sending an optional (the result of looking for a child node with a given name) position and scaling messages but if it's nil (because finding the child node failed) it won't have any impact.

The error suggests to me there was some problem converting the .dae file, which might explain why the scene can't locate the asset by name. Or it might be as simple as "billboard" vs. "Billboard".

Body:
I created a basic scene, and added an dae file.
First every time i run or save the project i get the popup:
The document “billboard.dae” could not be saved.

It still runs though but is annoying.

But the issue is I can't scale the object.
I have tried different values 0.5s and also > 1 but nothing seems to work. Here is my code

  override func viewDidLoad()
    {
        super.viewDidLoad()

        sceneView.delegate = self
        sceneView.showsStatistics = true

        let scene = SCNScene(named: "art.scnassets/billboard.dae")!
        let billboardNode = scene.rootNode.childNode(withName: "billboard", recursively: true)

        //  billboardNode?.position = SCNVector3Make(0, 0, 1)
        billboardNode?.position.z = 10
        billboardNode?.scale.z = 0.5
        //  billboardNode?.scale = SCNVector3Make(0.4,0.4, 0.4)

        sceneView.scene = scene
    }

Any ideas?

Thanks


问:
How does MFC's CTreeCtrl automatically displays a tool tip, containing the title of the item, if the entire title is not currently visible?
Background http://msdn.microsoft.com/en-us/library/b17bescz(v=VS.90).aspx
"The TVS_NOTOOLTIPS style disables the automatic tool tip feature of tree view controls. This feature automatically displays a tool tip, containing the title of the item under the mouse cursor, if the entire title is not currently visible."

Question: Where is this default feature [i.e. whenever the item is cutoff, auto show tooltip of the title] of the CTreeCtrl actually implemented in the MFC code (e.g. which file)?

Thanks

答:
It should be relatively straightforward to implement this.

Capture mouse move in treectrl  (OnMouseMove)

Get current cursor position

Get item under cursor (treectrl.HitTest)

Get item's display rect (treectrl.GetItemRect)

Get treectrl's display rect (treectrl.GetClientRect)

If right side of item's display rect > treectrl's display rect --> SHOW TOOLTIP AT (item.left, item.top)

If left side of item's display rect < treectrl's display rect --> SHOW TOOLTIP AT (treectrl.left, item.top)

Dunno if this helps.  I do a very similar thing in an MFC app to do specialist highlighting.


问:
How to get coordinates of a mxCell?
I need to get the coordinates (x,y) of a mxCell that i find by his Id, but when i call getGeometry() on it, it gives me null and after i get NullPointerException.

```<code>private double getX(String node){
    mxCell cell = (mxCell) ((mxGraphModel)map.getGraph().getModel()).getCell(node);
    mxGeometry geo = cell.getGeometry();//this line give me the null value
    double x = geo.getX();//NullPointerException
    return x;
}
</code>```

map is the mxGraphComponent that contains all the graph.

What am i missing?

答:
I assume your String node argument should be mapped to the cell's id.

Basically, you select all cells, get them and iterate over them. Since nearly everything in JGraph is Object, you need some casts.

```<code>private double getXForCell(String id) {
    double res = -1;
    graph.clearSelection();
    graph.selectAll();
    Object[] cells = graph.getSelectionCells();
    for (Object object : cells) {
        mxCell cell = (mxCell) object;
        if (id.equals(cell.getId())) {
            res = cell.getGeometry().getX();
        }
    }
    graph.clearSelection();
    return res;
}
</code>```

You might as well check if cell.isVertex() before calling getGeometry(), since its implemented differently on edges.

Edit: Followed your approach and the following works for me, too. Seems like you need the extra cast (mxCell).

```<code>mxGraphModel graphModel = (mxGraphModel) graph.getModel();
return ((mxCell) graphModel.getCell(id)).getGeometry().getX();
</code>```

Title: How to get coordinates of a mxCell?

Body:
I need to get the coordinates (x,y) of a mxCell that i find by his Id, but when i call getGeometry() on it, it gives me null and after i get NullPointerException.

private double getX(String node){
    mxCell cell = (mxCell) ((mxGraphModel)map.getGraph().getModel()).getCell(node);
    mxGeometry geo = cell.getGeometry();//this line give me the null value
    double x = geo.getX();//NullPointerException
    return x;
}

map is the mxGraphComponent that contains all the graph.

What am i missing?

Body:
I assume your String node argument should be mapped to the cell's id.

Basically, you select all cells, get them and iterate over them. Since nearly everything in JGraph is Object, you need some casts.

private double getXForCell(String id) {
    double res = -1;
    graph.clearSelection();
    graph.selectAll();
    Object[] cells = graph.getSelectionCells();
    for (Object object : cells) {
        mxCell cell = (mxCell) object;
        if (id.equals(cell.getId())) {
            res = cell.getGeometry().getX();
        }
    }
    graph.clearSelection();
    return res;
}

You might as well check if cell.isVertex() before calling getGeometry(), since its implemented differently on edges.

Edit: Followed your approach and the following works for me, too. Seems like you need the extra cast (mxCell).

mxGraphModel graphModel = (mxGraphModel) graph.getModel();
return ((mxCell) graphModel.getCell(id)).getGeometry().getX();


问:
I am making a login and sign up page for android but the sqlite database i use crashes on onCreate
```<code>package company.mystorage.com.mystorage;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper{

private static final String DATABASE_NAME = "mystorage.db";
private static final String TABLE_NAME = "userlist";

public static final String COLUMN_1 ="Id";
private static final String COLUMN_2 = "username";
private static final String COLUMN_3 = "password";
SQLiteDatabase db;

    public DatabaseHelper(Context context) {
        // database is created when constructor is called.
        super(context, DATABASE_NAME, null, 1);
        // to invoke onCreate() and onUpgrade() methods to create the tables
        SQLiteDatabase db = this.getWritableDatabase();

    }

    @Override
    public void onCreate(SQLiteDatabase db){
        db.execSQL("create table " + TABLE_NAME + "("
                + COLUMN_1 +" INTEGER PRIMARY KEY AUTOINCREMENT, "
                + COLUMN_2 +" TEXT, "
                + COLUMN_3 +" TEXT)"
        );

    }

    public boolean insertData(String username, String password){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COLUMN_2, username);
        contentValues.put(COLUMN_3, password);
        long result = db.insert(TABLE_NAME, null, contentValues);
        if (result == -1)
            return false;
        else
            return true;
    }

    public boolean searchPass(String user){
        db = this.getReadableDatabase();
        String query = "select * from  " + TABLE_NAME + " where " + COLUMN_2 + " = " + "'" + user + "'";
        Cursor cursor = db.rawQuery(query, null);

        cursor.moveToFirst();
        if (cursor.getCount() > 0) {

            return true;
        }
        cursor.close();
        db.close();

        return false;

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);
        onCreate(db);
    }

}
</code>```

This code will create a database and also contains the functions to search and add users to the database. I tried to debug the code and it showed that it crashed when the onCreate was called. I checked the onCreate but the query is being execute correctly.

Edited* I changed the this. for the db but it still crashed.

答:
```<code>public void onCreate(SQLiteDatabase db){
    this.db.execSQL(...)
</code>```

You should be calling execSQL() on the db parameter and not this.db field that has not yet been initialized.

Body:
package company.mystorage.com.mystorage;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper{

private static final String DATABASE_NAME = "mystorage.db";
private static final String TABLE_NAME = "userlist";

public static final String COLUMN_1 ="Id";
private static final String COLUMN_2 = "username";
private static final String COLUMN_3 = "password";
SQLiteDatabase db;

    public DatabaseHelper(Context context) {
        // database is created when constructor is called.
        super(context, DATABASE_NAME, null, 1);
        // to invoke onCreate() and onUpgrade() methods to create the tables
        SQLiteDatabase db = this.getWritableDatabase();

    }

    @Override
    public void onCreate(SQLiteDatabase db){
        db.execSQL("create table " + TABLE_NAME + "("
                + COLUMN_1 +" INTEGER PRIMARY KEY AUTOINCREMENT, "
                + COLUMN_2 +" TEXT, "
                + COLUMN_3 +" TEXT)"
        );

    }

    public boolean insertData(String username, String password){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COLUMN_2, username);
        contentValues.put(COLUMN_3, password);
        long result = db.insert(TABLE_NAME, null, contentValues);
        if (result == -1)
            return false;
        else
            return true;
    }

    public boolean searchPass(String user){
        db = this.getReadableDatabase();
        String query = "select * from  " + TABLE_NAME + " where " + COLUMN_2 + " = " + "'" + user + "'";
        Cursor cursor = db.rawQuery(query, null);

        cursor.moveToFirst();
        if (cursor.getCount() > 0) {

            return true;
        }
        cursor.close();
        db.close();

        return false;

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);
        onCreate(db);
    }

}

This code will create a database and also contains the functions to search and add users to the database. I tried to debug the code and it showed that it crashed when the onCreate was called. I checked the onCreate but the query is being execute correctly.

Edited* I changed the this. for the db but it still crashed.

Body:
public void onCreate(SQLiteDatabase db){
    this.db.execSQL(...)

You should be calling execSQL() on the db parameter and not this.db field that has not yet been initialized.


问:
Java execuetorService running too fast?
By the following code

```<code>    ExecutorService executorService = Executors.newFixedThreadPool(3)
    for (int i=0; i<10; i++){
            executorService.execute(new Runnable() {
                @Override
                void run() {
                    try {
                        Thread.sleep(1*1000)
                        System.out.println("Thread " + Thread.currentThread().getName() + " processing item " + i)
                    } catch (InterruptedException e) {
                        e.printStackTrace()
                    }
                }
            })
    }
</code>```

I am expecting the output as follows:

Thread pool-1-thread-2 processing item 1

Thread pool-1-thread-3 processing item 2

Thread pool-1-thread-2 processing item 3

Thread pool-1-thread-3 processing item 4

Thread pool-1-thread-2 processing item 5

Thread pool-1-thread-2 processing item 7

Thread pool-1-thread-3 processing item 6

Thread pool-1-thread-2 processing item 8

Thread pool-1-thread-3 processing item 9

Thread pool-1-thread-1 processing item 0

But it turns out to be:

Thread pool-1-thread-1 processing item 10

Thread pool-1-thread-1 processing item 10

Thread pool-1-thread-1 processing item 10

Thread pool-1-thread-1 processing item 10

Thread pool-1-thread-1 processing item 10

Thread pool-1-thread-1 processing item 10

Thread pool-1-thread-1 processing item 10

Thread pool-1-thread-1 processing item 10

Thread pool-1-thread-2 processing item 10

Thread pool-1-thread-3 processing item 10

The correct out put is by adding a temp variable before the executorService.exeute method. Here comes the question, what's the cause of the unexpected output?

答:
All your runnables share the same instance of i.

By the time they run, this variable has a value of 10

Hence the output.

If you use a closure, each runnable will get a new instance of i and you'll get the expected output:

```<code>ExecutorService executorService = Executors.newFixedThreadPool(3)
10.times { i ->
   executorService.execute { ->
       Thread.sleep(1000)
       println "Thread ${Thread.currentThread().getName()} processing item $i"
   }
}
executorService.shutdown()
</code>```

But they won't be in the order you say you expect, because threads...

Title: Java execuetorService running too fast?

Body:
By the following code

    ExecutorService executorService = Executors.newFixedThreadPool(3)
    for (int i=0; i<10; i++){
            executorService.execute(new Runnable() {
                @Override
                void run() {
                    try {
                        Thread.sleep(1*1000)
                        System.out.println("Thread " + Thread.currentThread().getName() + " processing item " + i)
                    } catch (InterruptedException e) {
                        e.printStackTrace()
                    }
                }
            })
    }

I am expecting the output as follows:

Thread pool-1-thread-2 processing item 1

Thread pool-1-thread-3 processing item 2

Thread pool-1-thread-2 processing item 3

Thread pool-1-thread-3 processing item 4

Thread pool-1-thread-2 processing item 5

Thread pool-1-thread-2 processing item 7

Thread pool-1-thread-3 processing item 6

Thread pool-1-thread-2 processing item 8

Thread pool-1-thread-3 processing item 9

Thread pool-1-thread-1 processing item 0

But it turns out to be:

Thread pool-1-thread-1 processing item 10

Thread pool-1-thread-1 processing item 10

Thread pool-1-thread-1 processing item 10

Thread pool-1-thread-1 processing item 10

Thread pool-1-thread-1 processing item 10

Thread pool-1-thread-1 processing item 10

Thread pool-1-thread-1 processing item 10

Thread pool-1-thread-1 processing item 10

Thread pool-1-thread-2 processing item 10

Thread pool-1-thread-3 processing item 10

The correct out put is by adding a temp variable before the executorService.exeute method. Here comes the question, what's the cause of the unexpected output?

Body:
All your runnables share the same instance of i.

By the time they run, this variable has a value of 10

Hence the output.

If you use a closure, each runnable will get a new instance of i and you'll get the expected output:

ExecutorService executorService = Executors.newFixedThreadPool(3)
10.times { i ->
   executorService.execute { ->
       Thread.sleep(1000)
       println "Thread ${Thread.currentThread().getName()} processing item $i"
   }
}
executorService.shutdown()

But they won't be in the order you say you expect, because threads...


问:
How to upload particular image on particular imageView click from gallery and camera in android
i have 4 diffrent imageview and try to click on all to upload diffrent images like LIcence,Rc,Profile  etc . I want to uploaded image from gallery or camera dialog..
 like this layout.
like uper layout example</p>

答:
```<code> private void imageBrowse() {
if(camera){
 Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, CAMERA_REQUEST);
}else{
    Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    // Start the Intent
    startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST);
}
}

 public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == RESULT_OK) {

        if(requestCode == PICK_IMAGE_REQUEST){
            Uri picUri = data.getData();

            filePath = getPath(picUri);
            uri =picUri;
            Log.d("picUri", picUri.toString());
            Log.d("filePath", filePath);

            imageView.setImageURI(picUri);

        }

  if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
        Bitmap photo = (Bitmap) data.getExtras().get("data");
        imageView.setImageBitmap(photo);
    }

    }

}
</code>```


问:
Python 3.6 SSL: CERTIFICATE_VERIFY_FAILED
I'm using the following code to connect with labeeb-iot broker.

```<code>import paho.mqtt.client as mqtt
import ssl

def on_connect(client, userdata, flags, rc):
  print("Connected with result code "+str(rc))
  client.subscribe("/focus/temp/SEnsor1/Model1/Temperature/data")

def on_message(client, userdata, msg):
  print(msg.payload.decode())

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.tls_set("/etc/ssl/certs/ca-certificates.crt", certfile=None, keyfile=None, cert_reqs=ssl.CERT_REQUIRED,tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None)

client.tls_insecure_set(False)

client.connect("mea.labeeb-iot.com",8883,60)

client.loop_forever()
</code>```

after the execution of the following code the result is :

答:
The certificate on the broker expired on the 26th May this year.

You can verify this with the following command:

```<code>openssl s_client -verify 2  -connect mea.labeeb-iot.com:8883 -CAfile /etc/ssl/certs/ca-certificates.crt
</code>```

Which will print something like:

depth=0 C = QA, ST = Qatar, L = Doha, O = Qatar Mobility Innovations
  Center (QMIC), CN = *.labeeb-iot.com notAfter=May 26 12:24:38 2017 GMT
  verify return:1

Body:
I'm using the following code to connect with labeeb-iot broker.

import paho.mqtt.client as mqtt
import ssl

def on_connect(client, userdata, flags, rc):
  print("Connected with result code "+str(rc))
  client.subscribe("/focus/temp/SEnsor1/Model1/Temperature/data")

def on_message(client, userdata, msg):
  print(msg.payload.decode())

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.tls_set("/etc/ssl/certs/ca-certificates.crt", certfile=None, keyfile=None, cert_reqs=ssl.CERT_REQUIRED,tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None)

client.tls_insecure_set(False)

client.connect("mea.labeeb-iot.com",8883,60)

client.loop_forever()

after the execution of the following code the result is :

Body:
The certificate on the broker expired on the 26th May this year.

You can verify this with the following command:

openssl s_client -verify 2  -connect mea.labeeb-iot.com:8883 -CAfile /etc/ssl/certs/ca-certificates.crt

Which will print something like:

depth=0 C = QA, ST = Qatar, L = Doha, O = Qatar Mobility Innovations
  Center (QMIC), CN = *.labeeb-iot.com notAfter=May 26 12:24:38 2017 GMT
  verify return:1


问:
TrimEnd for Java?
In the process of converting a C# application to Java, I came across the use of String's TrimEnd method. Is there an equivalent Java implementation? I can't seem to find one.

I'd rather not replace it with trim, since I don't want to change the meaning or operation of the program at this point unless I have to.

答:
If performance is not important one-liner could be used: </p>

```<code>("X" + str).trim().substring(1)
</code>```

Title: TrimEnd for Java?

Body:
If performance is not important one-liner could be used:

("X" + str).trim().substring(1)


问:
How to implement similar html page scrubber like Arc90's Readability or Instapaper?
I'm interested to find out how to scrub a html page and present it nicely -- remove all the clutters and reformat the main text into a very readable format -- like http://lab.arc90.com/experiments/readability or Instapaper.

Is it a simple page parsing and removing elements that are not within
 ?

Was this discussed somewhere else?

答: https://github.com/jiminoc/goose/wiki does something like you're asking, source code is openly available along with unit tests</p>


问:
Match any word of a List/Array in a Sentence java
I have an List of word like below

```<code>List<String> forbiddenWordList = Arrays.asList("LATE", "S/O", "SO", "W/O", "WO");
</code>```

How can I understand a String Contains any one of the word of the List. like....

```<code>String name1 = "Adam Smith";      // false (not found)
String name2 = "Late H Milton";   // true  (found Late)
String name3 = "S/O Furi Kerman"; // true  (found S/O)
String name4 = "Conl Faruk";      // false (not found)
String name5 = "Furi Kerman WO";  // true  (found WO)
</code>```

Regular Expression highly appreciated.

答:
turn the list to a string with the | delimiter

String listDelimited = String.join("|", forbiddenWordList )

create the regex

Pattern forbiddenWordPattern
        = Pattern.compile(listDelimited , Pattern.CASE_INSENSITIVE);

test your text

boolean hasForbiddenWord = forbiddenWordPattern.matcher(text).find();

(similar to the answer of @Maurice Perry)

Body:
I have an List of word like below

List<String> forbiddenWordList = Arrays.asList("LATE", "S/O", "SO", "W/O", "WO");

How can I understand a String Contains any one of the word of the List. like....

String name1 = "Adam Smith";      // false (not found)
String name2 = "Late H Milton";   // true  (found Late)
String name3 = "S/O Furi Kerman"; // true  (found S/O)
String name4 = "Conl Faruk";      // false (not found)
String name5 = "Furi Kerman WO";  // true  (found WO)

Regular Expression highly appreciated.


问:
setting schemaLocation for wsdl with jax-ws
Hye, i am using jax-ws for my webservices. The class for webservice as below

```<code>@WebService(
    portName = "GuidStatusPort",
    serviceName = "GuidStatusService",
    targetNamespace = "http://url/wsdl",
    endpointInterface = "com.smartap.ws.GuidStatusWs",
    wsdlLocation="https://myurl/guidstatus")
 public class GuidStatus implements GuidStatusWs{
 ...................
</code>```

After deploy, the wsdl file shows schemaLocation as below

```<code>... namespace="http://smartapws.org/wsdl"    schemaLocation="http://myurl:80/guidstatus?xsd=1" ...
</code>```

How can i set the schemaLocation from my java class?

Thank you

答:
as of JAXB v2.1, schema location can be set on XmlSchema annotation usually bound to package in package-info.java file

```<code>@javax.xml.bind.annotation.XmlSchema(namespace = "http://message", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED, location="http://my/schema/location/Message.xsd")
package my.beans;
</code>```

Body:
Hye, i am using jax-ws for my webservices. The class for webservice as below

@WebService(
    portName = "GuidStatusPort",
    serviceName = "GuidStatusService",
    targetNamespace = "http://url/wsdl",
    endpointInterface = "com.smartap.ws.GuidStatusWs",
    wsdlLocation="https://myurl/guidstatus")
 public class GuidStatus implements GuidStatusWs{
 ...................

After deploy, the wsdl file shows schemaLocation as below

... namespace="http://smartapws.org/wsdl"    schemaLocation="http://myurl:80/guidstatus?xsd=1" ...

How can i set the schemaLocation from my java class?

Thank you

Body:
as of JAXB v2.1, schema location can be set on XmlSchema annotation usually bound to package in package-info.java file

@javax.xml.bind.annotation.XmlSchema(namespace = "http://message", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED, location="http://my/schema/location/Message.xsd")
package my.beans;


答:
Use DecimalFormat

```<code>double price = 500.0;
DecimalFormat format = new DecimalFormat("0.###");
System.out.println(format.format(price));
</code>```

EDIT

Ok, than try something different:

```<code>public static String formatPrice ( double price){
    if (price == (long) price)
        return String.format("%d", (long) price);
    else
        return String.format("%s", price);
}
</code>```

Title: android - Format Double and put it in TextView without comma (if needed)

Body: I get the "price" value from the server in Double and I need to put it in TextView in my application. The problem is: when price = 500 I get 500.0 because it's Double. I want it to look like 500.55 or 500.50 or just 500 - how do I format these numbers in the right way?

Body:
Use DecimalFormat

double price = 500.0;
DecimalFormat format = new DecimalFormat("0.###");
System.out.println(format.format(price));

EDIT

Ok, than try something different:

public static String formatPrice ( double price){
    if (price == (long) price)
        return String.format("%d", (long) price);
    else
        return String.format("%s", price);
}


问:
Trouble styling divs on top of an image (css)
I have a rails app that i've been working on, and one of the functionality aspects I do with it is that I ask the user to import an image (i'm using the paperclip gem to do that). Once they do that and finish creating everything else, I'm taking that image that is imported and using it as a background image for their page.  Problem is.....i'm having serious problems actually doing that.

My html (haml) looks like this

```<code>#cafe_show
  .image_holding_div
    = image_tag @cafe.image.url(:medium)
    .cafe_info
      This is a quick test
</code>```

and my CSS is like so

```<code>#cafe_show {
  .image_holding_div {
    position: relative;
  }
  img {
    height: 100vh;
    width: 100%;
    position: relative;
    z-index: -1;
  }
}

.cafe_info {
  position: relative;
  float: center;
  height: 100px;
  width: auto;
  background-color: #808080;
  opacity:.9;
  text-align:center;
  color:white;
  }
</code>```

Problem I'm having is, the .cafe_info div sits below the image, and not on top of the image.  Would anyone have an idea what I can do for this?

答:
You can try absolute position rather than be using relative and defining the top & left as well. A sample CSS could be like this:</p>

```<code>.cafe_info {
   position: absolute;
   top: 200px;
   left: 0;
   width: 100%;
}
</code>```

Body:
I have a rails app that i've been working on, and one of the functionality aspects I do with it is that I ask the user to import an image (i'm using the paperclip gem to do that). Once they do that and finish creating everything else, I'm taking that image that is imported and using it as a background image for their page.  Problem is.....i'm having serious problems actually doing that.

My html (haml) looks like this

#cafe_show
  .image_holding_div
    = image_tag @cafe.image.url(:medium)
    .cafe_info
      This is a quick test

and my CSS is like so

#cafe_show {
  .image_holding_div {
    position: relative;
  }
  img {
    height: 100vh;
    width: 100%;
    position: relative;
    z-index: -1;
  }
}

.cafe_info {
  position: relative;
  float: center;
  height: 100px;
  width: auto;
  background-color: #808080;
  opacity:.9;
  text-align:center;
  color:white;
  }

Problem I'm having is, the .cafe_info div sits below the image, and not on top of the image.  Would anyone have an idea what I can do for this?

Body:
You can try absolute position rather than be using relative and defining the top & left as well. A sample CSS could be like this:

.cafe_info {
   position: absolute;
   top: 200px;
   left: 0;
   width: 100%;
}


问:
wcf implementation for interprocess communication
I have developed a .NET UI and windows service which communicate with each other using WCF through the NetNamedPipeBinding protocol. I chose NetNamedPipe because it is the best and efficient choice for interprocess communication on the same machine.

However, one of the key requirements of the application is that the UI should be able to send actions to the windows service and vice versa asynchronously. This means that the windows service should be able to call back the .NET UI application without the need for the .NET UI application to connect to the windows service first.

Keeping this in mind, I have hosted a WCF service in the windows service and a separate WCF service in the .NET UI application so that they can communicate asynchronously without the need to keep the communication channel always alive.

I would like to know if this makes good design sense.

I would appreciate your comments on the same.

Thanks in advance.

Subbu

答: WCF Callback allows server to drive events to the client. See a short and simple example here: A simple WCF Callback example


问:
How to use header redirect in PHP AJAX Call In Pure Javascript?
I am creating a login form and I need to redirect the user to his/her profile page! I am using AJAX Requests so header redirect is not working at all. It just stays on the homepage.

 So how can I redirect the user to another page in pure javascript PHP ajax call? Please give the answer in pure javascript. I don't like to use jQuery at all!

Javascript:

```<code>function ajaxCall(){
    var xhttp;

    if(window.XMLHttpRequest){
        xhttp = new XMLHttpRequest();
    }

    xhttp.onreadystatechange = function(){
        if(this.readyState === 4 && this.status === 200){
            document.getElementById('error').innerHTML = this.responseText;
        }
    };

    var parameters = 'email='+document.getElementById('email')+'&password='+document.getElementById('password');
    xhttp.open('POST', 'login.php', true);
    xhttp.setRequestHeader('Content-type', 'application/x-www/form/urlencoded');
    xhttp.send(parameters);
}
</code>```

Login.php(PHP)

```<code><?php
if(isset($_POST['email']) && isset($_POST['password'])){
    $ema = $_POST['email'];
    $pass = $_POST['password'];

    if(!empty($ema) && !empty($pass)){
        if($ema === 'Bill' && $pass === 'Cool'){
            header('Location: https://www.google.com');
        }
    }
}
</code>```

答:
try this bill if its works.</p>

```<code>  window.location.replace("http://www.google.com");
</code>```

Body:
I am creating a login form and I need to redirect the user to his/her profile page! I am using AJAX Requests so header redirect is not working at all. It just stays on the homepage.

 So how can I redirect the user to another page in pure javascript PHP ajax call? Please give the answer in pure javascript. I don't like to use jQuery at all!

Javascript:

function ajaxCall(){
    var xhttp;

    if(window.XMLHttpRequest){
        xhttp = new XMLHttpRequest();
    }

    xhttp.onreadystatechange = function(){
        if(this.readyState === 4 && this.status === 200){
            document.getElementById('error').innerHTML = this.responseText;
        }
    };

    var parameters = 'email='+document.getElementById('email')+'&password='+document.getElementById('password');
    xhttp.open('POST', 'login.php', true);
    xhttp.setRequestHeader('Content-type', 'application/x-www/form/urlencoded');
    xhttp.send(parameters);
}

Login.php(PHP)

<?php
if(isset($_POST['email']) && isset($_POST['password'])){
    $ema = $_POST['email'];
    $pass = $_POST['password'];

    if(!empty($ema) && !empty($pass)){
        if($ema === 'Bill' && $pass === 'Cool'){
            header('Location: https://www.google.com');
        }
    }
}

Body:
try this bill if its works.

  window.location.replace("http://www.google.com");


问:
How can I fill the space between values(geom_line) and an intercept with ggplot2? Different Colors for values over and under intercept
I want to do a graph with ggplot2, where I need the space/area between the intercept (=1) and the values (which I connected through geom_line) to be red (if the values are lower than 1) or green (if the values are bigger than 1). The data is from microsoft (price performance since 1999).

Data:

```<code>require(quantmod)
require(dplyr)
require(ggplot2)

getSymbols("MSFT", from ="1999-01-01")
microsoft <- data.frame(time(MSFT), MSFT[,6])
microsoft$time <- as.Date(microsoft$time.MSFT., "%Y-%m-%d")

microsoft <- microsoft %>%
mutate(change = MSFT.Adjusted - first(MSFT.Adjusted),
     change.pc = change/first(MSFT.Adjusted)+1)
</code>```

that is the ggplot I have so far:

```<code>ggplot(microsoft, aes(x = time, y = change.pc)) +
  geom_line(stat = "identity") +
  geom_hline(aes(yintercept=1), color="black") +
  theme_bw() +
  xlab("Jahr") + ylab("") +
  ggtitle("Microsoft Kursentwicklung seit Januar 1999")
</code>```

I want to fill the space between y = 1 and the values above in green, and the space between y = 1 and the values under in red. I tried geom_ribbon, geom_area, geom_polynom, but nothing worked. The biggest problem is, that it fills the space green, but not online above y = 1 but also under. and the red you can't even see...

here what I tried:

```<code>geom_area(data = subset(microsoft, change.pc > 1), fill = "green", alpha =0.5)
geom_area(data = subset(microsoft, change.pc < 1), fill = "red", alpha = 0.5)
</code>```

I put these to lines in my plot, and then the problem I described above appeared.

Among other things I also tried this (found here on stackoverflow.com):

```<code>microsoft$grp <- "orig"
microsoft <- microsoft[order(microsoft$time),]
microsoft_new <- do.call("rbind",
             sapply(1:(nrow(microsoft) -1), function(i){
               f <- lm(time ~ change.pc, microsoft[i:(i+1), ])
               if (f$qr$rank < 2) return(NULL)
               r <- predict(f, newdata = data.frame(change.pc = 0))
               if(microsoft[i, ]$time < r & r < microsoft[i+1, ]$time)
                 return(data.frame(time = r, change.pc = 0))
               else return(NULL)
             })
)
microsoft_2 <- rbind(microsoft, microsoft_new)
ggplot(microsoft_2, aes(x = time, y = change.pc)) +
  geom_area(data = subset(microsoft_2, change.pc <= 1), fill = "red") +
  geom_area(data = subset(microsoft_2, change.pc >= 1), fill = "blue") +
  scale_x_continuous("", expand = c(0,0), breaks = seq(1999, 2017, 3)) +
  theme_bw()
</code>```

That didn't work either.
Does anyone has an idea how I could achieve what I need?
This is how it should look

答:
You can use geom_ribbon for this. The following solution is similar to @Miff's solution, but with intersection at 1. I have in addition added the desired scales.

```<code>ggplot(microsoft, aes(x = time, y = change.pc)) +
  geom_ribbon(aes(ymin=pmin(change.pc,1), ymax=1), fill="red", col="red", alpha=0.5) +
  geom_ribbon(aes(ymin=1, ymax=pmax(microsoft$change.pc,1)), fill="green", col="green", alpha=0.5) +
  geom_hline(aes(yintercept=1), color="black") +
  theme_bw(base_size = 16) +
  scale_x_date(name = "Jahr",
               date_breaks = "3 years",
               date_minor_breaks = "1 year",
               date_labels = "%Y") +
  scale_y_continuous(name = "",
                     breaks = seq(.8, 2.8, by = .4),
                     labels = paste0(seq(80, 280, by = 40), "%")) +
  ggtitle("Microsoft Kursentwicklung seit Januar 1999")
</code>```

Body:
I want to do a graph with ggplot2, where I need the space/area between the intercept (=1) and the values (which I connected through geom_line) to be red (if the values are lower than 1) or green (if the values are bigger than 1). The data is from microsoft (price performance since 1999).

Data:

require(quantmod)
require(dplyr)
require(ggplot2)

getSymbols("MSFT", from ="1999-01-01")
microsoft <- data.frame(time(MSFT), MSFT[,6])
microsoft$time <- as.Date(microsoft$time.MSFT., "%Y-%m-%d")

microsoft <- microsoft %>%
mutate(change = MSFT.Adjusted - first(MSFT.Adjusted),
     change.pc = change/first(MSFT.Adjusted)+1)

that is the ggplot I have so far:

ggplot(microsoft, aes(x = time, y = change.pc)) +
  geom_line(stat = "identity") +
  geom_hline(aes(yintercept=1), color="black") +
  theme_bw() +
  xlab("Jahr") + ylab("") +
  ggtitle("Microsoft Kursentwicklung seit Januar 1999")

I want to fill the space between y = 1 and the values above in green, and the space between y = 1 and the values under in red. I tried geom_ribbon, geom_area, geom_polynom, but nothing worked. The biggest problem is, that it fills the space green, but not online above y = 1 but also under. and the red you can't even see...

here what I tried:

geom_area(data = subset(microsoft, change.pc > 1), fill = "green", alpha =0.5)
geom_area(data = subset(microsoft, change.pc < 1), fill = "red", alpha = 0.5)

I put these to lines in my plot, and then the problem I described above appeared.

Among other things I also tried this (found here on stackoverflow.com):

microsoft$grp <- "orig"
microsoft <- microsoft[order(microsoft$time),]
microsoft_new <- do.call("rbind",
             sapply(1:(nrow(microsoft) -1), function(i){
               f <- lm(time ~ change.pc, microsoft[i:(i+1), ])
               if (f$qr$rank < 2) return(NULL)
               r <- predict(f, newdata = data.frame(change.pc = 0))
               if(microsoft[i, ]$time < r & r < microsoft[i+1, ]$time)
                 return(data.frame(time = r, change.pc = 0))
               else return(NULL)
             })
)
microsoft_2 <- rbind(microsoft, microsoft_new)
ggplot(microsoft_2, aes(x = time, y = change.pc)) +
  geom_area(data = subset(microsoft_2, change.pc <= 1), fill = "red") +
  geom_area(data = subset(microsoft_2, change.pc >= 1), fill = "blue") +
  scale_x_continuous("", expand = c(0,0), breaks = seq(1999, 2017, 3)) +
  theme_bw()

That didn't work either.
Does anyone has an idea how I could achieve what I need?
This is how it should look

Body:
You can use geom_ribbon for this. The following solution is similar to @Miff's solution, but with intersection at 1. I have in addition added the desired scales.

ggplot(microsoft, aes(x = time, y = change.pc)) +
  geom_ribbon(aes(ymin=pmin(change.pc,1), ymax=1), fill="red", col="red", alpha=0.5) +
  geom_ribbon(aes(ymin=1, ymax=pmax(microsoft$change.pc,1)), fill="green", col="green", alpha=0.5) +
  geom_hline(aes(yintercept=1), color="black") +
  theme_bw(base_size = 16) +
  scale_x_date(name = "Jahr",
               date_breaks = "3 years",
               date_minor_breaks = "1 year",
               date_labels = "%Y") +
  scale_y_continuous(name = "",
                     breaks = seq(.8, 2.8, by = .4),
                     labels = paste0(seq(80, 280, by = 40), "%")) +
  ggtitle("Microsoft Kursentwicklung seit Januar 1999")


问:
NumberPicker.Formatter does not seem to be invoking in Android
I am trying to use a NumberPicker to display an array of Strings, but when I try and get the value back of the current String, the value is the integer index value of the String within the array which is the default response.

I have been trying to use NumberPicker.Formatter to get the actual String as a value back as opposed to the integer index value. I have implemented this, but it doesn't seem to be invoked. Could someone please tell me why this is and what I can do to fix it. Thanks in advance.

Here is the code:

```<code>final NumberPicker npUnits = (NumberPicker) numberPickerView.findViewById(R.id.numberPicker2);

            npUnits.setMinValue(1);
            npUnits.setDisplayedValues(tableUnitsArray);
            npUnits.setMaxValue(tableUnitsArray.length);
            npUnits.setFormatter(new NumberPicker.Formatter()
            {
                @Override
                public String format(int value)
                {
                    ArrayList<String> stringArrayList = (ArrayList<String>) Arrays.asList(tableUnitsArray);
                    String defaultUnits = stringArrayList.get(value);
                    System.out.println("Value formatted result: " + defaultUnits);

                    return defaultUnits;
                }
            });
            npUnits.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
</code>```

答: I found a solution for a few bugs in NumberPicker that works in APIs 18-26 without using reflection and without using setDisplayedValues() here.

Body:
I am trying to use a NumberPicker to display an array of Strings, but when I try and get the value back of the current String, the value is the integer index value of the String within the array which is the default response.

I have been trying to use NumberPicker.Formatter to get the actual String as a value back as opposed to the integer index value. I have implemented this, but it doesn't seem to be invoked. Could someone please tell me why this is and what I can do to fix it. Thanks in advance.

Here is the code:

final NumberPicker npUnits = (NumberPicker) numberPickerView.findViewById(R.id.numberPicker2);

            npUnits.setMinValue(1);
            npUnits.setDisplayedValues(tableUnitsArray);
            npUnits.setMaxValue(tableUnitsArray.length);
            npUnits.setFormatter(new NumberPicker.Formatter()
            {
                @Override
                public String format(int value)
                {
                    ArrayList<String> stringArrayList = (ArrayList<String>) Arrays.asList(tableUnitsArray);
                    String defaultUnits = stringArrayList.get(value);
                    System.out.println("Value formatted result: " + defaultUnits);

                    return defaultUnits;
                }
            });
            npUnits.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);


问:
dotnet core package versioning
How can I generate a semantic version number, based on a tag in Git, for a NuGet package (e.g. MyCode.0.1.1.nupkg) using the dotnet CLI?

GitInfo is correctly versioning our assemblies but I would like to extend this to versioning our NuGet packages. The following is a snippet from our .csproj :

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netcoreapp1.1</TargetFramework>
    <GenerateAssemblyInfo>False</GenerateAssemblyInfo>
    <GeneratePackageOnBuild>True</GeneratePackageOnBuild>
    <PackageVersion>$(GitSemVerMajor).$(GitSemVerMinor).$(GitSemVerPatch)$(GitSemVerDashLabel)</PackageVersion>
  </PropertyGroup>
  <ItemGroup>
    <Compile Include="..\..\GlobalAssemblyInfo.cs" Link="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="gitinfo" Version="1.1.66" />
  </ItemGroup>
</Project>
```

Note the GeneratePackageOnBuild.

What do I have to do to generate those build variables, $(GitSemVerMajor), etc. when I call dotnet build?

答:
Remove the <PackageVersion> line from the .csproj.

Add an InitialTargets statement to the Project:

<Project Sdk="Microsoft.NET.Sdk" InitialTargets="SetVersion">

Add an Import for the versioning targets file:

<Import Project="..\..\Version.targets" />

The Version.targets file:

<?xml version="1.0" encoding="utf-8"?>
<Project
    xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
        <Target Name="GitVersion">
        <PropertyGroup>

            <GitBaseVersionMajor>0</GitBaseVersionMajor>
            <GitBaseVersionMinor>1</GitBaseVersionMinor>
            <GitBaseVersionPatch>0</GitBaseVersionPatch>
            <GitCommits>0</GitCommits>
        </PropertyGroup>
    </Target>
    <Target Name="SetVersion" DependsOnTargets="GitVersion">
        <PropertyGroup>

            <GitSemVerDashLabel Condition="'$(GitBranch)' == 'undefined'">$(GitSemVerDashLabel)-pr</GitSemVerDashLabel>

            <GitSemVerDashLabel Condition="'$(GitSemVerDashLabel)' == '' And '$(GitCommits)' != '0'">-pre</GitSemVerDashLabel>
            <PackageVersion Condition="'$(GitSemVerDashLabel)' == ''">$(GitBaseVersionMajor).$(GitBaseVersionMinor).$(GitBaseVersionPatch)</PackageVersion>
            <PackageVersion Condition="'$(GitSemVerDashLabel)' != ''">$(GitBaseVersionMajor).$(GitBaseVersionMinor).$(GitBaseVersionPatch)$(GitSemVerDashLabel).$(GitCommits)</PackageVersion>
            <AssemblyVersion>$(GitBaseVersionMajor).$(GitBaseVersionMinor).$(GitBaseVersionPatch)</AssemblyVersion>
        </PropertyGroup>
    </Target>
</Project>
```

Title: dotnet core package versioning

Body:
How can I generate a semantic version number, based on a tag in Git, for a NuGet package (e.g. MyCode.0.1.1.nupkg) using the dotnet CLI?

GitInfo is correctly versioning our assemblies but I would like to extend this to versioning our NuGet packages. The following is a snippet from our .csproj :

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netcoreapp1.1</TargetFramework>
    <GenerateAssemblyInfo>False</GenerateAssemblyInfo>
    <GeneratePackageOnBuild>True</GeneratePackageOnBuild>
    <PackageVersion>$(GitSemVerMajor).$(GitSemVerMinor).$(GitSemVerPatch)$(GitSemVerDashLabel)</PackageVersion>
  </PropertyGroup>
  <ItemGroup>
    <Compile Include="..\..\GlobalAssemblyInfo.cs" Link="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="gitinfo" Version="1.1.66" />
  </ItemGroup>
</Project>

Note the GeneratePackageOnBuild.

What do I have to do to generate those build variables, $(GitSemVerMajor), etc. when I call dotnet build?

Body:
Remove the <PackageVersion> line from the .csproj.

Add an InitialTargets statement to the Project:

<Project Sdk="Microsoft.NET.Sdk" InitialTargets="SetVersion">

Add an Import for the versioning targets file:

<Import Project="..\..\Version.targets" />

The Version.targets file:

<?xml version="1.0" encoding="utf-8"?>
<Project
    xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
        <Target Name="GitVersion">
        <PropertyGroup>
            <!-- Dummy values allow dotnet restore to progress -->
            <GitBaseVersionMajor>0</GitBaseVersionMajor>
            <GitBaseVersionMinor>1</GitBaseVersionMinor>
            <GitBaseVersionPatch>0</GitBaseVersionPatch>
            <GitCommits>0</GitCommits>
        </PropertyGroup>
    </Target>
    <Target Name="SetVersion" DependsOnTargets="GitVersion">
        <PropertyGroup>
            <!-- CI checkouts may be against a specific commit, not a branch, so add -pr as label -->
            <GitSemVerDashLabel Condition="'$(GitBranch)' == 'undefined'">$(GitSemVerDashLabel)-pr</GitSemVerDashLabel>
            <!-- If there's no label, but we're not at the tip of the base version, add a -pre because this is not the base build -->
            <GitSemVerDashLabel Condition="'$(GitSemVerDashLabel)' == '' And '$(GitCommits)' != '0'">-pre</GitSemVerDashLabel>
            <PackageVersion Condition="'$(GitSemVerDashLabel)' == ''">$(GitBaseVersionMajor).$(GitBaseVersionMinor).$(GitBaseVersionPatch)</PackageVersion>
            <PackageVersion Condition="'$(GitSemVerDashLabel)' != ''">$(GitBaseVersionMajor).$(GitBaseVersionMinor).$(GitBaseVersionPatch)$(GitSemVerDashLabel).$(GitCommits)</PackageVersion>
            <AssemblyVersion>$(GitBaseVersionMajor).$(GitBaseVersionMinor).$(GitBaseVersionPatch)</AssemblyVersion>
        </PropertyGroup>
    </Target>
</Project>


问:
How do I delete all the rows of a table with a recursive structure (MySQL)?
I have a table in my DB, in which every row has a parent id which is the id of another row in the table (the table represents a tree-like structure). I would like to empty the table. But when I perform

```<code>DELETE FROM table_name WHERE true;
</code>```

I get an error (foreign key constraint). How do I empty the table anyway?

Clarification: I want to delete the whole table's contents, not the tables themselves.

答:
First delete the rows that have no children.

So if the id foreign key is parent_id, do something like:

```<code>DELETE FROM table_name WHERE parent_id IS NOT NULL;
</code>```

Then delete the rest:

```<code>DELETE FROM table_name;
</code>```

Body:
I have a table in my DB, in which every row has a parent id which is the id of another row in the table (the table represents a tree-like structure). I would like to empty the table. But when I perform

DELETE FROM table_name WHERE true;

I get an error (foreign key constraint). How do I empty the table anyway?

Clarification: I want to delete the whole table's contents, not the tables themselves.

Body:
First delete the rows that have no children.

So if the id foreign key is parent_id, do something like:

DELETE FROM table_name WHERE parent_id IS NOT NULL;

Then delete the rest:

DELETE FROM table_name;


问:
HTTP status: 409 vs 428
From List of HTTP status code (Wikipedia) it says:

409 Conflict

Indicates that the request could not be processed because of conflict in the request, such as an edit conflict between multiple simultaneous updates.

And

428 Precondition Required (RFC 6585)

The origin server requires the request to be conditional. Intended to prevent the 'lost update' problem, where a client GETs a resource's state, modifies it, and PUTs it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict."

However isn't the "lost update" issue mentioned in 428 item exactly the "edit conflict" issue mentioned in 409 item?

So question is what are the differences between the two status code and when should we use which of them?

答:
You send 428 to indicate to the client that you only accept conditional requests.

(Conditional requests are those carrying "conditional" request header fields, as described in https://www.greenbytes.de/tech/webdav/rfc7232.html)

Title: HTTP status: 409 vs 428


问:
How to place a div beside input box on focus?
I have a scenario,that I used css for extending search box on focus,when I focussed on search box then the search box must decrease and the cancel button must be placed beside of search box.

Css:

```<code>.clrble .frmcntr {
background:url("images/search.png") no-repeat 110px center;
text-align: center;
border-radius: 4px;
border: medium none;
cursor: pointer;
font-size: 20px;
font-family:SFUIDisplay;
padding: 6px 10px 6px 10px;
transition: all 0.5s ease 0s;
width: 95%;
background-color:rgba(247, 247, 247, 1);
 }

: content-box;
font-size: 100%;

.clrble .frmcntr:focus {
    width: 70%;
    text-align: left;
    background-color: #fff;
    border-color: #66CC75;
    -webkit-box-shadow: 0 0 5px rgba(109,207,246,.5);
    -moz-box-shadow: 0 0 5px rgba(109,207,246,.5);
    box-shadow: 0 0 5px rgba(109,207,246,.5);
    background-color:rgba(247, 247, 247, 1);
    background:url("images/search.png") no-repeat  10px center;
    padding-left:40px;
}

.clrble .frmcntr {
    -webkit-appearance: textfield;
    -webkit-box-sizing

}
</code>```

Here is my plunker link:

https://plnkr.co/edit/Z7mfglWEoDyjbDfFDbLM?p=preview

And the expected output will be like this:

Is it possible with Angularjs or JavaScript?

答:
You can use the blur event for the input and the mousedown event as mousedown event fires before the blur event.

var mouseDown = false;

$('input').blur(function() {
    if(mouseDown) // cancel the blur event
    {
        $('input').focus();
        mouseDown = false;
    }

});

$('#cancelBtn').mousedown(function(){
  mouseDown = true;
  console.log('Button Clicked');
});

$('input').focus(function(){
  $('#cancelBtn').css('display', 'block');
});

$('input').focusout(function(){
  $('#cancelBtn').css('display', 'none');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Styles go here */

.clrble .frmcntr {
    background:url("images/search.png") no-repeat 110px center;
    text-align: center;
    border-radius: 4px;
    border: medium none;
    cursor: pointer;
    font-size: 20px;
 font-family:SFUIDisplay;
    padding: 6px 10px 6px 10px;
    transition: all 0.5s ease 0s;
    width: 95%;
 background-color:rgba(247, 247, 247, 1);
  float:left;
}

.clrble .frmcntr:focus {
    width: 70%;
 text-align: left;
    background-color: green;
    border-color: #66CC75;
    -webkit-box-shadow: 0 0 5px rgba(109,207,246,.5);
    -moz-box-shadow: 0 0 5px rgba(109,207,246,.5);
    box-shadow: 0 0 5px rgba(109,207,246,.5);
 background-color:rgba(247, 247, 247, 1);
 background:url("images/search.png") no-repeat  10px center;
 padding-left:40px;
}

.clrble .frmcntr {
    -webkit-appearance: textfield;
    -webkit-box-sizing: content-box;
    font-size: 100%;
}

#cancelBtn {
color:blue;
float:left;
font-weight:bold;
display:none;
padding:5px;

}</code>```

<!DOCTYPE html>

    <link rel="stylesheet" href="style.css">

        <input type="text" placeholder="Search" class="frmcntr">

Cancel

```

Body:
I have a scenario,that I used css for extending search box on focus,when I focussed on search box then the search box must decrease and the cancel button must be placed beside of search box.

Css:

.clrble .frmcntr {
background:url("images/search.png") no-repeat 110px center;
text-align: center;
border-radius: 4px;
border: medium none;
cursor: pointer;
font-size: 20px;
font-family:SFUIDisplay;
padding: 6px 10px 6px 10px;
transition: all 0.5s ease 0s;
width: 95%;
background-color:rgba(247, 247, 247, 1);
 }

: content-box;
font-size: 100%;

.clrble .frmcntr:focus {
    width: 70%;
    text-align: left;
    background-color: #fff;
    border-color: #66CC75;
    -webkit-box-shadow: 0 0 5px rgba(109,207,246,.5);
    -moz-box-shadow: 0 0 5px rgba(109,207,246,.5);
    box-shadow: 0 0 5px rgba(109,207,246,.5);
    background-color:rgba(247, 247, 247, 1);
    background:url("images/search.png") no-repeat  10px center;
    padding-left:40px;
}

.clrble .frmcntr {
    -webkit-appearance: textfield;
    -webkit-box-sizing

}

Here is my plunker link:

https://plnkr.co/edit/Z7mfglWEoDyjbDfFDbLM?p=preview

And the expected output will be like this:

Is it possible with Angularjs or JavaScript?

Body:
You can use the blur event for the input and the mousedown event as mousedown event fires before the blur event.

var mouseDown = false;

$('input').blur(function() {
    if(mouseDown) // cancel the blur event
    {
        $('input').focus();
        mouseDown = false;
    }

});

$('#cancelBtn').mousedown(function(){
  mouseDown = true;
  console.log('Button Clicked');
});

$('input').focus(function(){
  $('#cancelBtn').css('display', 'block');
});

$('input').focusout(function(){
  $('#cancelBtn').css('display', 'none');
});

/* Styles go here */

.clrble .frmcntr {
    background:url("images/search.png") no-repeat 110px center;
    text-align: center;
    border-radius: 4px;
    border: medium none;
    cursor: pointer;
    font-size: 20px;
 font-family:SFUIDisplay;
    padding: 6px 10px 6px 10px;
    transition: all 0.5s ease 0s;
    width: 95%;
 background-color:rgba(247, 247, 247, 1);
  float:left;
}

.clrble .frmcntr:focus {
    width: 70%;
 text-align: left;
    background-color: green;
    border-color: #66CC75;
    -webkit-box-shadow: 0 0 5px rgba(109,207,246,.5);
    -moz-box-shadow: 0 0 5px rgba(109,207,246,.5);
    box-shadow: 0 0 5px rgba(109,207,246,.5);
 background-color:rgba(247, 247, 247, 1);
 background:url("images/search.png") no-repeat  10px center;
 padding-left:40px;
}

.clrble .frmcntr {
    -webkit-appearance: textfield;
    -webkit-box-sizing: content-box;
    font-size: 100%;
}

#cancelBtn {
color:blue;
float:left;
font-weight:bold;
display:none;
padding:5px;

}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

  <body>
   <div class="clrble">
        <input type="text" placeholder="Search" class="frmcntr">
                  <div id="cancelBtn">Cancel</div>
       </div>
  </body>

</html>


问:
Modify string representation of data in Python
O would like to modify my data. My function is:

```<code> print (str(freq[8:10])[2:-1])
</code>```

I have 2 results like this: 105.00000031 105.0000041

Can I modify the presentation of this to include newlines like this?:

```<code>105.00000031
105.00000041
</code>```

data to normalyze

答:
Or, as another alternative,

```<code>>>> data = '105.00000031 105.0000041'
>>> print('\n'.join(data.split()))
105.00000031
105.0000041
</code>```

Handles irregular spaces gracefully.

Body:
O would like to modify my data. My function is:

 print (str(freq[8:10])[2:-1])

I have 2 results like this: 105.00000031 105.0000041

Can I modify the presentation of this to include newlines like this?:

105.00000031
105.00000041

data to normalyze

Body:
Or, as another alternative,

>>> data = '105.00000031 105.0000041'
>>> print('\n'.join(data.split()))
105.00000031
105.0000041

Handles irregular spaces gracefully.


问:
Add index position Value of an array of array using Linq
We can do sum using arr.Sum() function. But if it is an array of arrays. How will we add all values.
suppose data is
Array/List is  [[1,2,3],[3,4,5],[5,4,3]]
how will you get s1 , sum of all first index value, s2 , sum of second index value and so on using LINQ.

答:
Use combination of Aggregate and Zip

```<code>var arrays = new[]
{
    new[] { 1, 2, 3 },
    new[] { 3, 4, 5 },
    new[] { 5, 4, 3 }
};

var result =
    arrays.Aggregate(Enumerable.Repeat(0, 3),
                    (total, array) => total.Zip(array, (sum, current) => sum + current));

// result = { 9, 10, 11 }
</code>```

Enumerable<T>.Zip executes provided function with items of same index.

Body:
Use combination of Aggregate and Zip

var arrays = new[]
{
    new[] { 1, 2, 3 },
    new[] { 3, 4, 5 },
    new[] { 5, 4, 3 }
};

var result =
    arrays.Aggregate(Enumerable.Repeat(0, 3),
                    (total, array) => total.Zip(array, (sum, current) => sum + current));

// result = { 9, 10, 11 }

Enumerable<T>.Zip executes provided function with items of same index.


问:
Python, how to iterate hex values in a tkinter spinbox widget
I have a function that gets 'start', 'finish' values and need to create a Spinbox widget. The values may be hex or integer with increment of 1.

When i get integers(ex: start = 1, finish = 6) it works great.
But when I get hex values (ex: start = 0x0, finish = 0xf) i get the following error:

_tkinter.TclError: bad spinbox format specifier "%.2x"

What is the right format to make it iterate on hex values?
I used this link as reference nmt.edu Spinbox

code:

```<code>def create_spinbox(self,min_value,max_value):
    self.current_value = StringVar()
    self.current_value.set(min_value)

    if re.match(r'^\s*(0[xX][0-9a-fA-F]+)\s*', min_value):  # hex index
        Spinbox(self.master,
               from_=min_value, to=max_value, width=5,
               format='%.2x',
               textvariable=self.corrent_value,
               command=lambda: self.update_loop_index())
    else:  # int index
        Spinbox(self.master, from_=min_value, to=max_value, width=2,
               textvariable = self.current_value,
               command = lambda: self.update_loop_index())
</code>```

I also tried to solve this problem by using spinbox with 'values' instead of from_/to

code:

```<code>def __init__(self,parent):
    self.master = parent
    self.variable_dict = dict()
    self.loop_value_frame = LabelFrame(self.master, text="Loop Variables: ", bg='white')
    self.loop_value_frame.grid(row=3, column=0, padx=5, sticky='we')

def add_loop_variable(self, min_value, max_value):
    self.variable_dict["min_value"] = min_value
    self.variable_dict["max_value"] = max_value
    self.variable_dict["current_value"] = StringVar()
    self.variable_dict["current_value"].set(min_value)

def clear(self):
    for widget in self.loop_value_frame.winfo_children():
        widget.destroy()
    self.loop_value_frame.grid_forget()    # remove from view

def create_spinbox(self):
    self.clear() # clear the frame

    if re.match(r'^\s*(0[xX][0-9a-fA-F]+)\s*', variable_dict["min_value"]):  # hex index
        int_base = 16
    else:  # int index
        int_base = 10
    index_list = [index if int_base==10 else hex(index) for index in range(int(self.variable_dict["min_value"],int_base),int(self.variable_dict["max_value"],int_base)+1)]      # parse the index list
    Spinbox(self.loop_value_frame, values=tuple(index_list), width=5,
              textvariable = self.variable_dict["current_value"],
              command = lambda: self.update_loop_index())

def update_loop_index(self):

    # do some calculation on the new index to display

    self.create_spinbox() # display the whole widget again
</code>```

This code doesn't get errors. But it doesnt work with the StringVar(). Pressing the up/down in the spinbox doesn't update the spinbox display, although when i read the value stored in the current_value is shows the new value.
What am I doing wrong?

答:
The format specifier doesn't support %x. From the official tcl/tk documentation:

format Specifies an alternate format to use when setting the string value when using the -from and -to range. This must be a format specifier of the form %.f, as it will format a floating-point number.

When I paste the code at the bottom of your question into a program and make reasonable assumptions about the missing code, the spinbox works fine and the StringVar is properly updated.

Body:
I have a function that gets 'start', 'finish' values and need to create a Spinbox widget. The values may be hex or integer with increment of 1.

When i get integers(ex: start = 1, finish = 6) it works great.
But when I get hex values (ex: start = 0x0, finish = 0xf) i get the following error:

_tkinter.TclError: bad spinbox format specifier "%.2x"

What is the right format to make it iterate on hex values?
I used this link as reference nmt.edu Spinbox

code:

def create_spinbox(self,min_value,max_value):
    self.current_value = StringVar()
    self.current_value.set(min_value)

    if re.match(r'^\s*(0[xX][0-9a-fA-F]+)\s*', min_value):  # hex index
        Spinbox(self.master,
               from_=min_value, to=max_value, width=5,
               format='%.2x',
               textvariable=self.corrent_value,
               command=lambda: self.update_loop_index())
    else:  # int index
        Spinbox(self.master, from_=min_value, to=max_value, width=2,
               textvariable = self.current_value,
               command = lambda: self.update_loop_index())

I also tried to solve this problem by using spinbox with 'values' instead of from_/to

code:

def __init__(self,parent):
    self.master = parent
    self.variable_dict = dict()
    self.loop_value_frame = LabelFrame(self.master, text="Loop Variables: ", bg='white')
    self.loop_value_frame.grid(row=3, column=0, padx=5, sticky='we')

def add_loop_variable(self, min_value, max_value):
    self.variable_dict["min_value"] = min_value
    self.variable_dict["max_value"] = max_value
    self.variable_dict["current_value"] = StringVar()
    self.variable_dict["current_value"].set(min_value)

def clear(self):
    for widget in self.loop_value_frame.winfo_children():
        widget.destroy()
    self.loop_value_frame.grid_forget()    # remove from view

def create_spinbox(self):
    self.clear() # clear the frame

    if re.match(r'^\s*(0[xX][0-9a-fA-F]+)\s*', variable_dict["min_value"]):  # hex index
        int_base = 16
    else:  # int index
        int_base = 10
    index_list = [index if int_base==10 else hex(index) for index in range(int(self.variable_dict["min_value"],int_base),int(self.variable_dict["max_value"],int_base)+1)]      # parse the index list
    Spinbox(self.loop_value_frame, values=tuple(index_list), width=5,
              textvariable = self.variable_dict["current_value"],
              command = lambda: self.update_loop_index())

def update_loop_index(self):

    # do some calculation on the new index to display

    self.create_spinbox() # display the whole widget again

This code doesn't get errors. But it doesnt work with the StringVar(). Pressing the up/down in the spinbox doesn't update the spinbox display, although when i read the value stored in the current_value is shows the new value.
What am I doing wrong?


问:
FFmpeg: how to produce MP4 CENC (Common Encryption) videos
What is the correct syntax to do CENC encryption with ffmpeg?

The ffmpeg 3.0 release notes include "Common Encryption (CENC) MP4 encoding and decoding support", and the files libavformat/movenccenc.h and  libavformat/movenccenc.c seem to include everything needed to encrypt MP4 files according to the Common Encryption standard.

However, I can't find any documentation on this topic in the ffmpeg manual pages.

Regards

答:
Mulvya's answer covered the ffmpeg-options.

I'm just adding a concrete example and talk about playback too, as i did some experiments yesterday (independently).

Encryption example

```<code>ffmpeg -i SampleVideo_1280x720_1mb.mp4 -vcodec copy -acodec copy -encryption_scheme cenc-aes-ctr -encryption_key 76a6c65c5ea762046bd749a2e632ccbb -encryption_kid a7e61c373e219033c21091fa607bf3b8 SampleVideo_1280x720_1mb_encrypted.mp4
</code>```

(of course usage might be different for your case; i just remuxed video and audio)

Playback / Decoding

ffplay

```<code>ffplay SampleVideo_1280x720_1mb_encrypted.mp4 -decryption_key 76a6c65c5ea762046bd749a2e632ccbb
</code>```

But as this is more or less a prototype-player, one might want to use something more powerful.

mpv

```<code>mpv --demuxer-lavf-o=decryption_key=76a6c65c5ea762046bd749a2e632ccbb SampleVideo_1280x720_1mb_encrypted.mp4
</code>```

There is some discussion here as my first expected command-line did not behave as expected!

Edit: trying to address Reino's questions

The encryption_key is just 128 bit = 16 bytes encoded as Hex (following the usage of AES-128-CTR). So random.org with a configuration of 16 bytes and hex.encoding would be a valid key (but i'm not recommending to trust external resources in general). I used python's secrets module which boils down to: secrets.token_hex(16). This encryption_key will be needed for decoding.

The encryption_kid Key ID is just an identifier for this key, probably needed for more complex usage-patterns (i'm !guessing! you could do something like: hey video... which of my 1000 keys do i need for you?). I suppose it's mandatory to pass it, but it's not required for decoding (if you know which key to use for which video).

The official references would be:

Standard

ffmpeg implementation: docs (available through command-line) or a short extraction

Body:
Mulvya's answer covered the ffmpeg-options.

I'm just adding a concrete example and talk about playback too, as i did some experiments yesterday (independently).

Encryption example

ffmpeg -i SampleVideo_1280x720_1mb.mp4 -vcodec copy -acodec copy -encryption_scheme cenc-aes-ctr -encryption_key 76a6c65c5ea762046bd749a2e632ccbb -encryption_kid a7e61c373e219033c21091fa607bf3b8 SampleVideo_1280x720_1mb_encrypted.mp4

(of course usage might be different for your case; i just remuxed video and audio)

Playback / Decoding

ffplay

ffplay SampleVideo_1280x720_1mb_encrypted.mp4 -decryption_key 76a6c65c5ea762046bd749a2e632ccbb

But as this is more or less a prototype-player, one might want to use something more powerful.

mpv

mpv --demuxer-lavf-o=decryption_key=76a6c65c5ea762046bd749a2e632ccbb SampleVideo_1280x720_1mb_encrypted.mp4

There is some discussion here as my first expected command-line did not behave as expected!

Edit: trying to address Reino's questions

The encryption_key is just 128 bit = 16 bytes encoded as Hex (following the usage of AES-128-CTR). So random.org with a configuration of 16 bytes and hex.encoding would be a valid key (but i'm not recommending to trust external resources in general). I used python's secrets module which boils down to: secrets.token_hex(16). This encryption_key will be needed for decoding.

The encryption_kid Key ID is just an identifier for this key, probably needed for more complex usage-patterns (i'm !guessing! you could do something like: hey video... which of my 1000 keys do i need for you?). I suppose it's mandatory to pass it, but it's not required for decoding (if you know which key to use for which video).

The official references would be:

Standard

ffmpeg implementation: docs (available through command-line) or a short extraction


问:
How can I position a background-image an absolute distance from the right of its container?
I can position a small background-image/icon 4 pixels from the center left of its container with:

```<code>background: url(...) no-repeat 4px 50%;
</code>```

How can I position it 4 pixels from the right?

答:
You might want to use percentage:

table.dataTable thead .sorting_asc {
  background: url("http://cdn.datatables.net/1.10.0/images/sort_asc.png") no-repeat 30% 50%;
}
table.dataTable thead .sorting_desc {
  background: url("http://cdn.datatables.net/1.10.0/images/sort_desc.png") no-repeat 30% 50%;
}
table.dataTable thead .sorting {
  background: url("http://cdn.datatables.net/1.10.0/images/sort_both.png") no-repeat 30% 50%;
}```

Body:
I can position a small background-image/icon 4 pixels from the center left of its container with:

background: url(...) no-repeat 4px 50%;

How can I position it 4 pixels from the right?


问:
how to get prompts from execution of playbook
I am running a playbook. Which contains script and that runs on windows machine.
That script asks for some input at middle of execution. How to capture that prompt and display that prompt from ansible?</p>

答:
It is not possible for Ansible to prompt in the middle of a playbook.
This is intentional in the design. What you can do is prompt at the beginning of a playbook to give a variable. I haven't seen this a lot though, people usually use the Ansible vault if they have secrets they don't want in the playbook.

The best thing to do would be to give the values to your script with parameters. That would be the safest. If not you can always try responding through the prompts but I would discourage that.


问:
how to take all tweets in a hashtag with tweepy?
I'm trying to take every open tweets in a hashtag but my code does not go further than 299 tweets.

I also trying to take tweets from a specific time line like tweets only in May 2015 and July 2016. Are there any way to do it in the main process or should I write a little code for it?

Here is my code:

```<code># if this is the first time, creates a new array which
# will store max id of the tweets for each keyword
if not os.path.isfile("max_ids.npy"):
    max_ids = np.empty(len(keywords))
    # every value is initialized as -1 in order to start from the beginning the first time program run
    max_ids.fill(-1)
else:
    max_ids = np.load("max_ids.npy")  # loads the previous max ids

# if there is any new keywords added, extends the max_ids array in order to correspond every keyword
if len(keywords) > len(max_ids):
    new_indexes = np.empty(len(keywords) - len(max_ids))
    new_indexes.fill(-1)
    max_ids = np.append(arr=max_ids, values=new_indexes)

count = 0
for i in range(len(keywords)):
    since_date="2015-01-01"
    sinceId = None
    tweetCount = 0
    maxTweets = 5000000000000000000000  # maximum tweets to find per keyword
    tweetsPerQry = 100
    searchQuery = "#{0}".format(keywords[i])
    while tweetCount < maxTweets:
        if max_ids[i] < 0:
                if (not sinceId):
                    new_tweets = api.search(q=searchQuery, count=tweetsPerQry)
                else:
                    new_tweets = api.search(q=searchQuery, count=tweetsPerQry,
                                            since_id=sinceId)
        else:
                if (not sinceId):
                    new_tweets = api.search(q=searchQuery, count=tweetsPerQry,
                                            max_id=str(max_ids - 1))
                else:
                    new_tweets = api.search(q=searchQuery, count=tweetsPerQry,
                                            max_id=str(max_ids - 1),
                                            since_id=sinceId)
        if not new_tweets:
            print("Keyword: {0}      No more tweets found".format(searchQuery))
            break
        for tweet in new_tweets:
            count += 1
            print(count)

            file_write.write(
                       .
                       .
                       .
                         )

            item = {
                .
                .
                .
                .
                .
            }

            # instead of using mongo's id for _id, using tweet's id
            raw_data = tweet._json
            raw_data["_id"] = tweet.id
            raw_data.pop("id", None)

            try:
                db["Tweets"].insert_one(item)
            except pymongo.errors.DuplicateKeyError as e:
                print("Already exists in 'Tweets' collection.")
            try:
                db["RawTweets"].insert_one(raw_data)
            except pymongo.errors.DuplicateKeyError as e:
                print("Already exists in 'RawTweets' collection.")

        tweetCount += len(new_tweets)
        print("Downloaded {0} tweets".format(tweetCount))
        max_ids[i] = new_tweets[-1].id

np.save(arr=max_ids, file="max_ids.npy")  # saving in order to continue mining from where left next time program run
</code>```

答:
Check twitter api documentation, probably it  allows just 300 tweets to parse.
I would recommend to forget api, make it with requests with streaming. The api is an implementation of requests with limitations. </p>

Body:
I'm trying to take every open tweets in a hashtag but my code does not go further than 299 tweets.

I also trying to take tweets from a specific time line like tweets only in May 2015 and July 2016. Are there any way to do it in the main process or should I write a little code for it?

Here is my code:

# if this is the first time, creates a new array which
# will store max id of the tweets for each keyword
if not os.path.isfile("max_ids.npy"):
    max_ids = np.empty(len(keywords))
    # every value is initialized as -1 in order to start from the beginning the first time program run
    max_ids.fill(-1)
else:
    max_ids = np.load("max_ids.npy")  # loads the previous max ids

# if there is any new keywords added, extends the max_ids array in order to correspond every keyword
if len(keywords) > len(max_ids):
    new_indexes = np.empty(len(keywords) - len(max_ids))
    new_indexes.fill(-1)
    max_ids = np.append(arr=max_ids, values=new_indexes)

count = 0
for i in range(len(keywords)):
    since_date="2015-01-01"
    sinceId = None
    tweetCount = 0
    maxTweets = 5000000000000000000000  # maximum tweets to find per keyword
    tweetsPerQry = 100
    searchQuery = "#{0}".format(keywords[i])
    while tweetCount < maxTweets:
        if max_ids[i] < 0:
                if (not sinceId):
                    new_tweets = api.search(q=searchQuery, count=tweetsPerQry)
                else:
                    new_tweets = api.search(q=searchQuery, count=tweetsPerQry,
                                            since_id=sinceId)
        else:
                if (not sinceId):
                    new_tweets = api.search(q=searchQuery, count=tweetsPerQry,
                                            max_id=str(max_ids - 1))
                else:
                    new_tweets = api.search(q=searchQuery, count=tweetsPerQry,
                                            max_id=str(max_ids - 1),
                                            since_id=sinceId)
        if not new_tweets:
            print("Keyword: {0}      No more tweets found".format(searchQuery))
            break
        for tweet in new_tweets:
            count += 1
            print(count)

            file_write.write(
                       .
                       .
                       .
                         )

            item = {
                .
                .
                .
                .
                .
            }

            # instead of using mongo's id for _id, using tweet's id
            raw_data = tweet._json
            raw_data["_id"] = tweet.id
            raw_data.pop("id", None)

            try:
                db["Tweets"].insert_one(item)
            except pymongo.errors.DuplicateKeyError as e:
                print("Already exists in 'Tweets' collection.")
            try:
                db["RawTweets"].insert_one(raw_data)
            except pymongo.errors.DuplicateKeyError as e:
                print("Already exists in 'RawTweets' collection.")

        tweetCount += len(new_tweets)
        print("Downloaded {0} tweets".format(tweetCount))
        max_ids[i] = new_tweets[-1].id

np.save(arr=max_ids, file="max_ids.npy")  # saving in order to continue mining from where left next time program run


问:
I want to apply a overlay image on hover
But I am struggling.

Code I have for css is:

```
#gallery img {
width:700px;
height:213px;
margin:0;
padding:0;
}
```

So I thought ...

```
#gallery img:hover {
    width:700px;
    height:213px;
    position: relative;
    z-index:10000;
    background: transparent url(../images/imgOverlay-Zoom.png) no-repeat center center;
}
```

Would work, but it doesnt.

The image I am transparently overlaying on hover is:

What am I doing wrong.
I think I may have a corrupt css tag somewhere.

Any help appreciated.

答:
Fixed.
css:

```
#container { position:relative; width:700px; height:213px;}
    .image { position:absolute; width:700px; height:213px; z-index:0;}
    .overlay { background-image:none); position:absolute; width:700px; height:213px; z-index:1;}
    .overlay:hover { background: transparent url(images/imgOverlay-Zoom.png)no-repeat center center;}
```

html:

```<code><div class="overlay" ></div>
<div class="image" ><img src="images/listing-page-with-gradient.png" /></div>
</code>```

Body:
But I am struggling.

Code I have for css is:

#gallery img {
width:700px;
height:213px;
margin:0;
padding:0;
}

So I thought ...

#gallery img:hover {
    width:700px;
    height:213px;
    position: relative;
    z-index:10000;
    background: transparent url(../images/imgOverlay-Zoom.png) no-repeat center center;
}

Would work, but it doesnt.

The image I am transparently overlaying on hover is:

What am I doing wrong.
I think I may have a corrupt css tag somewhere.

Any help appreciated.

Body:
Fixed.
css:

#container { position:relative; width:700px; height:213px;}
    .image { position:absolute; width:700px; height:213px; z-index:0;}
    .overlay { background-image:none); position:absolute; width:700px; height:213px; z-index:1;}
    .overlay:hover { background: transparent url(images/imgOverlay-Zoom.png)no-repeat center center;}

html:

<div class="overlay" ></div>
<div class="image" ><img src="images/listing-page-with-gradient.png" /></div>


问:
NDK not shown in SDK Manager
I want to download NDK by SDK manager like:
google developer.android.com ...

but my SDK manager didn't show NDK or even API 25.
what should I do?
for every simple and empty activity, I got this error

Error:The SDK Build Tools revision (23.0.3) is too low for project ':app'. Minimum required is 25.0.0
  Install Build Tools 25.0.0, update version in build file and sync project
Open File

答:
(Probably not relevant for OP but can help others)

SDK Manager shows only the relevant packages to your environment.
So, if your platform architecture is Linux 32-bit, you'll not see NDK options since Linux 32-bit NDK version are no longer supported by google.

Solutions:

1. Get a Windows/Mac System or 64-bit Linux (can be virtual as well).

2. Use an older NDK version for 32-bit Linux systems: https://dl.google.com/android/ndk/android-ndk-r10e-linux-x86.bin

If you're on Linux and not sure what is your OS arch, you can use:

$ uname -i

if the output is x86_64 then that's a 64-bit OS, otherwise - 32.

Title: NDK not shown in SDK Manager