问:
Android swipe listener in fragment
I'm following this tutorial http://www.brightec.co.uk/ideas/android-listview-alphabet-scroller to implement an alphabet list view with a side view containing letters that you can scroll to make the list view scroll directly to that letter. It works well with their example, however I neet to put this code in a fragment, and the scroll doesn't work anymore. I don't know how to transform the following so it works in a fragment:

```<code>private class SideIndexGestureListener extends GestureDetector.SimpleOnGestureListener {
    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        Log.d("DEBUG", "SideIndexGestureListener.onScroll() distanceX=" + distanceX + " distanceY=" + distanceY);
        // we know already coordinates of first touch
        // we know as well a scroll distance
        sideIndexX = sideIndexX - distanceX;
        sideIndexY = sideIndexY - distanceY;

        // when the user scrolls within our side index
        // we can show for every position in it a proper
        // item in the country list
        if (sideIndexX >= 0 && sideIndexY >= 0) {
            displayListItem();
        }

        return super.onScroll(e1, e2, distanceX, distanceY);
    }
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    if (mGestureDetector.onTouchEvent(event)) {
        return true;
    } else {
        return false;
    }
}
</code>```

I tired doing the following:

```<code>@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.activity_main_fragment_contacts, container, false);

    mGestureDetector = new GestureDetector(context, new SideIndexGestureListener());

    rootView.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            if (mGestureDetector.onTouchEvent(event)) {
                return true;
            } else {
                return false;
            }
        }
    });

    return rootView;
}
</code>```

But it never reaches the onScroll methos so I don't know what I'm doing wrong?

答: Okay I fiddled a bit with the code and managed to make it work by always returning true in the onTouch method of the listener I set to the rootwiew.</p>

Title: Android swipe listener in fragment

Body:
I'm following this tutorial http://www.brightec.co.uk/ideas/android-listview-alphabet-scroller to implement an alphabet list view with a side view containing letters that you can scroll to make the list view scroll directly to that letter. It works well with their example, however I neet to put this code in a fragment, and the scroll doesn't work anymore. I don't know how to transform the following so it works in a fragment:

private class SideIndexGestureListener extends GestureDetector.SimpleOnGestureListener {
    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        Log.d("DEBUG", "SideIndexGestureListener.onScroll() distanceX=" + distanceX + " distanceY=" + distanceY);
        // we know already coordinates of first touch
        // we know as well a scroll distance
        sideIndexX = sideIndexX - distanceX;
        sideIndexY = sideIndexY - distanceY;

        // when the user scrolls within our side index
        // we can show for every position in it a proper
        // item in the country list
        if (sideIndexX >= 0 && sideIndexY >= 0) {
            displayListItem();
        }

        return super.onScroll(e1, e2, distanceX, distanceY);
    }
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    if (mGestureDetector.onTouchEvent(event)) {
        return true;
    } else {
        return false;
    }
}

I tired doing the following:

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.activity_main_fragment_contacts, container, false);

    mGestureDetector = new GestureDetector(context, new SideIndexGestureListener());

    rootView.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            if (mGestureDetector.onTouchEvent(event)) {
                return true;
            } else {
                return false;
            }
        }
    });

    return rootView;
}

But it never reaches the onScroll methos so I don't know what I'm doing wrong?


来源: stackexchange

问:
how to print row in CVS file in one line?
I have a CSV file that contains two columns and I want to print the contents of the second column.

For example: (from this)

```<code>for row in file1:
    print(row[1])
</code>```

to this:

```<code>print([row[1] for row in file1])
</code>```

The problem is that it doesn't print anything. Can anyone tell me where I'm wrong?

答:
Solution without using any libraries

```<code>with open('file.txt') as file1:
  print([x.split(",")[1] for x in file1.read().split("\n")])
</code>```

More elegant output

```<code>with open('file.txt') as file1:
  print("\n".join([x.split(",")[1] for x in file1.read().split("\n")]))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a CSV file that contains two columns and I want to print the contents of the second column.

For example: (from this)

for row in file1:
    print(row[1])

to this:

print([row[1] for row in file1])

The problem is that it doesn't print anything. Can anyone tell me where I'm wrong?

Body:
Solution without using any libraries

with open('file.txt') as file1:
  print([x.split(",")[1] for x in file1.read().split("\n")])

More elegant output

with open('file.txt') as file1:
  print("\n".join([x.split(",")[1] for x in file1.read().split("\n")]))


问:
XSLT Help : Copy elements <choose>
With my limited knowledge of XSL programming I have come up with this code:

(Post updated: XSLT is now working - Updated for the benefit of others if at all!)

```<code><?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:nm="http://fsag.de/BusinessTransaction"
xmlns:env="http://www.w3.org/2001/12/soap-envelope"
exclude-result-prefixes="env">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/nm:Responses">
    <xsl:copy-of select="/"/>
</xsl:template>

<xsl:template match="/Envelope">
    <nm:Responses xmlns:nm="http://fsag.de/BusinessTransaction">
        <BTEMessages/>
        <SystemContext/>
                <Error>
        <xsl:copy-of select="Body"/>
               </Error>
    </nm:Responses>
</xsl:template>
</xsl:stylesheet>
</code>```

The purpose of the is to process the file (at the end of the post) and get the result below:

Required result for 'Error' file :

```<code><?xml version="1.0" encoding="UTF-8"?>
<nm:Response xmlns:nm="http://fsag.de/BusinessTransaction">
   <BTEMessages/>
   <SystemContext/>
   <Error>
      <Body>
         <Response status="1">
            <Description>DESC</Description>
            <Errors>
               <Error>500</Error>
            </Errors>
         </Response>
      </Body>
   </Error>
</nm:Response>
</code>```

Required result for 'Response' file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<nm:Response xmlns:nm="http://fsag.de/BusinessTransaction">
   <BTEMessages>
      <InOrderContext xmlns:n0="http://fsag.de/BusinessTransaction">
         <SendTimestamp>01-06-2017:0506230000</SendTimestamp>
      </InOrderContext>
      <SystemContext>
         <Client>FDP</Client>
         <CorrelationId>34553FTG25543SFD134</CorrelationId>
         <BusinessContext>RECONCL</BusinessContext>
      </SystemContext>
   </BTEMessages>
</nm:Response>
</code>```

*File 1: Error *

```<code><Envelope >
    <Body>
      <Response status="1">
        <Description>DESC</Description>
        <Errors>
          <Error>500</Error>
        </Errors>
      </Response>
    </Body>
  </Envelope>
</code>```

File 2: Response:

```<code><?xml version="1.0" encoding="UTF-8"?>
<nm:Response xmlns:nm="http://fsag.de/BusinessTransaction">
<BTEMessage>
  <InOrderContext>
     <SendTimestamp>01-06-2017:0506230000</SendTimestamp>
  </InOrderContext>
  <SystemContext>
    <Client>FDP</Client>
    <CorrelationId>34553FTG25543SFD134</CorrelationId>
    <BusinessContext>RECONCL</BusinessContext>
  </SystemContext>
</BTEMessage>
</nm:Response >
</code>```

When i try to run the XSL is failing. Please any help here?

答: XSL updated with working version.</p>

Title: XSLT Help : Copy elements <choose>

Body:
With my limited knowledge of XSL programming I have come up with this code:

(Post updated: XSLT is now working - Updated for the benefit of others if at all!)

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:nm="http://fsag.de/BusinessTransaction"
xmlns:env="http://www.w3.org/2001/12/soap-envelope"
exclude-result-prefixes="env">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/nm:Responses">
    <xsl:copy-of select="/"/>
</xsl:template>

<xsl:template match="/Envelope">
    <nm:Responses xmlns:nm="http://fsag.de/BusinessTransaction">
        <BTEMessages/>
        <SystemContext/>
                <Error>
        <xsl:copy-of select="Body"/>
               </Error>
    </nm:Responses>
</xsl:template>
</xsl:stylesheet>

The purpose of the is to process the file (at the end of the post) and get the result below:

Required result for 'Error' file :

<?xml version="1.0" encoding="UTF-8"?>
<nm:Response xmlns:nm="http://fsag.de/BusinessTransaction">
   <BTEMessages/>
   <SystemContext/>
   <Error>

         <Response status="1">
            <Description>DESC</Description>
            <Errors>
               <Error>500</Error>
            </Errors>
         </Response>

   </Error>
</nm:Response>

Required result for 'Response' file:

<?xml version="1.0" encoding="UTF-8"?>
<nm:Response xmlns:nm="http://fsag.de/BusinessTransaction">
   <BTEMessages>
      <InOrderContext xmlns:n0="http://fsag.de/BusinessTransaction">
         <SendTimestamp>01-06-2017:0506230000</SendTimestamp>
      </InOrderContext>
      <SystemContext>
         <Client>FDP</Client>
         <CorrelationId>34553FTG25543SFD134</CorrelationId>
         <BusinessContext>RECONCL</BusinessContext>
      </SystemContext>
   </BTEMessages>
</nm:Response>

*File 1: Error *

<Envelope >

      <Response status="1">
        <Description>DESC</Description>
        <Errors>
          <Error>500</Error>
        </Errors>
      </Response>

  </Envelope>

File 2: Response:

<?xml version="1.0" encoding="UTF-8"?>
<nm:Response xmlns:nm="http://fsag.de/BusinessTransaction">
<BTEMessage>
  <InOrderContext>
     <SendTimestamp>01-06-2017:0506230000</SendTimestamp>
  </InOrderContext>
  <SystemContext>
    <Client>FDP</Client>
    <CorrelationId>34553FTG25543SFD134</CorrelationId>
    <BusinessContext>RECONCL</BusinessContext>
  </SystemContext>
</BTEMessage>
</nm:Response >

When i try to run the XSL is failing. Please any help here?

Body: XSL updated with working version.


