问:
How to get internal Database/Table content in TYPO3 and display via JavaScript, JQuery or AJAX
I am a beginner in TYPO3 and have to say its very complex but I am struggling my way through.

I just want a simple way to get content from an internal TYPO3 Database Table which I created and forward it to JavaScript/JQuery/AJAX.

My BootstrapTable is working but just displays static content from var data.

I know there are ways from pageType, eID and $GLOBALS['TYPO3_DB']->exec_SELECTgetRows( /* ... */ ); to get the content of the Database Table, but how to forward it to JavaScript and display it?

There should not be another database call with credentials, just a way to the internal Database.

Searching for this answer since 2 days but can't find any easy and plausible answer.
Or do I have to take the long road via eID or pageType?

Edit due to comment:

Here is my JavaScript with bootstrapTable:

```<code>$(function () {
    $('#table').bootstrapTable({
        idField: 'name',
        pagination: true,
        search: true,
        data: data,
        columns: [{
            field: 'name',
            title: 'Name'
        }, {
            field: 'stargazers_count',
            title: 'Stars'
        }, {
            field: 'forks_count',
            title: 'Forks'
        }, {
            field: 'description',
            title: 'Description'
        }],
        onPostBody: function () {
            $('#table').editableTableWidget({editor: $('<textarea>')});
        }
    });
});

var data = [{
        "name": "bootstrap-table",
        "stargazers_count": "526",
        "forks_count": "122",
        "description": "An extended Bootstrap table with radio, checkbox, sort, pagination, and other added features. (supports twitter bootstrap v2 and v3) "
    }, {
        "name": "multiple-select",
        "stargazers_count": "288",
        "forks_count": "150",
        "description": "A jQuery plugin to select multiple elements with checkboxes :)"
    }, {
        "name": "bootstrap-show-password",
        "stargazers_count": "32",
        "forks_count": "11",
        "description": "Show/hide password plugin for twitter bootstrap."
    }, {
        "name": "blog",
        "stargazers_count": "13",
        "forks_count": "4",
        "description": "my blog"
    }, {
        "name": "scutech-redmine",
        "stargazers_count": "6",
        "forks_count": "3",
        "description": "Redmine notification tools for chrome extension."
    }
];
</code>```

And calling it in my html with :

My own created table in mysql database is: tx_table

I want the content of that table to be displayed in my bootstraptable Table

答:
First solution. You can output your results directly into html using
```

Now you can access this data in javascript data.var1

Also keep in mind that your data should be before bootstrapTable initialization.

Body:
I am a beginner in TYPO3 and have to say its very complex but I am struggling my way through.

I just want a simple way to get content from an internal TYPO3 Database Table which I created and forward it to JavaScript/JQuery/AJAX.

My BootstrapTable is working but just displays static content from var data.

I know there are ways from pageType, eID and $GLOBALS['TYPO3_DB']->exec_SELECTgetRows( /* ... */ ); to get the content of the Database Table, but how to forward it to JavaScript and display it?

There should not be another database call with credentials, just a way to the internal Database.

Searching for this answer since 2 days but can't find any easy and plausible answer.
Or do I have to take the long road via eID or pageType?

Edit due to comment:

Here is my JavaScript with bootstrapTable:

$(function () {
    $('#table').bootstrapTable({
        idField: 'name',
        pagination: true,
        search: true,
        data: data,
        columns: [{
            field: 'name',
            title: 'Name'
        }, {
            field: 'stargazers_count',
            title: 'Stars'
        }, {
            field: 'forks_count',
            title: 'Forks'
        }, {
            field: 'description',
            title: 'Description'
        }],
        onPostBody: function () {
            $('#table').editableTableWidget({editor: $('<textarea>')});
        }
    });
});

var data = [{
        "name": "bootstrap-table",
        "stargazers_count": "526",
        "forks_count": "122",
        "description": "An extended Bootstrap table with radio, checkbox, sort, pagination, and other added features. (supports twitter bootstrap v2 and v3) "
    }, {
        "name": "multiple-select",
        "stargazers_count": "288",
        "forks_count": "150",
        "description": "A jQuery plugin to select multiple elements with checkboxes :)"
    }, {
        "name": "bootstrap-show-password",
        "stargazers_count": "32",
        "forks_count": "11",
        "description": "Show/hide password plugin for twitter bootstrap."
    }, {
        "name": "blog",
        "stargazers_count": "13",
        "forks_count": "4",
        "description": "my blog"
    }, {
        "name": "scutech-redmine",
        "stargazers_count": "6",
        "forks_count": "3",
        "description": "Redmine notification tools for chrome extension."
    }
];

And calling it in my html with :

My own created table in mysql database is: tx_table

I want the content of that table to be displayed in my bootstraptable Table

Body:
First solution. You can output your results directly into html using <script> tag and v:format.json.encode ViewHelper

action code:

$yourDataArrayFromPHP = array(
    'var1' => 'val1',
    'var2' => 'val2'
);

$this->view->assign('yourDataArrayFromPHP', $yourDataArrayFromPHP);

html:

<script>
    var data = {v:format.json.encode(value: '{yourDataArrayFromPHP}')}
</script>

Now you can access this data in javascript data.var1

Also keep in mind that your data should be before bootstrapTable initialization.


来源: stackexchange

问:
How can I avoid inline styling, yet take advantage of the templating language?
For each instantiation of an object in the template, I'd like to extract it's associated ImageField's url in order to show the photo. But I'm having trouble finding a way to do this without inline styling:

```<code>{% for entry in entries %}
        <div class="row">
        <div class="col s4">
            <div class="card-panel" style="background-image: url('{{entry.image.url}}');">

        <h1>{{entry.title}}</h1>

        </div></div></div>
    {% endfor %}
</code>```

This works in bringing each individual image to the template, but I wonder if I can abstract away the css just to keep my css in a separate file.

edit:  same goes for the  tag:

this, in the template, would be dynamic. But I wouldn't be able to set this as a background-image

答:
It is possible to use the Django template system to render CSS and create dynamic css files. I don't recommend doing this, but if you really want to you can set it up like normal url/view.

For example, your urls.py would have something like this

url(r'^dynamic_style/(?P<pk>\w+)$', dynamic_style, name='dynamic')

Then your view would look something like

```<code>def dynamic_style(request, pk):
    entry = get_object_or_404(Entry, pk)

    return render_to_response('dynamic_style.css', {
        'image_url': entry.image.url
    }, content_type='text/css')
</code>```

Then in your template you could have

```<code><link href="{% url 'dynamic_style' pk=entry.id %}" rel="stylesheet">
</code>```

This is a clunky way to generate css. If you can use inline as suggested above, it's much better.

ContentLicense: CC BY-SA 3.0

Body:
For each instantiation of an object in the template, I'd like to extract it's associated ImageField's url in order to show the photo. But I'm having trouble finding a way to do this without inline styling:

{% for entry in entries %}

{{entry.title}}

    {% endfor %}

This works in bringing each individual image to the template, but I wonder if I can abstract away the css just to keep my css in a separate file.

edit:  same goes for the  tag:

this, in the template, would be dynamic. But I wouldn't be able to set this as a background-image

Body:
It is possible to use the Django template system to render CSS and create dynamic css files. I don't recommend doing this, but if you really want to you can set it up like normal url/view.

For example, your urls.py would have something like this

url(r'^dynamic_style/(?P<pk>\w+)$', dynamic_style, name='dynamic')

Then your view would look something like

def dynamic_style(request, pk):
    entry = get_object_or_404(Entry, pk)

    return render_to_response('dynamic_style.css', {
        'image_url': entry.image.url
    }, content_type='text/css')

Then in your template you could have

<link href="{% url 'dynamic_style' pk=entry.id %}" rel="stylesheet">

This is a clunky way to generate css. If you can use inline as suggested above, it's much better.


问:
How correct restore state on MVP
I use MVP and it's work fine.

User click button on the View

show progress

call peresenter.download file

after success download file call view.hideProgress

OK. It's work fine.

But has one problem.

When user click button the progressbar is show. But if I change screen orienation  then as result view is recreate and progress bar is hide. But operation was not finish yet. The operation is finish after 10 seconds.

So the question is:

How show progress bar (restore state) while file was not download success?

答:
You can use Moxy library. It helps to save and restore state on configuration changes because it adds ViewState layer.

https://github.com/Arello-Mobile/Moxy

If you prefer native ways you can use loaders or retain fragments

Title: How correct restore state on MVP


问:
Git push and commiter
when I make a push to GIT (Gitlab) repo in the commits I see that commit has been made by user set in 'user.email' and 'user.name'.

Why does it happen? I think that information about user, should be taken from Gitlab profile.
Now it's possible to spoof our identification.

答:
There's a few reasons that using an external identity source to rewrite author information isn't practical with Git:

Git is designed to be usable in a distributed environment, where there is no central server at all, and you can pull directly from other contributors' cloned repositories.  In this case, it's necessary to allow you to pass on commits that you did not create, and preserve author information.  Rewriting this information could cause data loss, where a developer passed commits on to you and then you tried to push them to Gitlab.  You didn't write them; Gitlab shouldn't assume that you did.  The Git model requires that you trust your peers not to lie to you about who wrote what.

Changing the author/committer information changes the commit ID and this would cause a large amount of unwanted branching, and severely confuse anyone who was trying to develop against this repository as their commits kept getting rewritten on the server any time they pushed.

Title: Git push and commiter


问:
I'm not able to validate less than and greater than in robot framework
I'm trying to validate 0<4.3<6, I tried with Robot framework evaluate but I couldn't get the result, because I don't find any method to convert string to float, Then I wrote a python class to achieve this but for all the conditions it showing pass

my python code:

```<code>def should_be_x_than_y (number1, relation, number2, relation1, number3):

    if relation =="<" and relation1 == "<":
        print(relation)
        print (relation1)
        print (number1)
        print (number2)
        print (number3)
        **return float(number1) < float(number2) < float(number3)**
    if relation ==">" and relation1 == ">":
        return float(number1) > float(number2) > float(number3)
    if relation =="=>" and relation1 == "<=":
        return float(number1) >= float(number2) <= float(number3)
    if relation =="<=" and relation1 == "=>":
        return float(number1) <= float(number2) >= float(number3)
    if relation =="=":
        return float(number1) == float(number2)
