问:
python set specific locale for date as a string
I am using python 3.4 & django 1.10.

I have some code that sets and then dynamically displays strings to the user depending on the language they select on the template, via a select list of languages.

For example, if user selects de, the German values are displayed, en displays English (US) details, etc.

I am trying to localise the today's date string to different language codes.

I have searched google and SO, but cannot figure this out, or even if this is possible.

Does any one have any suggestions?

Thanks.

Here is my code:

```<code>from django.template.defaultfilters import date as _date
from datetime import datetime

GENERIC_DETAILS_LIVE_PREVIEW_LABELS = {
    'ar': {
        ....
        'nac_generic_descriptor': u"موظف السنة",  # Employee of the year
        'nac_generic_preview_date': _date(datetime.now(), "N j, Y"),  # todays date localised
        ....
    },
    'en': {
        ....
        'nac_generic_descriptor': u"Employee of the year",  # Employee of the year
        'nac_generic_preview_date': _date(datetime.now(), "N j, Y"),  # todays date localised
        ....
    },
    'it': {
        ....
        'nac_generic_descriptor': u"Impiegato dell'anno",  # Employee of the year
        'nac_generic_preview_date': _date(datetime.now(), "N j, Y"),  # todays date localised
        ....
    },
    'de': {
        ....
        'nac_generic_descriptor': u"Mitarbeiter des Jahres",  # Employee of the year
        'nac_generic_preview_date': _date(datetime.now(), "N j, Y"),  # todays date localised
        ....
    },
    'fr': {
        ....
        'nac_generic_descriptor': u"Employé de l'année",  # Employee of the year
        'nac_generic_preview_date': _date(datetime.now(), "N j, Y"),  # todays date localised
        ....
    },
    'es': {
        ....
        'nac_generic_descriptor': u"Empleado del año",  # Employee of the year
        'nac_generic_preview_date': _date(datetime.now(), "N j, Y"),  # todays date localised
        ....
    },
}
</code>```

答:
I got this to work using Babel.

Here is my code:

```<code>from datetime import date, datetime, time
from babel.dates import format_date, format_datetime, format_time

GENERIC_DETAILS_LIVE_PREVIEW_LABELS = {
    'ar': {
        ....
        'nac_generic_descriptor': u"موظف السنة",  # Employee of the year
        'nac_generic_preview_date': format_date(datetime.now(), format='long', locale='ar'),  # todays date localised
        ....
    },
    'en': {
        ....
        'nac_generic_descriptor': u"Employee of the year",  # Employee of the year
        'nac_generic_preview_date': format_date(datetime.now(), format='long', locale='en_US'),  # todays date localised
        ....
    },
    'it': {
        ....
        'nac_generic_descriptor': u"Impiegato dell'anno",  # Employee of the year
        'nac_generic_preview_date': format_date(datetime.now(), format='long', locale='it_IT'),  # todays date localised
        ....
    },
    'de': {
        ....
        'nac_generic_descriptor': u"Mitarbeiter des Jahres",  # Employee of the year
        'nac_generic_preview_date': format_date(datetime.now(), format='long', locale='de_DE'),  # todays date localised
        ....
    },
    'fr': {
        ....
        'nac_generic_descriptor': u"Employé de l'année",  # Employee of the year
        'nac_generic_preview_date': format_date(datetime.now(), format='long', locale='fr_FR'),  # todays date localised
        ....
    },
    'es': {
        ....
        'nac_generic_descriptor': u"Empleado del año",  # Employee of the year
        'nac_generic_preview_date': format_date(datetime.now(), format='long', locale='es_ES'),  # todays date localised
        ....
    },
}
</code>```

In my template the dates are now displayed as:

en: April 3, 2017

fr: 3 avril 2017

es: 3 de abril de 2017

etcetra, etcetra.

I hope this helps someone.

Body:
I am using python 3.4 & django 1.10.

I have some code that sets and then dynamically displays strings to the user depending on the language they select on the template, via a select list of languages.

For example, if user selects de, the German values are displayed, en displays English (US) details, etc.

I am trying to localise the today's date string to different language codes.

I have searched google and SO, but cannot figure this out, or even if this is possible.

Does any one have any suggestions?

Thanks.

Here is my code:

from django.template.defaultfilters import date as _date
from datetime import datetime

GENERIC_DETAILS_LIVE_PREVIEW_LABELS = {
    'ar': {
        ....
        'nac_generic_descriptor': u"موظف السنة",  # Employee of the year
        'nac_generic_preview_date': _date(datetime.now(), "N j, Y"),  # todays date localised
        ....
    },
    'en': {
        ....
        'nac_generic_descriptor': u"Employee of the year",  # Employee of the year
        'nac_generic_preview_date': _date(datetime.now(), "N j, Y"),  # todays date localised
        ....
    },
    'it': {
        ....
        'nac_generic_descriptor': u"Impiegato dell'anno",  # Employee of the year
        'nac_generic_preview_date': _date(datetime.now(), "N j, Y"),  # todays date localised
        ....
    },
    'de': {
        ....
        'nac_generic_descriptor': u"Mitarbeiter des Jahres",  # Employee of the year
        'nac_generic_preview_date': _date(datetime.now(), "N j, Y"),  # todays date localised
        ....
    },
    'fr': {
        ....
        'nac_generic_descriptor': u"Employé de l'année",  # Employee of the year
        'nac_generic_preview_date': _date(datetime.now(), "N j, Y"),  # todays date localised
        ....
    },
    'es': {
        ....
        'nac_generic_descriptor': u"Empleado del año",  # Employee of the year
        'nac_generic_preview_date': _date(datetime.now(), "N j, Y"),  # todays date localised
        ....
    },
}

Body:
I got this to work using Babel.

Here is my code:

from datetime import date, datetime, time
from babel.dates import format_date, format_datetime, format_time

GENERIC_DETAILS_LIVE_PREVIEW_LABELS = {
    'ar': {
        ....
        'nac_generic_descriptor': u"موظف السنة",  # Employee of the year
        'nac_generic_preview_date': format_date(datetime.now(), format='long', locale='ar'),  # todays date localised
        ....
    },
    'en': {
        ....
        'nac_generic_descriptor': u"Employee of the year",  # Employee of the year
        'nac_generic_preview_date': format_date(datetime.now(), format='long', locale='en_US'),  # todays date localised
        ....
    },
    'it': {
        ....
        'nac_generic_descriptor': u"Impiegato dell'anno",  # Employee of the year
        'nac_generic_preview_date': format_date(datetime.now(), format='long', locale='it_IT'),  # todays date localised
        ....
    },
    'de': {
        ....
        'nac_generic_descriptor': u"Mitarbeiter des Jahres",  # Employee of the year
        'nac_generic_preview_date': format_date(datetime.now(), format='long', locale='de_DE'),  # todays date localised
        ....
    },
    'fr': {
        ....
        'nac_generic_descriptor': u"Employé de l'année",  # Employee of the year
        'nac_generic_preview_date': format_date(datetime.now(), format='long', locale='fr_FR'),  # todays date localised
        ....
    },
    'es': {
        ....
        'nac_generic_descriptor': u"Empleado del año",  # Employee of the year
        'nac_generic_preview_date': format_date(datetime.now(), format='long', locale='es_ES'),  # todays date localised
        ....
    },
}

In my template the dates are now displayed as:

en: April 3, 2017

fr: 3 avril 2017

es: 3 de abril de 2017

etcetra, etcetra.

I hope this helps someone.


来源: stackexchange

问:
Why is it "impossible" to implement garbage collection in C because of weak typing?
I was told by a rather smart person that you cannot implement garbage collection in C because of it's weakly typed. The basic idea seems to be that C gives you too much freedom. He mentioned casting pointers without type checking...

I don't really grok the idea. Can someone give me an explanation and possibly a code sample of why this wouldn't work.

NOTE: Obviously C is about speed and why would you want to add garbage collection? I'm just curious really.

答:
It's impossible to implement a precise garbage collector for C because of the freedoms afforded C's pointers and the fact that the length of a C array is anyone's guess. This means a lot of sophisticated garbage collection approaches can't be used. (Copying and compacting garbage collectors come to mind.)

It is, however, possible to implement a conservative garbage collector (boehm), which basically assumes everything that looks like it might be a pointer is a pointer. This isn't very efficient, but it works for a suitably lenient definition of "works".

OwnerDisplayName: Tim Merrifield

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Norman Ramsey

OwnerDisplayName: bendin