问:
select option selected by 2 times jquery not working properly
```<code>$(".treatment-btn").click(function()
{
    $("#treatmentModal").modal('show');
    $('.treatment-form')[0].reset();
    $('#treatmentModal #treatment_time option').removeAttr("selected");
    $('#treatmentModal #treatment_time option[value=""]').attr("selected", "selected");
}); //when i click on this button it resets form successfully but select option is not reset.

function makeEditHtml(response) {
var price = response[0].treatment_price.split(".")[0];
var cent = response[0].treatment_price.split(".")[1];
$("#treatmentModal #treatment").val(response[0].treatment_name);
$("#treatmentModal #price").val(price);
$('#treatmentModal #cent option[value='+cent+']').attr("selected", "selected");
$('#treatmentModal #treatment_time option').removeAttr("selected");
$('#treatmentModal #treatment_time option[value='+response[0].treatment_duration+']').attr("selected", "selected"); //i select it again at here after ajax call
$.each(response, function(i)
{
    $("#treatmentModal input[type=checkbox][value="+response[i].worker_id+"]").prop("checked",true);
});
$("#treatmentModal").modal('show');
}
</code>```

<p>// and this is called when ajax request fires i append data in same form but select box value not selected. it is showing correct in firebug but not display on screen. first time it is working fine</p>

答:
Problem solved i make mistake here</p>

```<code>function makeEditHtml(response) {

 $('#treatmentModal #treatment_time
  option[value='+response[0].treatment_duration+']').attr("selected", "selected"); //i select it again at here after ajax call
   //i replace it with this below line and it is working ok now
   //$('#treatmentModal #treatment_time option[value='+response[0].treatment_duration+']').prop("selected", true);
 }
</code>```

Body:
$(".treatment-btn").click(function()
{
    $("#treatmentModal").modal('show');
    $('.treatment-form')[0].reset();
    $('#treatmentModal #treatment_time option').removeAttr("selected");
    $('#treatmentModal #treatment_time option[value=""]').attr("selected", "selected");
}); //when i click on this button it resets form successfully but select option is not reset.

function makeEditHtml(response) {
var price = response[0].treatment_price.split(".")[0];
var cent = response[0].treatment_price.split(".")[1];
$("#treatmentModal #treatment").val(response[0].treatment_name);
$("#treatmentModal #price").val(price);
$('#treatmentModal #cent option[value='+cent+']').attr("selected", "selected");
$('#treatmentModal #treatment_time option').removeAttr("selected");
$('#treatmentModal #treatment_time option[value='+response[0].treatment_duration+']').attr("selected", "selected"); //i select it again at here after ajax call
$.each(response, function(i)
{
    $("#treatmentModal input[type=checkbox][value="+response[i].worker_id+"]").prop("checked",true);
});
$("#treatmentModal").modal('show');
}

// and this is called when ajax request fires i append data in same form but select box value not selected. it is showing correct in firebug but not display on screen. first time it is working fine

Body:
Problem solved i make mistake here

function makeEditHtml(response) {

 $('#treatmentModal #treatment_time
  option[value='+response[0].treatment_duration+']').attr("selected", "selected"); //i select it again at here after ajax call
   //i replace it with this below line and it is working ok now
   //$('#treatmentModal #treatment_time option[value='+response[0].treatment_duration+']').prop("selected", true);
 }


问:
Mysqli unique range of 2 columns
For the last couple of day I have been searching how to make the range of 2 columns in mysqli unique. For example column1 has value 2 and column2 has value 6. If the user tries to input in any of the columns 3,4,5 as a different row it must return an error. I could do that in php checking all the row but it will slow down the perfomance when too many records.

For my scenarion I have a From data(stored in unix timestamp) and Till data(again stored in unix timestamp).

Take for example

1497913200(20/06/2017) and 1498518000(27/06/2017)

Anything between these 2 dates must be invalid,

eg 22/06/2017-29/06/2017 or 18/06/2017-26/06/2017

while 28/06/2017 - 03/07/2017 or 12/06/2017-19/06/2017 are valid.

I think you get the point but I can elaborate if needed.

I obviously know how to make unique multiple column but not the range of these columns. That's the part i am struggling with.

Any help greatly appreciated.

答:
I believe you need to write a TRIGGER to perform this check, e.g.:

```<code>CREATE TRIGGER date_check_trigger BEFORE INSERT ON `table` FOR EACH ROW
BEGIN
    SET @EXISTING_RECORD_COUNT = (SELECT COUNT(*) FROM `table` WHERE NEW.date BETWEEN start_date AND end_date)
    IF (@EXISTING_RECORD_COUNT > 0) THEN
        SIGNAL SQLSTATE '45000' set message_text='Invalid date, a range already exists';
    END IF;
END
</code>```

Title: Mysqli unique range of 2 columns

Body:
I believe you need to write a TRIGGER to perform this check, e.g.:

CREATE TRIGGER date_check_trigger BEFORE INSERT ON `table` FOR EACH ROW
BEGIN
    SET @EXISTING_RECORD_COUNT = (SELECT COUNT(*) FROM `table` WHERE NEW.date BETWEEN start_date AND end_date)
    IF (@EXISTING_RECORD_COUNT > 0) THEN
        SIGNAL SQLSTATE '45000' set message_text='Invalid date, a range already exists';
    END IF;
END


问:
Dialog changes after user prompt
I have a dialog as follows to get user name and password from user

```<code>bot.dialog('/getUsernamePassword', [
function (session) {
    builder.Prompts.text(session, 'Please enter your username');
},
function (session, results) {
    session.userData.name = results.response;
    builder.Prompts.text(session, 'Please enter your password');
},
function (session, results) {
    session.userData.password = results.response;
    session.endDialogWithResult(results);
}
]);
</code>```

After user enter username, my dialog doesn't continue, instead it goes to root dialog and prints "I didn't understand please try again"(default message)

Can anyone help me to understand what I am doing wrong here?

my recognizers are configured as follows

```<code>var model = 'https://westus.api.cognitive.microsoft.com/luis/..;
var recognizer = new builder.LuisRecognizer(model);
bot.recognizer(recognizer);
// Add regular expression recognizer to bot
var helpRecognizer = new builder.RegExpRecognizer('HelpIntent', /^(help|options)/i);
var cancelRecognizer = new builder.RegExpRecognizer( "CancelIntent", /^(cancel|nevermind)/i);
bot.recognizer(helpRecognizer);
bot.recognizer(cancelRecognizer);
var intents = new builder.IntentDialog({ recognizers: [helpRecognizer,cancelRecognizer,recognizer] });
</code>```

答:
I think that what is happening is that your response is going through LUIS.

In order to avoid this, update your definition of the LuisRecognizer to be the following:

```<code>var model = 'https://westus.api.cognitive.microsoft.com/luis/..;
var recognizer = new builder.LuisRecognizer(model).onEnabled((context, callback) => {
    var enabled = context.dialogStack().length === 0;
    callback(null, enabled);
});
bot.recognizer(recognizer);
</code>```

Title: Dialog changes after user prompt

Body:
I have a dialog as follows to get user name and password from user

bot.dialog('/getUsernamePassword', [
function (session) {
    builder.Prompts.text(session, 'Please enter your username');
},
function (session, results) {
    session.userData.name = results.response;
    builder.Prompts.text(session, 'Please enter your password');
},
function (session, results) {
    session.userData.password = results.response;
    session.endDialogWithResult(results);
}
]);

After user enter username, my dialog doesn't continue, instead it goes to root dialog and prints "I didn't understand please try again"(default message)

Can anyone help me to understand what I am doing wrong here?

my recognizers are configured as follows

var model = 'https://westus.api.cognitive.microsoft.com/luis/..;
var recognizer = new builder.LuisRecognizer(model);
bot.recognizer(recognizer);
// Add regular expression recognizer to bot
var helpRecognizer = new builder.RegExpRecognizer('HelpIntent', /^(help|options)/i);
var cancelRecognizer = new builder.RegExpRecognizer( "CancelIntent", /^(cancel|nevermind)/i);
bot.recognizer(helpRecognizer);
bot.recognizer(cancelRecognizer);
var intents = new builder.IntentDialog({ recognizers: [helpRecognizer,cancelRecognizer,recognizer] });

Body:
I think that what is happening is that your response is going through LUIS.

In order to avoid this, update your definition of the LuisRecognizer to be the following:

var model = 'https://westus.api.cognitive.microsoft.com/luis/..;
var recognizer = new builder.LuisRecognizer(model).onEnabled((context, callback) => {
    var enabled = context.dialogStack().length === 0;
    callback(null, enabled);
});
bot.recognizer(recognizer);


问:
How to know that a thread in a Thread Pool hangs/freezes
I have queue of tasks for the ThreadPool, and each task has a tendency to froze locking up all the resources it is using. And these cant be released unless the service is restarted.

Is there a way in the ThreadPool to know that its thread is already frozen? I have an idea of using a time out, (though i still dont know how to write it), but i think its not safe because the length of time for processing is not uniform.

答:
(This is perhaps a bit lowlevel, but at least it is a simple solution. As I don't know C#'s API, this is a general solution for any language using thread-pools.)

Insert a watchdog task after each real task that updates a time value with the current time. If this value is larger than you max task run time (say 10 seconds), you know that something is stuck.

Instead of setting a time and polling it, you could continuously set and reset some timers 10 secs into the future. When it triggers, a task has hung.

The best way is probably to wrap each task in a "Watchdog" Task class that does this automatically. That way, upon completion, you'd clear the timer, and you could also set a per-task timeout, which might be useful.

You obviously need one time/timer object for each thread in the threadpool, but that's solvable via thread-local variables.

Note that this solution does not require you to modify your tasks' code. It only modifies the code putting tasks into the pool.

ContentLicense: CC BY-SA 2.5


问:
Django - How change all values of a colum to null?
I have a problem, I make some changes in my models, because I had an Integer field that had to be changed to a ForeignKey

Well for error I assign to all the objects in the field derived_to the value 1.

I would now like to mark all the rows in this column as null. How can I make this? these are my last two migrations

```<code>class Migration(migrations.Migration):

    dependencies = [
        ('work_order', '0026_auto_20170603_1517'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='workorder',
            options={'verbose_name': 'work order', 'verbose_name_plural': 'work orders'},
        ),
        migrations.AlterField(
            model_name='workorder',
            name='derived_to',
           field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='store.OutsourceOption', verbose_name='outsource'),
        preserve_default=False,
    ),
]
</code>```

And the last one

```<code>class Migration(migrations.Migration):

    dependencies = [
        ('work_order', '0027_auto_20170605_0836'),
    ]

    operations = [
        migrations.AlterField(
            model_name='workorder',
            name='derived_to',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='store.OutsourceOption', verbose_name='outsource'),
        ),
    ]
</code>```

Well thats all i need to make a new migration to assign null to all the objects in work_order in the column derived_to, because now all the objects have derived_to pointing to the first register on OutsourceOptions and that is not correct.

Thanks and sorry for my bad English.

答:
If I have understood you correctly, you want to set all existing derived_to values to null? You can do that with RunPython

Runs custom Python code in a historical context. code (and
  reverse_code if supplied) should be callable objects that accept two
  arguments;

```<code>def forwards_func(apps, schema_editor):

    Workorder = apps.get_model('appname','Workorder')
    Workorder.objects.update(derived_to=None)
</code>```

Add this into the migration like this:

```<code>operations = [
    migrations.AlterField(
        model_name='workorder',
        name='derived_to',
        field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='store.OutsourceOption', verbose_name='outsource'),
    ),
    migrations.RunPython(forwards_func),
]
</code>```

Body:
I have a problem, I make some changes in my models, because I had an Integer field that had to be changed to a ForeignKey

Well for error I assign to all the objects in the field derived_to the value 1.

I would now like to mark all the rows in this column as null. How can I make this? these are my last two migrations

class Migration(migrations.Migration):

    dependencies = [
        ('work_order', '0026_auto_20170603_1517'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='workorder',
            options={'verbose_name': 'work order', 'verbose_name_plural': 'work orders'},
        ),
        migrations.AlterField(
            model_name='workorder',
            name='derived_to',
           field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='store.OutsourceOption', verbose_name='outsource'),
        preserve_default=False,
    ),
]