</code>```

Robot Code:

```<code>should_be_x_than_y   0  <  ${words[0]}  <  3
</code>```

value of ${word[0]} is 4.3, so Ideally the case should fail, but It didn't

Body:
I'm trying to validate 0<4.3<6, I tried with Robot framework evaluate but I couldn't get the result, because I don't find any method to convert string to float, Then I wrote a python class to achieve this but for all the conditions it showing pass

my python code:

def should_be_x_than_y (number1, relation, number2, relation1, number3):

    if relation =="<" and relation1 == "<":
        print(relation)
        print (relation1)
        print (number1)
        print (number2)
        print (number3)
        **return float(number1) < float(number2) < float(number3)**
    if relation ==">" and relation1 == ">":
        return float(number1) > float(number2) > float(number3)
    if relation =="=>" and relation1 == "<=":
        return float(number1) >= float(number2) <= float(number3)
    if relation =="<=" and relation1 == "=>":
        return float(number1) <= float(number2) >= float(number3)
    if relation =="=":
        return float(number1) == float(number2)

Robot Code:

should_be_x_than_y   0  <  ${words[0]}  <  3

value of ${word[0]} is 4.3, so Ideally the case should fail, but It didn't

Body:
Maybe the original issue is that the 0 and 6 were not in ${}?

This works for me fine

*** Variables ***
@{words}      4.8    7.8

*** Test Cases ***
Test1
    [Tags]                             example
    Run Keyword Unless     ${0} < ${words[0]} < ${6}     Fail

Test2
    [Tags]                             example
    Run Keyword Unless     ${0} < ${words[1]} < ${6}     Fail

Hope that helps, let me know if it is not your issue!

==============================================================================
Basic
==============================================================================
Test1                                                                 | PASS |
------------------------------------------------------------------------------
Test2                                                                 | FAIL |
AssertionError


问:
What is the difference between if( pointer == NULL) and if(!pointer)?
What is the difference in between using:

```<code>if( pointer == NULL)
</code>```

And

```<code>if(!pointer)
</code>```

I am concerned with the differences between the two in respect to the following points:

 1. Are they different for the compiler? If yes, then how?

 2. Which of the two is the recommended coding style for general use and why?

 3. Can you please explain how NULL is "seen" by the compiler.

Edit: For the sake of simplicity let pointer be of type int *.

答:
They are both a comparison to 0; one is just explicit.  You can work out the difference to the compiler by looking at the assembly produced.

This is a matter of opinion and therefore off topic.

NULL is a macro that should equate to 0.  For this reason it's considered bad practice to use when comparing to pointers since the nullptr has an implicit conversion to pointer types, thus preventing it being used with integers; while NULL has no such conversion and thus can be compared to integers.

Body:
What is the difference in between using:

if( pointer == NULL)

And

if(!pointer)

I am concerned with the differences between the two in respect to the following points:

 1. Are they different for the compiler? If yes, then how?

 2. Which of the two is the recommended coding style for general use and why?

 3. Can you please explain how NULL is "seen" by the compiler.

Edit: For the sake of simplicity let pointer be of type int *.


问:
Programmatically prolonging the duration of Android loading indicator on the splash screen
Is there anyway via code to prolong the duration of the Android loading indicator on the splash screen?

In the Player Settings, I choose the large one and I also include:

```<code>#if UNITY_ANDROID
    Handheld.SetActivityIndicatorStyle(AndroidActivityIndicatorStyle.Large);
#endif
</code>```

But no matter which one is done, the loader only appears for a fraction of a second which is not noticeable to the user.

Our android app has a long loading time, so I would like a way of telling the user that something is happening...

I don't think there is anyway to place something on this splash screen (like a UI element with a message, etc...) for user feedback. Is there??

答:
You can prolong the Splash screen with Unity's SplashScreen API. Initialize splash screen with SplashScreen.Begin() then wait in a while loop while calling SplashScreen.Draw(); to draw the splash screen every frame. You must also yield or wait in that while loop so that your whole game will not freeze.

```<code>bool keepShowingSplashScreen = false;

IEnumerator Start()
{
    SplashScreen.Begin();

    while (keepShowingSplashScreen)
    {
        SplashScreen.Draw();
        yield return null;
    }
}
</code>```

When you want to exit the splash screen, set keepShowingSplashScreen  to false. The while loop will end and your game will continue.

Body:
Is there anyway via code to prolong the duration of the Android loading indicator on the splash screen?

In the Player Settings, I choose the large one and I also include:

#if UNITY_ANDROID
    Handheld.SetActivityIndicatorStyle(AndroidActivityIndicatorStyle.Large);
#endif

But no matter which one is done, the loader only appears for a fraction of a second which is not noticeable to the user.

Our android app has a long loading time, so I would like a way of telling the user that something is happening...

I don't think there is anyway to place something on this splash screen (like a UI element with a message, etc...) for user feedback. Is there??

Body:
You can prolong the Splash screen with Unity's SplashScreen API. Initialize splash screen with SplashScreen.Begin() then wait in a while loop while calling SplashScreen.Draw(); to draw the splash screen every frame. You must also yield or wait in that while loop so that your whole game will not freeze.

bool keepShowingSplashScreen = false;

IEnumerator Start()
{
    SplashScreen.Begin();

    while (keepShowingSplashScreen)
    {
        SplashScreen.Draw();
        yield return null;
    }
}

When you want to exit the splash screen, set keepShowingSplashScreen  to false. The while loop will end and your game will continue.


问:
Problems with JobScheduler - JobsService firing multiple times
I'm trying to do some background work in my android application. As the web suggested I'm using JobScheduler to do so.

The jobs are sometimes firing 5-15 times instead of once. Sometimes they are never firing.
My testdevices run on 5.1.1 and 7.0. The one with Nougat fires way less then the one with lollipop.

This is how I enable my jobs (the 5 seconds interval is only for test purpose):

```<code>fun enableTasks() {
    val jobScheduler = App.getContext().getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler

    if (PreferenceDao.getInstance().shouldUpdateJob()) jobScheduler.cancelAll()

    scheduleJob(jobScheduler, MoniInfoJob.getJob())
    scheduleJob(jobScheduler, QueueJob.getJob())
    scheduleJob(jobScheduler, MontageOrderUpdateJob.getJob())

    PreferenceDao.getInstance().setJobUpdated()
}

private fun scheduleJob(jobScheduler: JobScheduler, jobInfo: JobInfo) {
    val jobExists = jobScheduler.allPendingJobs.any { it.id == jobInfo.id }
    if (!jobExists) jobScheduler.schedule(jobInfo)
}
</code>```

All three jobs look kind of the same so I only post one:

The JobService

```<code>class QueueJob : JobService() {

override fun onStartJob(jobParameters: JobParameters?): Boolean {
    val receiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, p1: Intent?) {
            unregisterBroadcastReceiver(this)
            jobFinished(jobParameters, false)
        }
    }

    registerBroadcastReceiver(receiver)
    MainController.startQueueService()
    return true;
}

override fun onStopJob(jobParameters: JobParameters): Boolean {
    Log.d(MontageOrderUpdateJob.TAG, "onStopJob")
    return false;
}

private fun registerBroadcastReceiver(receiver: BroadcastReceiver) {
    LocalBroadcastManager.getInstance(this).registerReceiver(receiver, IntentFilter(JOB_FINISHED))
}

private fun unregisterBroadcastReceiver(receiver: BroadcastReceiver) {
    LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver)
}

companion object {
    val TAG = QueueJob::class.java.name
    val jobId: Int = 2
    val JOB_FINISHED =  TAG + "_finished"

    fun getJob(): JobInfo {
        val builder = JobInfo.Builder(jobId, ComponentName(App.getContext(), TAG))
        builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
        builder.setPeriodic(5000L)
        builder.setPersisted(true)
        return builder.build()
    }
}
}
</code>```

And the JobIntentService:

```<code>class QueueService : JobIntentService() {

private val TAG = QueueService::class.java.name

override fun onHandleWork(intent: Intent) {
    try {
        Log.d(TAG, "Jobservice started")
        TimerecordQueue().workThroughQueue()
        DangerAllowanceQueue().workThroughQueue()
        ProjektEndQueue().workThroughQueue()
        PhotoUploadQueue().workThroughQueue()
    } finally {
        sendFinishedBroadcast()
    }
}

private fun sendFinishedBroadcast() {
    val jobFinishedIntent = Intent(QueueJob.JOB_FINISHED)
    LocalBroadcastManager.getInstance(this).sendBroadcast(jobFinishedIntent)
}
}
</code>```

答:
I had a similar problem once. My problem then was that I didn't check for preexisting schedules.
Could it be you need to do the same?</p>

Body:
I'm trying to do some background work in my android application. As the web suggested I'm using JobScheduler to do so.

The jobs are sometimes firing 5-15 times instead of once. Sometimes they are never firing.
My testdevices run on 5.1.1 and 7.0. The one with Nougat fires way less then the one with lollipop.

This is how I enable my jobs (the 5 seconds interval is only for test purpose):

fun enableTasks() {
    val jobScheduler = App.getContext().getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler

    if (PreferenceDao.getInstance().shouldUpdateJob()) jobScheduler.cancelAll()

    scheduleJob(jobScheduler, MoniInfoJob.getJob())
    scheduleJob(jobScheduler, QueueJob.getJob())
    scheduleJob(jobScheduler, MontageOrderUpdateJob.getJob())

    PreferenceDao.getInstance().setJobUpdated()
}

private fun scheduleJob(jobScheduler: JobScheduler, jobInfo: JobInfo) {
    val jobExists = jobScheduler.allPendingJobs.any { it.id == jobInfo.id }
    if (!jobExists) jobScheduler.schedule(jobInfo)
}

All three jobs look kind of the same so I only post one:

The JobService

class QueueJob : JobService() {

override fun onStartJob(jobParameters: JobParameters?): Boolean {
    val receiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, p1: Intent?) {
            unregisterBroadcastReceiver(this)
            jobFinished(jobParameters, false)
        }
    }

    registerBroadcastReceiver(receiver)
    MainController.startQueueService()
    return true;
}

override fun onStopJob(jobParameters: JobParameters): Boolean {
    Log.d(MontageOrderUpdateJob.TAG, "onStopJob")
    return false;
}

private fun registerBroadcastReceiver(receiver: BroadcastReceiver) {
    LocalBroadcastManager.getInstance(this).registerReceiver(receiver, IntentFilter(JOB_FINISHED))
}

private fun unregisterBroadcastReceiver(receiver: BroadcastReceiver) {
    LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver)
}

companion object {
    val TAG = QueueJob::class.java.name
    val jobId: Int = 2
    val JOB_FINISHED =  TAG + "_finished"

    fun getJob(): JobInfo {
        val builder = JobInfo.Builder(jobId, ComponentName(App.getContext(), TAG))
        builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
        builder.setPeriodic(5000L)
        builder.setPersisted(true)
        return builder.build()
    }
}
}

And the JobIntentService:

class QueueService : JobIntentService() {

private val TAG = QueueService::class.java.name

override fun onHandleWork(intent: Intent) {
    try {
        Log.d(TAG, "Jobservice started")
        TimerecordQueue().workThroughQueue()
        DangerAllowanceQueue().workThroughQueue()
        ProjektEndQueue().workThroughQueue()
        PhotoUploadQueue().workThroughQueue()
    } finally {
        sendFinishedBroadcast()
    }
}

private fun sendFinishedBroadcast() {
    val jobFinishedIntent = Intent(QueueJob.JOB_FINISHED)
    LocalBroadcastManager.getInstance(this).sendBroadcast(jobFinishedIntent)
}
}


问:
I use ASP.net to generate a sitemap.xml, get Google Webmaster says: "Your Sitemap appears to be an HTML page."
I am trying to return an generated .xml file, but google picks it up as a html page. So I get: "Your Sitemap appears to be an HTML page. Please use a supported sitemap format instead."

Here is the ASP.net Controller that generate the sitemap.xml

```<code>[Route("sitemap.xml")]
public async Task<IActionResult> SitemapXmlAsync()
{

  using (var client = new HttpClient())
  {
    try
    {
      client.BaseAddress = new Uri("https://api.badgag.com/api/generateSitemap");
      var response = await client.GetAsync("");
      response.EnsureSuccessStatusCode();

      var stringResult = await response.Content.ReadAsStringAsync();
      var pages = JsonConvert.DeserializeObject<String[]>(stringResult);

      String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
      xml += "<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">";

      foreach (string s in pages)
      {

        xml += "<sitemap>";
        xml += "<loc>" + s + "</loc>";
        //xml += "<lastmod>" + DateTime.Now.ToString("yyyy-MM-dd") + "</lastmod>";
        xml += "</sitemap>";
      }

      xml += "</sitemapindex>";

      return Content(xml, "text/xml");

    }
    catch (HttpRequestException httpRequestException)
    {
      return BadRequest($"Error getting sitemap: {httpRequestException.Message}");
    }
  }

}
</code>```

I assume I am missing something. Setting a different header?

You can see the result here:

https://badgag.com/sitemap.xml

Thanks in advance :)

答:
I found this article about creating a XML sitemap with ASP.Net, this helped me to create a sitemap.ashx file with the correct sitemap layout Google and Bing require.

It basically is using XmlTextWriter to generate the required tags for a sitemap. This example is using HTTPContext to write an XML file. Here is the code from this site:

```<code>using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Web;
using System.Xml;