问:
Real World Windows Azure Costing Examples, Anyone?
OK, we're in Dec 2010, azure has been out now for a decent period. Sure I've come across silly articles predicting what it might costs to run with Azure (http://robburke.net/2010/01/28/windows-azures-pricing-model-discourages-small-scale-apps/). But what I'd really like to know is who has run Real World Live Azure Apps? What did your applications looks like - which services, how many roles, what storage, how many users etc. and ultimately how much did it cost you?

Right now, trying to figure out whether to invest 6 months in developing an azure app is looking grim because it's such a black box predicting what is might costs to run an application.

I'm surprised I couldn't find a good real world set of examples that would help developers have more visibility into helping them buy into the platform...

答:
I think its a fair question to ask, but anyone will struggle to give you an answer, as your results will always vary and replies from people in the field would be too specific to their particular situation.

I have a real-world solution that we run in Azure.  In fact, if you do decide to go with Azure, consider using it to optimize your compute-instance allocation for Azure: http://www.paraleap.com :)

I can tell you that you want to budget at least 20% extra computing hours due to various times when you need to deploy/redeploy/and re-deploy again an environment into staging area (which costs extra in hourly increments) only to find out that's something else in the cloud does not work when it worked in the dev fabric.  This is especially true in the initial unstable time of your application.  It does not matter if you have a large QA team that bangs the heck out of your Azure-QA environment or you're going to customers for beta-testing and they're testing your Azure-Prod environment.  You will need to be redeploying for them quiet often.
Furthermore, as I already mentioned, plan to adjust your instance counts to demand - hopefully automatically or on a schedule.  If you're going to write your own monitoring to do this, add a /bunch/ to development costs, storage costs, and transaction costs just for that.  Outsourcing this will still cost a little bit, as performance metrics will need to be at least saved once and at least loaded back once.  This will save you in the compute-instance costs easily as much as 50-80%, depending on how variable your demand is.

Storage costs - those should be easy to estimate if you know your usage patterns and target schema... Problem is, if you've worked with Relational databases before and now will be using table Storage, plan to have 3-4 times the size that you would have thought your relational database to have.  With table-storage you get to denormalize ALOT more.  3-4x maybe even too small of a multiplier - your results may vary.

Transaction costs.  I'm finding out that with these, I've been further-off in my estimates.  Coming from relational world, I wasn't totally prepared for the level of denormalization I needed to do.  Denormalization not only leads to higher storage costs, but also to more calls (alot more calls) to the storage - resulting in higher transaction count.

Unfortunately, my nature of the app, I can't very well use transactional model.  If you can use transactions, where a bunch of stuff is stored in one PartitionKey within one table and committed with one transaction - then the costs are much less.
So, whatever you think your transaction costs will be - multiply that by 10 or so to be on the pessimistic side.

I found that transfer costs were easiest to plan for, probably because those are part of the interfaces and are much better defined upfront.  Your mileage may vary.

And lastly, diagnostic data - you will want to save some trace/performance counter/etc. information.  Don't forget to plan for it.  It's somewhat denormalized and can take plenty of space.

SQL Azure is great as it does not charge by transaction cost and no transfer costs if inside the same data center - but is very limited by space and cost to store the data.  So, I use it for frequently queried for, but small data items.

Hope this helps


问:
Using sonar.test.exclusions with Sonarqube 6.3
I'm currently evaluating Sonarqube 6.3 (a big upgrade from my current 5.5 instance) and I'm getting confused trying to work out the functionality of the sonar.test.exclusions setting.

There's this question: Sonar Maven Plugin: How do I exclude test source directories? which seems to indicate that it is used to exclude test files from analysis (which is what I'm after - I don't want my sonar ruleset run over my unit tests). The documentation https://docs.sonarqube.org/display/SONAR/Narrowing+the+Focus also indicates that it is used to 'exclude unit test files' (perhaps this can be expanded upon to make it clearer?)

Thing is, when I add sonar.test.exclusions with a value of **/src/test/** and then run my analysis, I'm still getting code smells and the like being found for:

Foo/src/test/java/foo/bar/BarTest.java

Foo/src/test/java/lah/LahTest.java

etc.

When I use sonar.exclusions instead, they don't show up. Why is sonar.test.exclusions not doing what I expect?

答:
First of all: if you have a Maven project, you should use the scanner for Maven (mvn sonar:sonar). It will simplify your configuration, and will automatically register src/test/java folder as a test directory.

Now if you want to do the configuration manually, or understand what is going on under the hood, here is the explanation: SonarQube scanner work with 2 sets of files, main and test. Main source files are configured using the property sonar.sources. Test source files are configured using sonar.tests.

On top of that, you can filter some content using the sonar.[test.]exclusions properties.

In you case your problem is that Foo/src/test/java/foo/bar/BarTest.java seems to be considered as a main source file. That's why sonar.test.exclusions has no effect.

ContentLicense: CC BY-SA 3.0


问:
Convert DataTable columns to typed IEnumerable[]
How to convert DataTable columns to IEnumerable[] which is required to create a data frame in R.NET

I have the following code:

```<code>DataTable dt = CreateDateTable();
REngine e = REngine.GetInstance();
IEnumerable[] columns = new IEnumerable[dt.Columns.Count];
string[] columnNames = dt.Columns.Cast<DataColumn>()
                       .Select(x => x.ColumnName)
                       .ToArray();

for(int i=0; i<dt.Columns.Count; i++)
    //This is the place where I am stuck. How to convert column to base type array instead of object array
    columns[i] = dt.Rows.Cast<DataRow>().Select(row => row[i]).ToArray();

DataFrame df = e.CreateDataFrame(columns: columns,
 columnNames: columnNames,
 stringsAsFactors: false);
</code>```

I get the following exception:

```<code>Test 'XXX.ReadResultsTest' failed: System.NotSupportedException : Cannot convert type System.Object[] to an R vector
       w RDotNet.REngineExtension.ToVector(REngine engine, IEnumerable values)
       w System.Array.ConvertAll[TInput,TOutput](TInput[] array, Converter`2 converter)
       w RDotNet.REngineExtension.CreateDataFrame(REngine engine, IEnumerable[] columns, String[] columnNames, String[] rowNames, Boolean checkRows, Boolean checkNames, Boolean stringsAsFactors)
</code>```

DataTable has columns of different types and I don't know what are the types so I cannot do like in this example with double:

```<code>for (int i = 0; i < dt.Columns.Count; i++)
        columns[i] = dt.Rows.Cast<DataRow>().Select(row => row.Field<double>(i)).ToArray();
</code>```

UPDATE

So far I have an ugly solution, can it be done better?

```<code>for (int i = 0; i < dt.Columns.Count; i++)
{
    switch (Type.GetTypeCode(dt.Columns[i].DataType))
    {
        case TypeCode.String:
            columns[i] = dt.Rows.Cast<DataRow>().Select(row => row.Field<string>(i)).ToArray();
            break;

        case TypeCode.Double:
            columns[i] = dt.Rows.Cast<DataRow>().Select(row => row.Field<double>(i)).ToArray();
            break;

        case TypeCode.Int32:
            columns[i] = dt.Rows.Cast<DataRow>().Select(row => row.Field<int>(i)).ToArray();
            break;

        case TypeCode.Int64:
            columns[i] = dt.Rows.Cast<DataRow>().Select(row => row.Field<long>(i)).ToArray();
            break;

        default:
            //columns[i] = dt.Rows.Cast<DataRow>().Select(row => row[i]).ToArray();
            throw new InvalidOperationException(String.Format("Type {0} is not supported", dt.Columns[i].DataType.Name));
    }
}
</code>```

答:
```<code>public DataFrame DataTableToDataFrame(string name, DataTable dt)
{
    DataFrame dataFrame = null;

    IEnumerable[] columns = new IEnumerable[dt.Columns.Count];
    string[] columnNames = dt.Columns.Cast<DataColumn>()
                           .Select(x => x.ColumnName)
                           .ToArray();

    for (int i = 0; i < dt.Columns.Count; i++)
    {
        switch (Type.GetTypeCode(dt.Columns[i].DataType))
        {
            case TypeCode.String:
                columns[i] = dt.Rows.Cast<DataRow>().Select(row => row.Field<string>(i)).ToArray();
                break;

            case TypeCode.Double:
                columns[i] = dt.Rows.Cast<DataRow>().Select(row => row.Field<double>(i)).ToArray();
                break;

            case TypeCode.Int32:
                columns[i] = dt.Rows.Cast<DataRow>().Select(row => row.Field<int>(i)).ToArray();
                break;

            case TypeCode.Int64:
            case TypeCode.Decimal:
                IEnumerable array = dt.Rows.Cast<DataRow>().Select(row => row.Field<object>(i)).ToArray();

                //columns[i] = dt.Rows.Cast<DataRow>().Select(row => row.Field<long>(i)).ToArray();
                //columns[i] = dt.Rows.Cast<DataRow>().Select(row => row.Field<decimal>(i)).ToArray();

                columns[i] = ListToIenumerable(array);
                break;

            default:
                columns[i] = dt.Rows.Cast<DataRow>().Select(row => row[i]).ToArray();
                //throw new InvalidOperationException(String.Format("Type {0} is not supported", dt.Columns[i].DataType.Name));
                break;
        }
    }

    dataFrame = REngine.CreateDataFrame(columns: columns, columnNames: columnNames, stringsAsFactors: false);
    REngine.SetSymbol(name, dataFrame);

    return dataFrame;
}
</code>```

This is?

Body:
How to convert DataTable columns to IEnumerable[] which is required to create a data frame in R.NET

I have the following code:

DataTable dt = CreateDateTable();
REngine e = REngine.GetInstance();
IEnumerable[] columns = new IEnumerable[dt.Columns.Count];
string[] columnNames = dt.Columns.Cast<DataColumn>()
                       .Select(x => x.ColumnName)
                       .ToArray();

for(int i=0; i<dt.Columns.Count; i++)
    //This is the place where I am stuck. How to convert column to base type array instead of object array
    columns[i] = dt.Rows.Cast<DataRow>().Select(row => row[i]).ToArray();

DataFrame df = e.CreateDataFrame(columns: columns,
 columnNames: columnNames,
 stringsAsFactors: false);

I get the following exception:

Test 'XXX.ReadResultsTest' failed: System.NotSupportedException : Cannot convert type System.Object[] to an R vector
       w RDotNet.REngineExtension.ToVector(REngine engine, IEnumerable values)
       w System.Array.ConvertAll[TInput,TOutput](TInput[] array, Converter`2 converter)
       w RDotNet.REngineExtension.CreateDataFrame(REngine engine, IEnumerable[] columns, String[] columnNames, String[] rowNames, Boolean checkRows, Boolean checkNames, Boolean stringsAsFactors)

DataTable has columns of different types and I don't know what are the types so I cannot do like in this example with double:

for (int i = 0; i < dt.Columns.Count; i++)
        columns[i] = dt.Rows.Cast<DataRow>().Select(row => row.Field<double>(i)).ToArray();

UPDATE

So far I have an ugly solution, can it be done better?

for (int i = 0; i < dt.Columns.Count; i++)
{
    switch (Type.GetTypeCode(dt.Columns[i].DataType))
    {
        case TypeCode.String:
            columns[i] = dt.Rows.Cast<DataRow>().Select(row => row.Field<string>(i)).ToArray();
            break;

        case TypeCode.Double:
            columns[i] = dt.Rows.Cast<DataRow>().Select(row => row.Field<double>(i)).ToArray();
            break;

        case TypeCode.Int32:
            columns[i] = dt.Rows.Cast<DataRow>().Select(row => row.Field<int>(i)).ToArray();
            break;

        case TypeCode.Int64:
            columns[i] = dt.Rows.Cast<DataRow>().Select(row => row.Field<long>(i)).ToArray();
            break;

        default:
            //columns[i] = dt.Rows.Cast<DataRow>().Select(row => row[i]).ToArray();
            throw new InvalidOperationException(String.Format("Type {0} is not supported", dt.Columns[i].DataType.Name));
    }
}

Body:
public DataFrame DataTableToDataFrame(string name, DataTable dt)
{
    DataFrame dataFrame = null;

    IEnumerable[] columns = new IEnumerable[dt.Columns.Count];
    string[] columnNames = dt.Columns.Cast<DataColumn>()
                           .Select(x => x.ColumnName)
                           .ToArray();

    for (int i = 0; i < dt.Columns.Count; i++)
    {
        switch (Type.GetTypeCode(dt.Columns[i].DataType))
        {
            case TypeCode.String:
                columns[i] = dt.Rows.Cast<DataRow>().Select(row => row.Field<string>(i)).ToArray();
                break;

            case TypeCode.Double:
                columns[i] = dt.Rows.Cast<DataRow>().Select(row => row.Field<double>(i)).ToArray();
                break;

            case TypeCode.Int32:
                columns[i] = dt.Rows.Cast<DataRow>().Select(row => row.Field<int>(i)).ToArray();
                break;

            case TypeCode.Int64:
            case TypeCode.Decimal:
                IEnumerable array = dt.Rows.Cast<DataRow>().Select(row => row.Field<object>(i)).ToArray();

                //columns[i] = dt.Rows.Cast<DataRow>().Select(row => row.Field<long>(i)).ToArray();
                //columns[i] = dt.Rows.Cast<DataRow>().Select(row => row.Field<decimal>(i)).ToArray();

                columns[i] = ListToIenumerable(array);
                break;

            default:
                columns[i] = dt.Rows.Cast<DataRow>().Select(row => row[i]).ToArray();
                //throw new InvalidOperationException(String.Format("Type {0} is not supported", dt.Columns[i].DataType.Name));
                break;
        }
    }

    dataFrame = REngine.CreateDataFrame(columns: columns, columnNames: columnNames, stringsAsFactors: false);
    REngine.SetSymbol(name, dataFrame);

    return dataFrame;
}

This is?


问:
How to change src in Floating Action Button from Service.class?
I have method, which fulfills actions by pressing on buttons in notification.

```<code>private void handleIncomingActions(Intent playbackAction) {
        if (playbackAction == null || playbackAction.getAction() == null) {
            return;
        }

        String actionString = playbackAction.getAction();

        if (actionString.equalsIgnoreCase(ACTION_PLAY)) {
            if (mediaPlayer != null) {
                playMedia();
            }
        }
        if (actionString.equalsIgnoreCase(ACTION_PAUSE)) {
            if (mediaPlayer != null) {
                pauseMedia();

                //HERE NEED TO CHANGE SRC
            }
        }
        if (actionString.equalsIgnoreCase(ACTION_CLOSE)) {
            if (mediaPlayer != null) {
                stopService(new Intent(this, MediaService.class));
                getApplicationContext().unbindService(PlayerActivity.serviceConnection);
                PlayerActivity.serviceBound = false;

                //HERE NEED TO CHANGE SRC

            }
        }
    }
</code>```

In two cases I need to change FAB's icon in my PlayerActivity class from Service.class.
How can I access the FAB without using "static" and without singleton?

答:
Give this a try:

Add this to the PlayerActivity:

```<code>public void changeFloatingActionButtonIcon(int fabIcon) {

     fab.setImageResource(fabIcon);
};
</code>```

Add this to Services.class:

```<code>((PlayerActivity) getActivity()).changeFloatingActionButtonIcon(R.drawable.icon);
</code>```

Body:
I have method, which fulfills actions by pressing on buttons in notification.

private void handleIncomingActions(Intent playbackAction) {
        if (playbackAction == null || playbackAction.getAction() == null) {
            return;
        }

        String actionString = playbackAction.getAction();

        if (actionString.equalsIgnoreCase(ACTION_PLAY)) {
            if (mediaPlayer != null) {
                playMedia();
            }
        }
        if (actionString.equalsIgnoreCase(ACTION_PAUSE)) {
            if (mediaPlayer != null) {
                pauseMedia();

                //HERE NEED TO CHANGE SRC
            }
        }
        if (actionString.equalsIgnoreCase(ACTION_CLOSE)) {
            if (mediaPlayer != null) {
                stopService(new Intent(this, MediaService.class));
                getApplicationContext().unbindService(PlayerActivity.serviceConnection);
                PlayerActivity.serviceBound = false;

                //HERE NEED TO CHANGE SRC

            }
        }
    }

In two cases I need to change FAB's icon in my PlayerActivity class from Service.class.
How can I access the FAB without using "static" and without singleton?

Body:
Give this a try:

Add this to the PlayerActivity:

public void changeFloatingActionButtonIcon(int fabIcon) {

     fab.setImageResource(fabIcon);
};

Add this to Services.class:

((PlayerActivity) getActivity()).changeFloatingActionButtonIcon(R.drawable.icon);


问:
Google Apps Script file upload (by HTML form) only works when script is "bound" (when standalone script tested, HTTP 403 error)
To upload a local file to Google Drive, I have an HTML <form></form> (see code below) that displays in a modal overtop a Google Sheet the user has open. The HTML form has <input type="file" name="..."> in it, and when I click to send the form object, I successfully upload the file if this Google Apps Script is "bound" to a specific Sheets file (and was written using the Tools > Script Editor... menu).

If I save the script as a standalone script and then test it (installed and enabled) on a Sheets file of my choosing, then the <form>'s onclick action and the attempt to call google.script.run.aServerFunction(...) causes a "NetworkError: Connection failure due to HTTP 403". To clarify this is what I mean by creating a standalone script and testing it on a Sheets file: https://developers.google.com/apps-script/add-ons/#understand_the_development_cycle. In earlier code iterations I alternatively got a authorization scriptError of some kind. Same error when script is published privately for testers to use on a Sheet. Unfortunately, I think I need this as a standalone script that is later publishable as an add-on- not a side script bound to a single Sheet using the Tools > Script Editor... menu.

My first post to Stack Overflow- please forgive any jargon or typography mistakes, and thank you!

HTML adapted from tutorials:

```<code>    <!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
    </script>
    <script>
        function failed(event) {
          $("div.response").text(event);
          //google.script.run.selectStuff();
          //google.script.host.close();
        }
      </script>
  </head>
  <body>
    <form id="myForm">

    <label>Your Name</label>
    <input type="text" name="myName">

    <label>Pick a file</label>
    <input type="file" name="myFile">

    <input type="submit" value="Upload File"
               onclick="google.script.run.withFailureHandler(failed)
                        .uploadFiles(this.parentNode);
                        return false;">
</form>
<div class="response"></div>
  </body>

</html>
</code>```

In the code.gs:

```<code>function uploadFiles(formObject) {
  /*var sheet1 = SpreadsheetApp.getActiveSheet();
  sheet1.setActiveRange(sheet1.getRange(2, 2, 4, 4));

  var formBlob = formObject.myFile;
  var driveFile = DriveApp.createFile(formBlob);
  driveFile.addEditor("...");
  SpreadsheetApp.getActive().toast(driveFile.getUrl());
  sheet1.getRange(1,1,1,1).setValue(driveFile.getUrl());
  return driveFile.getUrl();*/

  return "it worked";
}
</code>```

答:
I believe the reason you are getting the HTTP 403 error is because form DOM elements are illegal arguments in google.script.run.myfunction(...) in sheet addons. Even though they are mentioned here as legal parameters here, I think add-on have the added restriction of not being able to pass any kind of DOM elements.

The solution I came up with is to convert the uploaded file to base64 encode string using Filereader.readAsDataUrl() function in native javascript and passing the string to google script and converting it back to a file to be uploaded into google drive.
The base64 encode string starts like this:

data:application/pdf;base64,JVBERi0xLjMKJcTl8uXrp/Og0MTG....

GAS

```<code>function uploadFiles(formObject) {
  // extract contentType from the encoded string
  var contentType = formObject.split(",")[0].split(";")[0].split(":")[1]
  // New Blob(data,contentType,name)
  // Use base64decode to get file data
  var blob = Utilities.newBlob(Utilities.base64Decode(formObject.split(",")[1]), contentType, "trial")
  var driveFile = DriveApp.getFolderById("your Folder ID here").createFile(blob);
  //return contentType, can be anything you like
  return blob.getContentType()
}
</code>```

HTML script

```<code><!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
    </script>

  </head>
  <body>
    <form id="myForm">

    <label>Your Name</label>
    <input type="text" name="myName">

    <label>Pick a file</label>
    <input type="file" id = "filemy" name="myFile">

    <input type="button" value="Upload File"
               onclick="upload(this.parentNode)">