And the last one

class Migration(migrations.Migration):

    dependencies = [
        ('work_order', '0027_auto_20170605_0836'),
    ]

    operations = [
        migrations.AlterField(
            model_name='workorder',
            name='derived_to',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='store.OutsourceOption', verbose_name='outsource'),
        ),
    ]

Well thats all i need to make a new migration to assign null to all the objects in work_order in the column derived_to, because now all the objects have derived_to pointing to the first register on OutsourceOptions and that is not correct.

Thanks and sorry for my bad English.

Body:
If I have understood you correctly, you want to set all existing derived_to values to null? You can do that with RunPython

Runs custom Python code in a historical context. code (and
  reverse_code if supplied) should be callable objects that accept two
  arguments;

def forwards_func(apps, schema_editor):

    Workorder = apps.get_model('appname','Workorder')
    Workorder.objects.update(derived_to=None)

Add this into the migration like this:

operations = [
    migrations.AlterField(
        model_name='workorder',
        name='derived_to',
        field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='store.OutsourceOption', verbose_name='outsource'),
    ),
    migrations.RunPython(forwards_func),
]


问:
How can I add a 3d object as a marker on Google Maps like Uber does
I want to add a 3d marker for showing cars on map with rotation like Uber does but I can't find any information on adding 3d objects on Google Maps SDK for iOS.

Would appreciate any help.

Apparently no one is seeing what OP and I are seeing so here's a video of a Uber car turning 90 degrees. Play it frame by frame and you'll notice that it's not a simple image rotation. Either Uber went through the trouble of doing ~360 angles of each vehicles, or it really is a 3D model. Doing 360 images of every car seems foolish to me.

答:
If you want to Rotated your image as the marker. Want to show a moving object you can use .git image. It would be help full for you.

Swift 3

```<code>let position = CLLocationCoordinate2D(latitude: 51.5, longitude: -0.127)

//Rotate a marker
let degrees = 90.0
let london = GMSMarker(position: position)
london.title = "London"

//Customize the marker image
london.icon = UIImage(named: "YourGifImageName")
london.groundAnchor = CGPoint(x: 0.5, y: 0.5)
london.rotation = degrees
london.map = mapView
</code>```

For more info Please check here

Body:
If you want to Rotated your image as the marker. Want to show a moving object you can use .git image. It would be help full for you.

Swift 3

let position = CLLocationCoordinate2D(latitude: 51.5, longitude: -0.127)

//Rotate a marker
let degrees = 90.0
let london = GMSMarker(position: position)
london.title = "London"

//Customize the marker image
london.icon = UIImage(named: "YourGifImageName")
london.groundAnchor = CGPoint(x: 0.5, y: 0.5)
london.rotation = degrees
london.map = mapView

For more info Please check here


问:
What algorithm in 'zsh' shell when it run "cat < 11 < 22 < 33 > 55 > 66"?
I write own shell, and I can't understand logic, what standard shell do with file descriptors before function execve() in this case cat < 11 < 22 < 33 > 55 > 66. How I see it, we open files 11, 22, 33, open or create files 55, 66, then we must create some pipe() or something like this, and run three times dup2(fd(11), 0), dup2(pip[1], 1), execve(), where each time we change fd() on 11, 22, 33. And after that two times dup2(pip[0], 0), dup2(fd(55), 1), execve(), and the same with fd(66)?
But in case wc < 11 < 22 < 33 > 55 > 66 it's must not will work, it write three wc command in 55 and 66, but standard shall take sum of tree files and result of wc command write into the files 55 and 66.
How does it work?

答:
Thanks to  Wumpus Q. Wumbley, I understand what happens in zsh when it run this command wc < 11 < 22 < 33 > 55 > 66.
Maybe somebody wants to know it, I write what I understand.
After open all file descriptors of files (11, 22, 33, 55, 66), we make a pipe(pip[]). Then one by one we run in each child process dup2(fd(11), 0) and dup2(pip[1], 1), end execve("/bin/cat", "cat", env), then repeat it with fd(22) and fd(33).
And after that we run in next child processes dup2(pip[0], 0), dup2(fd(55), 1) end here we make ecxecve(".../wc", "wc", env), end repeat for fd(66).


问:
Laravel Eloquent belongsToMany multiple "primary" keys
In laravel I'm connecting events to users like this:

```<code>class User extends Model
{
    public function events()
    {
        return $this->belongsToMany('App\Event', EventUser::TABLE_NAME, 'user_id', 'event_id');
    }
}
</code>```

which works great, but now I'm implementing repeat feature so I'm inserting repeating events for 2 years in the future in the database, and I don't want to make 1000 inserts, so I decided that I'll have parent event, and subevents will have parent_id in the database. Now the problem is that I can't get those events with belongsToMany, since I need to watch for 2 keys... id and parent_id.

Any idea how I can do that? I want to get events connected with user and events that have parent event connected with user.

答:
```<code>public function parentEvents()
{
    return $this->belongsToMany('App\Event', EventUser::TABLE_NAME, 'user_id', 'event_id');
}

public function childEvents()
{
    return $this->belongsToMany('App\Event', EventUser::TABLE_NAME, 'user_id', 'parent_id');
}

public function events()
{
    $parentEvents = $this->parentEvents;
    $childEvent = $this->childEvents;

    // Merge collections and return single collection.
    return $parentEvents->merge($childEvents);
}
</code>```

Body:
In laravel I'm connecting events to users like this:

class User extends Model
{
    public function events()
    {
        return $this->belongsToMany('App\Event', EventUser::TABLE_NAME, 'user_id', 'event_id');
    }
}

which works great, but now I'm implementing repeat feature so I'm inserting repeating events for 2 years in the future in the database, and I don't want to make 1000 inserts, so I decided that I'll have parent event, and subevents will have parent_id in the database. Now the problem is that I can't get those events with belongsToMany, since I need to watch for 2 keys... id and parent_id.

Any idea how I can do that? I want to get events connected with user and events that have parent event connected with user.


问:
Struts 2 radio button list
am working on Struts 2 radio button.
I want to retrieve the list from my action class but it is giving following error

org.apache.jasper.JasperException: tag
  'radio', field 'list', name
  'user.yourGender': The requested list
  key '#user.gender' could not be
  resolved as a
  collection/array/map/enumeration/iterator
  type. Example: people or people.{name}
  - [unknown location]

my action class & user class is as follow

HelloAction

```<code>package com.geekcap.struts2.action;

import com.geekcap.struts2.model.User;
import com.opensymphony.xwork2.ActionSupport;
import java.util.List;
import java.util.ArrayList;

public class HelloAction extends ActionSupport
{
 private User user;

 public String execute() throws Exception
 {
  return "success";
 }

 public void validate()
 {
  if(user.getName().length()==0)
  {
   addFieldError("user.name", "User Name is required");
  }

  if(user.getAge()==0)
  {
   addFieldError("user.age","Age is required");
  }

  if(user.getPassword().length()==0)
  {
   addFieldError("user.password","Please enter your password !");
  }

 /* if(user.getGender().equals("-1"))
  {
   addFieldError("user.gender","Please select gender !");
  }*/
 }

 public User getUser()
 {
  return user;
 }

 public void setUser(User userbean)
 {
  user=userbean;
 }

}
</code>```

User class