namespace Mikesdotnetting
{

    public class Sitemap : IHttpHandler
    {

        public void ProcessRequest(HttpContext context) {
            context.Response.ContentType = "text/xml";
            using (XmlTextWriter writer = new XmlTextWriter(context.Response.OutputStream, Encoding.UTF8)) {
                writer.WriteStartDocument();
                writer.WriteStartElement("urlset");
                writer.WriteAttributeString("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");
                writer.WriteStartElement("url");

                string connect = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString;
                string url = "http://www.mikesdotnetting.com/";
                using (SqlConnection conn = new SqlConnection(connect)) {
                    using (SqlCommand cmd = new SqlCommand("GetSiteMapContent", conn)) {
                        cmd.CommandType = CommandType.StoredProcedure;
                        conn.Open();
                        using (SqlDataReader rdr = cmd.ExecuteReader()) {
                            // Get the date of the most recent article
                            rdr.Read();
                            writer.WriteElementString("loc", string.Format("{0}Default.aspx", url));
                            writer.WriteElementString("lastmod", string.Format("{0:yyyy-MM-dd}", rdr[0]));
                            writer.WriteElementString("changefreq", "weekly");
                            writer.WriteElementString("priority", "1.0");
                            writer.WriteEndElement();
                            // Move to the Article IDs
                            rdr.NextResult();
                            while (rdr.Read()) {
                                writer.WriteStartElement("url");
                                writer.WriteElementString("loc", string.Format("{0}Article.aspx?ArticleID={1}", url,  rdr[0]));

                                if (rdr[1] != DBNull.Value)
                                writer.WriteElementString("lastmod", string.Format("{0:yyyy-MM-dd}", rdr[1]));
                                writer.WriteElementString("changefreq", "monthly");
                                writer.WriteElementString("priority", "0.5");
                                writer.WriteEndElement();
                            }
                            // Move to the Article Type IDs
                            rdr.NextResult();
                            while (rdr.Read()) {
                            writer.WriteStartElement("url");
                            writer.WriteElementString("loc", string.Format("{0}ArticleTypes.aspx?Type={1}", url, rdr[0]));
                            writer.WriteElementString("priority", "0.5");
                            writer.WriteEndElement();
                            }
                            // Finally move to the Category IDs
                            rdr.NextResult();
                            while (rdr.Read()) {
                                writer.WriteStartElement("url");
                                writer.WriteElementString("loc", string.Format("{0}Category.aspx?Category={1}", url, rdr[0]));
                                writer.WriteElementString("priority", "0.5");
                                writer.WriteEndElement();
                            }
                            writer.WriteEndElement();
                            writer.WriteEndDocument();
                            writer.Flush();
                        }
                        context.Response.End();
                    }
                }
            }
        }

        public bool IsReusable {
            get {
                return false;
            }
        }
    }
}
</code>```

Body:
I am trying to return an generated .xml file, but google picks it up as a html page. So I get: "Your Sitemap appears to be an HTML page. Please use a supported sitemap format instead."

Here is the ASP.net Controller that generate the sitemap.xml

[Route("sitemap.xml")]
public async Task<IActionResult> SitemapXmlAsync()
{

  using (var client = new HttpClient())
  {
    try
    {
      client.BaseAddress = new Uri("https://api.badgag.com/api/generateSitemap");
      var response = await client.GetAsync("");
      response.EnsureSuccessStatusCode();

      var stringResult = await response.Content.ReadAsStringAsync();
      var pages = JsonConvert.DeserializeObject<String[]>(stringResult);

      String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
      xml += "<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">";

      foreach (string s in pages)
      {

        xml += "<sitemap>";
        xml += "<loc>" + s + "</loc>";
        //xml += "<lastmod>" + DateTime.Now.ToString("yyyy-MM-dd") + "</lastmod>";
        xml += "</sitemap>";
      }

      xml += "</sitemapindex>";

      return Content(xml, "text/xml");

    }
    catch (HttpRequestException httpRequestException)
    {
      return BadRequest($"Error getting sitemap: {httpRequestException.Message}");
    }
  }

}

I assume I am missing something. Setting a different header?

You can see the result here:

https://badgag.com/sitemap.xml

Thanks in advance :)

Body:
I found this article about creating a XML sitemap with ASP.Net, this helped me to create a sitemap.ashx file with the correct sitemap layout Google and Bing require.

It basically is using XmlTextWriter to generate the required tags for a sitemap. This example is using HTTPContext to write an XML file. Here is the code from this site:

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Web;
using System.Xml;

namespace Mikesdotnetting
{

    public class Sitemap : IHttpHandler
    {

        public void ProcessRequest(HttpContext context) {
            context.Response.ContentType = "text/xml";
            using (XmlTextWriter writer = new XmlTextWriter(context.Response.OutputStream, Encoding.UTF8)) {
                writer.WriteStartDocument();
                writer.WriteStartElement("urlset");
                writer.WriteAttributeString("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");
                writer.WriteStartElement("url");

                string connect = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString;
                string url = "http://www.mikesdotnetting.com/";
                using (SqlConnection conn = new SqlConnection(connect)) {
                    using (SqlCommand cmd = new SqlCommand("GetSiteMapContent", conn)) {
                        cmd.CommandType = CommandType.StoredProcedure;
                        conn.Open();
                        using (SqlDataReader rdr = cmd.ExecuteReader()) {
                            // Get the date of the most recent article
                            rdr.Read();
                            writer.WriteElementString("loc", string.Format("{0}Default.aspx", url));
                            writer.WriteElementString("lastmod", string.Format("{0:yyyy-MM-dd}", rdr[0]));
                            writer.WriteElementString("changefreq", "weekly");
                            writer.WriteElementString("priority", "1.0");
                            writer.WriteEndElement();
                            // Move to the Article IDs
                            rdr.NextResult();
                            while (rdr.Read()) {
                                writer.WriteStartElement("url");
                                writer.WriteElementString("loc", string.Format("{0}Article.aspx?ArticleID={1}", url,  rdr[0]));

                                if (rdr[1] != DBNull.Value)
                                writer.WriteElementString("lastmod", string.Format("{0:yyyy-MM-dd}", rdr[1]));
                                writer.WriteElementString("changefreq", "monthly");
                                writer.WriteElementString("priority", "0.5");
                                writer.WriteEndElement();
                            }
                            // Move to the Article Type IDs
                            rdr.NextResult();
                            while (rdr.Read()) {
                            writer.WriteStartElement("url");
                            writer.WriteElementString("loc", string.Format("{0}ArticleTypes.aspx?Type={1}", url, rdr[0]));
                            writer.WriteElementString("priority", "0.5");
                            writer.WriteEndElement();
                            }
                            // Finally move to the Category IDs
                            rdr.NextResult();
                            while (rdr.Read()) {
                                writer.WriteStartElement("url");
                                writer.WriteElementString("loc", string.Format("{0}Category.aspx?Category={1}", url, rdr[0]));
                                writer.WriteElementString("priority", "0.5");
                                writer.WriteEndElement();
                            }
                            writer.WriteEndElement();
                            writer.WriteEndDocument();
                            writer.Flush();
                        }
                        context.Response.End();
                    }
                }
            }
        }

        public bool IsReusable {
            get {
                return false;
            }
        }
    }
}


问:
CMake uses "target_include_directories" differently on Linux (Ubuntu) than OS X
I have a multi-target CMake file where all the targets are building fine on OS X, but when I build the target on Ubuntu Linux, it does not link the system libraries added in target_include_directories.

Here's an example of a target (each target is similar).

```<code>set(SOURCE_FILES_TARGET)
set(RELEASE_LIBS iconv m xml2 z icucore resolv curl )
add_executable(TARGET_NAME ${SOURCE_FILES_TARGET)
target_include_directories(TARGET_NAME PRIVATE external_lib1/headers external_lib2/headers )
target_link_libraries(TARGET_NAME ${RELEASE_LIBS})
target_link_libraries(TARGET_NAME ${CMAKE_SOURCE_DIR}/lib1.a)
target_link_libraries(TARGET_NAME ${CMAKE_SOURCE_DIR}/lib2.a)
</code>```

The libraries are a little different for linux (comparing the .la files), but even one which is the same (xml2) results in undefined reference errors. Also, on OS X the "target_link_libraries" command works as listed above, and with -lxml2 format.

I tried to add the "pthreads" library on linux (as it asked for this, but not on OS X), and the only way I was able to add it was

```<code>set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -pthread")
</code>```

however, this is a global setting for all targets. Basically, if I put pthread into target_link_libraries it is ignored, just like the rest of them.

How should I best add these libraries to the targets? Maybe I'm missing something on the OS X side and it just happens to work?

答:
Not sure what your problem exactly is, but here some tips that may help you.

Instead of setting the library names and tell you program to compile against them, you should rather try to find the libraries using find_library() and link your program against the variable resulting from the CMake command. That way, CMake may actually tell you if the library is not found.

For example:

```<code>find_library(XML2_LIBRARY xml2)
add_executable(TARGET_NAME ${XML2_LIBRARY})
</code>```

That way, you can provide several possible library names (for example the names may be different depending on the system you are compiling on). Also, you can tell CMake to look into additional directories (eg. CMAKE_LIBRARY_PATH) without changing your CMakeLists.txt.

You should also check for CMake modules that provide configuration for the dependencies you are interested in (CMake 3.7 has a FindLibXml2 module).

For pthread, you should check CMake's FindThreads.

Body:
I have a multi-target CMake file where all the targets are building fine on OS X, but when I build the target on Ubuntu Linux, it does not link the system libraries added in target_include_directories.

Here's an example of a target (each target is similar).

set(SOURCE_FILES_TARGET)
set(RELEASE_LIBS iconv m xml2 z icucore resolv curl )
add_executable(TARGET_NAME ${SOURCE_FILES_TARGET)
target_include_directories(TARGET_NAME PRIVATE external_lib1/headers external_lib2/headers )
target_link_libraries(TARGET_NAME ${RELEASE_LIBS})
target_link_libraries(TARGET_NAME ${CMAKE_SOURCE_DIR}/lib1.a)
target_link_libraries(TARGET_NAME ${CMAKE_SOURCE_DIR}/lib2.a)

The libraries are a little different for linux (comparing the .la files), but even one which is the same (xml2) results in undefined reference errors. Also, on OS X the "target_link_libraries" command works as listed above, and with -lxml2 format.

I tried to add the "pthreads" library on linux (as it asked for this, but not on OS X), and the only way I was able to add it was

set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -pthread")

however, this is a global setting for all targets. Basically, if I put pthread into target_link_libraries it is ignored, just like the rest of them.

How should I best add these libraries to the targets? Maybe I'm missing something on the OS X side and it just happens to work?

Body:
Not sure what your problem exactly is, but here some tips that may help you.

Instead of setting the library names and tell you program to compile against them, you should rather try to find the libraries using find_library() and link your program against the variable resulting from the CMake command. That way, CMake may actually tell you if the library is not found.

For example:

find_library(XML2_LIBRARY xml2)
add_executable(TARGET_NAME ${XML2_LIBRARY})

That way, you can provide several possible library names (for example the names may be different depending on the system you are compiling on). Also, you can tell CMake to look into additional directories (eg. CMAKE_LIBRARY_PATH) without changing your CMakeLists.txt.

You should also check for CMake modules that provide configuration for the dependencies you are interested in (CMake 3.7 has a FindLibXml2 module).

For pthread, you should check CMake's FindThreads.


问:
Optional dependency injection for unit testing
I'm considering my options for setting up a class for unit testing. This particular class should ALWAYS use the same soap client configuration under normal circumstances. I feel like users of the class shouldn't need to be concerned with setting up a soap client when they use it. Or, even be aware that it uses soap at all.

Really the only exception is in unit testing. I'll need to be able to mock the Soap_Client. I've come up with the following approach where i create the soap client in the constructor and can optionally set it with setSoapClient().

```<code>class WebServiceLayer
{
    const WSDL_URL = 'https://www.example.com/?WSDL';

    private $soapClient;

    public function __construct()
    {
        $this->soapClient = new Soap_Client(self::WSDL_URL);
    }

    public function setSoapClient(Soap_Client $soapClient)
    {
        $this->soapClient = $soapClient;
    }

    public function fetchSomeResponse()
    {
        $soapClient = $this->soapClient;
        return $soapClient->someRequest();
    }
}
</code>```

Is this a valid way to handle this? The only problem i see with it, is that im instantiating the client in the constructor which "i've heard" is something to avoid.

I've run into this dilemma before on other classes, so it would be really nice to get peoples opinions on this.

答: Looks fine to me... you're using standard Setter injection. The only strange thing is returning a new client in the Getter. Why not return null if it hasn't been injected?</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm considering my options for setting up a class for unit testing. This particular class should ALWAYS use the same soap client configuration under normal circumstances. I feel like users of the class shouldn't need to be concerned with setting up a soap client when they use it. Or, even be aware that it uses soap at all.

Really the only exception is in unit testing. I'll need to be able to mock the Soap_Client. I've come up with the following approach where i create the soap client in the constructor and can optionally set it with setSoapClient().

class WebServiceLayer
{
    const WSDL_URL = 'https://www.example.com/?WSDL';

    private $soapClient;

    public function __construct()
    {
        $this->soapClient = new Soap_Client(self::WSDL_URL);
    }

    public function setSoapClient(Soap_Client $soapClient)
    {
        $this->soapClient = $soapClient;
    }

    public function fetchSomeResponse()
    {
        $soapClient = $this->soapClient;
        return $soapClient->someRequest();
    }
}

Is this a valid way to handle this? The only problem i see with it, is that im instantiating the client in the constructor which "i've heard" is something to avoid.

I've run into this dilemma before on other classes, so it would be really nice to get peoples opinions on this.

ContentLicense: CC BY-SA 2.5


问:
FOS User Bundle using parameters from ORM Database
I'm using FOS User Bundle and I need to use a value called "maxLoginAttempts" from a record of another Entity/table that I use for my parameters.

The Entity it's called Parameters. This is my current code and I would like to change the number 5 for the value from database.

```<code><?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;

/**
 * @ORM\Entity
 * @ORM\Table(name="`user`")
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     */
    protected $id;

    ...

    public function isAccountNonLocked()
    {
        if($this->getLoginAttempts() >= 5) {
            return false;
        } else {
            return true;
        }
     }
 }