</form>
<div class="response"></div>
  </body>
  <script>
        function failed(event) {
          $("div.response").text(event);
          //google.script.run.selectStuff();
          //google.script.host.close();
        }

        function upload(frmData){
        var file = document.getElementById("filemy").files[0]
        var reader = new FileReader()
        //reader.onload is triggered when readAsDataURL is has finished encoding
        //This will take a bit of time, so be patient
        reader.onload = function(event) {
        // The file's text will be printed here
        console.log("File being Uploaded")
        //console.log(event.target.result)
        google.script.run.withFailureHandler(failed).withSuccessHandler(failed)
                        .uploadFiles(event.target.result);
        };

        reader.readAsDataURL(file);
        console.log(reader.result)
        }
      </script>

</html>
</code>```

Final notes: I have not extensively tested the code, I have got it to work with a pdf file and an image/png file with a  Maximun size of 2.6MB. So please try these 2 file types out before going on to further types of file!
Also, files do take a while to upload so be patient(~5-10sec). Especially since there is no progress bar to show the upload progress, it feels like nothing is happening.

Hope that helps!

Body:
To upload a local file to Google Drive, I have an HTML <form></form> (see code below) that displays in a modal overtop a Google Sheet the user has open. The HTML form has <input type="file" name="..."> in it, and when I click to send the form object, I successfully upload the file if this Google Apps Script is "bound" to a specific Sheets file (and was written using the Tools > Script Editor... menu).

If I save the script as a standalone script and then test it (installed and enabled) on a Sheets file of my choosing, then the <form>'s onclick action and the attempt to call google.script.run.aServerFunction(...) causes a "NetworkError: Connection failure due to HTTP 403". To clarify this is what I mean by creating a standalone script and testing it on a Sheets file: https://developers.google.com/apps-script/add-ons/#understand_the_development_cycle. In earlier code iterations I alternatively got a authorization scriptError of some kind. Same error when script is published privately for testers to use on a Sheet. Unfortunately, I think I need this as a standalone script that is later publishable as an add-on- not a side script bound to a single Sheet using the Tools > Script Editor... menu.

My first post to Stack Overflow- please forgive any jargon or typography mistakes, and thank you!

HTML adapted from tutorials:

    <!DOCTYPE html>

    <base target="_top">
    <link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">

    <form id="myForm">

    Your Name
    <input type="text" name="myName">

    Pick a file
    <input type="file" name="myFile">

    <input type="submit" value="Upload File"
               onclick="google.script.run.withFailureHandler(failed)
                        .uploadFiles(this.parentNode);
                        return false;">
</form>

In the code.gs:

function uploadFiles(formObject) {
  /*var sheet1 = SpreadsheetApp.getActiveSheet();
  sheet1.setActiveRange(sheet1.getRange(2, 2, 4, 4));

  var formBlob = formObject.myFile;
  var driveFile = DriveApp.createFile(formBlob);
  driveFile.addEditor("...");
  SpreadsheetApp.getActive().toast(driveFile.getUrl());
  sheet1.getRange(1,1,1,1).setValue(driveFile.getUrl());
  return driveFile.getUrl();*/

  return "it worked";
}

Body:
I believe the reason you are getting the HTTP 403 error is because form DOM elements are illegal arguments in google.script.run.myfunction(...) in sheet addons. Even though they are mentioned here as legal parameters here, I think add-on have the added restriction of not being able to pass any kind of DOM elements.

The solution I came up with is to convert the uploaded file to base64 encode string using Filereader.readAsDataUrl() function in native javascript and passing the string to google script and converting it back to a file to be uploaded into google drive.
The base64 encode string starts like this:

data:application/pdf;base64,JVBERi0xLjMKJcTl8uXrp/Og0MTG....

GAS

function uploadFiles(formObject) {
  // extract contentType from the encoded string
  var contentType = formObject.split(",")[0].split(";")[0].split(":")[1]
  // New Blob(data,contentType,name)
  // Use base64decode to get file data
  var blob = Utilities.newBlob(Utilities.base64Decode(formObject.split(",")[1]), contentType, "trial")
  var driveFile = DriveApp.getFolderById("your Folder ID here").createFile(blob);
  //return contentType, can be anything you like
  return blob.getContentType()
}

HTML script

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
    </script>

  </head>
  <body>
    <form id="myForm">

    <label>Your Name</label>
    <input type="text" name="myName">

    <label>Pick a file</label>
    <input type="file" id = "filemy" name="myFile">

    <input type="button" value="Upload File"
               onclick="upload(this.parentNode)">
</form>
<div class="response"></div>
  </body>
  <script>
        function failed(event) {
          $("div.response").text(event);
          //google.script.run.selectStuff();
          //google.script.host.close();
        }

        function upload(frmData){
        var file = document.getElementById("filemy").files[0]
        var reader = new FileReader()
        //reader.onload is triggered when readAsDataURL is has finished encoding
        //This will take a bit of time, so be patient
        reader.onload = function(event) {
        // The file's text will be printed here
        console.log("File being Uploaded")
        //console.log(event.target.result)
        google.script.run.withFailureHandler(failed).withSuccessHandler(failed)
                        .uploadFiles(event.target.result);
        };

        reader.readAsDataURL(file);
        console.log(reader.result)
        }
      </script>

</html>

Final notes: I have not extensively tested the code, I have got it to work with a pdf file and an image/png file with a  Maximun size of 2.6MB. So please try these 2 file types out before going on to further types of file!
Also, files do take a while to upload so be patient(~5-10sec). Especially since there is no progress bar to show the upload progress, it feels like nothing is happening.

Hope that helps!


问:
How to show and hide menu based on start and scroll
I have two menus on a page, I am trying to show the one when the page is loaded and the other when there is a scroll.
This is my page Link

I would like to show the white part when position is at the top
and the blue part when there is a scroll past the top position

This is what am trying presently

```<code> <script type="text/javascript" src="//code.jquery.com/jquery-git.js"></script>
<script type='text/javascript'>//<![CDATA[
$(function(){
// Hide Header on on scroll down
var didScroll;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $('header').outerHeight();

$(window).scroll(function(event){
    didScroll = true;
});

setInterval(function() {
    if (didScroll) {
        hasScrolled();
        didScroll = false;
    }
}, 250);

function hasScrolled() {
    var st = $(this).scrollTop();

    // Make sure they scroll more than delta
    if(Math.abs(lastScrollTop - st) <= delta)
        return;

    // If they scrolled down and are past the navbar, add class .nav-up.
    // This is necessary so you never see what is "behind" the navbar.
    if (st > lastScrollTop && st > navbarHeight){
        // Scroll Down
        $('header').removeClass('nav-bar-below op-page-header cf').addClass('banner include-nav');
    } else {
        // Scroll Up
        if(st + $(window).height() < $(document).height()) {
            $('header').removeClass('banner include-nav').addClass('nav-bar-below op-page-header cf');
        }
    }

    lastScrollTop = st;
}
});//]]>