```<code>package com.geekcap.struts2.model;

import java.util.List;
import java.util.ArrayList;

public class User
{
 private String name,password;
// private List like;
 private int age;
 private List<String> gender;
 private String yourGender;

 public User()
 {
  gender= new ArrayList<String>();
  gender.add("MALE");
  gender.add("FEMALE");
  gender.add("UNKNOWN");
 }

 public String getName()
 {
  return name;
 }

 public void setName(String name)
 {
  this.name = name;
 }

 public String getPassword()
 {
  return password;
 }

 public void setPassword(String password)
 {
  this.password=password;
 }

 public int getAge()
 {
  return age;
 }

 public void setAge(int age)
 {
  this.age=age;
 }

 public List<String> getGender()
 {
  return gender;
 }

 public void setGender(List<String> gender)
 {
  this.gender=gender;
 }

 public void setYourGender(String yourGender)
 {
  this.yourGender=yourGender;
 }

 public String getYourGender()
 {
  return  yourGender;
 }

 public String getDefaultGenderValue()
 {
  return "UNKNOWN";
 }
</code>```

helloForm.jsp

```<code><%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome to Struts 2</title>
</head>
<body>

<s:form action="Hello">
  <s:textfield name="user.name" label="User name" value="shahid"/>
  <s:password name="user.password" label="Password"/>
  <s:textfield name="user.age" label="Age"/>
  <s:radio label="Gender" name="user.yourGender" list="user.gender" value="defaultGenderValue"/>
  <s:submit/>
</s:form>

</body>
</html>
</code>```

hello.jsp

```<code><%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello, Struts 2</title>
</head>
<body>
<h4>
Hello, <s:property value="user.name"/>!
<br>Your password :<s:property value="user.password"/></br>
<br>your age :<s:property value="user.age"/></br>
<br>Gender :<s:property value="user.yourGender"/></br>
</h4>
</body>
</html>
</code>```

答:
Are you sure the list gender is NOT null in the JSP?

If it is null, then struts will not see it and therefore think it isn't there

Title: Struts 2 radio button list

Body:
am working on Struts 2 radio button.
I want to retrieve the list from my action class but it is giving following error

org.apache.jasper.JasperException: tag
  'radio', field 'list', name
  'user.yourGender': The requested list
  key '#user.gender' could not be
  resolved as a
  collection/array/map/enumeration/iterator
  type. Example: people or people.{name}
  - [unknown location]

my action class & user class is as follow

HelloAction

package com.geekcap.struts2.action;

import com.geekcap.struts2.model.User;
import com.opensymphony.xwork2.ActionSupport;
import java.util.List;
import java.util.ArrayList;

public class HelloAction extends ActionSupport
{
 private User user;

 public String execute() throws Exception
 {
  return "success";
 }

 public void validate()
 {
  if(user.getName().length()==0)
  {
   addFieldError("user.name", "User Name is required");
  }

  if(user.getAge()==0)
  {
   addFieldError("user.age","Age is required");
  }

  if(user.getPassword().length()==0)
  {
   addFieldError("user.password","Please enter your password !");
  }

 /* if(user.getGender().equals("-1"))
  {
   addFieldError("user.gender","Please select gender !");
  }*/
 }

 public User getUser()
 {
  return user;
 }

 public void setUser(User userbean)
 {
  user=userbean;
 }

}

User class

package com.geekcap.struts2.model;

import java.util.List;
import java.util.ArrayList;

public class User
{
 private String name,password;
// private List like;
 private int age;
 private List<String> gender;
 private String yourGender;

 public User()
 {
  gender= new ArrayList<String>();
  gender.add("MALE");
  gender.add("FEMALE");
  gender.add("UNKNOWN");
 }

 public String getName()
 {
  return name;
 }

 public void setName(String name)
 {
  this.name = name;
 }

 public String getPassword()
 {
  return password;
 }

 public void setPassword(String password)
 {
  this.password=password;
 }

 public int getAge()
 {
  return age;
 }

 public void setAge(int age)
 {
  this.age=age;
 }

 public List<String> getGender()
 {
  return gender;
 }

 public void setGender(List<String> gender)
 {
  this.gender=gender;
 }

 public void setYourGender(String yourGender)
 {
  this.yourGender=yourGender;
 }

 public String getYourGender()
 {
  return  yourGender;
 }

 public String getDefaultGenderValue()
 {
  return "UNKNOWN";
 }

helloForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome to Struts 2</title>

<s:form action="Hello">
  <s:textfield name="user.name" label="User name" value="shahid"/>
  <s:password name="user.password" label="Password"/>
  <s:textfield name="user.age" label="Age"/>
  <s:radio label="Gender" name="user.yourGender" list="user.gender" value="defaultGenderValue"/>
  <s:submit/>
</s:form>

hello.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello, Struts 2</title>

Hello, <s:property value="user.name"/>!

Your password :<s:property value="user.password"/>

your age :<s:property value="user.age"/>

Gender :<s:property value="user.yourGender"/>


问:
Creating List in a loop
Is there any way to create a loop which will be creating new List

```<code>static Map<Integer, List> dataMap = new HashMap<>();
public static void dec_hex() {

        // Map<Integer, Integer> dataMap = new HashMap<>();
        // dataMap.put(0, 0);
        List<Integer> ls2 = new ArrayList<Integer>();
        List<Integer> ls3 = new ArrayList<Integer>();
        List<Integer> ls4 = new ArrayList<Integer>();
        List<Integer> ls5 = new ArrayList<Integer>();
        List<Integer> ls6 = new ArrayList<Integer>();
        List<Integer> ls7 = new ArrayList<Integer>();
        List<Integer> ls8 = new ArrayList<Integer>();
        List<Integer> ls9 = new ArrayList<Integer>();
        List<Integer> ls10 = new ArrayList<Integer>();

        System.out.println("Liczby");
        for (int i = 0; i < 201; i++) {
            String hex = Integer.toHexString(i);
            System.out.println("DEC: " + i + " HEX: " + hex);
            //for (int a = 2; a<11 ; a++){
            if (i % 2 == 0) {
                ls2.add(i);
                //myList.add(i);
                dataMap.put(2, ls2);
            }
            if (i % 3 == 0) {
                ls3.add(i);
                //myList.add(i);
                dataMap.put(3, ls3);
            }

            if (i % 4 == 0) {
                ls4.add(i);
                //myList.add(i);
                dataMap.put(4, ls4);
            }
            if (i % 5 == 0) {
                ls5.add(i);
                //myList.add(i);
                dataMap.put(5, ls5);
            }
            if (i % 6 == 0) {
                ls6.add(i);
                //myList.add(i);
                dataMap.put(6, ls6);
            }
            if (i % 7 == 0) {
                ls7.add(i);
                //myList.add(i);
                dataMap.put(7, ls7);
            }
            if (i % 8 == 0) {
                ls8.add(i);
            //  myList.add(i);
                dataMap.put(8, ls8);
            }
            if (i % 9 == 0) {
                ls9.add(i);
                //myList.add(i);
                dataMap.put(9, ls9);
            }
            if (i % 10 == 0) {
                ls10.add(i);
                //myList.add(i);
                dataMap.put(10, ls10);
            }
        }

        //String list = myList.toString();
        //System.out.println(list);
        dataMap.toString();
        System.out.println(dataMap);

    }
</code>```

Is there any way to create a loop to check if number is divisible?
If I'm going to use this

```<code>    for (int a = 2; a<11 ; a++){
 lsa.add(i); // lets say we've got one list
 dataMap.put(a, ls);
}
</code>```

The program won't work correctly cause the numbers will reapeat, cause I'm using the same lsa array.

答:
Yes, of course. That's what a Map is for: you give it a key, and it gives you back the value.

```<code>    Map<Integer, List<Integer>> dataMap = new HashMap<>();
    for (int i = 0; i < 10; i++) {
        dataMap.put(i, new ArrayList<>());
    }

    for (int i = 0; i < 201; i++) {
        int key = i % 10;
        List<Integer> list = dataMap.get(key);
        list.add(i);
    }
</code>```

But since your keys are integers from 0 to 9, you could also just use a List<List<Integer>>, instead of the map.

Title: Creating List in a loop

Body:
Is there any way to create a loop which will be creating new List

static Map<Integer, List> dataMap = new HashMap<>();
public static void dec_hex() {

        // Map<Integer, Integer> dataMap = new HashMap<>();
        // dataMap.put(0, 0);
        List<Integer> ls2 = new ArrayList<Integer>();
        List<Integer> ls3 = new ArrayList<Integer>();
        List<Integer> ls4 = new ArrayList<Integer>();
        List<Integer> ls5 = new ArrayList<Integer>();
        List<Integer> ls6 = new ArrayList<Integer>();
        List<Integer> ls7 = new ArrayList<Integer>();
        List<Integer> ls8 = new ArrayList<Integer>();
        List<Integer> ls9 = new ArrayList<Integer>();
        List<Integer> ls10 = new ArrayList<Integer>();

        System.out.println("Liczby");
        for (int i = 0; i < 201; i++) {
            String hex = Integer.toHexString(i);
            System.out.println("DEC: " + i + " HEX: " + hex);
            //for (int a = 2; a<11 ; a++){
            if (i % 2 == 0) {
                ls2.add(i);
                //myList.add(i);
                dataMap.put(2, ls2);
            }
            if (i % 3 == 0) {
                ls3.add(i);
                //myList.add(i);
                dataMap.put(3, ls3);
            }

            if (i % 4 == 0) {
                ls4.add(i);
                //myList.add(i);
                dataMap.put(4, ls4);
            }
            if (i % 5 == 0) {
                ls5.add(i);
                //myList.add(i);
                dataMap.put(5, ls5);
            }
            if (i % 6 == 0) {
                ls6.add(i);
                //myList.add(i);
                dataMap.put(6, ls6);
            }
            if (i % 7 == 0) {
                ls7.add(i);
                //myList.add(i);
                dataMap.put(7, ls7);
            }
            if (i % 8 == 0) {
                ls8.add(i);
            //  myList.add(i);
                dataMap.put(8, ls8);
            }
            if (i % 9 == 0) {
                ls9.add(i);
                //myList.add(i);
                dataMap.put(9, ls9);
            }
            if (i % 10 == 0) {
                ls10.add(i);
                //myList.add(i);
                dataMap.put(10, ls10);
            }
        }

        //String list = myList.toString();
        //System.out.println(list);
        dataMap.toString();
        System.out.println(dataMap);

    }

Is there any way to create a loop to check if number is divisible?
If I'm going to use this