</code>```

I imagine something like:

```<code>  $this->em->getRepository('AppBundle:Parameters')
        ->findOneBy(['name' => 'maxLoginAttempts']);
</code>```

Obviously right now I don't have access to the repository. As I'm not in the Controller I'm not sure how I should use these values from inside a function of an Entity.

答:
Finally the solution was to override the UserChecker using another functions with the same functionality.</p>

```<code><?php

namespace AppBundle\Checker;

use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\Exception\CredentialsExpiredException;
use Symfony\Component\Security\Core\Exception\DisabledException;
use Symfony\Component\Security\Core\Exception\LockedException;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Symfony\Component\Security\Core\User\UserChecker as BaseUserChecker;
use Symfony\Component\Security\Core\User\UserInterface;

class UserChecker extends BaseUserChecker
{
    private $em;

    public function __construct( EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    public function checkPreAuth(UserInterface $user)
    {
        //parent::checkPreAuth($user);
        $maxMinutesLocked = $this->em->getRepository('AppBundle:Parameters')->findOneBy(array('name' => 'maxTimeLocked'))->getValue();

        if (!$user instanceof AdvancedUserInterface) {
            return;
        }

        //So I just added a new function called isAccountLocked() to the User Entity that's a copy from isAccountNonLocked() but I could add a paramater
        if ($user->isAccountLocked($maxMinutesLocked)) {
            $ex = new LockedException('User account is locked.');
            $ex->setUser($user);
            throw $ex;
        }

        if (!$user->isEnabled()) {
            ...
        }
        if (!$user->isAccountNonExpired()) {
            ...
        }
    }

    public function checkPostAuth(UserInterface $user)
    {
         ...
    }
}
</code>```

Body:
I'm using FOS User Bundle and I need to use a value called "maxLoginAttempts" from a record of another Entity/table that I use for my parameters.

The Entity it's called Parameters. This is my current code and I would like to change the number 5 for the value from database.

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;

/**
 * @ORM\Entity
 * @ORM\Table(name="`user`")
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     */
    protected $id;

    ...

    public function isAccountNonLocked()
    {
        if($this->getLoginAttempts() >= 5) {
            return false;
        } else {
            return true;
        }
     }
 }

I imagine something like:

  $this->em->getRepository('AppBundle:Parameters')
        ->findOneBy(['name' => 'maxLoginAttempts']);

Obviously right now I don't have access to the repository. As I'm not in the Controller I'm not sure how I should use these values from inside a function of an Entity.

Body:
Finally the solution was to override the UserChecker using another functions with the same functionality.

<?php

namespace AppBundle\Checker;

use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\Exception\CredentialsExpiredException;
use Symfony\Component\Security\Core\Exception\DisabledException;
use Symfony\Component\Security\Core\Exception\LockedException;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Symfony\Component\Security\Core\User\UserChecker as BaseUserChecker;
use Symfony\Component\Security\Core\User\UserInterface;

class UserChecker extends BaseUserChecker
{
    private $em;

    public function __construct( EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    public function checkPreAuth(UserInterface $user)
    {
        //parent::checkPreAuth($user);
        $maxMinutesLocked = $this->em->getRepository('AppBundle:Parameters')->findOneBy(array('name' => 'maxTimeLocked'))->getValue();

        if (!$user instanceof AdvancedUserInterface) {
            return;
        }

        //So I just added a new function called isAccountLocked() to the User Entity that's a copy from isAccountNonLocked() but I could add a paramater
        if ($user->isAccountLocked($maxMinutesLocked)) {
            $ex = new LockedException('User account is locked.');
            $ex->setUser($user);
            throw $ex;
        }

        if (!$user->isEnabled()) {
            ...
        }
        if (!$user->isAccountNonExpired()) {
            ...
        }
    }

    public function checkPostAuth(UserInterface $user)
    {
         ...
    }
}


问:
hive julian date conversion
I am trying to convert Julian date in HIVE, for example 0167017 to calendar date. My example should covert to 1967-01-17 (01 should become 19, 67 considered as year 67 and 017 as 17 days in the year. What hive date format should I use to achieve this?

I tried this format, but didn't work. select
from_unixtime(unix_timestamp('0167121','CCYYDDD')) ;

答:
If 01 should become 19 then 02 =20 and so on, right? Then convert 01 to 19, concatenate it with rest of the string and apply yyyyDDD format:

```<code>hive> select  to_date(from_unixtime(unix_timestamp(concat(18+cast(substr('0167017',1,2)as int),substr('0167017',3)),'yyyyDDD')));
OK
1967-01-17
Time taken: 0.07 seconds, Fetched: 1 row(s)
</code>```

Use  to_date() or substr to remove '00:00:00' if necessary

Title: hive julian date conversion

Body:
If 01 should become 19 then 02 =20 and so on, right? Then convert 01 to 19, concatenate it with rest of the string and apply yyyyDDD format:

hive> select  to_date(from_unixtime(unix_timestamp(concat(18+cast(substr('0167017',1,2)as int),substr('0167017',3)),'yyyyDDD')));
OK
1967-01-17
Time taken: 0.07 seconds, Fetched: 1 row(s)

Use  to_date() or substr to remove '00:00:00' if necessary


问:
MySQL - SELECT equal amount of each in UNION by total LIMIT
In a MySQL database I have 3 tables: customers, projects and tasks. For a search that I am implementing, I want to search through all 3 tables and select found matches. The problem is that I would like to equally limit the amount of results returned by MySQL.

This is an example with the query that I currently have:

```<code>SELECT id, title, type
FROM (
    (
    SELECT id, title, 'customer' AS type, MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE) AS score
    FROM customers
    WHERE MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE)
    )
    UNION DISTINCT
    (
    SELECT id, title, 'project' AS type, MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE) AS score
    FROM projects
    WHERE MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE)
    )
    UNION DISTINCT
    (
    SELECT id, title, 'task' AS type, MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE) AS score
    FROM tasks
    WHERE MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE)
    )
) res
LIMIT 6;
</code>```

In this example, I want to limit the results to 6.

My desired endresult for this example is the following:

1) If all tables have at least 2 results, show 2 results for each.

```<code>id     title                      type
20     'First test customer'      'customer'
22     'Test customer 2'          'customer
48     'A project for testing'    'project'
17     'Test Project'             'project'
1      'Task test'                'task'
2      'Second test'              'task'
</code>```

2) If one table does not have any results, show 3 results for each of the 2 other tables. (If only one table has results, show 6 results for that table.)

```<code>id     title                      type
20     'First test customer'      'customer'
22     'Test customer 2'          'customer
56     'Customer test 56'         'customer'
1      'Task test'                'task'
2      'Second test'              'task'
3      'Test task'                'task'
</code>```

3) If 2 of the tables have more than 2 results, and the third table only has 1 result, show 3 results for one of the tables with enough results, 2 results for the other one of the two and 1 for the table with only 1 result.

```<code>id     title                      type
20     'First test customer'      'customer'
48     'A project for testing'    'project'
17     'Test Project'             'project'
34     'Testing project'          'project'
1      'Task test'                'task'
2      'Second test'              'task'
</code>```

Can anyone please help me with this?

Thanks in advance!

答:
To have the @kiks73 result in one query without declaring @rankX variables you can add a (SELECT @rankX:=0) AS t to the from clause. like this:

```<code>SELECT id, title, type, rank
FROM (
    (

    SELECT @rank1:=@rank1+1 AS rank, id, title, 'customer' AS type, MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE) AS score
    FROM customers,(SELECT @rank1:=0) AS t
    WHERE MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE)
    )
    UNION DISTINCT
    (

    SELECT @rank2:=@rank2+1 AS rank, id, title, 'project' AS type, MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE) AS score
    FROM projects,(SELECT @rank2:=0) AS t
    WHERE MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE)
    )
    UNION DISTINCT
    (

    SELECT @rank3:=@rank3+1 AS rank, id, title, 'task' AS type, MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE) AS score
    FROM tasks,(SELECT @rank3:=0) AS t
    WHERE MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE)
    )
) res
ORDER BY rank
LIMIT 6;
</code>```

Body:
In a MySQL database I have 3 tables: customers, projects and tasks. For a search that I am implementing, I want to search through all 3 tables and select found matches. The problem is that I would like to equally limit the amount of results returned by MySQL.

This is an example with the query that I currently have:

SELECT id, title, type
FROM (
    (
    SELECT id, title, 'customer' AS type, MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE) AS score
    FROM customers
    WHERE MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE)
    )
    UNION DISTINCT
    (
    SELECT id, title, 'project' AS type, MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE) AS score
    FROM projects
    WHERE MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE)
    )
    UNION DISTINCT
    (
    SELECT id, title, 'task' AS type, MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE) AS score
    FROM tasks
    WHERE MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE)
    )
) res
LIMIT 6;

In this example, I want to limit the results to 6.

My desired endresult for this example is the following:

1) If all tables have at least 2 results, show 2 results for each.

id     title                      type
20     'First test customer'      'customer'
22     'Test customer 2'          'customer
48     'A project for testing'    'project'
17     'Test Project'             'project'
1      'Task test'                'task'
2      'Second test'              'task'

2) If one table does not have any results, show 3 results for each of the 2 other tables. (If only one table has results, show 6 results for that table.)

id     title                      type
20     'First test customer'      'customer'
22     'Test customer 2'          'customer
56     'Customer test 56'         'customer'
1      'Task test'                'task'
2      'Second test'              'task'
3      'Test task'                'task'

3) If 2 of the tables have more than 2 results, and the third table only has 1 result, show 3 results for one of the tables with enough results, 2 results for the other one of the two and 1 for the table with only 1 result.

id     title                      type
20     'First test customer'      'customer'
48     'A project for testing'    'project'
17     'Test Project'             'project'
34     'Testing project'          'project'
1      'Task test'                'task'
2      'Second test'              'task'

Can anyone please help me with this?

Thanks in advance!

Body:
To have the @kiks73 result in one query without declaring @rankX variables you can add a (SELECT @rankX:=0) AS t to the from clause. like this:

SELECT id, title, type, rank
FROM (
    (

    SELECT @rank1:=@rank1+1 AS rank, id, title, 'customer' AS type, MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE) AS score
    FROM customers,(SELECT @rank1:=0) AS t
    WHERE MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE)
    )
    UNION DISTINCT
    (

    SELECT @rank2:=@rank2+1 AS rank, id, title, 'project' AS type, MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE) AS score
    FROM projects,(SELECT @rank2:=0) AS t
    WHERE MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE)
    )
    UNION DISTINCT
    (

    SELECT @rank3:=@rank3+1 AS rank, id, title, 'task' AS type, MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE) AS score
    FROM tasks,(SELECT @rank3:=0) AS t
    WHERE MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE)
    )
) res
ORDER BY rank
LIMIT 6;


问:
How to include -lm in Makefile.am or configure.ac

I have a program called neuromz that I compile using

```<code>gcc neuromz.c -lm -o neuromz
</code>```

It's work fine but if I try to add to my project a configure.ac and Makefile.am, with Makefile.am:

```<code>bin_PROGRAMS = neuromz
neuromz_SOURCES = neuromz.c neuromz.h ann.c ann.h
neuromz_CFLAGS = -lm
</code>```

the result is:

```<code>/home/mz/programming/ctest/ANN/ann.c:11: undefined reference to `exp'
/home/mz/programming/ctest/ANN/ann.c:11: undefined reference to `exp'
</code>```

How can I fix it?

答:
As @MikeKinghan already described, the Automake variables for specifying extra libraries into a program are *_LDADD.  I'll add, however, that if you're only building one program, or if all of the programs you're building need the same libraries, then you can use LDADD instead.  This can be more convenient, and it sometimes produces smaller Makefile's, too:

```<code>bin_PROGRAMS = neuromz
LDADD = -lm

