问:
unable to create superuser in python Django
I have read questions in Stackoverflow and googled, but no luck.

I am trying to create a superuser in pycharm(manage.py createsuperuser
) but got below error:

"cassandra.protocol.SyntaxException: "

```<code>Not checking migrations as it is not possible to access/create the django_migrations table.
Traceback (most recent call last):
  File "C:\Users\skum\PQP_Bridge\manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line
    utility.execute()
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 355, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Python27\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 63, in execute
    return super(Command, self).execute(*args, **options)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 330, in execute
    output = self.handle(*args, **options)
  File "C:\Python27\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 96, in handle
    default_username = get_default_username()
  File "C:\Python27\lib\site-packages\django\contrib\auth\management\__init__.py", line 148, in get_default_username
    auth_app.User._default_manager.get(username=default_username)
  File "C:\Python27\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Python27\lib\site-packages\django\db\models\query.py", line 374, in get
    num = len(clone)
  File "C:\Python27\lib\site-packages\django\db\models\query.py", line 232, in __len__
    self._fetch_all()
  File "C:\Python27\lib\site-packages\django\db\models\query.py", line 1118, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "C:\Python27\lib\site-packages\django\db\models\query.py", line 53, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch)
  File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py", line 894, in execute_sql
    raise original_exception
cassandra.protocol.SyntaxException: <Error from server: code=2000 [Syntax error in CQL query] message="line 1:260 no viable alternative at input '.' (
...auth_user.date_joined FROM auth_user WHERE [auth_user]....)">
</code>```

what am I doing wrong?

I am using Cassandra 3.0, Python Django 1.11.4, and pycharm.

答:
We can not use: python manage.py createsuperuser using Cassandra It do not work with default django model. You need to use external library for the same. user module does not work with Cassandra by default

Please read document on data-stax or below given link. https://pypi.python.org/pypi/django-cassandra-engine/

Body:
I have read questions in Stackoverflow and googled, but no luck.

I am trying to create a superuser in pycharm(manage.py createsuperuser
) but got below error:

"cassandra.protocol.SyntaxException: "

Not checking migrations as it is not possible to access/create the django_migrations table.
Traceback (most recent call last):
  File "C:\Users\skum\PQP_Bridge\manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line
    utility.execute()
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 355, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Python27\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 63, in execute
    return super(Command, self).execute(*args, **options)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 330, in execute
    output = self.handle(*args, **options)
  File "C:\Python27\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 96, in handle
    default_username = get_default_username()
  File "C:\Python27\lib\site-packages\django\contrib\auth\management\__init__.py", line 148, in get_default_username
    auth_app.User._default_manager.get(username=default_username)
  File "C:\Python27\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Python27\lib\site-packages\django\db\models\query.py", line 374, in get
    num = len(clone)
  File "C:\Python27\lib\site-packages\django\db\models\query.py", line 232, in __len__
    self._fetch_all()
  File "C:\Python27\lib\site-packages\django\db\models\query.py", line 1118, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "C:\Python27\lib\site-packages\django\db\models\query.py", line 53, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch)
  File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py", line 894, in execute_sql
    raise original_exception
cassandra.protocol.SyntaxException: <Error from server: code=2000 [Syntax error in CQL query] message="line 1:260 no viable alternative at input '.' (
...auth_user.date_joined FROM auth_user WHERE [auth_user]....)">

what am I doing wrong?

I am using Cassandra 3.0, Python Django 1.11.4, and pycharm.


来源: stackexchange

问:
Unselect the select all checkbox when one of the other checkboxes is unselected
I iterate through an array to create some checkboxes, like below:

```<code><div class="funnels">
    <label class="checkbox-inline">
    <input type="checkbox" id="selectall"> onClick="selectAll(this)" />All funnels
    </label>
    <?php foreach ($funnels as $funnel) { ?>
        <label class="checkbox-inline">
        <input type="checkbox" name="funnel[]" id ="funnel" value="<?php echo $funnel ?>" ><?php echo $funnel ?>
        </label>
    <?php } ?>
</div>
</code>```

I use the following javascript to select all checkboxes when the All checkbox has been clicked. What I need to do is to unselect the all checkbox once one of the other checkboxes has been unchecked.
Any help would be appreciated.

```<code>  function selectAll(source) {
         checkboxes = document.getElementsByName('funnel[]');
                for(i=0;i<checkboxes.length;i++)
                checkboxes[i].checked = source.checked;
    }
</code>```

答:
The id should be unique; so consider using class instead of id.

```<code>function selectAll(source) {
         checkboxes = document.querySelector('funnel[]');
                for(i=0;i<checkboxes.length;i++)
                checkboxes[i].checked = source.checked;
    }
</code>```

function selectAll(source) {

  var checkboxes = document.querySelectorAll('.funnel');

  for(i=0;i<checkboxes.length;i++)
     checkboxes[i].checked = source.checked;
}