    for (int a = 2; a<11 ; a++){
 lsa.add(i); // lets say we've got one list
 dataMap.put(a, ls);
}

The program won't work correctly cause the numbers will reapeat, cause I'm using the same lsa array.

Body:
Yes, of course. That's what a Map is for: you give it a key, and it gives you back the value.

    Map<Integer, List<Integer>> dataMap = new HashMap<>();
    for (int i = 0; i < 10; i++) {
        dataMap.put(i, new ArrayList<>());
    }

    for (int i = 0; i < 201; i++) {
        int key = i % 10;
        List<Integer> list = dataMap.get(key);
        list.add(i);
    }

But since your keys are integers from 0 to 9, you could also just use a List<List<Integer>>, instead of the map.


问:
Python3 Twisted Mysql Error
So today I have decided to start a new project (long story).
And in this project I need MySQL connections.
I am currently using python 3.6 and want to use twisted so I have imported the module by doing the following:

```<code>from twisted.enterprise import adbapi
</code>```

The only problem is, since I am using python3 I can't use MySQLdb right so I need mysqlclient, thing is how can I use it as a MySQL DB module ? Because this connection line here:

```<code>self.Connection = adbapi.ConnectionPool("mysqlclient", db = Config['Database'], port = 3306, user=Config['User'], passwd = Config['Password'], host = Config['Host'])
</code>```

give me this following error:ModuleNotFoundError: No module named 'mysqlclient'

If anyone could help I'd be thankful.
Have a great day/night.

答: You have to install whichever MySQL client library you want to use.</p>

Title: Python3 Twisted Mysql Error

Body:
So today I have decided to start a new project (long story).
And in this project I need MySQL connections.
I am currently using python 3.6 and want to use twisted so I have imported the module by doing the following:

from twisted.enterprise import adbapi

The only problem is, since I am using python3 I can't use MySQLdb right so I need mysqlclient, thing is how can I use it as a MySQL DB module ? Because this connection line here:

self.Connection = adbapi.ConnectionPool("mysqlclient", db = Config['Database'], port = 3306, user=Config['User'], passwd = Config['Password'], host = Config['Host'])

give me this following error:ModuleNotFoundError: No module named 'mysqlclient'

If anyone could help I'd be thankful.
Have a great day/night.


问:
async / await: If it doen't use threads what is it doing to running processing at the same time?
I am doing a little research to understand async / await of C# better.

I found a web site that has the following code to show how much slower synchronous processing is vs async / await:

```<code> public IActionResult Index()
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();

            ContentManagement service = new ContentManagement();
            var content = service.GetContent();
            var count = service.GetCount();
            var name = service.GetName();

            watch.Stop();
            ViewBag.WatchMilliseconds = watch.ElapsedMilliseconds;

            return View();
        }

        [HttpGet]
        public async Task<ActionResult> IndexAsync()
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();

            ContentManagement service = new ContentManagement();
            var contentTask = service.GetContentAsync();
            var countTask = service.GetCountAsync();
            var nameTask = service.GetNameAsync();

            var content = await contentTask;
            var count = await countTask;
            var name = await nameTask;

            watch.Stop();
            ViewBag.WatchMilliseconds = watch.ElapsedMilliseconds;
            return View("Index");
        }

        public class ContentManagement
        {
            public string GetContent()
            {
                Thread.Sleep(2000);
                return "content";
            }

            public int GetCount()
            {
                Thread.Sleep(5000);
                return 4;
            }

            public string GetName()
            {
                Thread.Sleep(3000);
                return "Matthew";
            }
            public async Task<string> GetContentAsync()
            {
                await Task.Delay(2000);
                return "content";
            }

            public async Task<int> GetCountAsync()
            {
                await Task.Delay(5000);
                return 4;
            }

            public async Task<string> GetNameAsync()
            {
                await Task.Delay(3000);
                return "Matthew";
            }
        }
</code>```

I understand the above code at a high level and why it performs faster.

What I don't understand is if threads are not being used, how is the processing running at the same time?

I have read in a couple of places that async / await does not create new threads to do the processing. So, what is async / await  doing to allow processing to happen at the same time? The three await Task.Delay are running in parallel, correct?  If it is not creating 3 threads, what is it doing?

I just want to understand what is happening at a high level.

Let me know.

Thanks in advance.

答:
What I don't understand is if threads are not being used, how is the processing running at the same time?

You can think of it as an event firing when the operation is complete, as opposed to a thread being blocked until the operation is complete.

I have read in a couple of places that async / await does not create new threads to do the processing.

async and await do not; that is true. For more about how async and await work, see my intro post.

So, what is async / await doing to allow processing to happen at the same time?

One of the primary use cases of async/await is for I/O-based code. I have a long blog post that goes into the details of how asynchronous I/O does not require threads.

The three await Task.Delay are running in parallel, correct?

I prefer to use the term "concurrently", just to avoid confusion with Parallel and Parallel LINQ, both of which were created for CPU-bound parallelism and do not work as generally expected with async/await. So, I would say that both parallelism and asynchrony are forms of concurrency, and this is an example of asynchronous concurrency.

(That said, using the term "parallel" is certainly in concord with the common usage of the term).

If it is not creating 3 threads, what is it doing?

Task.Delay is not an I/O-based operation, but it is very similar to one. It uses timers underneath, so it's completely different than Thread.Sleep.

Thread.Sleep will block a thread - I believe it does go all the way to an OS Sleep call, which causes the OS to place the thread in a wait state until its sleep time is expired.

Task.Delay acts more like an I/O operation. So, it sets up a timer that fires off an event when the time expires. Timers are managed by the OS itself - as time proceeds forward (clock ticks on the CPU), the OS will notify the timer when it has completed. It's a bit more complex than that (for efficiency, .NET will coalesce managed timers), but that's the general idea.

So, the point is that there is no dedicated thread for each Task.Delay that is blocked.

Body:
I am doing a little research to understand async / await of C# better.

I found a web site that has the following code to show how much slower synchronous processing is vs async / await:

 public IActionResult Index()
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();

            ContentManagement service = new ContentManagement();
            var content = service.GetContent();
            var count = service.GetCount();
            var name = service.GetName();

            watch.Stop();
            ViewBag.WatchMilliseconds = watch.ElapsedMilliseconds;

            return View();
        }

        [HttpGet]
        public async Task<ActionResult> IndexAsync()
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();

            ContentManagement service = new ContentManagement();
            var contentTask = service.GetContentAsync();
            var countTask = service.GetCountAsync();
            var nameTask = service.GetNameAsync();

            var content = await contentTask;
            var count = await countTask;
            var name = await nameTask;

            watch.Stop();
            ViewBag.WatchMilliseconds = watch.ElapsedMilliseconds;
            return View("Index");
        }

        public class ContentManagement
        {
            public string GetContent()
            {
                Thread.Sleep(2000);
                return "content";
            }

            public int GetCount()
            {
                Thread.Sleep(5000);
                return 4;
            }

            public string GetName()
            {
                Thread.Sleep(3000);
                return "Matthew";
            }
            public async Task<string> GetContentAsync()
            {
                await Task.Delay(2000);
                return "content";
            }

            public async Task<int> GetCountAsync()
            {
                await Task.Delay(5000);
                return 4;
            }

            public async Task<string> GetNameAsync()
            {
                await Task.Delay(3000);
                return "Matthew";
            }
        }

I understand the above code at a high level and why it performs faster.

What I don't understand is if threads are not being used, how is the processing running at the same time?

I have read in a couple of places that async / await does not create new threads to do the processing. So, what is async / await  doing to allow processing to happen at the same time? The three await Task.Delay are running in parallel, correct?  If it is not creating 3 threads, what is it doing?

I just want to understand what is happening at a high level.

Let me know.

Thanks in advance.


问:
SqlDependency vs SQLCLR call to WebService
I have a desktop application which should be notified on any table change.  So, I found only two solutions which fits well for my case: SqlDependency and SQLCLR. (I would like to know if there is better in .NET stack) I have built the both structure and made them work. I only able to compare the duration of a s̲i̲n̲gl̲e̲ response from SQL Server to the client.

SqlDependency

Duration: from 100ms to 4 secs

SQLCLR

Duration: from 10ms to 150ms

I would like this structure to be able to deal with high rate notifications*, I have read a few SO and blog posts (eg: here) and also am warned from a colleague that on mass requests SqlDependency may go wrong. Here, MS offers something which I didn't get that may be another solution to my problem.

*:Not all the time but for a season; 50-200 requests per sec on 1-2 servers.

On the basis of a high rate of notifications and in parallel with performance, which of these two should I go on with, or is there another option?

答:
Neither SqlDependency (i.e. Query Notifications) nor SQLCLR (i.e. call a Web Service via a Trigger) is going to work for that volume of traffic (50-200 req per sec). And in fact, both options are quite dangerous at those volumes.

The advice given in both linked pages (the one on SoftwareEngineering.StackExchange.com and the TechNet article) are all much better options. The advice on Best way to get push notifications to server from ms sql database (i.e. custom queue table that is polled every few seconds) is very similar to option #1 of the Planning for Notifications TechNet article (which uses Service Broker to handle the processing of the queue).

I like the queuing idea (fully custom or using Service Broker) the best and have used fully custom queues on highly transactional systems (easily the volume you are anticipating) with much success. The pros and cons between these two options (as I see them, of course) are:

Service Broker

Pro: Existing (and proven) framework (can scale and tied into Transactions)

Con: not always easy to configure or administer / debug, can't easily aggregate 200 individual events in 1 second into a single message (will still be 1 message per each Trigger event)

Fully custom queue