neuromz_SOURCES = neuromz.c neuromz.h ann.c ann.h
</code>```

HOWEVER, if you're satisfied to make a once-for-all decision about libm for the programs built by your build system, then I'd recommend handling it in Autoconf instead of Automake.  If you put this in your configure.ac ...

```<code>AC_SEARCH_LIBS([sqrt], [m])
</code>```

... then

Your configure script will check whether libm needs to be explicitly linked at all (which depends on your environment and tool chain), and will add -lm only if necessary.

You don't then need to say anything about it in your Makefile.am, nor be concerned with which Automake variable to use.

Body:
I have a program called neuromz that I compile using

gcc neuromz.c -lm -o neuromz

It's work fine but if I try to add to my project a configure.ac and Makefile.am, with Makefile.am:

bin_PROGRAMS = neuromz
neuromz_SOURCES = neuromz.c neuromz.h ann.c ann.h
neuromz_CFLAGS = -lm

the result is:

/home/mz/programming/ctest/ANN/ann.c:11: undefined reference to `exp'
/home/mz/programming/ctest/ANN/ann.c:11: undefined reference to `exp'

How can I fix it?

Body:
As @MikeKinghan already described, the Automake variables for specifying extra libraries into a program are *_LDADD.  I'll add, however, that if you're only building one program, or if all of the programs you're building need the same libraries, then you can use LDADD instead.  This can be more convenient, and it sometimes produces smaller Makefile's, too:

bin_PROGRAMS = neuromz
LDADD = -lm

neuromz_SOURCES = neuromz.c neuromz.h ann.c ann.h

HOWEVER, if you're satisfied to make a once-for-all decision about libm for the programs built by your build system, then I'd recommend handling it in Autoconf instead of Automake.  If you put this in your configure.ac ...

AC_SEARCH_LIBS([sqrt], [m])

... then

Your configure script will check whether libm needs to be explicitly linked at all (which depends on your environment and tool chain), and will add -lm only if necessary.

You don't then need to say anything about it in your Makefile.am, nor be concerned with which Automake variable to use.


问:
Camera Intent - how to?
Sorry to bother you guys, but I am not able to get a solution where In we take picture using intents. I know the default behavior of native camera is to save the picture at default directory/place of O.S. The thing is I have some requirements where I do not want to save the picture when clicked using camera app. There has to be a solution of this issue, be it like once we take a picture we could delete it right away, or there should be an alternate by which we won't allow O.S to save Image, please help.

Here is a piece of code I tried, tried several ways by creating a directory and then deleting file, nothing works.

```<code> public void takeImageFromCamera() {

        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(cameraIntent, CAMERA_REQUEST);
    }

  @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

// Check for the integer request code originally supplied to startResolutionForResult().
        if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {

            if (isCameraPermissionGranted()) {
                bitmap= (Bitmap) data.getExtras().get("data");
              //  bitmap = processReuiredImage(picUri);
                getProfileDetailViaFace(encodeImageBitmapToString(bitmap));
                Log.d("path",String.valueOf(Environment.getExternalStoragePublicDirectory(
                        Environment.DIRECTORY_PICTURES)));

              //  getApplicationContext().getContentResolver().delete(, "/storage/emulated/0/Pictures", null);
            //     mediaStorageDir.getPath().delete();

            } else {
                requestCameraPermission();
            }
        }

public void takeImageFromCamera() {

    File file = getOutputMediaFile(CAMERA_FILE_TYPE);

    if (Build.VERSION.SDK_INT >= 24) {
        try {

            Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure");
            m.invoke(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    picUri = Uri.fromFile(file);

    Intent takePictureIntent = new
   Intent(MediaStore.ACTION_IMAGE_CAPTURE_SECURE);
    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, picUri);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(takePictureIntent, CAMERA_REQUEST);
    }
    }

   private File getOutputMediaFile(int type) {
    mediaStorageDir  = new
     File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES), "peppercard");

    /**Create the storage directory if it does not exist*/
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            return null;
        }
    }

    /**Create a media file name*/
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());

    if (type == CAMERA_FILE_TYPE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                "IMG_" + timeStamp + ".jpeg");
    } else {
        return null;
    }