</script>
</code>```

can some one please help its not working for me

答:
You can just detect if the scroll is at the top of the page or not whenever scroll event fired. if yes, show white header, and vice versa

```<code>$(window).scroll( function() {
    var scrollPosition = $(window).scrollTop();

    if(scrollPosition === 0) {
        //show white header
    }
    else {
        //show blue header
    }
}
</code>```

Of course you have to make sure when page first load, it show the white one first (use css). since the code above won't run Until user do scroll (fire this event)

*EDIT

for this :
"and the blue part when there is a scroll past the top position"

you can try this plugin
http://stickyjs.com/

Body:
I have two menus on a page, I am trying to show the one when the page is loaded and the other when there is a scroll.
This is my page Link

I would like to show the white part when position is at the top
and the blue part when there is a scroll past the top position

This is what am trying presently

can some one please help its not working for me

Body:
You can just detect if the scroll is at the top of the page or not whenever scroll event fired. if yes, show white header, and vice versa

$(window).scroll( function() {
    var scrollPosition = $(window).scrollTop();

    if(scrollPosition === 0) {
        //show white header
    }
    else {
        //show blue header
    }
}

Of course you have to make sure when page first load, it show the white one first (use css). since the code above won't run Until user do scroll (fire this event)

*EDIT

for this :
"and the blue part when there is a scroll past the top position"

you can try this plugin
http://stickyjs.com/


问:
freecodecamp Golf Code
I am trying to solve Golf Code challenge in freecodecamp and I can't really figure out what is wrong with my code
here is the direct link. Link contains the code I am trying to run, just visit the link.

My JS:

```<code>function golfScore(par, strokes) {
    if(strokes == 1) return "Hole-in-one!";
    else if(strokes <= par -2) return "Eagle";
    else if(strokes === par -1) return "Birdie";
    else if(strokes === par) return "Par";
    else if(strokes === par + 1) return "Bogey";
    else if(strokes === par + 2) return "Double Bogey";
    else if(strokes >= par + 3) return "Go Home";

return "Change Me";
}
golfScore(5, 4);
</code>```

Requirement:

In the game of golf each hole has a par meaning the average number of strokes a golfer is expected to make in order to sink the ball in a hole to complete the play. Depending on how far above or below par your strokes are, there is a different nickname.

Your function will be passed par and strokes arguments. Return the correct string according to this table which lists the strokes in order of priority; top (highest) to bottom (lowest):

Strokes Return:

```<code>1                  "Hole-in-one!"
<= par - 2         "Eagle"
par - 1            "Birdie"
par                "Par"
par + 1            "Bogey"
par + 2            "Double Bogey"
>= par + 3         "Go Home!"
</code>```

Thanks for help in Advance.

答:
I hate nested if-else statements... Unless they made it in one shot or they are more than 2 shots over par, adding (strokes - par) to the index of "Par" in such an array will return the applicable score.

ie. Par 4, made in 3. Par = 3 in the array, and 3 - 1 = 2 which is Birdie.

I know this is more complicated than the course asks for, but I really dislike nested if-else...

```<code>function golfScore(par, strokes) {
  var arr = ["Eagle", "Eagle", "Birdie", "Par", "Bogey", "Double Bogey"];

  switch(true) {
    case (strokes == 1): return "Hole-in-one!";
    case (strokes - par > 2): return "Go Home!";
    default: return arr[arr.indexOf("Par") + (strokes - par)];
  }
}

// Change these values to test
golfScore(4, 7);
</code>```

Title: freecodecamp Golf Code

Body:
I am trying to solve Golf Code challenge in freecodecamp and I can't really figure out what is wrong with my code
here is the direct <a href="https://www.freecodecamp.com/challenges/golf-code#?solution=function%20golfScore(par%2C%20strokes)%20%7B%0A%20%20%2F%2F%20Only%20change%20code%20below%20this%20line%0A%20%20if(strokes%20%3D%3D%201)%20return%20%22Hole-in-one!%22%3B%0A%20%20else%20if(strokes%20%3C%3D%20par%20-2)%20return%20%22Eagle%22%3B%0A%20%20else%20if(strokes%20%3D%3D%3D%20par%20-1)%20return%20%22Birdie%22%3B%0A%20%20else%20if(strokes%20%3D%3D%3D%20par)%20return%20%22Par%22%3B%0A%20%20else%20if(strokes%20%3D%3D%3D%20par%20%2B%201)%20return%20%22Bogey%22%3B%0A%20%20else%20if(strokes%20%3D%3D%3D%20par%20%2B%202)%20return%20%22Double%20Bogey%22%3B%0A%20%20else%20if(strokes%20%3E%3D%20par%20%2B%203)%20return%20%22Go%20Home%22%3B%0A%20%20%0A%20%20return%20%22Change%20Me%22%3B%0A%20%20%2F%2F%20Only%20change%20code%20above%20this%20line%0A%7D%0A%0A%2F%2F%20Change%20these%20values%20to%20test%0AgolfScore(5%2C%204)%3B%0A" rel="nofollow noreferrer">link. Link contains the code I am trying to run, just visit the link.

My JS:

function golfScore(par, strokes) {
    if(strokes == 1) return "Hole-in-one!";
    else if(strokes <= par -2) return "Eagle";
    else if(strokes === par -1) return "Birdie";
    else if(strokes === par) return "Par";
    else if(strokes === par + 1) return "Bogey";
    else if(strokes === par + 2) return "Double Bogey";
    else if(strokes >= par + 3) return "Go Home";

return "Change Me";
}
golfScore(5, 4);

Requirement:

In the game of golf each hole has a par meaning the average number of strokes a golfer is expected to make in order to sink the ball in a hole to complete the play. Depending on how far above or below par your strokes are, there is a different nickname.

Your function will be passed par and strokes arguments. Return the correct string according to this table which lists the strokes in order of priority; top (highest) to bottom (lowest):

Strokes Return:

1                  "Hole-in-one!"
<= par - 2         "Eagle"
par - 1            "Birdie"
par                "Par"
par + 1            "Bogey"
par + 2            "Double Bogey"
>= par + 3         "Go Home!"

Thanks for help in Advance.

Body:
I hate nested if-else statements... Unless they made it in one shot or they are more than 2 shots over par, adding (strokes - par) to the index of "Par" in such an array will return the applicable score.

ie. Par 4, made in 3. Par = 3 in the array, and 3 - 1 = 2 which is Birdie.

I know this is more complicated than the course asks for, but I really dislike nested if-else...

function golfScore(par, strokes) {
  var arr = ["Eagle", "Eagle", "Birdie", "Par", "Bogey", "Double Bogey"];

  switch(true) {
    case (strokes == 1): return "Hole-in-one!";
    case (strokes - par > 2): return "Go Home!";
    default: return arr[arr.indexOf("Par") + (strokes - par)];
  }
}

// Change these values to test
golfScore(4, 7);


问:
How to remove multiple rows from mysql table, using an array of IDs in PHP
I'm having trouble using an array to make an sql query delete multiple rows of data at once. Please ignore that I'm using sql injection for now.

EDIT: A somewhat better explanation - my php does not work at all. I have edited it somewhat, after checking the link Sebastian provided in the comments

NOTE: I'm using AngularJS to post

This is my $data structure, from my controller.js function. devicesToDelete is just a simple array, e.g. ["1", "2", "3"]:

```<code>$http.post('./js/removeMultiple.php', { 'devicesToDeleteArray': devicesToDelete })
     .success(function(data) {
          $scope.results = data;
          devicesToDelete = [];
     })
     .error(function(err) {
         $log.error(err);
     })
</code>```

This is the updated php code im having trouble with. On clicking my deleteMultiple button, only the confirm alert fires, the selected items aren't deleted and the console is clear of errors:

```<code><?php

$data = json_decode(file_get_contents("php://input"));

include('config.php');

$sql = "DELETE FROM devices WHERE devID in ( implode(",", $data) )";

$qry = $conn->query($sql);

$sql = "SELECT * FROM devices";

$qry = $conn->query($sql);

$data = array();

if($qry->num_rows > 0){
    while($row = $qry->fetch_object()){
        $data[] = $row;
    }
}else {
    $data[] = null;
}

$conn->close();

echo json_encode($data);
</code>```

EDIT 2: I managed to solve the issue on my own. Here is the solution:

I used .join() on my array on the javascript side to have all of the IDs for deletion be separated by commas (e.g. 1, 2, 3):

```<code>$http.post('./js/removeMultiple.php', { 'devicesToDeleteArray': devicesToDelete.join(", ") })
                    .success(function(data) {
                        $scope.results = data;
                        devicesToDelete = [];
                    })
                    .error(function(err) {
                        $log.error(err);
                    })
</code>```

Then I just added what I completely glanced over in my php code which is the name of the array i was passing into it - devicesToDeleteArray

```<code><?php

$data = json_decode(file_get_contents("php://input"));

include('config.php');

$sql = "DELETE FROM devices WHERE devID in ($data->devicesToDeleteArray)";

$qry = $conn->query($sql);

$sql = "SELECT * FROM devices";

$qry = $conn->query($sql);

$data = array();

if($qry->num_rows > 0){
    while($row = $qry->fetch_object()){
        $data[] = $row;
    }
}else {
    $data[] = null;
}

$conn->close();

echo json_encode($data);
</code>```

答:
here is php code:</p>

```<code><?php
$ids = $_POST['devicesToDeleteArray'];
if(!is_array($data)) {
   $ids = json_decode($data, true);
}
if(!empty($ids)) {
include 'config.php';

$sql  = "DELETE FROM devices WHERE devID in (implode(",", $ids))";
$qry  = $conn->query($sql);
$sql  = "SELECT * FROM devices";
$qry  = $conn->query($sql);
$data = array();
if ($qry->num_rows > 0) {
    while ($row = $qry->fetch_object()) {
        $data[] = $row;
    }
} else {
    $data[] = null;
}
$conn->close();
echo json_encode($data);
</code>```

Body:
I'm having trouble using an array to make an sql query delete multiple rows of data at once. Please ignore that I'm using sql injection for now.

EDIT: A somewhat better explanation - my php does not work at all. I have edited it somewhat, after checking the link Sebastian provided in the comments

NOTE: I'm using AngularJS to post

This is my $data structure, from my controller.js function. devicesToDelete is just a simple array, e.g. ["1", "2", "3"]:

$http.post('./js/removeMultiple.php', { 'devicesToDeleteArray': devicesToDelete })
     .success(function(data) {
          $scope.results = data;
          devicesToDelete = [];
     })
     .error(function(err) {
         $log.error(err);
     })

This is the updated php code im having trouble with. On clicking my deleteMultiple button, only the confirm alert fires, the selected items aren't deleted and the console is clear of errors:

<?php

$data = json_decode(file_get_contents("php://input"));

include('config.php');

$sql = "DELETE FROM devices WHERE devID in ( implode(",", $data) )";

$qry = $conn->query($sql);

$sql = "SELECT * FROM devices";

$qry = $conn->query($sql);

$data = array();

if($qry->num_rows > 0){
    while($row = $qry->fetch_object()){
        $data[] = $row;
    }
}else {
    $data[] = null;
}

$conn->close();

echo json_encode($data);

EDIT 2: I managed to solve the issue on my own. Here is the solution:

I used .join() on my array on the javascript side to have all of the IDs for deletion be separated by commas (e.g. 1, 2, 3):

$http.post('./js/removeMultiple.php', { 'devicesToDeleteArray': devicesToDelete.join(", ") })
                    .success(function(data) {
                        $scope.results = data;
                        devicesToDelete = [];
                    })
                    .error(function(err) {
                        $log.error(err);
                    })

Then I just added what I completely glanced over in my php code which is the name of the array i was passing into it - devicesToDeleteArray

<?php

$data = json_decode(file_get_contents("php://input"));

include('config.php');

$sql = "DELETE FROM devices WHERE devID in ($data->devicesToDeleteArray)";

$qry = $conn->query($sql);

$sql = "SELECT * FROM devices";

$qry = $conn->query($sql);

$data = array();

if($qry->num_rows > 0){
    while($row = $qry->fetch_object()){
        $data[] = $row;
    }
}else {
    $data[] = null;
}

$conn->close();

echo json_encode($data);

Body:
here is php code:

<?php
$ids = $_POST['devicesToDeleteArray'];
if(!is_array($data)) {
   $ids = json_decode($data, true);
}
if(!empty($ids)) {
include 'config.php';

$sql  = "DELETE FROM devices WHERE devID in (implode(",", $ids))";
$qry  = $conn->query($sql);
$sql  = "SELECT * FROM devices";
$qry  = $conn->query($sql);
$data = array();
if ($qry->num_rows > 0) {
    while ($row = $qry->fetch_object()) {
        $data[] = $row;
    }
} else {
    $data[] = null;
}
$conn->close();
echo json_encode($data);


问:
How can I check if a letter in a string is uppercase using the power of TypeScript?
My question is very brief. I am new to TypeScript, been searching around here and there but didn't find yet an answer.

I have this code written in C#

```<code>private bool MaskValidateChar(KeyPressEventArgs e, int index)
{
    string c = e.KeyChar.ToString();
    if (Char.IsUpper(c[0])) //Need to this with TypeScript :-\
    {
        //Do Something....
    }
}
</code>```

When I convert above code into Type script, I can simply write a code something like if (c[0] == c[0].toUpperCase())

I just need to know whether there is a built in method in Typescript to check whether a given character is uppercase. I couldn't find such thing on the internet, but I doubt it.

Please advise.

答:
yes.you can try with linq </p>

```<code>if (yourString.Any(char.IsUpper) &&
    yourString.Any(char.IsLower))
</code>```

Body:
My question is very brief. I am new to TypeScript, been searching around here and there but didn't find yet an answer.

I have this code written in C#

private bool MaskValidateChar(KeyPressEventArgs e, int index)
{
    string c = e.KeyChar.ToString();
    if (Char.IsUpper(c[0])) //Need to this with TypeScript :-\
    {
        //Do Something....
    }
}

When I convert above code into Type script, I can simply write a code something like if (c[0] == c[0].toUpperCase())

I just need to know whether there is a built in method in Typescript to check whether a given character is uppercase. I couldn't find such thing on the internet, but I doubt it.

Please advise.

Body:
yes.you can try with linq

if (yourString.Any(char.IsUpper) &&
    yourString.Any(char.IsLower))


问:
destruction es6 default value in react's props
<ComponentB from="3/1/2016" to="12/1/2016" />

and in componentB's constructor I can do

const { from, to } = this.props but my from to value is optional. I can't do

this.state = { from, to } if they are or null. Any way to set default value for destruction?

I can do if(from && to) {} but just curious what's the best way to handle optional props in react.

答:
You can use any of these two ways:

1. Assign the default values to variable during the destructuring, like this:

```<code>const { from = 'abc', to ='abc' } = this.props;
</code>```

If this.props doesn't contains any key it will take the default value 'abc'.

2. Use defaultProps to assign the default values to props variable, like this:

```<code>ComponentName.defaultProps = {
    from: 'abc',
    to: 'abc'
};
</code>```

All the props passed from parent component will be assigned these default values.

Check this example:

var obj = {a: 1, b: 2, c: 3};

var {a=5, b=5, d=5} = obj;

console.log(a, b, d);```

Body:
You can use any of these two ways:

1. Assign the default values to variable during the destructuring, like this:

const { from = 'abc', to ='abc' } = this.props;

If this.props doesn't contains any key it will take the default value 'abc'.

2. Use defaultProps to assign the default values to props variable, like this:

ComponentName.defaultProps = {
    from: 'abc',
    to: 'abc'
};

All the props passed from parent component will be assigned these default values.

Check this example:

var obj = {a: 1, b: 2, c: 3};

var {a=5, b=5, d=5} = obj;

console.log(a, b, d);


问:
Automatically create One-To-One relation when using reverse field
When creating two instances of a model and connecting them using a OneToOneField, the connection gets created and saved automatically at object creation:

```<code>from django.db import models

class MyModel(models.Model):
    name = models.CharField(primary_key=True, max_length=255)
    next = models.OneToOneField('self', on_delete=models.SET_NULL, related_name='prev', null=True, blank=True)

>>> m2 = MyModel.objects.create(name="2")
>>> m1 = MyModel.objects.create(name="1", next=m2)
>>> m2.prev
<MyModel: 1>
>>> m2.refresh_from_db()
>>> m2.prev
<MyModel: 2>
</code>```

However, when creating the same connection but using the reverse field, the creation is also done automatically but not the save.

```<code>>>> m1 = MyModel.objects.create(name="1")
>>> m2 = MyModel.objects.create(name="2", prev=m1)
>>> m1.next
<MyModel: 2>
>>> m1.refresh_from_db()
>>> m1.next
</code>```

Note that the last statement doesn't print anything since it returns None

How can I have it always save the relation when created using the reverse field without having to manually use .save() each time?

答:
This is a terrible idea.

You will confuse everyone looking at your code.

I'm even surprised that MyModel.objects.create works instead of throwing an invalid keyword argument. I'll probably open a ticked for this.

When you call:

```<code>m2 = MyModel.objects.create(name="2", prev=m1)
</code>```

in order to work as you expect, the .create method needs to call save on the m1 instance, because m1 is the instance that holds the relation (via next)

Who would expect that? You are hiding functionality. Some quotes from PEP 20

Explicit is better than implicit.

There should be one-- and preferably only one --obvious way to do it.

My advice is to change the relation to:

```<code>class MyModel(models.Model):
    name = models.CharField(primary_key=True, max_length=255)
    prev = models.OneToOneField('self',
                                null=True,
                                blank=True,
                                related_name='next',
                                on_delete=models.SET_NULL)
</code>```

Because, its much more likely to know what prev is at a creation time.

Body:
When creating two instances of a model and connecting them using a OneToOneField, the connection gets created and saved automatically at object creation:

from django.db import models

class MyModel(models.Model):
    name = models.CharField(primary_key=True, max_length=255)
    next = models.OneToOneField('self', on_delete=models.SET_NULL, related_name='prev', null=True, blank=True)

>>> m2 = MyModel.objects.create(name="2")
>>> m1 = MyModel.objects.create(name="1", next=m2)
>>> m2.prev
<MyModel: 1>
>>> m2.refresh_from_db()
>>> m2.prev
<MyModel: 2>

However, when creating the same connection but using the reverse field, the creation is also done automatically but not the save.

>>> m1 = MyModel.objects.create(name="1")
>>> m2 = MyModel.objects.create(name="2", prev=m1)
>>> m1.next
<MyModel: 2>
>>> m1.refresh_from_db()
>>> m1.next

Note that the last statement doesn't print anything since it returns None

How can I have it always save the relation when created using the reverse field without having to manually use .save() each time?

Body:
This is a terrible idea.

You will confuse everyone looking at your code.

I'm even surprised that MyModel.objects.create works instead of throwing an invalid keyword argument. I'll probably open a ticked for this.

When you call:

m2 = MyModel.objects.create(name="2", prev=m1)

in order to work as you expect, the .create method needs to call save on the m1 instance, because m1 is the instance that holds the relation (via next)

Who would expect that? You are hiding functionality. Some quotes from PEP 20

Explicit is better than implicit.

There should be one-- and preferably only one --obvious way to do it.

My advice is to change the relation to:

class MyModel(models.Model):
    name = models.CharField(primary_key=True, max_length=255)
    prev = models.OneToOneField('self',
                                null=True,
                                blank=True,
                                related_name='next',
                                on_delete=models.SET_NULL)

Because, its much more likely to know what prev is at a creation time.


问:
Concurrently sum the inner dictionary in the Dict{Tuple, Dict{String,Int64}} in a single loop
Given a countmap object that counts words in a text:

```<code>vocab_counter = countmap(split("the lazy fox jumps over the brown dog"))
</code>```

[out]:

```<code>Dict{SubString{String},Int64} with 7 entries:
  "brown" => 1
  "lazy"  => 1
  "jumps" => 1
  "the"   => 2
  "fox"   => 1
  "over"  => 1
  "dog"   => 1
</code>```

And to get a character bigram counter, per word:

```<code>ngram_word_counter = Dict{Tuple,Dict}()
for (word, count) in vocab_counter
    for ng in ngrams(word, n) # bigrams.
        if ! haskey(ngram_word_counter, ng) || ! haskey(ngram_word_counter[ng], word)
            ngram_word_counter[ng] = Dict{String,Int64}()
            ngram_word_counter[ng][word] = 0
        end
        ngram_word_counter[ng][word] += count
    end
end
</code>```

[ngram_word_counter]:

```<code>Dict{Tuple,Dict} with 20 entries:
  ('b','r') => Dict("brown"=>1)
  ('t','h') => Dict("the"=>2)
  ('o','w') => Dict("brown"=>1)
  ('z','y') => Dict("lazy"=>1)
  ('o','g') => Dict("dog"=>1)
  ('u','m') => Dict("jumps"=>1)
  ('o','x') => Dict("fox"=>1)
  ('e','r') => Dict("over"=>1)
  ('a','z') => Dict("lazy"=>1)
  ('p','s') => Dict("jumps"=>1)
  ('h','e') => Dict("the"=>2)
  ('d','o') => Dict("dog"=>1)
  ('w','n') => Dict("brown"=>1)
  ('m','p') => Dict("jumps"=>1)
  ('l','a') => Dict("lazy"=>1)
  ('o','v') => Dict("over"=>1)
  ('v','e') => Dict("over"=>1)
  ('r','o') => Dict("brown"=>1)
  ('f','o') => Dict("fox"=>1)
  ('j','u') => Dict("jumps"=>1)
</code>```

With the Dict{Tuple, Dict{String,Int64}} object, I would need to re-loop the ngram_word_counter to get the ngram_counter without the word, i.e. Dict{Tuple,Int64}:

```<code>ngram_counter = Dict{Tuple,Int64}()
for ng in keys(ngram_word_counter)
    ngram_counter[ng] = sum(values(ngram_word_counter[ng]))
end
</code>```

[ngram_counter]:

```<code>Dict{Tuple,Int64} with 20 entries:
  ('b','r') => 1
  ('t','h') => 2
  ('o','w') => 1
  ('z','y') => 1
  ('o','g') => 1
  ('u','m') => 1
  ('o','x') => 1
  ('e','r') => 1
  ('a','z') => 1
  ('p','s') => 1
  ('h','e') => 2
  ('d','o') => 1
  ('w','n') => 1
  ('m','p') => 1
  ('l','a') => 1
  ('o','v') => 1
  ('v','e') => 1
  ('r','o') => 1
  ('f','o') => 1
  ('j','u') => 1
</code>```

Currently, to get both object, I could do an ad-hoc 2nd count with:

```<code>function compute_statistics(vocab_counter, n)
    ngram_word_counter = Dict{Tuple,Dict}()
    for (word, count) in vocab_counter
        for ng in ngrams(word, n) # bigrams.
            if ! haskey(ngram_word_counter, ng) || ! haskey(ngram_word_counter[ng], word)
                ngram_word_counter[ng] = Dict{String,Int64}()
                ngram_word_counter[ng][word] = 0
            end
            ngram_word_counter[ng][word] += count
        end
    end
    ngram_counter = Dict{Tuple,Int64}()
    for ng in keys(ngram_word_counter)
        ngram_counter[ng] = sum(values(ngram_word_counter[ng]))
    end
    return ngram_word_counter, ngram_counter
end
</code>```

Or concurrently update both ngram_word_counter and ngram_counter at the first loop:

```<code>function compute_statistics(vocab_counter, n)
    ngram_word_counter = Dict{Tuple,Dict}()
    ngram_counter = Dict{Tuple,Int64}()
    for (word, count) in vocab_counter
        for ng in ngrams(word, n) # bigrams.
            if ! haskey(ngram_word_counter, ng) || ! haskey(ngram_word_counter[ng], word)
                ngram_word_counter[ng] = Dict{String,Int64}()
                ngram_word_counter[ng][word] = 0
            end
            ngram_word_counter[ng][word] += count
            ngram_counter[ng] += 1
        end
    end
    return ngram_word_counter, ngram_counter
end

ngram_word_counter, ngram_counter
</code>```

But I'm getting a KeyError, when updating ngram_counter:

```<code>KeyError: key ('b','r') not found
</code>```

I've added an additional check and it worked:

```<code>function compute_statistics(vocab_counter, n)
    ngram_word_counter = Dict{Tuple,Dict}()
    ngram_counter = Dict{Tuple,Int64}()
    for (word, count) in vocab_counter
        for ng in ngrams(word, n) # bigrams.
            if ! haskey(ngram_word_counter, ng) || ! haskey(ngram_word_counter[ng], word)
                ngram_word_counter[ng] = Dict{String,Int64}()
                ngram_word_counter[ng][word] = 0
            end
            if !haskey(ngram_counter, ng)
                ngram_counter[ng] = 0
            end
            ngram_word_counter[ng][word] += count
            ngram_counter[ng] += 1
        end
    end
    return ngram_word_counter, ngram_counter
end

ngram_word_counter, ngram_counter
</code>```

[out]:

```<code>(Dict{Tuple,Dict}(Pair{Tuple,Dict}(('b','r'),Dict("brown"=>1)),Pair{Tuple,Dict}(('t','h'),Dict("the"=>2)),Pair{Tuple,Dict}(('o','w'),Dict("brown"=>1)),Pair{Tuple,Dict}(('z','y'),Dict("lazy"=>1)),Pair{Tuple,Dict}(('o','g'),Dict("dog"=>1)),Pair{Tuple,Dict}(('u','m'),Dict("jumps"=>1)),Pair{Tuple,Dict}(('o','x'),Dict("fox"=>1)),Pair{Tuple,Dict}(('e','r'),Dict("over"=>1)),Pair{Tuple,Dict}(('a','z'),Dict("lazy"=>1)),Pair{Tuple,Dict}(('p','s'),Dict("jumps"=>1))…),Dict{Tuple,Int64}(Pair{Tuple,Int64}(('b','r'),1),Pair{Tuple,Int64}(('t','h'),1),Pair{Tuple,Int64}(('o','w'),1),Pair{Tuple,Int64}(('z','y'),1),Pair{Tuple,Int64}(('o','g'),1),Pair{Tuple,Int64}(('u','m'),1),Pair{Tuple,Int64}(('o','x'),1),Pair{Tuple,Int64}(('e','r'),1),Pair{Tuple,Int64}(('a','z'),1),Pair{Tuple,Int64}(('p','s'),1)…))
</code>```

Is there a way to concurrently sum the inner dictionary in the Dict{Tuple, Dict{String,Int64}} in a single loop?

答:
Not sure if this answers the question, but you can make compute_statistics cleaner as follows:

```<code>function compute_statistics(vocab_counter, n)
    ngram_word_counter = Dict{Tuple,Dict{String,Int}}()
    ngram_counter = Dict{Tuple,Int}()
    for (word, count) in vocab_counter, ng in ngrams(word,n)
        ngram_word_counter[ng] = get(ngram_word_counter,ng,Dict{String,Int}())
        ngram_word_counter[ng][word] = get(ngram_word_counter[ng],word,0)+count
        ngram_counter[ng] = get(ngram_counter,ng,0)+count
    end
    return ngram_word_counter, ngram_counter
end
</code>```

(this uses get to avoid haskey and shorter for syntax)

Another way to get ngram_counter calculated from ngram_word_counter is:

```<code>ngram_counter = map(x->x[1]=>sum(values(x[2])),ngram_word_counter)
</code>```

or

```<code>ngram_counter = Dict(k=>sum(values(d)) for (k,d) in ngram_word_counter)
</code>```

Body:
Given a countmap object that counts words in a text:

vocab_counter = countmap(split("the lazy fox jumps over the brown dog"))

[out]:

Dict{SubString{String},Int64} with 7 entries:
  "brown" => 1
  "lazy"  => 1
  "jumps" => 1
  "the"   => 2
  "fox"   => 1
  "over"  => 1
  "dog"   => 1

And to get a character bigram counter, per word:

ngram_word_counter = Dict{Tuple,Dict}()
for (word, count) in vocab_counter
    for ng in ngrams(word, n) # bigrams.
        if ! haskey(ngram_word_counter, ng) || ! haskey(ngram_word_counter[ng], word)
            ngram_word_counter[ng] = Dict{String,Int64}()
            ngram_word_counter[ng][word] = 0
        end
        ngram_word_counter[ng][word] += count
    end
end

[ngram_word_counter]:

Dict{Tuple,Dict} with 20 entries:
  ('b','r') => Dict("brown"=>1)
  ('t','h') => Dict("the"=>2)
  ('o','w') => Dict("brown"=>1)
  ('z','y') => Dict("lazy"=>1)
  ('o','g') => Dict("dog"=>1)
  ('u','m') => Dict("jumps"=>1)
  ('o','x') => Dict("fox"=>1)
  ('e','r') => Dict("over"=>1)
  ('a','z') => Dict("lazy"=>1)
  ('p','s') => Dict("jumps"=>1)
  ('h','e') => Dict("the"=>2)
  ('d','o') => Dict("dog"=>1)
  ('w','n') => Dict("brown"=>1)
  ('m','p') => Dict("jumps"=>1)
  ('l','a') => Dict("lazy"=>1)
  ('o','v') => Dict("over"=>1)
  ('v','e') => Dict("over"=>1)
  ('r','o') => Dict("brown"=>1)
  ('f','o') => Dict("fox"=>1)
  ('j','u') => Dict("jumps"=>1)

With the Dict{Tuple, Dict{String,Int64}} object, I would need to re-loop the ngram_word_counter to get the ngram_counter without the word, i.e. Dict{Tuple,Int64}:

ngram_counter = Dict{Tuple,Int64}()
for ng in keys(ngram_word_counter)
    ngram_counter[ng] = sum(values(ngram_word_counter[ng]))
end

[ngram_counter]:

Dict{Tuple,Int64} with 20 entries:
  ('b','r') => 1
  ('t','h') => 2
  ('o','w') => 1
  ('z','y') => 1
  ('o','g') => 1
  ('u','m') => 1
  ('o','x') => 1
  ('e','r') => 1
  ('a','z') => 1
  ('p','s') => 1
  ('h','e') => 2
  ('d','o') => 1
  ('w','n') => 1
  ('m','p') => 1
  ('l','a') => 1
  ('o','v') => 1
  ('v','e') => 1
  ('r','o') => 1
  ('f','o') => 1
  ('j','u') => 1

Currently, to get both object, I could do an ad-hoc 2nd count with:

function compute_statistics(vocab_counter, n)
    ngram_word_counter = Dict{Tuple,Dict}()
    for (word, count) in vocab_counter
        for ng in ngrams(word, n) # bigrams.
            if ! haskey(ngram_word_counter, ng) || ! haskey(ngram_word_counter[ng], word)
                ngram_word_counter[ng] = Dict{String,Int64}()
                ngram_word_counter[ng][word] = 0
            end
            ngram_word_counter[ng][word] += count
        end
    end
    ngram_counter = Dict{Tuple,Int64}()
    for ng in keys(ngram_word_counter)
        ngram_counter[ng] = sum(values(ngram_word_counter[ng]))
    end
    return ngram_word_counter, ngram_counter
end

Or concurrently update both ngram_word_counter and ngram_counter at the first loop:

function compute_statistics(vocab_counter, n)
    ngram_word_counter = Dict{Tuple,Dict}()
    ngram_counter = Dict{Tuple,Int64}()
    for (word, count) in vocab_counter
        for ng in ngrams(word, n) # bigrams.
            if ! haskey(ngram_word_counter, ng) || ! haskey(ngram_word_counter[ng], word)
                ngram_word_counter[ng] = Dict{String,Int64}()
                ngram_word_counter[ng][word] = 0
            end
            ngram_word_counter[ng][word] += count
            ngram_counter[ng] += 1
        end
    end
    return ngram_word_counter, ngram_counter
end

ngram_word_counter, ngram_counter

But I'm getting a KeyError, when updating ngram_counter:

KeyError: key ('b','r') not found

I've added an additional check and it worked:

function compute_statistics(vocab_counter, n)
    ngram_word_counter = Dict{Tuple,Dict}()
    ngram_counter = Dict{Tuple,Int64}()
    for (word, count) in vocab_counter
        for ng in ngrams(word, n) # bigrams.
            if ! haskey(ngram_word_counter, ng) || ! haskey(ngram_word_counter[ng], word)
                ngram_word_counter[ng] = Dict{String,Int64}()
                ngram_word_counter[ng][word] = 0
            end
            if !haskey(ngram_counter, ng)
                ngram_counter[ng] = 0
            end
            ngram_word_counter[ng][word] += count
            ngram_counter[ng] += 1
        end
    end
    return ngram_word_counter, ngram_counter
end

ngram_word_counter, ngram_counter

[out]:

(Dict{Tuple,Dict}(Pair{Tuple,Dict}(('b','r'),Dict("brown"=>1)),Pair{Tuple,Dict}(('t','h'),Dict("the"=>2)),Pair{Tuple,Dict}(('o','w'),Dict("brown"=>1)),Pair{Tuple,Dict}(('z','y'),Dict("lazy"=>1)),Pair{Tuple,Dict}(('o','g'),Dict("dog"=>1)),Pair{Tuple,Dict}(('u','m'),Dict("jumps"=>1)),Pair{Tuple,Dict}(('o','x'),Dict("fox"=>1)),Pair{Tuple,Dict}(('e','r'),Dict("over"=>1)),Pair{Tuple,Dict}(('a','z'),Dict("lazy"=>1)),Pair{Tuple,Dict}(('p','s'),Dict("jumps"=>1))…),Dict{Tuple,Int64}(Pair{Tuple,Int64}(('b','r'),1),Pair{Tuple,Int64}(('t','h'),1),Pair{Tuple,Int64}(('o','w'),1),Pair{Tuple,Int64}(('z','y'),1),Pair{Tuple,Int64}(('o','g'),1),Pair{Tuple,Int64}(('u','m'),1),Pair{Tuple,Int64}(('o','x'),1),Pair{Tuple,Int64}(('e','r'),1),Pair{Tuple,Int64}(('a','z'),1),Pair{Tuple,Int64}(('p','s'),1)…))

Is there a way to concurrently sum the inner dictionary in the Dict{Tuple, Dict{String,Int64}} in a single loop?

Body:
Not sure if this answers the question, but you can make compute_statistics cleaner as follows:

function compute_statistics(vocab_counter, n)
    ngram_word_counter = Dict{Tuple,Dict{String,Int}}()
    ngram_counter = Dict{Tuple,Int}()
    for (word, count) in vocab_counter, ng in ngrams(word,n)
        ngram_word_counter[ng] = get(ngram_word_counter,ng,Dict{String,Int}())
        ngram_word_counter[ng][word] = get(ngram_word_counter[ng],word,0)+count
        ngram_counter[ng] = get(ngram_counter,ng,0)+count
    end
    return ngram_word_counter, ngram_counter
end

(this uses get to avoid haskey and shorter for syntax)

Another way to get ngram_counter calculated from ngram_word_counter is:

ngram_counter = map(x->x[1]=>sum(values(x[2])),ngram_word_counter)

or

ngram_counter = Dict(k=>sum(values(d)) for (k,d) in ngram_word_counter)


问:
PHP preg_replace in javascript
I had working preg_replace in PHP, but I had to move it to JavaScript code and it doesn't work there. I've searched here in topics, but haven't found working solution for me...
My PHP looked like:

```<code>preg_replace('/^\d+_/', '', $docTypes);
</code>```

And now, my JS looks like, important thing, var documentTypes is object:

```<code>   var documentTypesObj = {};
   var counter = 0;
   {foreach $documentTypes as $key =>$value}
   documentTypesObj[counter + '_' + {$key}] = {$value};
   counter++;
   {/foreach}

    var documentTypes = documentTypesObj;

    documentTypes = documentTypes.map(d => { return d.replace(/^\d+_/g, "")});

    console.log(documentTypes);
</code>```

Inside var documentTypes are values with prefix, which I have to remove. Values are for example:

```<code>0_xxxx
1_xxxx
2_xxxx
</code>```

Thank you for advices!

答:
```<code><script type="text/javascript">
    documentTypes = '0_xxxx';
    documentTypes = documentTypes.replace(/^\d+_/, '');
    document.write(documentTypes);
</script>
</code>```

Title: PHP preg_replace in javascript

Body:
I had working preg_replace in PHP, but I had to move it to JavaScript code and it doesn't work there. I've searched here in topics, but haven't found working solution for me...
My PHP looked like:

preg_replace('/^\d+_/', '', $docTypes);

And now, my JS looks like, important thing, var documentTypes is object:

   var documentTypesObj = {};
   var counter = 0;
   {foreach $documentTypes as $key =>$value}
   documentTypesObj[counter + '_' + {$key}] = {$value};
   counter++;
   {/foreach}

    var documentTypes = documentTypesObj;

    documentTypes = documentTypes.map(d => { return d.replace(/^\d+_/g, "")});

    console.log(documentTypes);

Inside var documentTypes are values with prefix, which I have to remove. Values are for example:

0_xxxx
1_xxxx
2_xxxx

Thank you for advices!


问:
How to parse json value from server, and display it in tableview cell
```<code>  "Names":[
  {
     "type":"Name",
     "id":{
        "type":"Point",
        "coordinates":[
           80.26483,
           13.08891
        ]
     },
     "properties":{
       "region":"Tamil Nadu",
        "region_gid":"whosonfirst:region:85672245",
        "county":"Chennai",
        "county_gid":"whosonfirst:county:890505403",
        "label":"Chennai, India"
     }
  },
  {
     "type":"Name",
     "id":{
        "type":"Point",
        "coordinates":[
           80.27847,
           13.08784
        ]
     },

 for(NSDictionary * dict in autocompletedata)
             {
                 Autodata *data = [[Autodata alloc]init];

                 NSMutableArray *coordinates =[dict valueForKey:@"geometry"];
                 NSMutableArray *propertiesarray = [dict valueForKey:@"properties"];

                 for(NSDictionary *properties_dict in propertiesarray)
                 {
                     data.searchterm = [properties_dict objectForKey:@"label"];
                 }
                 NSLog(@"searchterm%@",coordinates);
                  NSLog(@"coordinates%@",propertiesarray);

                 [autodataarray addObject:data];

             }
</code>```

Parse json value from server and display it in tableview cell.

I need to show the label and coordinates, region in tableview cell.

However, I have an error. I don't know how to parse it. I was thinking perhaps I can save the id and properties in different array, and from that I can get value of coordinates and label.

答:
```<code>NSArray *YourArray =[Json objectForKey:@"Names"];

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *strlabel =[[[YourArray objectAtIndex:indexPath.row]objectForKey:@"properties"]objectForKey:@"label"];

NSString *strregion =[[[YourArray objectAtIndex:indexPath.row]objectForKey:@"properties"]objectForKey:@"region"];

NSArray *cordintateArray =[[[YourArray objectAtIndex:indexPath.row]ojectForKey:@"id"]objectForKey:@"coordinates"];
}
</code>```

Body:
  "Names":[
  {
     "type":"Name",
     "id":{
        "type":"Point",
        "coordinates":[
           80.26483,
           13.08891
        ]
     },
     "properties":{
       "region":"Tamil Nadu",
        "region_gid":"whosonfirst:region:85672245",
        "county":"Chennai",
        "county_gid":"whosonfirst:county:890505403",
        "label":"Chennai, India"
     }
  },
  {
     "type":"Name",
     "id":{
        "type":"Point",
        "coordinates":[
           80.27847,
           13.08784
        ]
     },

 for(NSDictionary * dict in autocompletedata)
             {
                 Autodata *data = [[Autodata alloc]init];

                 NSMutableArray *coordinates =[dict valueForKey:@"geometry"];
                 NSMutableArray *propertiesarray = [dict valueForKey:@"properties"];

                 for(NSDictionary *properties_dict in propertiesarray)
                 {
                     data.searchterm = [properties_dict objectForKey:@"label"];
                 }
                 NSLog(@"searchterm%@",coordinates);
                  NSLog(@"coordinates%@",propertiesarray);

                 [autodataarray addObject:data];

             }

Parse json value from server and display it in tableview cell.

I need to show the label and coordinates, region in tableview cell.

However, I have an error. I don't know how to parse it. I was thinking perhaps I can save the id and properties in different array, and from that I can get value of coordinates and label.


问:
Typescript enum switch not working
i have the following enum

```<code>enum EditMode {
    View = 0,
    Edit = 1,
    Delete = 2
}
</code>```

Let's assume i have a variable of the enum type

```<code>var editMode = EditMode.Edit;
</code>```

Why does the following code not work (goes straight to default)?

```<code>switch (editMode) {
    case EditMode.Delete:
        ...
        break;
    case EditMode.Edit:
        ...
        break;
    default:
        ...
        break;
    }
</code>```

答:
I also had this problem.  Easy way to get around it: add a + sign before your variable in the switch, i.e.

```<code>switch (+editMode) {
    case EditMode.Delete:
        ...
        break;
    case EditMode.Edit:
        ...
        break;
    default:
        ...
        break;
    }
</code>```

Title: Typescript enum switch not working

Body:
i have the following enum

enum EditMode {
    View = 0,
    Edit = 1,
    Delete = 2
}

Let's assume i have a variable of the enum type

var editMode = EditMode.Edit;

Why does the following code not work (goes straight to default)?

switch (editMode) {
    case EditMode.Delete:
        ...
        break;
    case EditMode.Edit:
        ...
        break;
    default:
        ...
        break;
    }

Body:
I also had this problem.  Easy way to get around it: add a + sign before your variable in the switch, i.e.

switch (+editMode) {
    case EditMode.Delete:
        ...
        break;
    case EditMode.Edit:
        ...
        break;
    default:
        ...
        break;
    }


问:
Getting current session id when session data is stored in the ci_Sessions table
I am using ion auth to handle my authorization to controllers and i am storing session data into the database. I can see the session info is being stored into the database.

I am logged in as admin and i need to update the current session data to show that another user is logged in,in short, i am trying to impersonate a user by updating session user id with a user id i know of.

```<code>$user = $this->ion_auth->user()->row();

echo "```";
//print_r($res);
    echo 'Hello  '.$user->email;
echo "```";

    $this->db->order_by('id', 'DESC');
    $this->db->limit(1);
    $last_session = $this->db->get('ci_sessions')->row_array();

    print_r($last_session['data']);//prints current session data
</code>```

The first echo gets the correct email of logged in user and also the correct session data. My question is, is the this line print_r($last_session['data']);

always going to get me my session data even if multiple users are logged in?.

答:
Another reason why it won't work: The id in the ci_sessions table isn't a simple escalating integer, it's something like this: 5f53811d120de015d8189d72fcfb0a13242b382a. And ordering by the id will simply put into a random order. At most you could try ordering by 'timestamp' instead of id.

I'm not sure if the problem Jeffrey mentions occurs with ion_auth or not however.

Body:
I am using ion auth to handle my authorization to controllers and i am storing session data into the database. I can see the session info is being stored into the database.

I am logged in as admin and i need to update the current session data to show that another user is logged in,in short, i am trying to impersonate a user by updating session user id with a user id i know of.

$user = $this->ion_auth->user()->row();

echo "
";
//print_r($res);
    echo 'Hello  '.$user->email;
echo "
";

    $this->db->order_by('id', 'DESC');
    $this->db->limit(1);
    $last_session = $this->db->get('ci_sessions')->row_array();

    print_r($last_session['data']);//prints current session data

The first echo gets the correct email of logged in user and also the correct session data. My question is, is the this line print_r($last_session['data']);

always going to get me my session data even if multiple users are logged in?.


问:
"textAllCaps=false" does not work for textview?
I am using custom list view with sections. I am using below xml for the section layout

```<code><TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Large Text"
android:textColor="#000000"
android:background="#c3c3e5"
android:id="@+id/tv_li_section"
android:padding="8dp"
android:gravity="center"
android:layout_alignParentTop="true"
android:textStyle="bold"
android:textAllCaps="false" />
</code>```

Here textAllCaps= false is not working for me. Any help would be appreciated.

答:
If you are using AppCompat 23.2.0 android support library then Update for design library 23.2.0+

and You can use this style and define this in xml

```<code><style name="MyCustomTextAppearance" parent="TextAppearance.Design.Tab">
      <item name="textAllCaps">false</item>
      <item name="android:textAllCaps">false</item>
</style>
</code>```

For reference you can see this https://code.google.com/p/android/issues/detail?id=202117

Body:
I am using custom list view with sections. I am using below xml for the section layout

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Large Text"
android:textColor="#000000"
android:background="#c3c3e5"
android:id="@+id/tv_li_section"
android:padding="8dp"
android:gravity="center"
android:layout_alignParentTop="true"
android:textStyle="bold"
android:textAllCaps="false" />

Here textAllCaps= false is not working for me. Any help would be appreciated.

Body:
If you are using AppCompat 23.2.0 android support library then Update for design library 23.2.0+

and You can use this style and define this in xml

<style name="MyCustomTextAppearance" parent="TextAppearance.Design.Tab">
      <item name="textAllCaps">false</item>
      <item name="android:textAllCaps">false</item>
</style>

For reference you can see this https://code.google.com/p/android/issues/detail?id=202117


问:
Angular - getting ng-bind to work on nested directives
I've built a small pattern that recursively creates different sub-directives based on the model. I'm using $compile to build child directives recursively, then append them to the parent.

The directive building itself seems to work just fine, but for some reason, embedded expressions or ng-bind or interpolation doesn't seem to work on nested directive.

Here's a snippet:

```<code>app.directive("child", function ($compile) {
  function getTemplate(depth) {
    if (depth % 2 == 0) {
      return "<even depth='deeper'/>"
    } else {
      return "<odd depth='deeper'/>"
    }
  }
  return {
    scope: {
      depth: "="
    },
    link: function linker($scope, $element) {
      if ($scope.depth == 0) {
        var child = angular.element("<span ng-bind='depth'/>");
        child = $compile(child)($scope);
        $element.append(child);
      } else {
        $scope.deeper = $scope.depth - 1;
        var child = angular.element(getTemplate($scope.depth));
        child = $compile(child)($scope);
        $element.append(child);
      }
    }
  }
})
</code>```

Basically in this test the directive will recursively dive down until the depth reaches 0, then spit out a  element.

The expected result should be a span element with the value of 0. But it doesn't seem to evaluate. Using {{depth}} also results in in a literal html instead of evaluating the contents.

I'm trying to achieve a result of nested <even><odd><even> directives removing the surrounding <child> - directive.

Here's a complete jsFiddle: https://jsfiddle.net/eg1e1aLz/

The resulting DOM should look like this:

<test depth="4" class="ng-isolate-scope">
  <even depth="depth-1" class="ng-scope ng-isolate-scope">
    <odd depth="depth-1" class="ng-scope ng-isolate-scope">
      <even depth="depth-1" class="ng-scope ng-isolate-scope">
        <odd depth="depth-1" class="ng-scope ng-isolate-scope">0</odd>
      </even>
    </odd>
  </even>
</test>```

答:
Based on your comments below and the update to the question, how about the following...

It uses the template function getTemplate to build the structure, and identical directives: odd and even as placeholders for building the functionality.

```<code>var app = angular.module("app", []);

app.directive("test", function($compile) {
  return {
    scope: {
      depth: "="
    },
    link: function linker($scope, $element, $attrs) {

      // template accessible to the child directives
      $scope.getTemplate = function(depth) {
        if (depth <= 0) {
          return "<span ng-bind='depth'/>"; // also bindings like {{depth}} work
        } else if (depth % 2 === 0) {
          return "<even depth='depth-1'></even>"; // bindings like {{depth}} work
        } else {
          return "<odd depth='depth-1'></odd>";
        }
      }

      var child = angular.element($scope.getTemplate($scope.depth));
      $compile(child)($scope);
      $element.append(child);
    }
  }
});
app.directive("odd", function($compile) {
  return {
    scope: {
      depth: "="
    },
    link: function linker($scope, $element) {
      $scope.getTemplate = $scope.$parent.getTemplate; // bring template into current scope
      var child = angular.element($scope.getTemplate($scope.depth));
      $compile(child)($scope);
      $element.append(child);
    }
  }
})
app.directive("even", function($compile) {
  return {
    scope: {
      depth: "=",
    },
    link: function linker($scope, $element) {
      $scope.getTemplate = $scope.$parent.getTemplate; // bring template into current scope
      var child = angular.element($scope.getTemplate($scope.depth));
      $compile(child)($scope);
      $element.append(child);
    }
  }
})

var controller = app.controller("controller", function($scope) {});
</code>```

Updated Fiddle: https://jsfiddle.net/bda411fj/15/

Result:

```<code><test depth="4" class="ng-isolate-scope">
  <even depth="depth-1" class="ng-binding ng-scope ng-isolate-scope">
    <odd depth="depth-1" class="ng-binding ng-scope ng-isolate-scope">
      <even depth="depth-1" class="ng-binding ng-scope ng-isolate-scope">
        <odd depth="depth-1" class="ng-binding ng-scope ng-isolate-scope">
          <span ng-bind="depth" class="ng-binding ng-scope">0</span>
        </odd>
      </even>
    </odd>
  </even>
</test>
</code>```

Body:
I've built a small pattern that recursively creates different sub-directives based on the model. I'm using $compile to build child directives recursively, then append them to the parent.

The directive building itself seems to work just fine, but for some reason, embedded expressions or ng-bind or interpolation doesn't seem to work on nested directive.

Here's a snippet:

app.directive("child", function ($compile) {
  function getTemplate(depth) {
    if (depth % 2 == 0) {
      return "<even depth='deeper'/>"
    } else {
      return "<odd depth='deeper'/>"
    }
  }
  return {
    scope: {
      depth: "="
    },
    link: function linker($scope, $element) {
      if ($scope.depth == 0) {
        var child = angular.element("");
        child = $compile(child)($scope);
        $element.append(child);
      } else {
        $scope.deeper = $scope.depth - 1;
        var child = angular.element(getTemplate($scope.depth));
        child = $compile(child)($scope);
        $element.append(child);
      }
    }
  }
})

Basically in this test the directive will recursively dive down until the depth reaches 0, then spit out a  element.

The expected result should be a span element with the value of 0. But it doesn't seem to evaluate. Using {{depth}} also results in in a literal html instead of evaluating the contents.

I'm trying to achieve a result of nested <even><odd><even> directives removing the surrounding <child> - directive.

Here's a complete jsFiddle: https://jsfiddle.net/eg1e1aLz/

The resulting DOM should look like this:

<test depth="4" class="ng-isolate-scope">
  <even depth="depth-1" class="ng-scope ng-isolate-scope">
    <odd depth="depth-1" class="ng-scope ng-isolate-scope">
      <even depth="depth-1" class="ng-scope ng-isolate-scope">
        <odd depth="depth-1" class="ng-scope ng-isolate-scope">0</odd>
      </even>
    </odd>
  </even>
</test>

Body:
Based on your comments below and the update to the question, how about the following...

It uses the template function getTemplate to build the structure, and identical directives: odd and even as placeholders for building the functionality.

var app = angular.module("app", []);

app.directive("test", function($compile) {
  return {
    scope: {
      depth: "="
    },
    link: function linker($scope, $element, $attrs) {

      // template accessible to the child directives
      $scope.getTemplate = function(depth) {
        if (depth <= 0) {
          return "<span ng-bind='depth'/>"; // also bindings like {{depth}} work
        } else if (depth % 2 === 0) {
          return "<even depth='depth-1'></even>"; // bindings like {{depth}} work
        } else {
          return "<odd depth='depth-1'></odd>";
        }
      }

      var child = angular.element($scope.getTemplate($scope.depth));
      $compile(child)($scope);
      $element.append(child);
    }
  }
});
app.directive("odd", function($compile) {
  return {
    scope: {
      depth: "="
    },
    link: function linker($scope, $element) {
      $scope.getTemplate = $scope.$parent.getTemplate; // bring template into current scope
      var child = angular.element($scope.getTemplate($scope.depth));
      $compile(child)($scope);
      $element.append(child);
    }
  }
})
app.directive("even", function($compile) {
  return {
    scope: {
      depth: "=",
    },
    link: function linker($scope, $element) {
      $scope.getTemplate = $scope.$parent.getTemplate; // bring template into current scope
      var child = angular.element($scope.getTemplate($scope.depth));
      $compile(child)($scope);
      $element.append(child);
    }
  }
})

var controller = app.controller("controller", function($scope) {});

Updated Fiddle: https://jsfiddle.net/bda411fj/15/

Result:

<test depth="4" class="ng-isolate-scope">
  <even depth="depth-1" class="ng-binding ng-scope ng-isolate-scope">
    <odd depth="depth-1" class="ng-binding ng-scope ng-isolate-scope">
      <even depth="depth-1" class="ng-binding ng-scope ng-isolate-scope">
        <odd depth="depth-1" class="ng-binding ng-scope ng-isolate-scope">
          <span ng-bind="depth" class="ng-binding ng-scope">0</span>
        </odd>
      </even>
    </odd>
  </even>
</test>


问:
NSURLSession background transfer not working
I’m trying to download a series of files from server to iOS app, with the intent that the download of these files happen even when the App is in the background mode.

I'm using background transfer provided by NSURLSession and its series of APIs.

I initiated download task when app was running in foreground mode and it gave me expected result as series of download was working good but if I press the home button when series of download is in progress then it will stop immediately and when I go into the app again download shall resume.

If say it in simple words background transfer isn’t even working me.

EDIT

Initially I was testing this in simulator it didn’t work well and someone commented to test the same in real device, so I tested it by connecting real device in debug mode it really worked well and I thought everything was solved but again it gave me a shock that is if I disconnect the device from Xcode and check app, it did not work at all :(

I created a sample application to demonstrate this issue, please download it from here

Note: In this sample application I reinitiated download call in the didFinishDownloadingToURL to simulate series of download files

Can you anyone please help me to solve this?

答:
You have not selected the correct background mode in the Capabilities tab. Check the Background fetch option.

Also, if you are testing in the simulator only, click on Debug -> Simulate Background Fetch in the menu. Otherwise, the background fetch will not be initiated in the simulator.


问:
WWF or WPF for flowcharts?
I want to be able to present my data using a flowchart. I can use wpf to do this, but I dont want to have to code all the arrows, connectors etc - I would like to use a library if possible..

Also could I use windows workflow foundation to do this in any way? Would this help? I get the impression although WWF is workflow, its more to do with the process as opposed to presenting data.

It appears that I might have to obtain a third party control to do this....any recommendations - the component should be able to draw a flowchart at the minimum!

Thanks

答:
I've used Visifire for charting, it's got some pretty great visuals and it's reasonably intuitive and easy to use...give it a go:

visifire.codeplex.com

Hope it helps,

Aj

Title: WWF or WPF for flowcharts?


问:
Integer value converting to floating point
I have two ushort integer. Integers :-32768, 16992

Basically those two values are modbus holding registers integer value. I want to convert to float this integers. When higher/lower order value comes in negative my bit converter logic thorws below exception but Modbus poll shows that value as 35.12

Error:- Value was either too large or too small for a UInt16.

```<code>void Main()
{
    GetSingle(16992,-32768);
}
public static float GetSingle(ushort highOrderValue, ushort lowOrderValue)
{
    return BitConverter.ToSingle(BitConverter.GetBytes(lowOrderValue).Concat(BitConverter.GetBytes(highOrderValue)).ToArray(), 0);
}
</code>```

答:
It seems that you are looking for unchecked in the context (do not throw IntegerOverlow but use silently binary complement value):

```<code>void Main()
{
    // unchecked(...) <- do not throw exception
    GetSingle(16992, unchecked((ushort)-32768));
}
</code>```

Or

```<code>void Main()
{
    unchecked
    {
        GetSingle(16992, -32768);
    }
}
</code>```

The outcome of GetSingle method is

```<code>56.125
</code>```

Body:
I have two ushort integer. Integers :-32768, 16992

Basically those two values are modbus holding registers integer value. I want to convert to float this integers. When higher/lower order value comes in negative my bit converter logic thorws below exception but Modbus poll shows that value as 35.12

Error:- Value was either too large or too small for a UInt16.

void Main()
{
    GetSingle(16992,-32768);
}
public static float GetSingle(ushort highOrderValue, ushort lowOrderValue)
{
    return BitConverter.ToSingle(BitConverter.GetBytes(lowOrderValue).Concat(BitConverter.GetBytes(highOrderValue)).ToArray(), 0);
}

Body:
It seems that you are looking for unchecked in the context (do not throw IntegerOverlow but use silently binary complement value):

void Main()
{
    // unchecked(...) <- do not throw exception
    GetSingle(16992, unchecked((ushort)-32768));
}

Or

void Main()
{
    unchecked
    {
        GetSingle(16992, -32768);
    }
}

The outcome of GetSingle method is

56.125


问:
cv2.pyd not generated when building opencv 3.1 from source on Windows
I've followed the methods shown over here and here to install opencv from source. But despite following it step by step, cv2.pyd is not generated. The reason I'm building from source is because I need to apply a patch in matchers.cpp before building it, which I cannot do if I install from an executable.</p>

答:
I have faced the same problem. And I dont know the reason why it is not being generated. But, the workaround is using the .whl (wheel) file to install the built libraries. So once you have built using Visual Studio, just download the corresponding wheel file from here and then,

go to that location from cmd(Run as administrator)

run pip install (whl file)
Example  : pip install opencv_python-3.2.0+contrib-cp36-cp36m-win32.whl

Thats it. You should see the files in site-packages inside Python/Lib/.
What the whl file does is just move the files to the site packages. It somehow creates the cv2.pyd as well. If someone can explain in depth how that works it will be really helpful!

Hopefully, this works for you.