Pro: can aggregate many simultaneous trigger events into single "message" to client (i.e. polling service picks up whatever changes happened since last polling), can make use of Change Tracking / Change Data Capture as the source of "what changed" so you might not need to build a queue table.

Con: Is only as scalable as you are able to make it (might be as good, or better, than Service Broker, but highly dependent on your skill and experience to achieve this), needs thorough testing of edge cases to make sure the queue processing doesn't miss, or double-count, events.

You might be able to combine Service Broker with Change Tracking / Change Detection. If there is an easy-enough way to determine the last change processed (change as noted in Change Tracking / Change Data Capture table(s)), then you can set up a SQL Server Agent job to poll every few seconds, and if you find that new changes have come in, then grab all of those changes into a single message to send to Service Broker.

Some documentation to get you started:

Track Data Changes (covers both Change Tracking and Change Data Capture)

SQL Server Service Broker


问:
How to force CocoaPods to use the latest release for a Github repo?
I am trying to create my first CocoaPods Printer. I have gone through all the steps which are required to create your own. This is the latest release version to which I want my pod to point. But somehow the pod is pointing to some other version which I have deleted to overcome "duplicate entry" error. What should I do to force CocoaPods to use the latest release available? For a note, if you could check the pod on the CocoaPods it has a difference of "stars" received for the repo. I am not sure what I am doing wrong here?

This is the Podspec file for that repo.

答:
Thanks, King T. for help through. Finally, I read this comment on this answer,

When this happens to me I usually just remove the line from my Podfile, run pod install, re-add the line and re-run pod installs. Maybe there is a better way but this one is pretty simple.

And that work for me.

Force updating Cocoapod with same tag


问:
wpf datagrid total row
I want to make a total row in a wpf datagrid like
this one.
I don't know how to create such a row in xaml. It should be frozen when I scroll through the other rows.

Someone said it is possible to add a total item to the data source and create a special template for that item. But this seems a bit weird.

I found no working solution for that. Has someone an idea how to do that?

答: I had a similar issue, to solve it I created a dock panel and docked the Data Grid to the top. I then created a horizontal stack panel with a text box for each table column and populated them with the required totals, this was then docked at the bottom of the dock panel. With the Data grids ScrollViewer.VerticalScrollBarVisibility set to auto, the totals rows is always visible at the bottom of the data grid and if the data grid gets to large for its container it is wrapped in a scrolling container (with the totals row still visible).</p>

Title: wpf datagrid total row


问:
MIT Scheme - Merge Sort + Timing Execution
I've implemented my own merge sort in MIT Scheme. I want to test it against the builtin merge-sort and compare times; however, I don't know how to get the run time of both. Also how do you increase the stack size/recursion depth as i'm testing up to 1 million elements.

答:
There's a bunch of timing procedures in MIT Scheme, check the documentation. In particular, try this one:

```<code>(with-timings
 (lambda ()
   (merge-sort '(1 2 3 4 5) >))
 (lambda (run-time gc-time real-time)
   (write (internal-time/ticks->seconds run-time))
   (write-char #\space)
   (write (internal-time/ticks->seconds gc-time))
   (write-char #\space)
   (write (internal-time/ticks->seconds real-time))
   (newline)))
</code>```

The built-in sort shouldn't have a problem with one million elements, if your own implementation is a good one, it shouldn't have problems producing a result with that data size.

Body:
There's a bunch of timing procedures in MIT Scheme, check the documentation. In particular, try this one:

(with-timings
 (lambda ()
   (merge-sort '(1 2 3 4 5) >))
 (lambda (run-time gc-time real-time)
   (write (internal-time/ticks->seconds run-time))
   (write-char #\space)
   (write (internal-time/ticks->seconds gc-time))
   (write-char #\space)
   (write (internal-time/ticks->seconds real-time))
   (newline)))

The built-in sort shouldn't have a problem with one million elements, if your own implementation is a good one, it shouldn't have problems producing a result with that data size.


问:
Action send, sending file how to change file name
Hello I want to send file from my phone using intent. I get file patch in this way:

```<code>Intent get=new Intent();
                get.setAction(Intent.ACTION_GET_CONTENT);
                get.setType("*/*");
                startActivityForResult(get,2);
</code>```

and I receive path and send file in this way:

```<code> if (requestCode == 2)
            {
                path = data.getData();

                Log.d("PATH", path.getPath());
                Intent send=new Intent();
                send.setAction(Intent.ACTION_SENDTO);
                send.setType("*/*");
                send.putExtra(Intent.EXTRA_STREAM,path);
                //startActivity(Intent.createChooser(send,"Sending"));
            }
</code>```

Everything would be right but when I send file, it has an odd name, eg: orca_share_media1496666382761
how can I change the file name to be as it should be? I found different solution but there path was in String

答: I think you should rename file before sending if you want this to work. Here is some reference on how to do that android, How to rename a file?</p>

Body:
Hello I want to send file from my phone using intent. I get file patch in this way:

Intent get=new Intent();
                get.setAction(Intent.ACTION_GET_CONTENT);
                get.setType("*/*");
                startActivityForResult(get,2);

and I receive path and send file in this way:

 if (requestCode == 2)
            {
                path = data.getData();

                Log.d("PATH", path.getPath());
                Intent send=new Intent();
                send.setAction(Intent.ACTION_SENDTO);
                send.setType("*/*");
                send.putExtra(Intent.EXTRA_STREAM,path);
                //startActivity(Intent.createChooser(send,"Sending"));
            }

Everything would be right but when I send file, it has an odd name, eg: orca_share_media1496666382761
how can I change the file name to be as it should be? I found different solution but there path was in String


问:
How to handle a change in system level font size on iOS with React Native?
We have a situation where if a user decides to increase the "Larger Text" size in iOS Settings (see image below), it then messes up our view layouts in React Native, as the font size will now be larger.

For example here is a ListView row BEFORE changing the "Larger Text" setting in iOS system settings:

And here is the same row AFTER increasing the "Larger Text" setting:

What is best practice to handle such font scale increase in React Native ? This is obviously just one example, and there are other scenario's such as a View that only contains Text, but we do not want to increase the height of that View at runtime.

Appreciate anyone's advice on this, thanks!

答:
You can do the following to block such changes (do it on your root js file):</p>

```<code>Text.defaultProps.allowFontScaling = false;
</code>```

Body:
You can do the following to block such changes (do it on your root js file):

Text.defaultProps.allowFontScaling = false;


问:
Algorithm to always sum sliders to 100% failing due to zeroes
This is (supposed to be) a function which makes sure that the the sum of a number of slider's values always adds up to globalTotal.

A slider value can be changed manually by the user to changer.value and then when applying this function to the values of the other sliders, it can determine their new or endVal.

It takes the startVal of the slider which needs changing and the original value of the slider that changed changerStartVal and can determine the new value others by weighting.

The problem and my question is. Sometimes remainingStartVals can be zero (when the slider changing gets moved all the way to maximum) or startVal can be zero (when the slider changing is moved to zero and then another slider is moved). When this happens I get a divide-by-zero or a multiply-by-zero respectively. Both of which are bad and lead to incorrect results. Is there an easy way to fix this?

```<code>func calcNewVal(startVal: Float, changerStartVal: Float) -> Float {

    let remainingStartVals = globalTotal - changerStartVal

    let remainingNewVals = globalTotal - changer.value

    let endVal = ((startVal * (100 / remainingStartVals)) / 100) * remainingNewVals

    return endVal

}
</code>```

答:
This is a mathematical problem, not a problem related to Swift or any specific programming language so I'll answer with mathematical formulas and explanations rather than code snippets.

I don't really understand your algorithm either. For example in this line:

```<code>let endVal = ((startVal * (100 / remainingStartVals)) / 100) * remainingNewVals
</code>```

you first multiply by 100 and then divide by 100, so you could just leave all these 100 factors out in the first place!

However, I think I understand what you're trying to achieve and the problem is that there is no generic solution. Before writing an algorithm you have to define exactly how you want it to behave, including all edge cases.

Let's define:

vi as the value of the i-th slider and

Δi as the change of the i-th slider's value

Then you have to think of the following cases:

Case 1:

0 < vi ≤ 1 for all sliders (other than the one you changed)

This is probably the common case you were thinking about. In this case you want to adjust the values of your unchanged sliders so that their total change is equal to the change Δchanged of the slider you changed. In other words:

∑i Δi = 0

If you have 3 sliders this reduces to:

Δ1 + Δ2 + Δ3 = 0

And if the slider that changed is the one with i = 1 then this requirement would read:

Δ1 = – (Δ2 + Δ3)

You want the sliders to adjust proportionally which means that this change Δ1 should not be distributed equally on the other sliders but depending on their current value:

Δ2 = – w2 * Δ1

Δ3 = – w3 * Δ1

The normed weight factors are

w2 = v2 / (v2 + v3)

w3 = v3 / (v2 + v3)

Thus we get:

Δ2 = – v2 / (v2 + v3) * Δ1

Δ3 = – v3 / (v2 + v3) * Δ1

So these are the formulas to applied for this particular case.

However, there are quite a few other cases that don't work with this approach:

Case 2:

vi = 0 for at least one, but not all of the sliders (other than the one you changed)

In this case the approach from case 1 would still work (plus it would be the logical thing to do). However, a slider's value would never change if it's zero. All of the change will be distributed over the sliders with a value > 0.

Case 3:

vi = 0 for all sliders (other than the one you changed)

In this case the proportional change doesn't work because there is simply no information how to distribute the change over the sliders. They're all zero! This is actually your zero division problem: In the case where we have 3 sliders and the slider 1 changes we'll get

v2 + v3 = 0

This is only another manifestation of the fact that the weight factors wi are simply undefined. Thus, you'll have to manually define what will happen in this case.

The most plausible thing to do in this case is to distribute the change evenly over all sliders:

Δi = – (1 / n) * Δ1

where n is the number of sliders (excluding the one that was changed!). With this logic, every slider gets "the same share" of the change.

Now that we're clear with our algorithm you can implement these cases in code. Here some pseudo code as an example:

```<code>if sum(valuesOfAllSlidersOtherThanTheSliderThatChanged) == 0 {
    for allUnchangedSliders {
        // distribute change evenly over the sliders
        Δi = – (1 / n) * Δ_changedSlider
    }
}
else {
    for allUnchangedSliders {
        // use weight factor to change proportionally
        Δi = – v_i / ∑(v_i) * Δ_changedSlider
    }
}
</code>```

Please be aware that you must cache the values of the current state of your sliders at the beginning or (even better) first compute all the changes and then apply all the changes in a batch. Otherwise you will use a value v2' that you just computed for determining the value v3' which will obviously result in incorrect values.

Body:
This is (supposed to be) a function which makes sure that the the sum of a number of slider's values always adds up to globalTotal.

A slider value can be changed manually by the user to changer.value and then when applying this function to the values of the other sliders, it can determine their new or endVal.

It takes the startVal of the slider which needs changing and the original value of the slider that changed changerStartVal and can determine the new value others by weighting.

The problem and my question is. Sometimes remainingStartVals can be zero (when the slider changing gets moved all the way to maximum) or startVal can be zero (when the slider changing is moved to zero and then another slider is moved). When this happens I get a divide-by-zero or a multiply-by-zero respectively. Both of which are bad and lead to incorrect results. Is there an easy way to fix this?

func calcNewVal(startVal: Float, changerStartVal: Float) -> Float {

    let remainingStartVals = globalTotal - changerStartVal

    let remainingNewVals = globalTotal - changer.value

    let endVal = ((startVal * (100 / remainingStartVals)) / 100) * remainingNewVals

    return endVal

}

Body:
This is a mathematical problem, not a problem related to Swift or any specific programming language so I'll answer with mathematical formulas and explanations rather than code snippets.

I don't really understand your algorithm either. For example in this line:

let endVal = ((startVal * (100 / remainingStartVals)) / 100) * remainingNewVals

you first multiply by 100 and then divide by 100, so you could just leave all these 100 factors out in the first place!

However, I think I understand what you're trying to achieve and the problem is that there is no generic solution. Before writing an algorithm you have to define exactly how you want it to behave, including all edge cases.

Let's define:

vi as the value of the i-th slider and

Δi as the change of the i-th slider's value

Then you have to think of the following cases:

Case 1:

0 < vi ≤ 1 for all sliders (other than the one you changed)

This is probably the common case you were thinking about. In this case you want to adjust the values of your unchanged sliders so that their total change is equal to the change Δchanged of the slider you changed. In other words:

∑i Δi = 0

If you have 3 sliders this reduces to:

Δ1 + Δ2 + Δ3 = 0

And if the slider that changed is the one with i = 1 then this requirement would read:

Δ1 = – (Δ2 + Δ3)

You want the sliders to adjust proportionally which means that this change Δ1 should not be distributed equally on the other sliders but depending on their current value:

Δ2 = – w2 * Δ1

Δ3 = – w3 * Δ1

The normed weight factors are

w2 = v2 / (v2 + v3)

w3 = v3 / (v2 + v3)

Thus we get:

Δ2 = – v2 / (v2 + v3) * Δ1

Δ3 = – v3 / (v2 + v3) * Δ1

So these are the formulas to applied for this particular case.

However, there are quite a few other cases that don't work with this approach:

Case 2:

vi = 0 for at least one, but not all of the sliders (other than the one you changed)

In this case the approach from case 1 would still work (plus it would be the logical thing to do). However, a slider's value would never change if it's zero. All of the change will be distributed over the sliders with a value > 0.

Case 3:

vi = 0 for all sliders (other than the one you changed)

In this case the proportional change doesn't work because there is simply no information how to distribute the change over the sliders. They're all zero! This is actually your zero division problem: In the case where we have 3 sliders and the slider 1 changes we'll get

v2 + v3 = 0

This is only another manifestation of the fact that the weight factors wi are simply undefined. Thus, you'll have to manually define what will happen in this case.

The most plausible thing to do in this case is to distribute the change evenly over all sliders:

Δi = – (1 / n) * Δ1

where n is the number of sliders (excluding the one that was changed!). With this logic, every slider gets "the same share" of the change.

Now that we're clear with our algorithm you can implement these cases in code. Here some pseudo code as an example:

if sum(valuesOfAllSlidersOtherThanTheSliderThatChanged) == 0 {
    for allUnchangedSliders {
        // distribute change evenly over the sliders
        Δi = – (1 / n) * Δ_changedSlider
    }
}
else {
    for allUnchangedSliders {
        // use weight factor to change proportionally
        Δi = – v_i / ∑(v_i) * Δ_changedSlider
    }
}

Please be aware that you must cache the values of the current state of your sliders at the beginning or (even better) first compute all the changes and then apply all the changes in a batch. Otherwise you will use a value v2' that you just computed for determining the value v3' which will obviously result in incorrect values.


问:
how to refresh data every 5 second using observable
I am quite new to angular2 and rxjs. I am trying to create an angular2 app that gets some data from jsonAPI,

i want to get data every 5 second,
i found a solution with Observable.interval(5000) but i have some error while compiling,

how to insert Observable.interval(500) in ngOnInit() code

please!!

```<code>   import { Component, OnInit }  from '@angular/core';

import { IProduct } from './product';
import { ProductService } from './product.service';

@Component({
    templateUrl: 'app/products/product-list.component.html',
    styleUrls: ['app/products/product-list.component.css']
})
export class ProductListComponent implements OnInit {
    pageTitle: string = 'Product List';
    imageWidth: number = 50;
    imageMargin: number = 2;
    showImage: boolean = false;
    listFilter: string;
    errorMessage: string;

    products: IProduct[];

    constructor(private _productService: ProductService) {

    }

    toggleImage(): void {
        this.showImage = !this.showImage;
    }

    ngOnInit(): void {
        this._productService.getProducts()
                .subscribe(products => this.products = products,
                           error => this.errorMessage = <any>error);
    }

    onRatingClicked(message: string): void {
        this.pageTitle = 'Product List: ' + message;
    }
}
</code>```

productservice.ts

```<code>import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/throw';

import { IProduct } from './product';

@Injectable()
export class ProductService {
    private _productUrl = 'api/products/products.json';

    constructor(private _http: Http) { }

    getProducts(): Observable<IProduct[]> {
        return this._http.get(this._productUrl)
            .map((response: Response) => <IProduct[]> response.json())
            .do(data => console.log('All: ' +  JSON.stringify(data)))
            .catch(this.handleError);
    }

    getProduct(id: number): Observable<IProduct> {
        return this.getProducts()
            .map((products: IProduct[]) => products.find(p => p.productId === id));
    }

    private handleError(error: Response) {
        // in a real world app, we may send the server to some remote logging infrastructure
        // instead of just logging it to the console
        console.error(error);
        return Observable.throw(error.json().error || 'Server error');
    }
}
</code>```

答:
You need to modify inside your ProductService.ts as follows,</p>

```<code> getProducts(){
    Observable.interval(5000)
      .flatMap(() => this.http.get(URL)
      .map( res => res.json() )
      .catch( (error:any) => Observable.throw(error.json().error || 'Server error') ) )
      .subscribe(data => {
         console.log(data)
      })
}
</code>```

Body:
I am quite new to angular2 and rxjs. I am trying to create an angular2 app that gets some data from jsonAPI,

i want to get data every 5 second,
i found a solution with Observable.interval(5000) but i have some error while compiling,

how to insert Observable.interval(500) in ngOnInit() code

please!!

   import { Component, OnInit }  from '@angular/core';

import { IProduct } from './product';
import { ProductService } from './product.service';

@Component({
    templateUrl: 'app/products/product-list.component.html',
    styleUrls: ['app/products/product-list.component.css']
})
export class ProductListComponent implements OnInit {
    pageTitle: string = 'Product List';
    imageWidth: number = 50;
    imageMargin: number = 2;
    showImage: boolean = false;
    listFilter: string;
    errorMessage: string;

    products: IProduct[];

    constructor(private _productService: ProductService) {

    }

    toggleImage(): void {
        this.showImage = !this.showImage;
    }

    ngOnInit(): void {
        this._productService.getProducts()
                .subscribe(products => this.products = products,
                           error => this.errorMessage = <any>error);
    }

    onRatingClicked(message: string): void {
        this.pageTitle = 'Product List: ' + message;
    }
}

productservice.ts

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/throw';

import { IProduct } from './product';

@Injectable()
export class ProductService {
    private _productUrl = 'api/products/products.json';

    constructor(private _http: Http) { }

    getProducts(): Observable<IProduct[]> {
        return this._http.get(this._productUrl)
            .map((response: Response) => <IProduct[]> response.json())
            .do(data => console.log('All: ' +  JSON.stringify(data)))
            .catch(this.handleError);
    }

    getProduct(id: number): Observable<IProduct> {
        return this.getProducts()
            .map((products: IProduct[]) => products.find(p => p.productId === id));
    }

    private handleError(error: Response) {
        // in a real world app, we may send the server to some remote logging infrastructure
        // instead of just logging it to the console
        console.error(error);
        return Observable.throw(error.json().error || 'Server error');
    }
}

Body:
You need to modify inside your ProductService.ts as follows,

 getProducts(){
    Observable.interval(5000)
      .flatMap(() => this.http.get(URL)
      .map( res => res.json() )
      .catch( (error:any) => Observable.throw(error.json().error || 'Server error') ) )
      .subscribe(data => {
         console.log(data)
      })
}


问:
What is pm.Normal.dist.logp?
I'm reading Probabilistic Programming and Bayesian Methods for Hackers. In Ch5, it is written that logp = pm.Normal.dist(mu=price_estimate, sd=(3e3)).logp(true_price).

What is this? I know pm.Normal() but don't know .dist() and .logp().

答: pm.Normal creates a new random variable and adds that to the model. pm.Normal.dist represents the distribution itself, it does not interact with the model at all. pm.Normal.dist(...).logp(value) is the log of the probability density function (or probability mass function if the distribution is discrete) at the point value.

Title: What is pm.Normal.dist.logp?


问:
Strings and List of Strings in Mustache - Java
is there a simple way to output Strings and List of Strings with Mustache in a HTML-File?

I started to make a HashMap with all the information:

```<code>hashMap1.put("time", a.getTime().toString());
</code>```

And so on. But i also want to write a List<String> into the html file. How can I do that properly?

答:
I am not entirely sure if I correctly understand your question. Do you just want to convert a List of strings into single string? If so you could either use

```<code>Arrays.toString(newList.toArray());
</code>```

which prints in a format

```<code>[string-1][string-2]...[string-n]
</code>```

The other option is to use String.join(" separator ", newList); which prints out

```<code>string-1 separator string-2 separator (...) separator string-n
</code>```

Body:
is there a simple way to output Strings and List of Strings with Mustache in a HTML-File?

I started to make a HashMap with all the information:

hashMap1.put("time", a.getTime().toString());

And so on. But i also want to write a List<String> into the html file. How can I do that properly?

Body:
I am not entirely sure if I correctly understand your question. Do you just want to convert a List of strings into single string? If so you could either use

Arrays.toString(newList.toArray());

which prints in a format

[string-1][string-2]...[string-n]

The other option is to use String.join(" separator ", newList); which prints out

string-1 separator string-2 separator (...) separator string-n


问:
Cannot Use Two Splines in Highchart
I am trying to use two spline into my graph created from highcharts.  My first Spline is displyed in center and second is displayed correctly . My output look like below,

Am trying the following code,

```<code><script type="text/javascript">

var categories = [];
$(document).ready(function () {

    var left = [ 5, 0, 0, 0, 0, 3, 0, 0,  0, 0, 5];
    var right = [-5, -0, -0, -0, -0, -3, -0, -0, -0, -0, -5];

Highcharts.chart('container', {
    chart: {
        type: 'bar'
    },
      tooltip: { enabled: false },
    xAxis: [{
        categories: categories,
        reversed: false,

    }, {
        opposite: true,
        reversed: false,
        categories: categories,
        linkedTo: 0,

    }],
    yAxis: {

        title: {
            text: null
        },

   },

  plotOptions: {
        series: {
            pointWidth: 2,
            stacking: 'normal'
        }
    },

    exporting: { enabled: false },
    credits: {enabled: false},

    series: [{
        showInLegend: false,

        data: right

    }, {
       showInLegend: false,

       data: left
    }
    ,{
        showInLegend: false,
        type: 'spline',
        name:'test1',
        marker:'disabled',
        color:'black',
        data: [-5,-4,-3,-3,-3,-3,-3,-3,-3,-4,-5],
        pointPlacement: -.15

    },
    {
        showInLegend: false,
        type: 'spline',
        name:'test2',
        marker:'disabled',
        color:'black',
        data: [5,4,3,3,3,3,3,3,3,4,5]

    }
    ]

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

And My Excepted Output  is ,

Please help me to solve this issues.

答:
For Solving this Issues just change the first spline data value into double . </p>

```<code><!DOCTYPE html>
<html>
<head>
<title>Test Graph</title>

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>

</head>
<body>

   <div id="container" style="min-width: 310px; max-width: 800px; height:     400px; margin: 0 auto"></div>

  </body>

  </html>

 <script type="text/javascript">

 var categories = [];
 $(document).ready(function () {

    var left = [ 5, 0, 0, 0, 0, 3, 0, 0,  0, 0, 5];
    var right = [-5, -0, -0, -0, -0, -3, -0, -0, -0, -0, -5];

 Highcharts.chart('container', {
    chart: {
        type: 'bar'
    },
      tooltip: { enabled: false },
    xAxis: [{
        categories: categories,
        reversed: false,

    }, {
        opposite: true,
        reversed: false,
        categories: categories,
        linkedTo: 0,

    }],
    yAxis: {

        title: {
            text: null
        },

    },

  plotOptions: {
        series: {
            pointWidth: 0,
            stacking: 'normal'
        }
    },

    exporting: { enabled: false },
    credits: {enabled: false},

    series: [{
        showInLegend: false,
        data: right

    },
    {
       showInLegend: false,
       data: left
    },
    {
        showInLegend: false,
        type: 'spline',
        marker:'disabled',
        color:'black',
        data: [-10,-8,-6,-6,-6,-6,-6,-6,-6,-8,-10]

    },
    {
        showInLegend: false,
        type: 'spline',
        marker:'disabled',
        color:'black',
        data: [5,4,3,3,3,3,3,3,3,4,5]

    }]

   });
 });

</script>
</code>```

Title: Cannot Use Two Splines in Highchart

Body:
For Solving this Issues just change the first spline data value into double .

<!DOCTYPE html>
<html>
<head>
<title>Test Graph</title>

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>

</head>
<body>

   <div id="container" style="min-width: 310px; max-width: 800px; height:     400px; margin: 0 auto"></div>

  </body>

  </html>

 <script type="text/javascript">

 var categories = [];
 $(document).ready(function () {

    var left = [ 5, 0, 0, 0, 0, 3, 0, 0,  0, 0, 5];
    var right = [-5, -0, -0, -0, -0, -3, -0, -0, -0, -0, -5];

 Highcharts.chart('container', {
    chart: {
        type: 'bar'
    },
      tooltip: { enabled: false },
    xAxis: [{
        categories: categories,
        reversed: false,

    }, {
        opposite: true,
        reversed: false,
        categories: categories,
        linkedTo: 0,

    }],
    yAxis: {

        title: {
            text: null
        },

    },

  plotOptions: {
        series: {
            pointWidth: 0,
            stacking: 'normal'
        }
    },

    exporting: { enabled: false },
    credits: {enabled: false},

    series: [{
        showInLegend: false,
        data: right

    },
    {
       showInLegend: false,
       data: left
    },
    {
        showInLegend: false,
        type: 'spline',
        marker:'disabled',
        color:'black',
        data: [-10,-8,-6,-6,-6,-6,-6,-6,-6,-8,-10]

    },
    {
        showInLegend: false,
        type: 'spline',
        marker:'disabled',
        color:'black',
        data: [5,4,3,3,3,3,3,3,3,4,5]

    }]

   });
 });

</script>


问:
Error when adding field to Inquiry form
Working with the Voucher transactions inquiry, I've added a custom field to the GeneralJournalEntry table.

When I try to add this field to my inquiry form, it adds correctly (renders as a drop down), and I can input a value or select one from the drop down list -- the issue is if I attempt to put in a wildcard character (*), I'll get a stack trace error:

```<code>SysDictType object not initialized.

(S)\Classes\SysTableRelation\getDictFieldID - line 7
(S)\Classes\SysTableRelation\findRelation - line 41
(C)\Classes\SysLookup\lookupTableRelation - line 13
(C)\Classes\SysLookup\lookupRange - line 133
(C)\Forms\SysQueryForm\Data Sources\Range\Fields\RangeValue\Methods\lookup - line 36
(C)\Classes\FormStringControl\PerformDBLookup
(C)\Classes\FormStringControl\lookup
(C)\Forms\SysQueryForm\Designs\DesignList\RangeValue\Methods\lookup - line 27
</code>```

There aren't any modifications to these classes, and I can't find anything that would lead me to believe that the wildcard is invalid in this field.

答:
This problem occurs because the method \SysTableRelation\getDictFieldID uses the EDT of the field at the line dictType = new SysDictType (sysDictField.typeId ()) line;

I fixed by adding an EDT to the field.

Title: Error when adding field to Inquiry form

Body:
Working with the Voucher transactions inquiry, I've added a custom field to the GeneralJournalEntry table.

When I try to add this field to my inquiry form, it adds correctly (renders as a drop down), and I can input a value or select one from the drop down list -- the issue is if I attempt to put in a wildcard character (*), I'll get a stack trace error:

SysDictType object not initialized.

(S)\Classes\SysTableRelation\getDictFieldID - line 7
(S)\Classes\SysTableRelation\findRelation - line 41
(C)\Classes\SysLookup\lookupTableRelation - line 13
(C)\Classes\SysLookup\lookupRange - line 133
(C)\Forms\SysQueryForm\Data Sources\Range\Fields\RangeValue\Methods\lookup - line 36
(C)\Classes\FormStringControl\PerformDBLookup
(C)\Classes\FormStringControl\lookup
(C)\Forms\SysQueryForm\Designs\DesignList\RangeValue\Methods\lookup - line 27

There aren't any modifications to these classes, and I can't find anything that would lead me to believe that the wildcard is invalid in this field.


问:
restfb: get page picture
I am trying to get the Page picture. However it always comes back as null. Am i doing something wrong?

```<code>FacebookClient facebookClient = new DefaultFacebookClient(accessToken)
def page = facebookClient.fetchObject(PAGE_ID, Page.class);
println page.picture //prints null
</code>```

any ideas?

答:
```<code>FacebookClient facebookClient = new DefaultFacebookClient(facebookAccessToken, Version.LATEST);

JsonObject jsonObject = facebookClient.fetchObject("/" + userId + "/picture", JsonObject.class,
        Parameter.with("type", "large"), Parameter.with("redirect", "false"));
JsonValue jsonValue = jsonObject.get("data");
JsonObject object = jsonValue.asObject();
String profileImageUrl = object.get("url").asString();
</code>```

Title: restfb: get page picture

Body:
I am trying to get the Page picture. However it always comes back as null. Am i doing something wrong?

FacebookClient facebookClient = new DefaultFacebookClient(accessToken)
def page = facebookClient.fetchObject(PAGE_ID, Page.class);
println page.picture //prints null

any ideas?