function unSelect(element) {
if(!element.checked){
// uncheck "select all" when 1,2 or 3 is unchecked
  document.querySelector('#selectall').checked = false;
  // if you want to unselect also the others checkboxes of the class "funnel",uncomment the following block
  /*var others = document.querySelectorAll('.funnel');

  for(i=0;i<others.length;i++)
     others[i].checked = false;*/

}else{
// check "select all" when 1, 2, 3 is checked
  document.querySelector('#selectall').checked = true;
}

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox" onclick="selectAll(this)" id="selectall"/> all select <br>

<input type="checkbox" class = "funnel" onclick="unSelect(this)"/> 1 <br>
<input type="checkbox" class = "funnel" onclick="unSelect(this)"/> 2 <br>
<input type="checkbox" class = "funnel" onclick="unSelect(this)"/> 3 <br></code>```

ContentLicense: CC BY-SA 3.0

Body:
I iterate through an array to create some checkboxes, like below:

    <input type="checkbox" id="selectall"> onClick="selectAll(this)" />All funnels

    <?php foreach ($funnels as $funnel) { ?>

        <input type="checkbox" name="funnel[]" id ="funnel" value="<?php echo $funnel ?>" ><?php echo $funnel ?>

    <?php } ?>

I use the following javascript to select all checkboxes when the All checkbox has been clicked. What I need to do is to unselect the all checkbox once one of the other checkboxes has been unchecked.
Any help would be appreciated.

  function selectAll(source) {
         checkboxes = document.getElementsByName('funnel[]');
                for(i=0;i<checkboxes.length;i++)
                checkboxes[i].checked = source.checked;
    }

Body:
The id should be unique; so consider using class instead of id.

function selectAll(source) {
         checkboxes = document.querySelector('funnel[]');
                for(i=0;i<checkboxes.length;i++)
                checkboxes[i].checked = source.checked;
    }

function selectAll(source) {

  var checkboxes = document.querySelectorAll('.funnel');

  for(i=0;i<checkboxes.length;i++)
     checkboxes[i].checked = source.checked;
}

function unSelect(element) {
if(!element.checked){
// uncheck "select all" when 1,2 or 3 is unchecked
  document.querySelector('#selectall').checked = false;
  // if you want to unselect also the others checkboxes of the class "funnel",uncomment the following block
  /*var others = document.querySelectorAll('.funnel');

  for(i=0;i<others.length;i++)
     others[i].checked = false;*/

}else{
// check "select all" when 1, 2, 3 is checked
  document.querySelector('#selectall').checked = true;
}

}

<input type="checkbox" onclick="selectAll(this)" id="selectall"/> all select <br>

<input type="checkbox" class = "funnel" onclick="unSelect(this)"/> 1 <br>
<input type="checkbox" class = "funnel" onclick="unSelect(this)"/> 2 <br>
<input type="checkbox" class = "funnel" onclick="unSelect(this)"/> 3 <br>


问:
Visual Studio 2010 Express C# limitations
I am trying to develop the nerddinner mvc website, so I downloaded Visual Studio 2010 Express but I do not see an option for MVC or even asp.net website.  Can I download this for Visual Studio?</p>

答:
Visual web developer express is what your looking for

http://www.microsoft.com/express/Web/

ContentLicense: CC BY-SA 2.5


问:
running queries in firebase using async / await
Appreciating that firebase has added support for promises, is there a way to run a query like the following inside of an async function?:

```<code>const eventref = this.db.ref('cats/whiskers');
const value = await eventref.once('value')
</code>```

Running the above returns a promise for value, I'm hoping to get the json blob that is stored at cats/whiskers.

答:
The result of value is a snapshot, we need 1 more step to get the value. This should be like:

```<code>const eventref = this.db.ref('cats/whiskers');
const snapshot = await eventref.once('value');
const value = snapshot.val();
</code>```

Body:
Appreciating that firebase has added support for promises, is there a way to run a query like the following inside of an async function?:

const eventref = this.db.ref('cats/whiskers');
const value = await eventref.once('value')

Running the above returns a promise for value, I'm hoping to get the json blob that is stored at cats/whiskers.

Body:
The result of value is a snapshot, we need 1 more step to get the value. This should be like:

const eventref = this.db.ref('cats/whiskers');
const snapshot = await eventref.once('value');
const value = snapshot.val();


问:
Implementing tar command in c
I'm trying to create a basic version of the linux "tar" command using C, i used perror to see if there are any errors during execution, and i got this

```<code>./tar
Error2: Bad file descriptor
</code>```

and this is what i did so far

```<code>#include <stdio.h>
#include <libtar.h>
#include <fcntl.h>

int main(void)
{
   TAR *pTar;
   char *prefix = ".";
   char *filename = "file.tar";

   if ((tar_open(&pTar, filename, NULL, O_WRONLY, 0644, TAR_GNU)) == -1)
     perror("Error1");
   else if ((tar_extract_all(pTar, prefix)) == -1)
     perror("Error2");
   else if ((tar_close(pTar)) == -1)
     perror("Error3");
}
</code>```

Thanks in advance:)

答:
For any one referencing to this in the future,

while creating the tar - say abc.tar
if you have appended the abc.tar (it is also in the same directory and append_tree appends all file, including the one),  your abc.tar file, on tar_extract_all, this .tar file (with the same name) is also extracted overwriting the original tar file.

atleast this was what causing the mysterious "Invalid argument" for me.
I fixed it by renaming the original file before extracting.

Title: Implementing tar command in c

Body:
I'm trying to create a basic version of the linux "tar" command using C, i used perror to see if there are any errors during execution, and i got this

./tar
Error2: Bad file descriptor

and this is what i did so far

#include <stdio.h>
#include <libtar.h>
#include <fcntl.h>

int main(void)
{
   TAR *pTar;
   char *prefix = ".";
   char *filename = "file.tar";

   if ((tar_open(&pTar, filename, NULL, O_WRONLY, 0644, TAR_GNU)) == -1)
     perror("Error1");
   else if ((tar_extract_all(pTar, prefix)) == -1)
     perror("Error2");
   else if ((tar_close(pTar)) == -1)
     perror("Error3");
}

Thanks in advance:)


问:
Xcode 9.1 iOS simulator Window > Physical Size disabled
I need to make screen shots (specifically iPad Pro 12.9") for the App Store. I resized the simulator to fit it on my mac's screen. Now I can't resize it back to 100%, which is required to make a new screen shot. Both sizing options, Physical Size (Cmd-1) and Pixel Accurate (Cmd-2) are grayed out. How do I reset the simulator back to 100%?

Workaround: I was able to manually resize the simulator window using the mouse to grab the corner (the new way to adjust size in 9.1). Using trial-and-error by resizing, making new screen shots, and checking the resulting pixel dimensions, I was able to manually get it back to 100% (2048x2732). The original question still remains; is there a way to reset the simulator to 100% without using this workaround?

答: In xcode(mine is 9.1), uncheck Window->Show Device Brezels to make changes on simulator, then check it to make screenshots.</p>


问:
Set date input field's max date to today
I just have a simple line of code like this:

```<code><input type='date' min='1899-01-01' max='2000-01-01'></input>
</code>```

Is there a simple way to set the max date to "today" instead of 2000-01-01? Or do I have to use Javascript to do this?

答:
I also had same issue .I build it trough this way.I used struts 2 framework.

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

  $(document).ready(function () {
  var year = (new Date).getFullYear();
  $( "#effectiveDateId" ).datepicker({dateFormat: "mm/dd/yy", maxDate:
  0});

  });

  </script>

        <s:textfield name="effectiveDate" cssClass="input-large"
   key="label.warrantRateMappingToPropertyTypeForm.effectiveDate"
   id="effectiveDateId" required="true"/>
</code>```

This worked for me.

Body:
I just have a simple line of code like this:

<input type='date' min='1899-01-01' max='2000-01-01'></input>

Is there a simple way to set the max date to "today" instead of 2000-01-01? Or do I have to use Javascript to do this?

Body:
I also had same issue .I build it trough this way.I used struts 2 framework.

  <script type="text/javascript">

  $(document).ready(function () {
  var year = (new Date).getFullYear();
  $( "#effectiveDateId" ).datepicker({dateFormat: "mm/dd/yy", maxDate:
  0});

  });

  </script>

        <s:textfield name="effectiveDate" cssClass="input-large"
   key="label.warrantRateMappingToPropertyTypeForm.effectiveDate"
   id="effectiveDateId" required="true"/>

This worked for me.


问:
Implement Gocardless webhook in Laravel
I was trying to implement a webhook in laravel.

I have created access token and created webhook endpoint also.

my webhook end point is like,https://www.example.com/gocardless.php

and my route is like,

```<code>Route::get('/gocardless.php',
'\App\Http\Controllers\gocardlessController@remote')->name('remote');
</code>```

Controller code like,

```<code>class gocardlessController extends Controller
 {

  public function remote(Request $request)
  {

 $token ="token";

 $raw_payload = file_get_contents('php://input');

 $headers = getallheaders();

 $provided_signature = $headers["Webhook-Signature"];
 $calculated_signature = hash_hmac("sha256",$raw_payload,$token);
 if ($provided_signature == $calculated_signature) {

  $payload = json_decode($raw_payload, true);
   }
   }
   }
</code>```

But when i clik on send test webhook in gocardless account,they are given "405 no method found" as responce.

How i can solve this?

答:
A few remarks and fixes

Remark

Why do you include the "ugly" .php extension in your route, there is no need for that

Fix

Change your route (in web.php) to

```<code>Route::get('gocardless', 'gocardlessController@remote');
</code>```

Remark

I also see you start your controller name with lowercase, this is not common practise

Fix

Don't forget to add these lines in your controller at the top

```<code>namespace App\Http\Controllers; // declare right namespace

use Illuminate\Http\Request; // Hint which Request class to use below
</code>```

For the body: that you really have to write yourself and return the data as json for example

Title: Implement Gocardless webhook in Laravel

Body:
I was trying to implement a webhook in laravel.

I have created access token and created webhook endpoint also.

my webhook end point is like,https://www.example.com/gocardless.php

and my route is like,

Route::get('/gocardless.php',
'\App\Http\Controllers\gocardlessController@remote')->name('remote');

Controller code like,

class gocardlessController extends Controller
 {

  public function remote(Request $request)
  {

 $token ="token";

 $raw_payload = file_get_contents('php://input');

 $headers = getallheaders();

 $provided_signature = $headers["Webhook-Signature"];
 $calculated_signature = hash_hmac("sha256",$raw_payload,$token);
 if ($provided_signature == $calculated_signature) {

  $payload = json_decode($raw_payload, true);
   }
   }
   }

But when i clik on send test webhook in gocardless account,they are given "405 no method found" as responce.

How i can solve this?

Body:
A few remarks and fixes

Remark

Why do you include the "ugly" .php extension in your route, there is no need for that

Fix

Change your route (in web.php) to

Route::get('gocardless', 'gocardlessController@remote');

Remark

I also see you start your controller name with lowercase, this is not common practise

Fix

Don't forget to add these lines in your controller at the top

namespace App\Http\Controllers; // declare right namespace

use Illuminate\Http\Request; // Hint which Request class to use below

For the body: that you really have to write yourself and return the data as json for example


问:
How to keep imports neat in Django?
This might seem like a subjective question, but I'm sure there are good techniques that some of you employ to ensure the imports in Django projects stay maintainable. I'm used to having a list of about 30 different imports in every file, and that clearly violates the DRY principle. So it's not just about aesthetics, it's also about not duplicating code.

I'm looking for  a method that keeps the import sections in Django files manageable. What seems to me like a good idea is to have a generic import file for every file type (views, models, etc.), which is then imported at the top, with further application-specific imports after that. But would that cause a lot of unnecessary overhead? How should those files look, and what are the important classes for every file-type?

Update

On request, here is an example from one of my views.py files.

```<code>from django.shortcuts import render_to_response, get_object_or_404
from shortcuts import render_to_context, render_template
from django.http import HttpResponseRedirect
from django.contrib.comments.models import Comment
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_POST

from django.core.urlresolvers import reverse

from models import Listing, LocationData

from django.template import RequestContext

import sys
import urllib
if sys.version_info <= (2, 5):
    import simplejson as json
else:
    import json

import forms
import sanitize

from models import RentListing, VacationListing, SaleListing

from django.forms.models import model_to_dict
from django.forms.formsets import formset_factory

from django.core.urlresolvers import reverse
</code>```

which, as you can see, is just really messy, since I just add to the bottom of the list every time I need something in the file. Keeping it in alphabetical order would obviously help, but there has to be a better way to generalize than what I'm doing now.

Is it worth breaking the style guideline of not using the * import for the sake of shorter, more maintainable import sections in the actual file?

答: Tomasz already mentioned one interesting part of google's documentation concerning imports, but I think also this section is worth reading!</p>

Title: How to keep imports neat in Django?

Body:
This might seem like a subjective question, but I'm sure there are good techniques that some of you employ to ensure the imports in Django projects stay maintainable. I'm used to having a list of about 30 different imports in every file, and that clearly violates the DRY principle. So it's not just about aesthetics, it's also about not duplicating code.

I'm looking for  a method that keeps the import sections in Django files manageable. What seems to me like a good idea is to have a generic import file for every file type (views, models, etc.), which is then imported at the top, with further application-specific imports after that. But would that cause a lot of unnecessary overhead? How should those files look, and what are the important classes for every file-type?

Update

On request, here is an example from one of my views.py files.

from django.shortcuts import render_to_response, get_object_or_404
from shortcuts import render_to_context, render_template
from django.http import HttpResponseRedirect
from django.contrib.comments.models import Comment
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_POST

from django.core.urlresolvers import reverse

from models import Listing, LocationData

from django.template import RequestContext

import sys
import urllib
if sys.version_info <= (2, 5):
    import simplejson as json
else:
    import json

import forms
import sanitize

from models import RentListing, VacationListing, SaleListing

from django.forms.models import model_to_dict
from django.forms.formsets import formset_factory

from django.core.urlresolvers import reverse

which, as you can see, is just really messy, since I just add to the bottom of the list every time I need something in the file. Keeping it in alphabetical order would obviously help, but there has to be a better way to generalize than what I'm doing now.

Is it worth breaking the style guideline of not using the * import for the sake of shorter, more maintainable import sections in the actual file?


问:
ceph runtime config is not the same with ceph.conf
i am using ceph-deploy to deploy ceph cluster. after deployment is finished, i found the runtime config is not the same with ceph.conf. i did not modify the runtime config in manual.

```<code>[root@sz02 ~]# ceph daemon osd.0 config show | grep rbd_cache
"rbd_cache": "true",
"rbd_cache_writethrough_until_flush": "true",
"rbd_cache_size": "33554432",
"rbd_cache_max_dirty": "25165824",
"rbd_cache_target_dirty": "16777216",
"rbd_cache_max_dirty_age": "1",
"rbd_cache_max_dirty_object": "0",
"rbd_cache_block_writes_upfront": "false",
[root@sz02 ~]# cat /etc/ceph/ceph.conf | grep "rbd cache size"
rbd cache size = 268435456
</code>```

we can see that rbd_cache_size is different. so i want to know:

whether ceph runtime config reads the value from ceph.conf or not? if not, what's the meaning of ceph.conf?

thanks

答:
An OSD while it's starting reads /etc/ceph/ceph.conf and applies found parameters from this file to its runtime config. If it doesn't find some parameters, it uses the default values described in the docs. So the setting rbd cache size = 268435456 should take an effect.

You can do the following:

Restart the osd daemon.

Check that the setting rbd cache size = 268435456 is under [client] config section in your ceph.conf.

Body:
i am using ceph-deploy to deploy ceph cluster. after deployment is finished, i found the runtime config is not the same with ceph.conf. i did not modify the runtime config in manual.

[root@sz02 ~]# ceph daemon osd.0 config show | grep rbd_cache
"rbd_cache": "true",
"rbd_cache_writethrough_until_flush": "true",
"rbd_cache_size": "33554432",
"rbd_cache_max_dirty": "25165824",
"rbd_cache_target_dirty": "16777216",
"rbd_cache_max_dirty_age": "1",
"rbd_cache_max_dirty_object": "0",
"rbd_cache_block_writes_upfront": "false",
[root@sz02 ~]# cat /etc/ceph/ceph.conf | grep "rbd cache size"
rbd cache size = 268435456

we can see that rbd_cache_size is different. so i want to know:

whether ceph runtime config reads the value from ceph.conf or not? if not, what's the meaning of ceph.conf?

thanks


问:
Setup Min Date in Bootstrap Datepicker
In My case i want to change mindate dynamically when changing of one input

```<code>$('#text1').on('changeDate', function () {
                var sdate = moment.utc((<any>$('#text1')).datepicker('getFormattedDate')).subtract(1, "days");
                (<any>$("#LossDate")).datepicker('minDate', sdate.format("MM-DD-YYYY"));
            });
</code>```

i am also try with

```<code>$('#text1').on('changeDate', function () {
                    var sdate = moment.utc((<any>$('#text1')).datepicker('getFormattedDate')).subtract(1, "days");
                    (<any>$("#LossDate")).datepicker('setStartDate', sdate.format("MM-DD-YYYY"));
                });
</code>```

and

```<code> $('#text1').on('changeDate', function () {
                        var sdate = moment.utc((<any>$('#text1')).datepicker('getFormattedDate')).subtract(1, "days");
                        (<any>$("#LossDate")).datepicker('startDate', sdate.format("MM-DD-YYYY"));
                    });
</code>```

and

```<code> $('#text1').on('changeDate', function () {
                            var sdate = moment.utc((<any>$('#text1')).datepicker('getFormattedDate')).subtract(1, "days");
                            (<any>$("#LossDate")).datepicker('SetstartDate', sdate.format("MM-DD-YYYY"));
                        });
</code>```

but nothing is working in my case

答:
Use this</p>

```<code>$("#text1").datepicker({
 autoclose: true
}).on('changeDate', function (selected) {
    var minDate = new Date('2017-12-01');
    $('#text1').datepicker('setStartDate', minDate);
});
</code>```

Title: Setup Min Date in Bootstrap Datepicker

Body:
In My case i want to change mindate dynamically when changing of one input

$('#text1').on('changeDate', function () {
                var sdate = moment.utc((<any>$('#text1')).datepicker('getFormattedDate')).subtract(1, "days");
                (<any>$("#LossDate")).datepicker('minDate', sdate.format("MM-DD-YYYY"));
            });

i am also try with

$('#text1').on('changeDate', function () {
                    var sdate = moment.utc((<any>$('#text1')).datepicker('getFormattedDate')).subtract(1, "days");
                    (<any>$("#LossDate")).datepicker('setStartDate', sdate.format("MM-DD-YYYY"));
                });

and

 $('#text1').on('changeDate', function () {
                        var sdate = moment.utc((<any>$('#text1')).datepicker('getFormattedDate')).subtract(1, "days");
                        (<any>$("#LossDate")).datepicker('startDate', sdate.format("MM-DD-YYYY"));
                    });

and

 $('#text1').on('changeDate', function () {
                            var sdate = moment.utc((<any>$('#text1')).datepicker('getFormattedDate')).subtract(1, "days");
                            (<any>$("#LossDate")).datepicker('SetstartDate', sdate.format("MM-DD-YYYY"));
                        });

but nothing is working in my case

Body:
Use this

$("#text1").datepicker({
 autoclose: true
}).on('changeDate', function (selected) {
    var minDate = new Date('2017-12-01');
    $('#text1').datepicker('setStartDate', minDate);
});


问:
jQuery: Missing 'timeout' error, error callback does not fire
When doing the registration, I want to check immediately if the email address is already associated with an account.
Therefore I use the jQuery Validation Plugin and send a synchronous ajax request to the server. That works fine.

To test what happens in case of a timeout, I have chosen a timeout of 5ms for the ajax request. On the server side (php-file) programme execution is delayed by 5 seconds using sleep(5).

But instead of getting a timeout error after 5ms, the success callback returns the correct data from the server after 5 seconds.

So the ajax timeout parameter doesn't seem to work.
This is my code:

```<code>    $.validator.addMethod('ist_ProvEmail_noch_frei',function(value, element) {
    var bValidEmail;

    var jqXHR = $.ajax({
        url:  'ajax/IstProvEmailVergeben.php',
        data: {
            email:  value
        },
        success : function(data, textStatus, jqXHR) {
            console.log("success1: " + textStatus);
      // some code
        },
        error : function(jqXHR, textStatus, errorThrown) {
            console.log("textStatus1: " + textStatus + ", type: " + typeof textStatus );
      // some code
            bValidEmail = true; // to prevent jQueryValidation from showing an error message
        },

        method: "POST",
        async:  false,
        timeout: 5,         // 5 ms
        dataType: 'json'
    });

    console.log("jqXHR.responseText: " + jqXHR.responseText);
    return bValidEmail;
}, 'This email address is already associated with an account.');
</code>```

I have checked the code several times with other articles but can't find out what is wrong.

Does anybody have an idea?

Henry

答:
async: false is your problem. See here with a asynchronous call:

$.ajax({
    url: "/ajax_json_echo/",
    type: "GET",
    dataType: "json",
    timeout: 5,
    success: function(response) { alert("success"); },
    error: function(xmlhttprequest, textstatus, message) {
        if(textstatus==="timeout") {
            alert("got timeout");
        } else {
            alert(textstatus);
        }
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

And here with async: false:

$.ajax({
    url: "/ajax_json_echo/",
    type: "GET",
    dataType: "json",
    timeout: 5,
    async:  false,
    success: function(response) { alert("success"); },
    error: function(x, t, m) {
        if(t==="timeout") {
            alert("got timeout");
        } else {
            console.log(t);
        }
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

The reason: during a synchronous ajax request, the browser is blocked and no javascript can be executed while the browser is blocked.

Edit: The workaround for using timeout and synchronous request: https://stackoverflow.com/a/36008375/1670090

$.ajax({
    url : '/ajax_json_echo/',
    type: 'GET',
    timeout: 5,
    dataType : 'json',
    success : function(data, textStatus) {
        $.ajax({
            url : '/ajax_json_echo/',
            async: false,
            type: 'GET',
            dataType : 'json',
            success: function(response) { alert("success"); },
            error: function(xmlhttprequest, textstatus, message) {
                if(textstatus==="timeout") {
                    alert("got timeout");
                } else {
                    alert(textstatus);
                }
            }
        });
    },
    error : function(jqhdr, textstatus,
                     errorThrown) {
        if(textstatus==="timeout") {
            alert("got timeout");
        } else {
            alert(textstatus);
        }
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Body:
When doing the registration, I want to check immediately if the email address is already associated with an account.
Therefore I use the jQuery Validation Plugin and send a synchronous ajax request to the server. That works fine.

To test what happens in case of a timeout, I have chosen a timeout of 5ms for the ajax request. On the server side (php-file) programme execution is delayed by 5 seconds using sleep(5).

But instead of getting a timeout error after 5ms, the success callback returns the correct data from the server after 5 seconds.

So the ajax timeout parameter doesn't seem to work.
This is my code:

    $.validator.addMethod('ist_ProvEmail_noch_frei',function(value, element) {
    var bValidEmail;

    var jqXHR = $.ajax({
        url:  'ajax/IstProvEmailVergeben.php',
        data: {
            email:  value
        },
        success : function(data, textStatus, jqXHR) {
            console.log("success1: " + textStatus);
      // some code
        },
        error : function(jqXHR, textStatus, errorThrown) {
            console.log("textStatus1: " + textStatus + ", type: " + typeof textStatus );
      // some code
            bValidEmail = true; // to prevent jQueryValidation from showing an error message
        },

        method: "POST",
        async:  false,
        timeout: 5,         // 5 ms
        dataType: 'json'
    });

    console.log("jqXHR.responseText: " + jqXHR.responseText);
    return bValidEmail;
}, 'This email address is already associated with an account.');

I have checked the code several times with other articles but can't find out what is wrong.

Does anybody have an idea?

Henry

Body:
async: false is your problem. See here with a asynchronous call:

$.ajax({
    url: "/ajax_json_echo/",
    type: "GET",
    dataType: "json",
    timeout: 5,
    success: function(response) { alert("success"); },
    error: function(xmlhttprequest, textstatus, message) {
        if(textstatus==="timeout") {
            alert("got timeout");
        } else {
            alert(textstatus);
        }
    }
});

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

And here with async: false:

$.ajax({
    url: "/ajax_json_echo/",
    type: "GET",
    dataType: "json",
    timeout: 5,
    async:  false,
    success: function(response) { alert("success"); },
    error: function(x, t, m) {
        if(t==="timeout") {
            alert("got timeout");
        } else {
            console.log(t);
        }
    }
});

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

The reason: during a synchronous ajax request, the browser is blocked and no javascript can be executed while the browser is blocked.

Edit: The workaround for using timeout and synchronous request: https://stackoverflow.com/a/36008375/1670090

$.ajax({
    url : '/ajax_json_echo/',
    type: 'GET',
    timeout: 5,
    dataType : 'json',
    success : function(data, textStatus) {
        $.ajax({
            url : '/ajax_json_echo/',
            async: false,
            type: 'GET',
            dataType : 'json',
            success: function(response) { alert("success"); },
            error: function(xmlhttprequest, textstatus, message) {
                if(textstatus==="timeout") {
                    alert("got timeout");
                } else {
                    alert(textstatus);
                }
            }
        });
    },
    error : function(jqhdr, textstatus,
                     errorThrown) {
        if(textstatus==="timeout") {
            alert("got timeout");
        } else {
            alert(textstatus);
        }
    }
});

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


问:
Cannot loop an action. libGDX
I've asked a question like 4 days ago. Got some help and now my code looks like

```<code>ColorAction actionBtG = new ColorAction();
ColorAction actionGtB = new ColorAction();
SequenceAction sequenceAction;
RepeatAction repeatAction = new RepeatAction();
ShapeRenderer shapeRenderer;
Color blue = new Color(Color.BLUE);

@Override
public void create () {

    shapeRenderer = new ShapeRenderer();
    actionBtG.setColor(blue);
    actionBtG.setEndColor(Color.GOLD);
    actionBtG.setDuration(5);

    actionGtB.setColor(blue);
    actionGtB.setEndColor(Color.BLUE);
    actionGtB.setDuration(5);
    sequenceAction = new sequenceAction(actionBtG,actionGtB);

    repeatAction = new RepeatAction():
    repeatAction.setAction(sequenceAction);
    repeatAction.setCount(RepeatAction.FOREVER);
}

@Override
public void render () {

    repeatAction.act(Gdx.graphics.getDeltaTime());
    Gdx.gl.glClearColor(1,1,1,1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
    shapeRenderer.setColor(blue);
    shapeRenderer.rect(100, 100, 40, 40);
    shapeRenderer.end();

}
</code>```

But it still works wrong. It does action once and stops. When I need to loop that. From blue to gold, then from gold to blue.
I would really appreciate any help, because I'm just learning libGDX. Thanks.

I have read all of the answers and edited my code, but it still doesnt work:

```<code>private Actor actionManager = new Actor();
ColorAction actionBtG = new ColorAction();
ColorAction actionGtB = new ColorAction();
SequenceAction sequenceAction;
RepeatAction repeatAction;
Color activeColor = new Color(Color.BLUE);
ShapeRenderer shapeRenderer;

@Override
public void create () {

    shapeRenderer = new ShapeRenderer();
    actionBtG.setColor(activeColor);
    actionBtG.setEndColor(Color.GOLD);
    actionBtG.setDuration(5);

    actionGtB.setColor(activeColor);
    actionGtB.setEndColor(Color.BLUE);
    actionGtB.setDuration(5);
    sequenceAction = new SequenceAction(actionBtG,actionGtB);
    repeatAction = new RepeatAction();
    repeatAction.setAction(sequenceAction);
    repeatAction.setCount(RepeatAction.FOREVER);

    actionManager.addAction(repeatAction);
}
</code>```

Here is render()

```<code>@Override
    public void render () {
    Gdx.gl.glClearColor(1, 1, 1, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    actionManager.act(Gdx.graphics.getDeltaTime());

    shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
    shapeRenderer.setColor(blue);
    shapeRenderer.rect(100, 100, 40, 40);
    shapeRenderer.end();
}
</code>```

Now it's not changing the color, it's always blue.

答:
So the following sample worked for me (infinite rotation)

Method 1: (recommended)

```<code>loadingActor.addAction(Actions.repeat(RepeatAction.FOREVER, Actions.rotateBy(360, 1)));
</code>```

Method 2:

```<code>Image loadingActor = new Image(AssetsController.getInstance().getLoading());
loadingActor.setOrigin(Align.center);
final SequenceAction infiniteRotate = Actions.sequence();
infiniteRotate.addAction(Actions.rotateTo(0 , 0f) );
infiniteRotate.addAction(Actions.rotateTo(360 , 1f) );
loadingActor.addAction(Actions.forever(infiniteRotate));
</code>```

Title: Cannot loop an action. libGDX

Body:
I've asked a question like 4 days ago. Got some help and now my code looks like

ColorAction actionBtG = new ColorAction();
ColorAction actionGtB = new ColorAction();
SequenceAction sequenceAction;
RepeatAction repeatAction = new RepeatAction();
ShapeRenderer shapeRenderer;
Color blue = new Color(Color.BLUE);

@Override
public void create () {

    shapeRenderer = new ShapeRenderer();
    actionBtG.setColor(blue);
    actionBtG.setEndColor(Color.GOLD);
    actionBtG.setDuration(5);

    actionGtB.setColor(blue);
    actionGtB.setEndColor(Color.BLUE);
    actionGtB.setDuration(5);
    sequenceAction = new sequenceAction(actionBtG,actionGtB);

    repeatAction = new RepeatAction():
    repeatAction.setAction(sequenceAction);
    repeatAction.setCount(RepeatAction.FOREVER);
}

@Override
public void render () {

    repeatAction.act(Gdx.graphics.getDeltaTime());
    Gdx.gl.glClearColor(1,1,1,1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
    shapeRenderer.setColor(blue);
    shapeRenderer.rect(100, 100, 40, 40);
    shapeRenderer.end();

}

But it still works wrong. It does action once and stops. When I need to loop that. From blue to gold, then from gold to blue.
I would really appreciate any help, because I'm just learning libGDX. Thanks.

I have read all of the answers and edited my code, but it still doesnt work:

private Actor actionManager = new Actor();
ColorAction actionBtG = new ColorAction();
ColorAction actionGtB = new ColorAction();
SequenceAction sequenceAction;
RepeatAction repeatAction;
Color activeColor = new Color(Color.BLUE);
ShapeRenderer shapeRenderer;

@Override
public void create () {

    shapeRenderer = new ShapeRenderer();
    actionBtG.setColor(activeColor);
    actionBtG.setEndColor(Color.GOLD);
    actionBtG.setDuration(5);

    actionGtB.setColor(activeColor);
    actionGtB.setEndColor(Color.BLUE);
    actionGtB.setDuration(5);
    sequenceAction = new SequenceAction(actionBtG,actionGtB);
    repeatAction = new RepeatAction();
    repeatAction.setAction(sequenceAction);
    repeatAction.setCount(RepeatAction.FOREVER);

    actionManager.addAction(repeatAction);
}

Here is render()

@Override
    public void render () {
    Gdx.gl.glClearColor(1, 1, 1, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    actionManager.act(Gdx.graphics.getDeltaTime());

    shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
    shapeRenderer.setColor(blue);
    shapeRenderer.rect(100, 100, 40, 40);
    shapeRenderer.end();
}

Now it's not changing the color, it's always blue.

Body:
So the following sample worked for me (infinite rotation)

Method 1: (recommended)

loadingActor.addAction(Actions.repeat(RepeatAction.FOREVER, Actions.rotateBy(360, 1)));

Method 2:

Image loadingActor = new Image(AssetsController.getInstance().getLoading());
loadingActor.setOrigin(Align.center);
final SequenceAction infiniteRotate = Actions.sequence();
infiniteRotate.addAction(Actions.rotateTo(0 , 0f) );
infiniteRotate.addAction(Actions.rotateTo(360 , 1f) );
loadingActor.addAction(Actions.forever(infiniteRotate));


问:
I have completed building an angular application. How to build it to run on server i.e cordova
I have completed an angular application. I ran ng build command and I got dist folder. No I want to run in Apache Cordova server. How to do it?

答:
1.- You must to use HashLocationStrategy strategies. That's in your app.module

```<code>import { CommonModule, HashLocationStrategy, LocationStrategy } from '@angular/common';
 ...
providers: [..
    { provide: LocationStrategy, useClass: HashLocationStrategy }]
</code>```

2.-Remove the < base href="./" > in your index.html

3.-be carrefull. it's posible you must to change in your index.html the tags script

```<code><script src="....."/>
//change by
<script src="....."/></script>
</code>```

Body:
1.- You must to use HashLocationStrategy strategies. That's in your app.module

import { CommonModule, HashLocationStrategy, LocationStrategy } from '@angular/common';
 ...
providers: [..
    { provide: LocationStrategy, useClass: HashLocationStrategy }]

2.-Remove the < base href="./" > in your index.html

3.-be carrefull. it's posible you must to change in your index.html the tags script

<script src="....."/>
//change by
<script src="....."/></script>


问:
How to store column value in Comma Separated row in SQL
I am stuck with one requirement and need some expert input.

Requirement

Employee will have 3 types of phones types like Home, Pager, Cell. I have a table called EmpPhone and whenever phones numbers are entered in UI this will stored in a different row.

So if I take EmpID = 744, currently he has 4 phone numbers(check pic)

Earlier we were not sure that UI can handle Same type phone numbers in this case its Type = 0. I could able to move these 3 row data to single row which is what I needed.

here is where I stuck, since UI can contain multiple phone types of any numbers, current data is showing only first data and hides other, so I need Type 0 phone numbers to accommodate in single HomePhone cell.

I even browsed and could able to get the values in single cell however I was not able to implement same code in actual stored procedure.

THIS IS WHAT I DID

```<code>DECLARE @HomePhoneNumbers varchar(MAX)
SET @HomePhoneNumbers = ''
SELECT @HomePhoneNumbers = @HomePhoneNumbers + CONVERT(varchar, PhoneNumber)
+ ','
FROM EmpPhone
where EmployeeID=744 and EmpPhone.Type =0

-- Remove last comma
SELECT LEFT(@HomePhoneNumbers, LEN(@HomePhoneNumbers) - 1)
</code>```

Which gives me what i need

if you observe the code I have hardcoded employeeID and I cannot do it actual StorProc since EmployeeID is not passed as parameter. here is my sample code snippet.

```<code>SELECT
    ,MAX(CASE WHEN EmpPhone.Type = 0 THEN ISNULL(EmpPhone.PhoneNumber,'') END) HomePhone
    ,MAX(CASE WHEN EmpPhone.Type = 2 THEN ISNULL(EmpPhone.PhoneNumber,'') END) Cell
    ,MAX(CASE WHEN EmpPhone.Type = 5 THEN ISNULL(EmpPhone.PhoneNumber,'') END) Pager
    ,E.EmployeeID

    From
    //JOINING FEW TABLES
</code>```

Let me know if I am clear enough.

SOLUTION

Guess what I implemented that without CTE, but your answer helped me to solve :)

```<code>SELECT
EmployeeID,
Type,
STUFF(
    (
    SELECT
        ', ' + PhoneNumber
    FROM EmpPhone E
    WHERE E.EmployeeID = T.EmployeeID AND E.Type = T.Type
    FOR XML PATH(''),TYPE
    ).value('.','VARCHAR(MAX)'
    ), 1, 1, ''
) AS Phones
INTO #PhoneNumbers
    FROM EmpPhone AS T
    GROUP BY EmployeeID, Type

    Select
    ,MAX(CASE WHEN PH.Type = 0 THEN ISNULL(PH.Phones,'') END) HomePhone
    ,MAX(CASE WHEN PH.Type = 2 THEN ISNULL(PH.Phones,'') END) Cell
    ,MAX(CASE WHEN PH.Type = 5 THEN ISNULL(PH.Phones,'') END) Pager
</code>```

I just used temptable and added that to joins, worked.

答:
As I understand you need to concatenate string using SQL coming from different rows into a single value
Please check referrred tutorial and try following SQL Select statement

```<code>SELECT
    EmployeeID,
    Type,
    STUFF(
        (
        SELECT
            ', ' + PhoneNumber
        FROM EmpPhone e
        WHERE e.EmployeeID = t.EmployeeID and
              e.Type = t.Type
        FOR XML PATH(''),TYPE
        ).value('.','VARCHAR(MAX)'
        ), 1, 1, ''
    ) As Phones
FROM EmpPhone as t
Group By EmployeeID, Type
</code>```

I hope it helps

Referring to your first comment, I modified above query into a CTE expression and added an aggregation logic as follows

```<code>;with cte as (
SELECT
    EmployeeID,
    Type,
    STUFF(
        (
        SELECT
            ', ' + PhoneNumber
        FROM EmpPhone e
        WHERE e.EmployeeID = t.EmployeeID and
              e.Type = t.Type
        FOR XML PATH(''),TYPE
        ).value('.','VARCHAR(MAX)'
        ), 1, 1, ''
    ) As Phones
FROM EmpPhone as t
Group By EmployeeID, Type
)
select
    EmployeeID,
    MAX(case when type = 0 then phones end) as 'HOME',
    MAX(case when type = 2 then phones end) as 'PAGER',
    MAX(case when type = 5 then phones end) as 'CELL'
from cte
group by
    EmployeeID
</code>```

The output is now as follows

Body:
I am stuck with one requirement and need some expert input.

Requirement

Employee will have 3 types of phones types like Home, Pager, Cell. I have a table called EmpPhone and whenever phones numbers are entered in UI this will stored in a different row.

So if I take EmpID = 744, currently he has 4 phone numbers(check pic)

Earlier we were not sure that UI can handle Same type phone numbers in this case its Type = 0. I could able to move these 3 row data to single row which is what I needed.

here is where I stuck, since UI can contain multiple phone types of any numbers, current data is showing only first data and hides other, so I need Type 0 phone numbers to accommodate in single HomePhone cell.

I even browsed and could able to get the values in single cell however I was not able to implement same code in actual stored procedure.

THIS IS WHAT I DID

DECLARE @HomePhoneNumbers varchar(MAX)
SET @HomePhoneNumbers = ''
SELECT @HomePhoneNumbers = @HomePhoneNumbers + CONVERT(varchar, PhoneNumber)
+ ','
FROM EmpPhone
where EmployeeID=744 and EmpPhone.Type =0

-- Remove last comma
SELECT LEFT(@HomePhoneNumbers, LEN(@HomePhoneNumbers) - 1)

Which gives me what i need

if you observe the code I have hardcoded employeeID and I cannot do it actual StorProc since EmployeeID is not passed as parameter. here is my sample code snippet.

SELECT
    ,MAX(CASE WHEN EmpPhone.Type = 0 THEN ISNULL(EmpPhone.PhoneNumber,'') END) HomePhone
    ,MAX(CASE WHEN EmpPhone.Type = 2 THEN ISNULL(EmpPhone.PhoneNumber,'') END) Cell
    ,MAX(CASE WHEN EmpPhone.Type = 5 THEN ISNULL(EmpPhone.PhoneNumber,'') END) Pager
    ,E.EmployeeID

    From
    //JOINING FEW TABLES

Let me know if I am clear enough.

SOLUTION

Guess what I implemented that without CTE, but your answer helped me to solve :)

SELECT
EmployeeID,
Type,
STUFF(
    (
    SELECT
        ', ' + PhoneNumber
    FROM EmpPhone E
    WHERE E.EmployeeID = T.EmployeeID AND E.Type = T.Type
    FOR XML PATH(''),TYPE
    ).value('.','VARCHAR(MAX)'
    ), 1, 1, ''
) AS Phones
INTO #PhoneNumbers
    FROM EmpPhone AS T
    GROUP BY EmployeeID, Type

    Select
    ,MAX(CASE WHEN PH.Type = 0 THEN ISNULL(PH.Phones,'') END) HomePhone
    ,MAX(CASE WHEN PH.Type = 2 THEN ISNULL(PH.Phones,'') END) Cell
    ,MAX(CASE WHEN PH.Type = 5 THEN ISNULL(PH.Phones,'') END) Pager

I just used temptable and added that to joins, worked.

Body:
As I understand you need to concatenate string using SQL coming from different rows into a single value
Please check referrred tutorial and try following SQL Select statement

SELECT
    EmployeeID,
    Type,
    STUFF(
        (
        SELECT
            ', ' + PhoneNumber
        FROM EmpPhone e
        WHERE e.EmployeeID = t.EmployeeID and
              e.Type = t.Type
        FOR XML PATH(''),TYPE
        ).value('.','VARCHAR(MAX)'
        ), 1, 1, ''
    ) As Phones
FROM EmpPhone as t
Group By EmployeeID, Type

I hope it helps

Referring to your first comment, I modified above query into a CTE expression and added an aggregation logic as follows

;with cte as (
SELECT
    EmployeeID,
    Type,
    STUFF(
        (
        SELECT
            ', ' + PhoneNumber
        FROM EmpPhone e
        WHERE e.EmployeeID = t.EmployeeID and
              e.Type = t.Type
        FOR XML PATH(''),TYPE
        ).value('.','VARCHAR(MAX)'
        ), 1, 1, ''
    ) As Phones
FROM EmpPhone as t
Group By EmployeeID, Type
)
select
    EmployeeID,
    MAX(case when type = 0 then phones end) as 'HOME',
    MAX(case when type = 2 then phones end) as 'PAGER',
    MAX(case when type = 5 then phones end) as 'CELL'
from cte
group by
    EmployeeID

The output is now as follows


问:
How to compare Attribute value with string
I am using below code to getAttribute of a field on web page :-

```<code>    List<WebElement> EngDesc = driver.findElements(By.xpath("//input[@id='EngDesc']"));
        System.out.println("List size: "+EngDesc.size());
        for(WebElement list : EngDesc ){
            System.out.println("search value: "+list.getAttribute("value"));
            if(list.getAttribute("Value").equals("CHARGEABLE")) {
                System.out.println("This is General");
             }
</code>```

and below is the output I am getting:-

List size: 1
  search value: CHARGEABLE
  Exception in thread "main" java.lang.NullPointerException
      at newrequestFlow.Index.main(Index.java:81)

Can someone help me with this?

答:
The error you are seeing says it all as follows :

```<code>NullPointerException at newrequestFlow.Index.main(Index.java:81)
</code>```

The line findElements(By.xpath("//input[@id='EngDesc']")); returns only 1 entry.
Initially in the for() loop you are using list.getAttribute("value"). But later you are trying to use list.getAttribute("Value")

value and Value are different attribute and probably there were no attribute present as Value . Hence Null is returned and java.lang.NullPointerException is observed.

Solution

```<code>List<WebElement> EngDesc = driver.findElements(By.xpath("//input[@id='EngDesc']"));
    System.out.println("List size: "+EngDesc.size());
    for(WebElement list : EngDesc )
    {
        System.out.println("search value: "+list.getAttribute("value"));
        if(list.getAttribute("value").equals("CHARGEABLE"))
        {
            System.out.println("This is General");
        }
    }
</code>```

Body:
I am using below code to getAttribute of a field on web page :-

    List<WebElement> EngDesc = driver.findElements(By.xpath("//input[@id='EngDesc']"));
        System.out.println("List size: "+EngDesc.size());
        for(WebElement list : EngDesc ){
            System.out.println("search value: "+list.getAttribute("value"));
            if(list.getAttribute("Value").equals("CHARGEABLE")) {
                System.out.println("This is General");
             }

and below is the output I am getting:-

List size: 1
  search value: CHARGEABLE
  Exception in thread "main" java.lang.NullPointerException
      at newrequestFlow.Index.main(Index.java:81)

Can someone help me with this?

Body:
The error you are seeing says it all as follows :

NullPointerException at newrequestFlow.Index.main(Index.java:81)

The line findElements(By.xpath("//input[@id='EngDesc']")); returns only 1 entry.
Initially in the for() loop you are using list.getAttribute("value"). But later you are trying to use list.getAttribute("Value")

value and Value are different attribute and probably there were no attribute present as Value . Hence Null is returned and java.lang.NullPointerException is observed.

Solution

List<WebElement> EngDesc = driver.findElements(By.xpath("//input[@id='EngDesc']"));
    System.out.println("List size: "+EngDesc.size());
    for(WebElement list : EngDesc )
    {
        System.out.println("search value: "+list.getAttribute("value"));
        if(list.getAttribute("value").equals("CHARGEABLE"))
        {
            System.out.println("This is General");
        }
    }


问:
Mock modules using jest that are imported using import * to test react components
File name Postman.js

```<code>"use strict";

define([], function() {
    var postManSingleton = (function() {
        var postManInstance
            , createPostMan = function() {
                var events = {};
                return  {
                    publish: function(event, payload) {
                        if(!events.hasOwnProperty(event))
                            return;
                        events[event].forEach(function(listener){
                            listener(payload || {});
                        });

                    },
                    subscribe: function(event, listener) {
                        if(!events.hasOwnProperty(event))
                            events[event] = [];

                        var index = events[event].push(listener)-1;
                        return {
                            remove: function () {
                                delete events[event][index];
                            }
                        }
                    }
                }
            };

        return {
            getInstance: function() {
                if(!postManInstance)
                    postManInstance = createPostMan();
                return postManInstance;
            }
        }
    }());
    return postManSingleton.getInstance();
});
</code>```

Importing this file as in index.test.js

```<code>import * as Postman from 'postman.js';
</code>```

How do I mock its publish and subscribe events in jest.
I have tried

```<code>jest.mock('Postman.publish', () =>({//some code}))
</code>```

Error : Cannot find module Postman.publish from 'index.test.js'

Please help how it is possible to  mock the above file. Is it even possible?

答:
Your Postman.js is in AMD & Jest does not support AMD. So you need to convert AMD to commonjs.

You can use babel-plugin-transform-amd-to-commonjs for conversion.

Body:
File name Postman.js

"use strict";

define([], function() {
    var postManSingleton = (function() {
        var postManInstance
            , createPostMan = function() {
                var events = {};
                return  {
                    publish: function(event, payload) {
                        if(!events.hasOwnProperty(event))
                            return;
                        events[event].forEach(function(listener){
                            listener(payload || {});
                        });

                    },
                    subscribe: function(event, listener) {
                        if(!events.hasOwnProperty(event))
                            events[event] = [];

                        var index = events[event].push(listener)-1;
                        return {
                            remove: function () {
                                delete events[event][index];
                            }
                        }
                    }
                }
            };

        return {
            getInstance: function() {
                if(!postManInstance)
                    postManInstance = createPostMan();
                return postManInstance;
            }
        }
    }());
    return postManSingleton.getInstance();
});

Importing this file as in index.test.js

import * as Postman from 'postman.js';

How do I mock its publish and subscribe events in jest.
I have tried

jest.mock('Postman.publish', () =>({//some code}))

Error : Cannot find module Postman.publish from 'index.test.js'

Please help how it is possible to  mock the above file. Is it even possible?


问:
Need to run cron job for my php file on hosting server
I have php file on my linux hosting server and i want to execute it 2 times a day. Below is my link of my php file. Kindly tell me command line code for my php file.

http://viewpackages.com/prices/generator/footer.php

See attached image which is my hosting cron job form. Tell me what i have to write in command line text field
click here to see image of my hosting cron job form

答:
Try pasting this on the command option:

```<code>wget -O /dev/null http://viewpackages.com/prices/generator/footer.php
</code>```

Test it and tell me if there's anything wrong

Body:
Try pasting this on the command option:

wget -O /dev/null http://viewpackages.com/prices/generator/footer.php

Test it and tell me if there's anything wrong


问:
Validation expression in asp.net
How to disallow use of double quotes " in a textbox

答: If you don't want users to be able to type quotes in the textbox in the first place, consider using a FilteredTextBox from the AJAX Control Toolkit.</p>

Title: Validation expression in asp.net


问:
How to convert Moment.js date to users local timezone?
I use the Moment.js and Moment-Timezone frameworks, and have a Moment.js date object which is explicitly in UTC timezone. How can I convert that to the current timezone of the browser?

```<code>var testDateUtc = moment.tz("2015-01-30 10:00:00", "UTC");
var localDate = ???
</code>```

So it would be fine if I could find out the users local time zone; or alternatively I'd like to convert the date object into another data object which just uses the "local timezone", no matter what that actually is.

答:
Here's what I did:

```<code>var timestamp = moment.unix({{ time }});
var utcOffset = moment().utcOffset();
var local_time = timestamp.add(utcOffset, "minutes");
var dateString = local_time.fromNow();
</code>```

Where {{ time }} is the utc timestamp.

ContentLicense: CC BY-SA 4.0

Body:
I use the Moment.js and Moment-Timezone frameworks, and have a Moment.js date object which is explicitly in UTC timezone. How can I convert that to the current timezone of the browser?

var testDateUtc = moment.tz("2015-01-30 10:00:00", "UTC");
var localDate = ???

So it would be fine if I could find out the users local time zone; or alternatively I'd like to convert the date object into another data object which just uses the "local timezone", no matter what that actually is.

Body:
Here's what I did:

var timestamp = moment.unix({{ time }});
var utcOffset = moment().utcOffset();
var local_time = timestamp.add(utcOffset, "minutes");
var dateString = local_time.fromNow();

Where {{ time }} is the utc timestamp.


问:
Is AND part of query executed always?
I have a query in SQL Server stored procedure like this:

IF (@EDITED = 1) AND (EXISTS (SELECT 1 FROM InventarizacijaZurnals WHERE RECORD_UNIQUE_ID=@RECORD_UNIQUE_ID)) ....

My question is - will query part after AND always be executed even if first statement is True? I know some languages do it and some doesn't. How does it work in SQL Server? Can't seem to find a clear answer online.

答:
always be executed even if first statement is True

Do you mean first statement is False, not True? When first statement is True we have still possibility that second will be false and then "True and False" is just False. So in that case second query part will be executed.

Title: Is AND part of query executed always?


问:
AttributeError while unpickling: Can't get attribute 'Location'
I'm writing a Python CGI script for an inventory system. It needs to store through pickle a list (called locations) of objects. Here's the code I'm using:

```<code>try:
    with open(".config/autosave.bin", "rb") as dataFile:
        locations = pickle.load(dataFile)
except (FileNotFoundError, PermissionError):
    dispHTML("p", contents="Error in load:  Save file incorrectly configured!")
    locations = []
</code>```

However, this results in:

```<code> /Applications/MAMP/cgi-bin/ic/main.py in ()
     16 try:
     17         with open(".config/autosave.bin", "rb") as dataFile:
=>   18                 locations = pickle.load(dataFile)
     19 except (FileNotFoundError, PermissionError):
     20         dispHTML("p", contents="Error in load:  Save file incorrectly configured!")
AttributeError: Can't get attribute 'Location' on <module '__main__' from '/Applications/MAMP/cgi-bin/ic/main.py'>
      args = ("Can't get attribute 'Location' on <module '__main__' from '/Applications/MAMP/cgi-bin/ic/main.py'>",)
      with_traceback = <built-in method with_traceback of AttributeError object>
</code>```

As you can see the save file is stored at .config/autosave.bin. Writing to it seems to work fine but I haven't been able to check.

How can I fix this?

答:
The pickle reading code requires the definition of the Location class. If not it will not be able to reconstruct custom objects of that class.

```<code># config_writer.py

import pickle

class Location:
    def __init__(self, store, aisle):
        self.store = store
        self.aisle = aisle

locations = [Location(i, i) for i in range(10)]
with open('.config/autosave.bin', 'wb') as f:
    pickle.dump(locations, f)
</code>```

Here is a example that tries to read the pickle file without having the class definition of Location (run this code in another terminal/session):

```<code>>>> import pickle
>>> with open('.config/autosave.bin','rb') as f:
...     data = pickle.load(f)
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
AttributeError: Can't get attribute 'Location' on <module '__main__' (built-in)>
</code>```

However, with access to the class definition:

```<code>>>> from config_writer import Location
>>> with open('.config/autosave.bin','rb') as f:
...     data = pickle.load(f)
>>> data
[<config_writer.Location object at 0x7f8b472111d0>, <config_writer.Location object at 0x7f8b41ad6e48>, <config_writer.Location object at 0x7f8b41adb0f0>, <config_writer.Location object at 0x7f8b41adb128>, <config_writer.Location object at 0x7f8b41adb160>, <config_writer.Location object at 0x7f8b41adb198>, <config_writer.Location object at 0x7f8b41adb1d0>, <config_writer.Location object at 0x7f8b41adb208>, <config_writer.Location object at 0x7f8b41adb240>, <config_writer.Location object at 0x7f8b41adb278>]
</code>```

Hopefully the code that reads the pickle file is able to import the class definition for Location from some other module as does my example.

Body:
I'm writing a Python CGI script for an inventory system. It needs to store through pickle a list (called locations) of objects. Here's the code I'm using:

try:
    with open(".config/autosave.bin", "rb") as dataFile:
        locations = pickle.load(dataFile)
except (FileNotFoundError, PermissionError):
    dispHTML("p", contents="Error in load:  Save file incorrectly configured!")
    locations = []

However, this results in:

 /Applications/MAMP/cgi-bin/ic/main.py in ()
     16 try:
     17         with open(".config/autosave.bin", "rb") as dataFile:
=>   18                 locations = pickle.load(dataFile)
     19 except (FileNotFoundError, PermissionError):
     20         dispHTML("p", contents="Error in load:  Save file incorrectly configured!")
AttributeError: Can't get attribute 'Location' on <module '__main__' from '/Applications/MAMP/cgi-bin/ic/main.py'>
      args = ("Can't get attribute 'Location' on <module '__main__' from '/Applications/MAMP/cgi-bin/ic/main.py'>",)
      with_traceback = <built-in method with_traceback of AttributeError object>

As you can see the save file is stored at .config/autosave.bin. Writing to it seems to work fine but I haven't been able to check.

How can I fix this?

Body:
The pickle reading code requires the definition of the Location class. If not it will not be able to reconstruct custom objects of that class.

# config_writer.py

import pickle

class Location:
    def __init__(self, store, aisle):
        self.store = store
        self.aisle = aisle

locations = [Location(i, i) for i in range(10)]
with open('.config/autosave.bin', 'wb') as f:
    pickle.dump(locations, f)

Here is a example that tries to read the pickle file without having the class definition of Location (run this code in another terminal/session):

>>> import pickle
>>> with open('.config/autosave.bin','rb') as f:
...     data = pickle.load(f)
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
AttributeError: Can't get attribute 'Location' on <module '__main__' (built-in)>

However, with access to the class definition:

>>> from config_writer import Location
>>> with open('.config/autosave.bin','rb') as f:
...     data = pickle.load(f)
>>> data
[<config_writer.Location object at 0x7f8b472111d0>, <config_writer.Location object at 0x7f8b41ad6e48>, <config_writer.Location object at 0x7f8b41adb0f0>, <config_writer.Location object at 0x7f8b41adb128>, <config_writer.Location object at 0x7f8b41adb160>, <config_writer.Location object at 0x7f8b41adb198>, <config_writer.Location object at 0x7f8b41adb1d0>, <config_writer.Location object at 0x7f8b41adb208>, <config_writer.Location object at 0x7f8b41adb240>, <config_writer.Location object at 0x7f8b41adb278>]

Hopefully the code that reads the pickle file is able to import the class definition for Location from some other module as does my example.


问:
One-liner Algorithm to Combine Arrays into Arrays of All Possible Value Combinations?
Not quite sure I have the question fully formed, but what I'm trying to do is basically this:

```<code># where the indices correspond to attributes fore example:
# [type, status]
x = %w(a b)
y = %w(c d)
combine(x, y) #=> [["a", "b"], ["a", "d"], ["c", "a"], ["c", "b"]]
</code>```

The order of the array is always the same, so the reverse of each, such as [b, a], are not included in the result.

What is this called and what's an efficient way to implement this?

I see Array#permutation, but that's not quite it...

This would hopefully work for any number of arrays and values: combine(*arrays)

Thanks!

Update

Here's a better example of what I'm looking for:

This (x | y).combination(x.length).to_a produces the following:

```<code>x = ["front_door", "open"]
y = ["back_door", "closed"]
(x | y).combination(x.length).to_a
=> [["front_door", "open"], ["front_door", "back_door"], ["front_door", "closed"], ["open", "back_door"], ["open", "closed"], ["back_door", "closed"]]
</code>```

The actual result I'm looking for is this:

```<code>=> [["front_door", "open"], ["front_door", "closed"], ["back_door", "open"], ["back_door", "closed"]]
</code>```

Or if it were a longer array:

```<code>x = ["house", "front_door", "open"]
y = ["building", "back_door", "closed"]
compute(x, y)
=> ["house", "front_door", "open"], ["house", "back_door", "open"], ["house", "front_door", "closed"], ["house", "back_door", "closed"], ["building", "front_door", "open"], ["building", "back_door", "open"], ["building", "front_door", "closed"], ["building", "back_door", "closed"]
</code>```

Any ideas?

答:
```<code>def combine(*arrays)
  head, *tail = arrays.transpose
  head.product(*tail)
end

combine(x, y)
combine(x, y, z, ...)
</code>```

Side note digression: this is one of the scenarios in which you get the point that functional languages make about functions being the important stuff. The fact that you have to call an object's method in OOP forces you -in this case- to contrivedly get their head/tail. When you have product as a function, for example in Python, you don't have this kind of problems:

```<code>itertools.product(*zip(*arrays))
</code>```

Body:
Not quite sure I have the question fully formed, but what I'm trying to do is basically this:

# where the indices correspond to attributes fore example:
# [type, status]
x = %w(a b)
y = %w(c d)
combine(x, y) #=> [["a", "b"], ["a", "d"], ["c", "a"], ["c", "b"]]

The order of the array is always the same, so the reverse of each, such as [b, a], are not included in the result.

What is this called and what's an efficient way to implement this?

I see Array#permutation, but that's not quite it...

This would hopefully work for any number of arrays and values: combine(*arrays)

Thanks!

Update

Here's a better example of what I'm looking for:

This (x | y).combination(x.length).to_a produces the following:

x = ["front_door", "open"]
y = ["back_door", "closed"]
(x | y).combination(x.length).to_a
=> [["front_door", "open"], ["front_door", "back_door"], ["front_door", "closed"], ["open", "back_door"], ["open", "closed"], ["back_door", "closed"]]

The actual result I'm looking for is this:

=> [["front_door", "open"], ["front_door", "closed"], ["back_door", "open"], ["back_door", "closed"]]

Or if it were a longer array:

x = ["house", "front_door", "open"]
y = ["building", "back_door", "closed"]
compute(x, y)
=> ["house", "front_door", "open"], ["house", "back_door", "open"], ["house", "front_door", "closed"], ["house", "back_door", "closed"], ["building", "front_door", "open"], ["building", "back_door", "open"], ["building", "front_door", "closed"], ["building", "back_door", "closed"]

Any ideas?

Body:
def combine(*arrays)
  head, *tail = arrays.transpose
  head.product(*tail)
end

combine(x, y)
combine(x, y, z, ...)

Side note digression: this is one of the scenarios in which you get the point that functional languages make about functions being the important stuff. The fact that you have to call an object's method in OOP forces you -in this case- to contrivedly get their head/tail. When you have product as a function, for example in Python, you don't have this kind of problems:

itertools.product(*zip(*arrays))


问:
Django serializer not save data to database but response is OK
The serializer below don't save changes to database but JSON response from API has new correct values!
What is wrong with it?</p>

```<code>class FieldSerializer(serializers.ModelSerializer):
    class Meta:
        model = Field
        fields = 'id', 'name', 'default'

class DocumentSerializer(serializers.HyperlinkedModelSerializer):
    field = FieldSerializer(many=False, read_only=True)

    def _save_field(self, instance):
        field = self.initial_data.pop('field', None)
        field_ids = field['id']
        field = Field.objects.get(pk=field_ids)
        instance.field = field

    def save(self, **kwargs):
        instance = super().save(**kwargs)
        self._save_field(instance)
</code>```

答:
You're not saving instance after setting the field:

```<code>def _save_field(self, instance):
    field = self.initial_data.pop('field', None)
    field_ids = field['id']
    field = Field.objects.get(pk=field_ids)
    instance.field = field
    instance.save()  # <-- mandatory
</code>```

The field was properly attributed to the instance which was serialized, but not saved to the DB, that's why you saw the right response with the new values.

Body:
The serializer below don't save changes to database but JSON response from API has new correct values!
What is wrong with it?

class FieldSerializer(serializers.ModelSerializer):
    class Meta:
        model = Field
        fields = 'id', 'name', 'default'

class DocumentSerializer(serializers.HyperlinkedModelSerializer):
    field = FieldSerializer(many=False, read_only=True)

    def _save_field(self, instance):
        field = self.initial_data.pop('field', None)
        field_ids = field['id']
        field = Field.objects.get(pk=field_ids)
        instance.field = field

    def save(self, **kwargs):
        instance = super().save(**kwargs)
        self._save_field(instance)

Body:
You're not saving instance after setting the field:

def _save_field(self, instance):
    field = self.initial_data.pop('field', None)
    field_ids = field['id']
    field = Field.objects.get(pk=field_ids)
    instance.field = field
    instance.save()  # <-- mandatory

The field was properly attributed to the instance which was serialized, but not saved to the DB, that's why you saw the right response with the new values.


问:
NPM: Field 'browser' doesn't contain a valid alias configuration
Executing This:

```<code>node .\node_modules\webpack\bin\webpack.js --config scripts/webpack.config.js --display-error-details
</code>```

Produces this error.

I am just testing this at the moment, so application.ts just has this

```<code>export class Aureus {

    constructor() {
        alert('1');
    }

}
</code>```

The webpack file looks as follows:

```<code>const globule = require("globule");
const path = require("path");
const webpack = require("webpack");
const extractTextPlugin = require("extract-text-webpack-plugin");

const config = {
};

const configuration = {
    context: __dirname,
    entry: {
        "application":
            "application.ts",
            ...globule.find("aureus/**/*.ts", { srcBase: "./scripts" }),
        ,
        "vendor": [
            "bootstrap",
            "jquery",
            "angular",
            "moment",
            "lodash",
            "ramda",
        ],
    },
    output: {
        path: path.join(__dirname, "../"),
        filename: "packed.js"
    },
    devtool: "source-map",
    plugins: [
        new webpack.LoaderOptionsPlugin({
            debug: true
        }),
        new webpack.optimize.CommonsChunkPlugin({
            name: "vendor",
            filename: "vendor.js"
        }),
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery",
            "window.jQuery": "jquery",
            "window.jquery": "jquery",
        }),
    ],
    resolve:
    {
        alias: {
        }
    },
    module: {
        rules: [
            {
                test: /^((?!\.spec\.ts).)*.ts$/,
                use: [
                    {
                        loader: "awesome-typescript-loader"
                    }
                ],
                exclude: /(node_modules)/
            },
        ]
    }
};

module.exports = configuration;
</code>```

I am getting this error?
application.ts is in ./scripts/application.ts
(same directory as webpack.config.js)

```<code>ERROR in Entry module not found: Error: Can't resolve 'application.ts' in 'C:\Projects\Github\Aureus\Aureus.Web\scripts'
resolve 'application.ts' in 'C:\Projects\Github\Aureus\Aureus.Web\scripts'
  Parsed request is a module
  using description file: C:\Projects\Github\Aureus\Aureus.Web\package.json (relative path: ./scripts)
    Field 'browser' doesn't contain a valid alias configuration
  after using description file: C:\Projects\Github\Aureus\Aureus.Web\package.json (relative path: ./scripts)
    resolve as module
      C:\Projects\Github\Aureus\Aureus.Web\scripts\node_modules doesn't exist or is not a directory
      C:\Projects\Github\Aureus\node_modules doesn't exist or is not a directory
      C:\Projects\Github\node_modules doesn't exist or is not a directory
      C:\Projects\node_modules doesn't exist or is not a directory
      C:\node_modules doesn't exist or is not a directory
      looking for modules in C:\Projects\Github\Aureus\Aureus.Web\node_modules
        using description file: C:\Projects\Github\Aureus\Aureus.Web\package.json (relative path: ./node_modules)
          Field 'browser' doesn't contain a valid alias configuration
        after using description file: C:\Projects\Github\Aureus\Aureus.Web\package.json (relative path: ./node_modules)
          using description file: C:\Projects\Github\Aureus\Aureus.Web\package.json (relative path: ./node_modules/application.ts)
            no extension
              Field 'browser' doesn't contain a valid alias configuration
              C:\Projects\Github\Aureus\Aureus.Web\node_modules\application.ts doesn't exist
            .js
              Field 'browser' doesn't contain a valid alias configuration
              C:\Projects\Github\Aureus\Aureus.Web\node_modules\application.ts.js doesn't exist
            .json
              Field 'browser' doesn't contain a valid alias configuration
              C:\Projects\Github\Aureus\Aureus.Web\node_modules\application.ts.json doesn't exist
            as directory
              C:\Projects\Github\Aureus\Aureus.Web\node_modules\application.ts doesn't exist
</code>```

答:
Unless you provide an actual resolve rule, your imports of anything in the node_modules will default to looking in the folder provided to the context.

Try this rather:

```<code>resolve: {
  modules: [
    /* assuming that one up is where your node_modules sit,
       relative to the currently executing script
    */
    path.join(__dirname, '../node_modules')
  ]
}
</code>```

Also, make sure that you are referencing your entry relative to the context like so:

```<code>"application": "./application.ts"
</code>```

instead of

```<code>"application": "application.ts"
</code>```

Body:
Executing This:

node .\node_modules\webpack\bin\webpack.js --config scripts/webpack.config.js --display-error-details

Produces this error.

I am just testing this at the moment, so application.ts just has this

export class Aureus {

    constructor() {
        alert('1');
    }

}

The webpack file looks as follows:

const globule = require("globule");
const path = require("path");
const webpack = require("webpack");
const extractTextPlugin = require("extract-text-webpack-plugin");

const config = {
};

const configuration = {
    context: __dirname,
    entry: {
        "application":
            "application.ts",
            ...globule.find("aureus/**/*.ts", { srcBase: "./scripts" }),
        ,
        "vendor": [
            "bootstrap",
            "jquery",
            "angular",
            "moment",
            "lodash",
            "ramda",
        ],
    },
    output: {
        path: path.join(__dirname, "../"),
        filename: "packed.js"
    },
    devtool: "source-map",
    plugins: [
        new webpack.LoaderOptionsPlugin({
            debug: true
        }),
        new webpack.optimize.CommonsChunkPlugin({
            name: "vendor",
            filename: "vendor.js"
        }),
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery",
            "window.jQuery": "jquery",
            "window.jquery": "jquery",
        }),
    ],
    resolve:
    {
        alias: {
        }
    },
    module: {
        rules: [
            {
                test: /^((?!\.spec\.ts).)*.ts$/,
                use: [
                    {
                        loader: "awesome-typescript-loader"
                    }
                ],
                exclude: /(node_modules)/
            },
        ]
    }
};

module.exports = configuration;

I am getting this error?
application.ts is in ./scripts/application.ts
(same directory as webpack.config.js)

ERROR in Entry module not found: Error: Can't resolve 'application.ts' in 'C:\Projects\Github\Aureus\Aureus.Web\scripts'
resolve 'application.ts' in 'C:\Projects\Github\Aureus\Aureus.Web\scripts'
  Parsed request is a module
  using description file: C:\Projects\Github\Aureus\Aureus.Web\package.json (relative path: ./scripts)
    Field 'browser' doesn't contain a valid alias configuration
  after using description file: C:\Projects\Github\Aureus\Aureus.Web\package.json (relative path: ./scripts)
    resolve as module
      C:\Projects\Github\Aureus\Aureus.Web\scripts\node_modules doesn't exist or is not a directory
      C:\Projects\Github\Aureus\node_modules doesn't exist or is not a directory
      C:\Projects\Github\node_modules doesn't exist or is not a directory
      C:\Projects\node_modules doesn't exist or is not a directory
      C:\node_modules doesn't exist or is not a directory
      looking for modules in C:\Projects\Github\Aureus\Aureus.Web\node_modules
        using description file: C:\Projects\Github\Aureus\Aureus.Web\package.json (relative path: ./node_modules)
          Field 'browser' doesn't contain a valid alias configuration
        after using description file: C:\Projects\Github\Aureus\Aureus.Web\package.json (relative path: ./node_modules)
          using description file: C:\Projects\Github\Aureus\Aureus.Web\package.json (relative path: ./node_modules/application.ts)
            no extension
              Field 'browser' doesn't contain a valid alias configuration
              C:\Projects\Github\Aureus\Aureus.Web\node_modules\application.ts doesn't exist
            .js
              Field 'browser' doesn't contain a valid alias configuration
              C:\Projects\Github\Aureus\Aureus.Web\node_modules\application.ts.js doesn't exist
            .json
              Field 'browser' doesn't contain a valid alias configuration
              C:\Projects\Github\Aureus\Aureus.Web\node_modules\application.ts.json doesn't exist
            as directory
              C:\Projects\Github\Aureus\Aureus.Web\node_modules\application.ts doesn't exist

Body:
Unless you provide an actual resolve rule, your imports of anything in the node_modules will default to looking in the folder provided to the context.

Try this rather:

resolve: {
  modules: [
    /* assuming that one up is where your node_modules sit,
       relative to the currently executing script
    */
    path.join(__dirname, '../node_modules')
  ]
}

Also, make sure that you are referencing your entry relative to the context like so:

"application": "./application.ts"

instead of

"application": "application.ts"


问:
pod2man not found while installing Wireshark
I was trying to install WireShark 1.10.5 in linux.I was following the instructions provided with the software. Now,I am having problems while installing. It says pod2man cannot be found. How can i fix this? </p>

```<code>checking for pod2man... no
configure: error: I couldn't find pod2man; make sure it's installed and in your path
</code>```

答:
try

apt-get install perl-modules

Body:
I was trying to install WireShark 1.10.5 in linux.I was following the instructions provided with the software. Now,I am having problems while installing. It says pod2man cannot be found. How can i fix this?

checking for pod2man... no
configure: error: I couldn't find pod2man; make sure it's installed and in your path

Body:
try

apt-get install perl-modules


问:
Rotate Image Clockwise using LibGDX
How can we rotate a Image Clockwise using LibGDX? what i am looking is when a image is loaded,suppose a star, i need to rotate it from beginning of screen to end of the screen horizontally, with star rotating,how can i do that in libgdx?</p>

Title: Rotate Image Clockwise using LibGDX

Body:
So the following sample worked for me (infinite rotation)

Method 1: (recommended)

loadingActor.addAction(Actions.repeat(RepeatAction.FOREVER, Actions.rotateBy(360, 1)));

Method 2:

Image loadingActor = new Image(AssetsController.getInstance().getLoading());
loadingActor.setOrigin(Align.center);
final SequenceAction infiniteRotate = Actions.sequence();
infiniteRotate.addAction(Actions.rotateTo(0 , 0f) );
infiniteRotate.addAction(Actions.rotateTo(360 , 1f) );
loadingActor.addAction(Actions.forever(infiniteRotate));


问:
Ionic Framework Posting to Django Rest Framework Using HTTP Requests
I'm trying to create a new user in my Ionic app using Django as the backend. So far I can create a user no problem using Postman, but when I try to make an HTTP post request through my app I get the following error: {"password":["This field is required."],"username":["This field is required."]}. I am passing the username and password field to my Django app, but for some reason it doesn't register it. Is my post call wrong?

DJANGO APP CODE

serializers.py

```<code>class UserSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)
    languages = serializers.ListField(child=serializers.CharField(max_length=30, allow_blank=True), source="userprofile.languages")

    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email', 'username', 'password', 'languages')

    def create(self, validated_data, instance=None):
        profile_data = validated_data.pop('userprofile')
        user = User.objects.create(**validated_data)
        user.set_password(validated_data['password'])
        user.save()
        UserProfile.objects.update_or_create(user=user, **profile_data)
        return user
</code>```

views.py

```<code>@api_view(['POST'])
@permission_classes((AllowAny,))
def create_user(request):
    serialized = UserSerializer(data=request.data)
    if serialized.is_valid():
        serialized.save()
        return Response(serialized.data, status=status.HTTP_201_CREATED)
    else:
        return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)
</code>```

IONIC APP CODE

http.ts

```<code>  register(username, password, email, first_name, last_name, languages) {
    let url = "https://www.example.com/api/create_user/";
    let headers = new Headers()
    headers.append("Content-Type", "application/x-www-form-urlencoded");

    return this.http.post(url,
      {"first_name": first_name,
        "last_name": last_name,
        "email": email,
        "username": username,
        "password": password,
        "languages": languages
      }, {headers: headers})
      .map(res => res.json());
  }
</code>```

register.ts

```<code>import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';

import { HttpProvider } from "../../providers/http/http";

@IonicPage()
@Component({
  selector: 'page-register',
  templateUrl: 'register.html',
})
export class RegisterPage {

  //basic info
  username:any;
  email:any;
  fname:any;
  lname:any;
  password:any;
  passwordConfirm:any;
  languages:any = [];
  cantonese:any;
  french:any;
  german:any;
  italian:any;
  japanese:any;
  korean:any;
  mandarin:any;
  portuguese:any;
  russian:any;
  spanish:any;

  constructor(public navCtrl: NavController, public navParams: NavParams, private http: HttpProvider) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad RegisterPage');
  }

  register() {
    if(this.cantonese) {
      this.languages.push("Cantonese")
    }
    if(this.french) {
      this.languages.push("French")
    }
    if(this.german) {
      this.languages.push("German")
    }
    if(this.italian) {
      this.languages.push("Italian")
    }
    if(this.japanese) {
      this.languages.push("Japanese")
    }
    if(this.korean) {
      this.languages.push("Korean")
    }
    if(this.mandarin) {
      this.languages.push("Mandarin")
    }
    if(this.portuguese) {
      this.languages.push("Portuguese")
    }
    if(this.russian) {
      this.languages.push("Russian")
    }
    if(this.spanish) {
      this.languages.push("Spanish")
    }
    alert(this.username+" "+this.password);
    this.http.register(this.username,
      this.password,
      this.email,
      this.fname,
      this.lname,
      this.languages).subscribe((stuff) => {
      console.log(stuff);
    });
  }

}
</code>```

package.json

```<code>{
  "name": "project_name",
  "version": "0.0.1",
  "author": "Ionic Framework",
  "homepage": "http://ionicframework.com/",
  "private": true,
  "scripts": {
    "clean": "ionic-app-scripts clean",
    "build": "ionic-app-scripts build",
    "lint": "ionic-app-scripts lint",
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/common": "5.0.1",
    "@angular/compiler": "5.0.1",
    "@angular/compiler-cli": "5.0.1",
    "@angular/core": "5.0.1",
    "@angular/forms": "5.0.1",
    "@angular/http": "5.0.1",
    "@angular/platform-browser": "5.0.1",
    "@angular/platform-browser-dynamic": "5.0.1",
    "@ionic-native/core": "4.4.0",
    "@ionic-native/splash-screen": "4.4.0",
    "@ionic-native/status-bar": "4.4.0",
    "@ionic/storage": "2.1.3",
    "ionic-angular": "3.9.2",
    "ionicons": "3.0.0",
    "rxjs": "5.5.2",
    "sw-toolbox": "3.6.0",
    "zone.js": "0.8.18"
  },
  "devDependencies": {
    "@ionic/app-scripts": "3.1.2",
    "typescript": "2.4.2"
  },
  "description": "An Ionic project"
}
</code>```

答:
You want to change request.data in your django view to request.POST

Details here: http://www.django-rest-framework.org/tutorial/2-requests-and-responses/

Specifically

```<code>request.POST  # Only handles form data.  Only works for 'POST' method.
request.data  # Handles arbitrary data.  Works for 'POST', 'PUT' and 'PATCH' methods.
</code>```

Body:
I'm trying to create a new user in my Ionic app using Django as the backend. So far I can create a user no problem using Postman, but when I try to make an HTTP post request through my app I get the following error: {"password":["This field is required."],"username":["This field is required."]}. I am passing the username and password field to my Django app, but for some reason it doesn't register it. Is my post call wrong?

DJANGO APP CODE

serializers.py

class UserSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)
    languages = serializers.ListField(child=serializers.CharField(max_length=30, allow_blank=True), source="userprofile.languages")

    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email', 'username', 'password', 'languages')

    def create(self, validated_data, instance=None):
        profile_data = validated_data.pop('userprofile')
        user = User.objects.create(**validated_data)
        user.set_password(validated_data['password'])
        user.save()
        UserProfile.objects.update_or_create(user=user, **profile_data)
        return user

views.py

@api_view(['POST'])
@permission_classes((AllowAny,))
def create_user(request):
    serialized = UserSerializer(data=request.data)
    if serialized.is_valid():
        serialized.save()
        return Response(serialized.data, status=status.HTTP_201_CREATED)
    else:
        return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)

IONIC APP CODE

http.ts

  register(username, password, email, first_name, last_name, languages) {
    let url = "https://www.example.com/api/create_user/";
    let headers = new Headers()
    headers.append("Content-Type", "application/x-www-form-urlencoded");

    return this.http.post(url,
      {"first_name": first_name,
        "last_name": last_name,
        "email": email,
        "username": username,
        "password": password,
        "languages": languages
      }, {headers: headers})
      .map(res => res.json());
  }

register.ts

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';

import { HttpProvider } from "../../providers/http/http";

@IonicPage()
@Component({
  selector: 'page-register',
  templateUrl: 'register.html',
})
export class RegisterPage {

  //basic info
  username:any;
  email:any;
  fname:any;
  lname:any;
  password:any;
  passwordConfirm:any;
  languages:any = [];
  cantonese:any;
  french:any;
  german:any;
  italian:any;
  japanese:any;
  korean:any;
  mandarin:any;
  portuguese:any;
  russian:any;
  spanish:any;

  constructor(public navCtrl: NavController, public navParams: NavParams, private http: HttpProvider) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad RegisterPage');
  }

  register() {
    if(this.cantonese) {
      this.languages.push("Cantonese")
    }
    if(this.french) {
      this.languages.push("French")
    }
    if(this.german) {
      this.languages.push("German")
    }
    if(this.italian) {
      this.languages.push("Italian")
    }
    if(this.japanese) {
      this.languages.push("Japanese")
    }
    if(this.korean) {
      this.languages.push("Korean")
    }
    if(this.mandarin) {
      this.languages.push("Mandarin")
    }
    if(this.portuguese) {
      this.languages.push("Portuguese")
    }
    if(this.russian) {
      this.languages.push("Russian")
    }
    if(this.spanish) {
      this.languages.push("Spanish")
    }
    alert(this.username+" "+this.password);
    this.http.register(this.username,
      this.password,
      this.email,
      this.fname,
      this.lname,
      this.languages).subscribe((stuff) => {
      console.log(stuff);
    });
  }

}

package.json

{
  "name": "project_name",
  "version": "0.0.1",
  "author": "Ionic Framework",
  "homepage": "http://ionicframework.com/",
  "private": true,
  "scripts": {
    "clean": "ionic-app-scripts clean",
    "build": "ionic-app-scripts build",
    "lint": "ionic-app-scripts lint",
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/common": "5.0.1",
    "@angular/compiler": "5.0.1",
    "@angular/compiler-cli": "5.0.1",
    "@angular/core": "5.0.1",
    "@angular/forms": "5.0.1",
    "@angular/http": "5.0.1",
    "@angular/platform-browser": "5.0.1",
    "@angular/platform-browser-dynamic": "5.0.1",
    "@ionic-native/core": "4.4.0",
    "@ionic-native/splash-screen": "4.4.0",
    "@ionic-native/status-bar": "4.4.0",
    "@ionic/storage": "2.1.3",
    "ionic-angular": "3.9.2",
    "ionicons": "3.0.0",
    "rxjs": "5.5.2",
    "sw-toolbox": "3.6.0",
    "zone.js": "0.8.18"
  },
  "devDependencies": {
    "@ionic/app-scripts": "3.1.2",
    "typescript": "2.4.2"
  },
  "description": "An Ionic project"
}

Body:
You want to change request.data in your django view to request.POST

Details here: http://www.django-rest-framework.org/tutorial/2-requests-and-responses/

Specifically

request.POST  # Only handles form data.  Only works for 'POST' method.
request.data  # Handles arbitrary data.  Works for 'POST', 'PUT' and 'PATCH' methods.