</code>```

}
        return mediaFile;

}

答:
The thing is I have some requirements where I do not want to save the picture when clicked using camera app

The decision of whether or not to save an image is up to the camera app, not you. There are hundreds of camera apps that might respond to ACTION_IMAGE_CAPTURE, and the developers of those apps can do whatever they want.

There has to be a solution of this issue, be it like once we take a picture we could delete it right away, or there should be an alternate by which we won't allow O.S to save Image,

Take the photo yourself, using the camera APIs or libraries that wrap around them (e.g., CameraKit-Android, Fotoapparat).

Title: Camera Intent - how to?

Body:
Sorry to bother you guys, but I am not able to get a solution where In we take picture using intents. I know the default behavior of native camera is to save the picture at default directory/place of O.S. The thing is I have some requirements where I do not want to save the picture when clicked using camera app. There has to be a solution of this issue, be it like once we take a picture we could delete it right away, or there should be an alternate by which we won't allow O.S to save Image, please help.

Here is a piece of code I tried, tried several ways by creating a directory and then deleting file, nothing works.

 public void takeImageFromCamera() {

        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(cameraIntent, CAMERA_REQUEST);
    }

  @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

// Check for the integer request code originally supplied to startResolutionForResult().
        if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {

            if (isCameraPermissionGranted()) {
                bitmap= (Bitmap) data.getExtras().get("data");
              //  bitmap = processReuiredImage(picUri);
                getProfileDetailViaFace(encodeImageBitmapToString(bitmap));
                Log.d("path",String.valueOf(Environment.getExternalStoragePublicDirectory(
                        Environment.DIRECTORY_PICTURES)));

              //  getApplicationContext().getContentResolver().delete(, "/storage/emulated/0/Pictures", null);
            //     mediaStorageDir.getPath().delete();

            } else {
                requestCameraPermission();
            }
        }

public void takeImageFromCamera() {

    File file = getOutputMediaFile(CAMERA_FILE_TYPE);

    if (Build.VERSION.SDK_INT >= 24) {
        try {

            Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure");
            m.invoke(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    picUri = Uri.fromFile(file);

    Intent takePictureIntent = new
   Intent(MediaStore.ACTION_IMAGE_CAPTURE_SECURE);
    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, picUri);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(takePictureIntent, CAMERA_REQUEST);
    }
    }

   private File getOutputMediaFile(int type) {
    mediaStorageDir  = new
     File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES), "peppercard");

    /**Create the storage directory if it does not exist*/
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            return null;
        }
    }

    /**Create a media file name*/
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());

    if (type == CAMERA_FILE_TYPE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                "IMG_" + timeStamp + ".jpeg");
    } else {
        return null;
    }

}
        return mediaFile;

}


问:
Does using tokens break REST principles
Does using tokens for authentication break REST principles, which is supposed to be stateless.

I have an application which is required to be REST and I stored some tokens in a database. Each time a user wants to do an action, they should get a token (by sending a username and a password) and send it to the server with every request.

答:
Authentication Tokens are a standard way of authenticating REST Clients.

Authentication token themselves do not beak REST principles as long as your API doesn't behave differently based on the Auth token passed to the API.

i.e. if 2 consumers place the same request with different auth token, and they are both allowed to perform that operation, the result should be the same.

You can find more info on REST API authentication here: https://dzone.com/articles/api-security-ways-to-authenticate-and-authorize

Title: Does using tokens break REST principles


问:
Plotting two curves with different x-datapoints in the same figure (Python, Pandas)
I want to have two curves with different x-datapoints shown in the same plot:

```<code>import pandas as pd

df1 = pd.DataFrame()
df1['Date']= ['2014-12-31', '2015-12-31', '2016-12-31', '2017-12-31']
df1['Value'] = [22, 44, 11, 55]
df2 = pd.DataFrame()
df2['Date']= ['2015-03-31', '2015-07-31', '2015-8-31', '2015-12-31']
df2['Value'] = [34, 39, 31, 27]

ax1 = df1.plot(x='Date', marker='o')
df2.plot(ax=ax1, marker='o')
</code>```

In the above code the 2nd curve (df2-data) uses the x-datapoints of the df1-data, not it's own.

I can make it work by manipulating the data (e.g. add the missing Dates in df1 and df2 with NaN accordingly), but I would like to know if there is something like a simple setting directly in the df.plot()-function.

答:
Note: I did convert those dates to datetimes using df['Date'] =
  pd.to_datetime(df.Date)

One way to do this is to use pd.concat then use pandas plot:

```<code>pd.concat([df1,df2], keys=['df1','df2'])\
  .set_index('Date', append=True)\
  .unstack(0)['Value']\
  .reset_index(0, drop=True)\
  .fillna(0).plot(marker='o')
</code>```

More like a scatter plot:

```<code>pd.concat([df1,df2], keys=['df1','df2'])\
   .set_index('Date', append=True)\
   .unstack(0)['Value']\
   .reset_index(0, drop=True)\
   .plot(marker='o',linestyle='none')
</code>```

Body:
I want to have two curves with different x-datapoints shown in the same plot:

import pandas as pd

df1 = pd.DataFrame()
df1['Date']= ['2014-12-31', '2015-12-31', '2016-12-31', '2017-12-31']
df1['Value'] = [22, 44, 11, 55]
df2 = pd.DataFrame()
df2['Date']= ['2015-03-31', '2015-07-31', '2015-8-31', '2015-12-31']
df2['Value'] = [34, 39, 31, 27]

ax1 = df1.plot(x='Date', marker='o')
df2.plot(ax=ax1, marker='o')

In the above code the 2nd curve (df2-data) uses the x-datapoints of the df1-data, not it's own.

I can make it work by manipulating the data (e.g. add the missing Dates in df1 and df2 with NaN accordingly), but I would like to know if there is something like a simple setting directly in the df.plot()-function.

Body:
Note: I did convert those dates to datetimes using df['Date'] =
  pd.to_datetime(df.Date)

One way to do this is to use pd.concat then use pandas plot:

pd.concat([df1,df2], keys=['df1','df2'])\
  .set_index('Date', append=True)\
  .unstack(0)['Value']\
  .reset_index(0, drop=True)\
  .fillna(0).plot(marker='o')

More like a scatter plot:

pd.concat([df1,df2], keys=['df1','df2'])\
   .set_index('Date', append=True)\
   .unstack(0)['Value']\
   .reset_index(0, drop=True)\
   .plot(marker='o',linestyle='none')


问:
Compare A Variable Regularaly Using Linux Scripts and Cron
I'm trying to check if a number differs from what it was last time it was checked, in this case checking a number every minute, using Linux scripts and cron.

eg:

```<code>newNum = getNum()

if oldNum != newNum: run some code

oldNum = newNum

(repeat every minute using crontab)
</code>```

But the problem I am having is that the variables aren't accessible between scripts and using source (eg. source script.sh) runs the script again, hence getting the latest version, not the one from a minute ago.

The best I've got is running a first script which gets the current number, then sleeps for a minute, then runs a second script which is essentially the first two lines of the code above.

eg:

```<code>oldNum = getNum()

sleep 60

export oldNum

script2.sh
</code>```

This seems inefficient to me and I'd like to know if there is a better solution if possible.

答:
You could cache the previous number in a file:</p>

```<code>number_cache=/path/to/cache_file

# read the previous number
oldNum=$(< "$number_cache" )
# acquire the new number
newNum=$(getNum)

if [[ "$oldNum" -eq "$newNum" ]]; then
    do_something
fi

# cache the new number
printf "%d\n" "$newNum" > "$number_cache"
</code>```

Body:
I'm trying to check if a number differs from what it was last time it was checked, in this case checking a number every minute, using Linux scripts and cron.

eg:

newNum = getNum()

if oldNum != newNum: run some code

oldNum = newNum

(repeat every minute using crontab)

But the problem I am having is that the variables aren't accessible between scripts and using source (eg. source script.sh) runs the script again, hence getting the latest version, not the one from a minute ago.

The best I've got is running a first script which gets the current number, then sleeps for a minute, then runs a second script which is essentially the first two lines of the code above.

eg:

oldNum = getNum()

sleep 60

export oldNum

script2.sh

This seems inefficient to me and I'd like to know if there is a better solution if possible.

Body:
You could cache the previous number in a file:

number_cache=/path/to/cache_file

# read the previous number
oldNum=$(< "$number_cache" )
# acquire the new number
newNum=$(getNum)

if [[ "$oldNum" -eq "$newNum" ]]; then
    do_something
fi

# cache the new number
printf "%d\n" "$newNum" > "$number_cache"


问:
How to invoke specific execution
I am trying to replace maven exec with MavenInvokerPlugin because of problems on Jenkins with forwarding the maven settings file.

So in bash it looks straight:

```<code>mvn dependency:copy-dependencies@resolve-maven-deps
</code>```

My translation to MavenInvokerPlugin configuration is

```<code>             <plugin>
                <artifactId>maven-invoker-plugin</artifactId>
                <version>3.0.1</version>
                <configuration>
                    <projectsDirectory>${project.basedir}/src/main/docker</projectsDirectory>
                    <localRepositoryPath>${project.build.mavenDependencies}</localRepositoryPath>
                    <goal>dependency:copy-dependencies@resolve-maven-deps</goal>
                </configuration>
                <executions>
                    <execution>
                        <id>integration-test</id>
                        <goals>
                            <goal>run</goal>
                        </goals>
                        <phase>compile</phase>
                    </execution>
                </executions>
            </plugin>
</code>```

It looks like that execution id is completely ignored, because I tried random strings and mvn builds the project with success.

```<code>mvn dependency:copy-dependencies@asdfasdfa
</code>```

So I'd like to know whether this feature is supported at all and what I am doing wrong.

P.S. I know that calling maven out of maven is anti pattern, but here is exactly that rare case when there is no other way.

答:
After looking at projects using maven invoker I figured out the trick.

goal tag is not used, instead provide invokerPropertiesFile:

```<code><pom>${project.basedir}/xxx/pom.xml</pom>
<invokerPropertiesFile>${project.basedir}/invoker.properties</invokerPropertiesFile>
</code>```

content of the file:

```<code>invoker.goals=compile -P resolve-maven-deps
</code>```

Title: How to invoke specific execution

Body:
I am trying to replace maven exec with MavenInvokerPlugin because of problems on Jenkins with forwarding the maven settings file.

So in bash it looks straight:

mvn dependency:copy-dependencies@resolve-maven-deps

My translation to MavenInvokerPlugin configuration is

             <plugin>
                <artifactId>maven-invoker-plugin</artifactId>
                <version>3.0.1</version>
                <configuration>
                    <projectsDirectory>${project.basedir}/src/main/docker</projectsDirectory>
                    <localRepositoryPath>${project.build.mavenDependencies}</localRepositoryPath>
                    <goal>dependency:copy-dependencies@resolve-maven-deps</goal>
                </configuration>
                <executions>
                    <execution>
                        <id>integration-test</id>
                        <goals>
                            <goal>run</goal>
                        </goals>
                        <phase>compile</phase>
                    </execution>
                </executions>
            </plugin>

It looks like that execution id is completely ignored, because I tried random strings and mvn builds the project with success.

mvn dependency:copy-dependencies@asdfasdfa

So I'd like to know whether this feature is supported at all and what I am doing wrong.

P.S. I know that calling maven out of maven is anti pattern, but here is exactly that rare case when there is no other way.

Body:
After looking at projects using maven invoker I figured out the trick.

goal tag is not used, instead provide invokerPropertiesFile:

<pom>${project.basedir}/xxx/pom.xml</pom>
<invokerPropertiesFile>${project.basedir}/invoker.properties</invokerPropertiesFile>

content of the file:

invoker.goals=compile -P resolve-maven-deps


问:
Visual Studio 2017 cMake diagram view
Recently I have opened a .sln project in VS 2017 and I noticed that I can view diagram of all classes - its 1st time I ever noticed it and I'm quite "wow this is epic".

I now have a cMake based project that I open via > open Folder > cmake root folder. Even tho it opens/ compiles I don't see any view diagram option. Does any1 know how to enable it?

答: CMake should generate a Visual Studio solution (sln). You need to run CMake and then open the generated solution which will be put in your build folder. You will have to view/edit your CMakeSettings.json to see where your build folder is when opening a CMake project in Visual Studio. Alternatively just run CMake from the command line to get the solution file.</p>

Title: Visual Studio 2017 cMake diagram view


问:
Download Neo4j server version 2.0.4
I could not find the Neo4j server version 2.0.4. The older releases that I could find are listed here https://neo4j.com/download/other-releases/. But the oldest release is 2.3.11. Does anyone know where I can find older versions?</p>

答:
You can download Neo4j 2.0.4 source code from this link on Neo4j Github Repo, but I strongly recommend you to use the current version of Neo4j database.

Building instructions of Neo4j 2.0.4 (from REDME.md)

Neo4j is built using Apache Maven version 3.0.x and a recent version of Java 7.

The Neo4j Browser module is built using Node.js. For skipping that part of the build, see below.

A plain mvn clean install will only build the individual jar files.

Test execution is, of course, part of the build.

To add execution of integration tests, use: mvn clean install -DrunITs

In case you just want the jars, without compiling the tests, this is for you: mvn clean install -DminimalBuild

To skip building the browser module, use -DskipBrowser (note that you might not be able to build the server without it.)

To build everything, including running all tests, producing documentation and assembling product packages, use mvn clean install -DfullBuild

To build the documentation see the Neo4j manual

When building on Windows, use -Dlicensing.skip to avoid problems related to line endings.

The license header check can be skipped by appending the following to the command line: -Dlicense.skip=true

Title: Download Neo4j server version 2.0.4


问:
replace value of a column if it is 0 by the value of another column SQLServer
HOW replace value of a column(cant_pallets_completo) if it is 0 by the value of another column (cant_sku)

```<code>SELECT SUM(cant_pallets_completo) AS 'volumen_de_pallets'
FROM estadistica_productividad_picking_rf
WHERE cd='faseSQL' AND c_emp_user_grua <> '' ;
</code>```

thanks!

答:
in case of SQL server you could try: </p>

```<code>    SELECT SUM(CASE WHEN cant_pallets_completo = 0
                    THEN cant_sku
                    ELSE cant_pallets_completo END) AS 'volumen_de_pallets'
    FROM estadistica_productividad_picking_rf
    WHERE cd='faseSQL' AND c_emp_user_grua <> '' ;
</code>```

Body:
HOW replace value of a column(cant_pallets_completo) if it is 0 by the value of another column (cant_sku)

SELECT SUM(cant_pallets_completo) AS 'volumen_de_pallets'
FROM estadistica_productividad_picking_rf
WHERE cd='faseSQL' AND c_emp_user_grua <> '' ;

thanks!

Body:
in case of SQL server you could try:

    SELECT SUM(CASE WHEN cant_pallets_completo = 0
                    THEN cant_sku
                    ELSE cant_pallets_completo END) AS 'volumen_de_pallets'
    FROM estadistica_productividad_picking_rf
    WHERE cd='faseSQL' AND c_emp_user_grua <> '' ;


问:
how to create a dictionary using lists in a python class?
I am trying to create a portfolio class. I want to zip my two lists into a dictionary but when a i try to print it out, it is empty(even though my lists are not). Am i missing something??</p>

```<code>import numpy as np

class Portfolio(object):
    """description of class"""

    array_of_stock_prices=[]
    array_of_stock_names=[]
    #create a dictionary of stocks
    stocks=dict(zip(array_of_stock_names,array_of_stock_prices))

    def __init__(self):
        print()

    def AddStock(self,stock_ticker,stock_price):
        self.array_of_stock_names.append(stock_ticker)
        self.array_of_stock_prices.append(stock_price)

    def printObject(self):
        for key,value in self.stocks.items():
            print(key,value)

port1=Portfolio()
port1.AddStock('AApl',100)
port1.printObject()
</code>```

答:
You create the dictionary only once, with empty lists. If you want to keep it up to date, put that line of code after every extension of the lists (in the end of AddStock), and keep this dictionary as an attribute of self, like

```<code>self.stocks = dict(zip(self.array_of_stock_names, self.array_of_stock_prices))
</code>```

Body:
I am trying to create a portfolio class. I want to zip my two lists into a dictionary but when a i try to print it out, it is empty(even though my lists are not). Am i missing something??

import numpy as np

class Portfolio(object):
    """description of class"""

    array_of_stock_prices=[]
    array_of_stock_names=[]
    #create a dictionary of stocks
    stocks=dict(zip(array_of_stock_names,array_of_stock_prices))

    def __init__(self):
        print()

    def AddStock(self,stock_ticker,stock_price):
        self.array_of_stock_names.append(stock_ticker)
        self.array_of_stock_prices.append(stock_price)

    def printObject(self):
        for key,value in self.stocks.items():
            print(key,value)

port1=Portfolio()
port1.AddStock('AApl',100)
port1.printObject()

Body:
You create the dictionary only once, with empty lists. If you want to keep it up to date, put that line of code after every extension of the lists (in the end of AddStock), and keep this dictionary as an attribute of self, like

self.stocks = dict(zip(self.array_of_stock_names, self.array_of_stock_prices))


问:
dynamic LINQ query
Hi I am using dynamic linq, using PredicateBuilder of LinqKit.

If you look at the code, line after TODO comment, i want to accomplish something like
Lets say there are 2 objects in objectList viz. object1, object2
(object1.property1 AND object1.property2) OR (object2.property1 AND object2.property2)

I know the line after TODO is incorrect, but I am looking for correct version of that line.

```

  var finalPredicate = PredicateBuilder.True();

  foreach (var item in objectList)
  {
    var predicate = PredicateBuilder.True();
    predicate = predicate.And (p => p.Description.Contains (item.property1));
    predicate = predicate.And (p => p.Description.Contains (item.property2));
    //TODO:
    finalPredicate = finalPredicate.Or(predicate);
  }
}
```

答:
```<code>var finalPredicate = PredicateBuilder.True();
</code>```

should be

```<code>var finalPredicate = PredicateBuilder.False();
</code>```

True or x = always true (x is ignored).

False or x = x.

The other problem is the way loop variables are captured in lambda expressions.

```<code>foreach (var item in objectList)
{
  var loopItem = item;
  //now use loopItem instead of item.
  ...
}
</code>```

Title: dynamic LINQ query

Body:
Hi I am using dynamic linq, using PredicateBuilder of LinqKit.

If you look at the code, line after TODO comment, i want to accomplish something like
Lets say there are 2 objects in objectList viz. object1, object2
(object1.property1 AND object1.property2) OR (object2.property1 AND object2.property2)

I know the line after TODO is incorrect, but I am looking for correct version of that line.

  var finalPredicate = PredicateBuilder.True();

  foreach (var item in objectList)
  {
    var predicate = PredicateBuilder.True();
    predicate = predicate.And (p => p.Description.Contains (item.property1));
    predicate = predicate.And (p => p.Description.Contains (item.property2));
    //TODO:
    finalPredicate = finalPredicate.Or(predicate);
  }
}

Body:
var finalPredicate = PredicateBuilder.True();

should be

var finalPredicate = PredicateBuilder.False();

True or x = always true (x is ignored).

False or x = x.

The other problem is the way loop variables are captured in lambda expressions.

foreach (var item in objectList)
{
  var loopItem = item;
  //now use loopItem instead of item.
  ...
}


问:
Verifying HMAC from Microsoft Teams custom Bot in PHP
I am trying to authenticate a Microsoft Teams custom Bot with PHP, following the Microsoft instructions and read de C# example code.

Microsoft Intructions steps:

  1. Generate the hmac from the request body of the message. There are standard libraries on most platforms. Microsoft Teams uses standard
  SHA256 HMAC cryptography. You will need to convert the body to a byte
  array in UTF8.

  2. To compute the hash, provide the byte array of the shared secret.

  3. Convert the hash to a string using UTF8 encoding.

  4. Compare the string value of the generated hash with the value provided in the HTTP request.

I had write a small php script to test this in local:

```<code>        <?php
        //Function to generate C# byte[] equivalent
        function unpak_str($val){
            $b = unpack('C*', $val);
            foreach ($b as $key => $value)
                $byte_a .= $value;

           return $byte_a;
          }

        //multi test outputs
        function hasher($values=[], &$output){
            //my secret share
            $secret="ejWiKHgsKY1ZfpJwJ+wIiN4+bgsFad/lkpu9/MWNXgM=";
            //diferent test
            $secret_64=base64_decode($secret);
            $secret_b=unpak_str($secret);
            $secret_b_64=unpak_str(base64_decode($secret));

            foreach($values as $msg){
                $hs = hash_hmac("sha256",$msg,$secret, true);
                $hs_64 = hash_hmac("sha256",$msg,$secret_64, true);
                $hs_b = hash_hmac("sha256",$msg,$secret_b, true);
                $hs_b_64 = hash_hmac("sha256",$msg,$secret_b_64, true);

                $output.=base64_encode($hs)." <BR>";
                $output.=base64_encode($hs_64)." <BR>";
                $output.=base64_encode($hs_b)." <BR>";
                $output.=base64_encode($hs_b_64)." <BR>";
             }
          }

    //Get data
    $data=file_get_contents('php://input');

    //real data request content for test
    $data ='{type":"message","id":"1512376018086","timestamp":"2017-12-04T08:26:58.237Z","localTimestamp":"2017-12-04T09:26:58.237+01:00","serviceUrl":"https://smba.trafficmanager.net/emea-client-ss.msg/","channelId":"msteams","from":{"id":"29:1aq6GCrC6lM9dv3YkAYi1gxTPiLnojGFgVr0_Th-2x6DhqmHAOhFwQHFzSyDy5RruXY4_FZjJebKHU7bpxfHpXA","name":"ROBERTO ALONSO FERNANDEZ","aadObjectId":"1e0dc7a0-9d5e-488b-bcf2-7e39c84076b8"},"conversation":{"isGroup":true,"id":"19:9e1c52275dfb4d0b873ddf34eb9f4979@thread.skype;messageid=1512376018086","name":null},"recipient":null,"textFormat":"plain","attachmentLayout":null,"membersAdded":[],"membersRemoved":[],"topicName":null,"historyDisclosed":null,"locale":null,"text":"<at>PandoBot</at> fff","speak":null,"inputHint":null,"summary":null,"suggestedActions":null,"attachments":[{"contentType":"text/html","contentUrl":null,"content":"<div><span itemscope=\"\" itemtype=\"http://schema.skype.com/Mention\" itemid=\"0\">PandoBot</span> fff</div>","name":null,"thumbnailUrl":null}],"entities":[{"type":"clientInfo","locale":"es-ES","country":"ES","platform":"iOS"}],"channelData":{"teamsChannelId":"19:9e1c52275dfb4d0b873ddf34eb9f4979@thread.skype","teamsTeamId":"19:1e04f564ce5e4596bf2f266dbcff439e@thread.skype","channel":{"id":"19:9e1c52275dfb4d0b873ddf34eb9f4979@thread.skype"},"team":{"id":"19:1e04f564ce5e4596bf2f266dbcff439e@thread.skype"},"tenant":{"id":"9744600e-3e04-492e-baa1-25ec245c6f10"}},"action":null,"replyToId":null,"value":null,"name":null,"relatesTo":null,"code":null}';

    //generate HMAC hash with diferent $data formats
    $test = [$data, unpak_str($data), base64_encode($data), unpak_str(base64_encode($data))];
    hasher($test, $output);

    //microsoft provided HMAC
    $output.="<HR>EW2993goL1q7nGhytIb3jKmV6luXLz15Bq2aYwuCeiE=";

    echo $output;
    /*
    Calculates:
    0HsKoHza/QBvdz+nZw9tOti/eSWjyMMt/U77bfDqiE8=
    3jSq3I0HNQkjB9QfnnsxC1c3pF5PjqweHlSVcicrShY=
    bTQcGVTHX8/Gh4xovnN0WiJUiNaOQwvUZnwyFfiCaJE=
    qHBT2Y2ITyoxz2gmBbG8P1CrClvETus6dTffET3bAR8=
    8BcrXEQDDi77qgxCZLYyb/6ez8p9Qg2ZhTyZPWkdn/g=
    +8RSU5SSJKxqRLKkI+NkTE01xwu6PwPkKKMuvyyUvlo=
    PdL5ZpEwcN6Fe5kfX7zeAZLJvt0uLNTzu7lhuoOcr2o=
    s6M5pYruEgWeNMEOFfQRjVKQqtPBVaW3TJb2MzObF2c=
    xOTLhddbAwczQVneuTDQhPzmoIXGQljpf27c+hlhQII=
    aUMm5b2sKfmwGZOglfiu228fWqoLlwjc7z1QRdIbakE=
    5a7bAj9tzqhP9l85OvfVasURW0GSV5rykRutFFPO2fk=
    kwg6P2LoDL9rc3SSwJxQeoYJzZYlh+FHFefe38UokBM=
    eHeAzI7TV6vYDzxTxwyKWxMeVKFiFlIffWRiIMAk6fk=
    ZCyj2UppacQOTXogLPMFLDeMArQg03rhhlIwhynDvng=
    uQYK+7u9fppb62zXqtVYfkNK9wVawB3g+BlTyu4dc74=
    vjOFA3fqpwUx/VO9dQv3XviNhpjTNQsUwaJIwH4JjdY=
    ------------ MS PROVIDED HMAC ---------------
    EW2993goL1q7nGhytIb3jKmV6luXLz15Bq2aYwuCeiE=
     */
</code>```

I've zero hash matching...

答:
You don't need unpack(), or that unpak_str() function (which is also broken because it just overwrites each byte with the next one, not appending them).

Byte arrays are not a thing in PHP - the language doesn't have different string types; how strings are interpreted is entirely up to the functions using them. That is, your shared secret should be just the result of base64_encode($secret).

Body:
I am trying to authenticate a Microsoft Teams custom Bot with PHP, following the Microsoft instructions and read de C# example code.

Microsoft Intructions steps:

  1. Generate the hmac from the request body of the message. There are standard libraries on most platforms. Microsoft Teams uses standard
  SHA256 HMAC cryptography. You will need to convert the body to a byte
  array in UTF8.

  2. To compute the hash, provide the byte array of the shared secret.

  3. Convert the hash to a string using UTF8 encoding.

  4. Compare the string value of the generated hash with the value provided in the HTTP request.

I had write a small php script to test this in local:

        <?php
        //Function to generate C# byte[] equivalent
        function unpak_str($val){
            $b = unpack('C*', $val);
            foreach ($b as $key => $value)
                $byte_a .= $value;

           return $byte_a;
          }

        //multi test outputs
        function hasher($values=[], &$output){
            //my secret share
            $secret="ejWiKHgsKY1ZfpJwJ+wIiN4+bgsFad/lkpu9/MWNXgM=";
            //diferent test
            $secret_64=base64_decode($secret);
            $secret_b=unpak_str($secret);
            $secret_b_64=unpak_str(base64_decode($secret));

            foreach($values as $msg){
                $hs = hash_hmac("sha256",$msg,$secret, true);
                $hs_64 = hash_hmac("sha256",$msg,$secret_64, true);
                $hs_b = hash_hmac("sha256",$msg,$secret_b, true);
                $hs_b_64 = hash_hmac("sha256",$msg,$secret_b_64, true);

                $output.=base64_encode($hs)."
";
                $output.=base64_encode($hs_64)."
";
                $output.=base64_encode($hs_b)."
";
                $output.=base64_encode($hs_b_64)."
";
             }
          }

    //Get data
    $data=file_get_contents('php://input');

    //real data request content for test
    $data ='{type":"message","id":"1512376018086","timestamp":"2017-12-04T08:26:58.237Z","localTimestamp":"2017-12-04T09:26:58.237+01:00","serviceUrl":"https://smba.trafficmanager.net/emea-client-ss.msg/","channelId":"msteams","from":{"id":"29:1aq6GCrC6lM9dv3YkAYi1gxTPiLnojGFgVr0_Th-2x6DhqmHAOhFwQHFzSyDy5RruXY4_FZjJebKHU7bpxfHpXA","name":"ROBERTO ALONSO FERNANDEZ","aadObjectId":"1e0dc7a0-9d5e-488b-bcf2-7e39c84076b8"},"conversation":{"isGroup":true,"id":"19:9e1c52275dfb4d0b873ddf34eb9f4979@thread.skype;messageid=1512376018086","name":null},"recipient":null,"textFormat":"plain","attachmentLayout":null,"membersAdded":[],"membersRemoved":[],"topicName":null,"historyDisclosed":null,"locale":null,"text":"<at>PandoBot</at> fff","speak":null,"inputHint":null,"summary":null,"suggestedActions":null,"attachments":[{"contentType":"text/html","contentUrl":null,"content":"
PandoBot fff
","name":null,"thumbnailUrl":null}],"entities":[{"type":"clientInfo","locale":"es-ES","country":"ES","platform":"iOS"}],"channelData":{"teamsChannelId":"19:9e1c52275dfb4d0b873ddf34eb9f4979@thread.skype","teamsTeamId":"19:1e04f564ce5e4596bf2f266dbcff439e@thread.skype","channel":{"id":"19:9e1c52275dfb4d0b873ddf34eb9f4979@thread.skype"},"team":{"id":"19:1e04f564ce5e4596bf2f266dbcff439e@thread.skype"},"tenant":{"id":"9744600e-3e04-492e-baa1-25ec245c6f10"}},"action":null,"replyToId":null,"value":null,"name":null,"relatesTo":null,"code":null}';

    //generate HMAC hash with diferent $data formats
    $test = [$data, unpak_str($data), base64_encode($data), unpak_str(base64_encode($data))];
    hasher($test, $output);

    //microsoft provided HMAC
    $output.="
EW2993goL1q7nGhytIb3jKmV6luXLz15Bq2aYwuCeiE=";

    echo $output;
    /*
    Calculates:
    0HsKoHza/QBvdz+nZw9tOti/eSWjyMMt/U77bfDqiE8=
    3jSq3I0HNQkjB9QfnnsxC1c3pF5PjqweHlSVcicrShY=
    bTQcGVTHX8/Gh4xovnN0WiJUiNaOQwvUZnwyFfiCaJE=
    qHBT2Y2ITyoxz2gmBbG8P1CrClvETus6dTffET3bAR8=
    8BcrXEQDDi77qgxCZLYyb/6ez8p9Qg2ZhTyZPWkdn/g=
    +8RSU5SSJKxqRLKkI+NkTE01xwu6PwPkKKMuvyyUvlo=
    PdL5ZpEwcN6Fe5kfX7zeAZLJvt0uLNTzu7lhuoOcr2o=
    s6M5pYruEgWeNMEOFfQRjVKQqtPBVaW3TJb2MzObF2c=
    xOTLhddbAwczQVneuTDQhPzmoIXGQljpf27c+hlhQII=
    aUMm5b2sKfmwGZOglfiu228fWqoLlwjc7z1QRdIbakE=
    5a7bAj9tzqhP9l85OvfVasURW0GSV5rykRutFFPO2fk=
    kwg6P2LoDL9rc3SSwJxQeoYJzZYlh+FHFefe38UokBM=
    eHeAzI7TV6vYDzxTxwyKWxMeVKFiFlIffWRiIMAk6fk=
    ZCyj2UppacQOTXogLPMFLDeMArQg03rhhlIwhynDvng=
    uQYK+7u9fppb62zXqtVYfkNK9wVawB3g+BlTyu4dc74=
    vjOFA3fqpwUx/VO9dQv3XviNhpjTNQsUwaJIwH4JjdY=
    ------------ MS PROVIDED HMAC ---------------
    EW2993goL1q7nGhytIb3jKmV6luXLz15Bq2aYwuCeiE=
     */

I've zero hash matching...