问:
Java 8: Executing reduce operation on Stream
I've got a java.util.stream.Stream containing key value pairs like:

```<code><1,3> <1,5> <3,1> <4,2> <4,7> <4,8>
</code>```

Now I would like to merge all entries, which have got the same key:

```<code><1,[3,5]>  <3,[1]> <4,[2,7,8]>
</code>```

The data is already sorted, so only consecutive datasets have to be merged.

Now I'm searching for a way to transform the the content of the stream like above, without loading all datasets into memory.

I'd prefer to get a java.util.stream.Stream as result with a different object type containing a list of values instead of a single value.

My only approach is a custom iterator, which performs the merge, but it seems to be pretty ugly to convert to an iterator and back to stream.

What is the best approach for it?

答:
Here is the solution by SteamEx.

```<code>int[][] datasets = { { 1, 3 }, { 1, 5 }, { 3, 1 }, { 4, 2 }, { 4, 7 }, { 4, 8 } };

StreamEx.of(datasets) //
        .collapse((a, b) -> a[0] == b[0], groupingBy(a -> a[0], mapping(a -> a[1], toList()))) //
        .forEach(System.out::println);
</code>```

you can replace int[] with your dataset object. We can add peek to verify if it's lazy loading/calculation:

```<code>StreamEx.of(datasets) //
        .peek(System.out::println) //
        .collapse((a, b) -> a[0] == b[0], groupingBy(a -> a[0], mapping(a -> a[1], toList()))) //
        .limit(1) //
        .forEach(System.out::println);
</code>```

Body:
I've got a java.util.stream.Stream containing key value pairs like:

<1,3> <1,5> <3,1> <4,2> <4,7> <4,8>

Now I would like to merge all entries, which have got the same key:

<1,[3,5]>  <3,[1]> <4,[2,7,8]>

The data is already sorted, so only consecutive datasets have to be merged.

Now I'm searching for a way to transform the the content of the stream like above, without loading all datasets into memory.

I'd prefer to get a java.util.stream.Stream as result with a different object type containing a list of values instead of a single value.

My only approach is a custom iterator, which performs the merge, but it seems to be pretty ugly to convert to an iterator and back to stream.

What is the best approach for it?

Body:
Here is the solution by SteamEx.

int[][] datasets = { { 1, 3 }, { 1, 5 }, { 3, 1 }, { 4, 2 }, { 4, 7 }, { 4, 8 } };

StreamEx.of(datasets) //
        .collapse((a, b) -> a[0] == b[0], groupingBy(a -> a[0], mapping(a -> a[1], toList()))) //
        .forEach(System.out::println);

you can replace int[] with your dataset object. We can add peek to verify if it's lazy loading/calculation:

StreamEx.of(datasets) //
        .peek(System.out::println) //
        .collapse((a, b) -> a[0] == b[0], groupingBy(a -> a[0], mapping(a -> a[1], toList()))) //
        .limit(1) //
        .forEach(System.out::println);


来源: stackexchange

问:
centos: Another MySQL daemon already running with the same unix socket
I have a strange error when starting mysqld service:

```<code>Another MySQL daemon already running with the same unix socket.
</code>```

I've tried to list running services and stopping them but the same error happens when starting mysqld service.

I can try to remove the mysqld and reinstall it but will this remove the database too?

答:
It's just happen because of abnormal termination of mysql service. delete or take backup of /var/lib/mysql/mysql.sock file and restart mysql.

Please let me know if in case any issue..

ContentLicense: CC BY-SA 3.0

Body:
I have a strange error when starting mysqld service:

Another MySQL daemon already running with the same unix socket.

I've tried to list running services and stopping them but the same error happens when starting mysqld service.

I can try to remove the mysqld and reinstall it but will this remove the database too?


问:
Problems with building OpenCV 3.2 and python bindings on Windows
I am attempting to build OpenCV on Windows 10 with extra modules and python bindings (and thus following this guide), and I'm running into some issues. Firstly, I am only seeing a Visual Studio project called "opencv_python3" under the "bindings" folder, and not the project for python2. I am not seeing any errors related to this in CMake and filling in the appropriate variables for python 2 like I am with python 3.</p>

答: I have solved the issue by installing Python 2.7 (64 bit). I had previously been trying to install OpenCV with Python 2.7 (32 bit). I can't speak to whether or not it is possible to install OpenCV 3.2 with Python 2.7 (32 bit) bindings, but making this change did work for me.


问:
Change Text to Bold or Add Images using Google Script
This is the Code I have so far and it works great! I just want to know how to change the text to bold and add images if possible.For where it says grows, glows, apropos. I would like that to be bolded for example.</p>

```<code>       function sendEmails() {
  var allData,counter,emailAddress,fourRowsOfData,i,lastRow,
      message,messageStart,messageEnd,numRows,
      row,sheet,startRow,studentName,subject;

  //USER INPUT
  startRow = 2;  // First row of data to process
  numRows = 4;   // Number of rows to process
  subject = "Camp Pursuit: Report Card ";
  messageStart = "Dear Parents,"+'\n' +'\n' +
  "Every week at Camp Pursuit, we ask the teachers to make observations about how the kiddos did." +'\n' +
  "We know that one week isn't enough to truly know a child, so we call this our " +"Glows, Grows, & Apropos." +'\n' +
    "Meaning..." + '\n' +'\n' +
    "Glows: Positive things the teacher noticed" +'\n' +
    "Grows: Areas for continued growth" +'\n' +
    "Apropos: Ways to continue your son/daughter's enrichment" +'\n' +
    "We hope you appreciate seeing what the teachers saw last week, and perhaps you can use some of"+'\n' +
    "the recommendations for further enrichment this summer.  Feel free to let us know your thoughts on the camp through our anonymous online survey."+'\n' +
     "Your feedback helps us improve the experience for all kiddos! "+'\n' +
"Survey Link: https://docs.google.com/forms/d/1g4LvA9a8sdKECr1yvp5uOoPnvKACFm3HvbTBfvQGRyo/viewform?usp=send_form" +'\n' +
"We look forward to seeing your child at our programs throughout the year!" +'\n' +
"Sincerely, "+'\n' +
"The Camp Pursuit Team"
+'\n';
  //END USER INPUT

  sheet = SpreadsheetApp.getActiveSheet();
  lastRow = sheet.getLastRow();

  allData = sheet.getRange(startRow, 1, lastRow-startRow, 10);// Get All data first

  counter = 0;

  while (counter < lastRow-startRow) {
    Logger.log('counter: ' + counter)

    fourRowsOfData = sheet.getRange(startRow + counter, 1, numRows, 6).getValues();
    emailAddress = fourRowsOfData[0][0];  // First column of first row
    Logger.log('emailAddress: ' + emailAddress)

    studentName = fourRowsOfData[0][1];

    messageEnd = "";//Reset on every outer loop

    for (i = 0; i < numRows; i++) {//loop numRows times - once for each row
        row = fourRowsOfData[i];

        messageEnd = messageEnd + '\n' +
            "Class: " + row[2] + '\n' +'\n' +
              "Glows: " + row[3]+ '\n' +
              "Grows: " + row[4] +'\n' +
                "Apropos: " + row[5] +'\n';
    }

    message = messageStart + "\n" + studentName + "\n" + messageEnd;

    MailApp.sendEmail(emailAddress, subject, message);//Send the email outside of inner loop
    counter+=numRows;//Increment counter by number of rows to process
  }
}
</code>```

答:
As per the official MailApp Documentation, to send HTML body you'll need to use htmlBody parameter in your MailApp.sendEmail() method. Have a look at the example below (copied from official documentation page)

To make a text bold use tag

For example: "This text will be displayed in bold.

To show an image in email use

```<code>MailApp.sendEmail({
     to: "recipient@example.com",
     subject: "Logos",
     htmlBody: "inline Google Logo<img src='URL_PATH'> images! <br>" +
               "inline YouTube Logo <img src='URL_PATH'><br>" +
               "<b>Using bold tag</b> ",
     inlineImages:
       {
         googleLogo: googleLogoBlob,
         youtubeLogo: youtubeLogoBlob
       }
   });
</code>```

Hope this helps.

Body:
This is the Code I have so far and it works great! I just want to know how to change the text to bold and add images if possible.For where it says grows, glows, apropos. I would like that to be bolded for example.

       function sendEmails() {
  var allData,counter,emailAddress,fourRowsOfData,i,lastRow,
      message,messageStart,messageEnd,numRows,
      row,sheet,startRow,studentName,subject;

  //USER INPUT
  startRow = 2;  // First row of data to process
  numRows = 4;   // Number of rows to process
  subject = "Camp Pursuit: Report Card ";
  messageStart = "Dear Parents,"+'\n' +'\n' +
  "Every week at Camp Pursuit, we ask the teachers to make observations about how the kiddos did." +'\n' +
  "We know that one week isn't enough to truly know a child, so we call this our " +"Glows, Grows, & Apropos." +'\n' +
    "Meaning..." + '\n' +'\n' +
    "Glows: Positive things the teacher noticed" +'\n' +
    "Grows: Areas for continued growth" +'\n' +
    "Apropos: Ways to continue your son/daughter's enrichment" +'\n' +
    "We hope you appreciate seeing what the teachers saw last week, and perhaps you can use some of"+'\n' +
    "the recommendations for further enrichment this summer.  Feel free to let us know your thoughts on the camp through our anonymous online survey."+'\n' +
     "Your feedback helps us improve the experience for all kiddos! "+'\n' +
"Survey Link: https://docs.google.com/forms/d/1g4LvA9a8sdKECr1yvp5uOoPnvKACFm3HvbTBfvQGRyo/viewform?usp=send_form" +'\n' +
"We look forward to seeing your child at our programs throughout the year!" +'\n' +
"Sincerely, "+'\n' +
"The Camp Pursuit Team"
+'\n';
  //END USER INPUT

  sheet = SpreadsheetApp.getActiveSheet();
  lastRow = sheet.getLastRow();

  allData = sheet.getRange(startRow, 1, lastRow-startRow, 10);// Get All data first

  counter = 0;

  while (counter < lastRow-startRow) {
    Logger.log('counter: ' + counter)

    fourRowsOfData = sheet.getRange(startRow + counter, 1, numRows, 6).getValues();
    emailAddress = fourRowsOfData[0][0];  // First column of first row
    Logger.log('emailAddress: ' + emailAddress)

    studentName = fourRowsOfData[0][1];

    messageEnd = "";//Reset on every outer loop

    for (i = 0; i < numRows; i++) {//loop numRows times - once for each row
        row = fourRowsOfData[i];

        messageEnd = messageEnd + '\n' +
            "Class: " + row[2] + '\n' +'\n' +
              "Glows: " + row[3]+ '\n' +
              "Grows: " + row[4] +'\n' +
                "Apropos: " + row[5] +'\n';
    }

    message = messageStart + "\n" + studentName + "\n" + messageEnd;

    MailApp.sendEmail(emailAddress, subject, message);//Send the email outside of inner loop
    counter+=numRows;//Increment counter by number of rows to process
  }
}

Body:
As per the official MailApp Documentation, to send HTML body you'll need to use htmlBody parameter in your MailApp.sendEmail() method. Have a look at the example below (copied from official documentation page)

To make a text bold use <b></b>tag

For example: "This text will be displayed in bold.

To show an image in email use <img src="hostname.com/image.png">

MailApp.sendEmail({
     to: "recipient@example.com",
     subject: "Logos",
     htmlBody: "inline Google Logo<img src='URL_PATH'> images! <br>" +
               "inline YouTube Logo <img src='URL_PATH'><br>" +
               "<b>Using bold tag</b> ",
     inlineImages:
       {
         googleLogo: googleLogoBlob,
         youtubeLogo: youtubeLogoBlob
       }
   });

Hope this helps.


问:
Writing to a file - file not created in Visual Studio 2015 (fstream)
I checked my current working directory

(C:\Users\Ada\Documents\Visual Studio 2015\Projects\ProjektPO\ProjektPO)

and tried to create a new file there but I did not work. No errors,just won't create a file.

Here's my code:

```<code>(#include<fstream>)

    fstream file;
    file.open("C:\Users\Ada\Documents\Visual Studio 2015\Projects\ProjektPO\ProjektPO\file.txt");
    for (unsigned int i = 0; i < cass.size(); i++)
    {
        file << cass[i]->name << ";" << cass[i]->debt << endl;
    }
    file.close();
    system("pause");
</code>```

Any tips?

答:
As far as I know you need to add this:
ios::in | ios::out
because by default only ios::in is used.

Body:
I checked my current working directory

(C:\Users\Ada\Documents\Visual Studio 2015\Projects\ProjektPO\ProjektPO)

and tried to create a new file there but I did not work. No errors,just won't create a file.

Here's my code:

(#include<fstream>)

    fstream file;
    file.open("C:\Users\Ada\Documents\Visual Studio 2015\Projects\ProjektPO\ProjektPO\file.txt");
    for (unsigned int i = 0; i < cass.size(); i++)
    {
        file << cass[i]->name << ";" << cass[i]->debt << endl;
    }
    file.close();
    system("pause");

Any tips?


问:
Does struct assignment guarantee padding to also be equal
Say I have a struct with 2 fields and the implementation of C that I have also has some padding between these fields.

If I create two variables of the struct and assign one to another, will the padding be guaranteed to be equal?

I know that for most compilers it would be so (because they just call memcpy), but I want to know what is specified about the padding in the standard?

Intention for this question is, can I use memcmp to check equality of structs.

Say I have a compiler which emits code that just assigns all the members of the struct instead of doing memcpy, will it be a valid implementation of the assignment of struct operation?

答:
6.2.6.1 General

...

6    When a value is stored in an object of structure or union type, including in a member
object, the bytes of the object representation that correspond to any padding bytes take
unspecified values.51) The value of a structure or union object is never a trap representation, even though the value of a member of the structure or union object may be
a trap representation.

7    When a value is stored in a member of an object of union type, the bytes of the object
representation that do not correspond to that member but do correspond to other members
take unspecified values.

51) Thus, for example, structure assignment need not copy any padding bits.

C 2011 Online Draft

Footnote 51 directly addresses your question - contents of padding bits may not be copied over in assignment, so memcmp may not work for comparing two structs for equality.


问:
Symfony2 - use Sonata field type outside the bundle
I would like to have good looking EntityType for multiple selection as Sonata does with sonata_type_model (ModelType).

The question would be, how can I use sonata_type_model outside SonataAdminBundle on my custom form?

I tried:

```<code>->add('countries', 'sonata_type_model', array(
    'label' => 'Countries',
    'property' => 'name',
    'multiple' => true
))
</code>```

Also I tried:

```<code>use Sonata\AdminBundle\Form\Type\ModelType;

...

->add('countries', ModelType::class, array(
    'label' => 'Countries',
    'property' => 'name',
    'multiple' => true
))
</code>```

But unfortunately I am getting an error:

Catchable Fatal Error: Argument 1 passed to
  Sonata\AdminBundle\Form\ChoiceList\ModelChoiceLoader::__construct()
  must implement interface
  Sonata\AdminBundle\Model\ModelManagerInterface, null given, called in
  C:\xampp\htdocs\trainingexperience_symfony\app\cache\dev\classes.php
  on line 18005 and defined

UPDATE

I followed an advice to define model_manager property inside form type options:

```<code>protected $modelManager;

function __construct(ModelManager $modelManager)
{
    $this->modelManager = $modelManager;
}

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('preferredCountries', ModelType::class, array(
            'label' => 'Countries',
            'property' => 'name',
            'multiple' => true,
            'model_manager' => $this->modelManager
        ));

    ...
}
</code>```

I pass it from controller like:

```<code>/** @var ModelManager $modelManager */
$modelManager = $this->get('sonata.media.admin.media.manager');
$formType = new FormType($modelManager);

...
</code>```

But now I get an error:

Class does not exist

500 Internal Server Error - ReflectionException

Stack Trace

```<code>in vendor\doctrine\common\lib\Doctrine\Common\Persistence\AbstractManagerRegistry.php at line 197   -

   $class = $this->getAliasNamespace($namespaceAlias) . '\\' . $simpleClassName;
        }
        $proxyClass = new \ReflectionClass($class);
        if ($proxyClass->implementsInterface($this->proxyInterfaceName)) {
            if (! $parentClass = $proxyClass->getParentClass()) {

at ReflectionClass ->__construct ('')
in vendor\doctrine\common\lib\Doctrine\Common\Persistence\AbstractManagerRegistry.php at line 197   +
at AbstractManagerRegistry ->getManagerForClass (null)
in vendor\sonata-project\doctrine-orm-admin-bundle\Model\ModelManager.php at line 272   +
at ModelManager ->getEntityManager (null)
in vendor\sonata-project\doctrine-orm-admin-bundle\Model\ModelManager.php at line 64   +
at ModelManager ->getMetadata (null)
in vendor\sonata-project\doctrine-orm-admin-bundle\Model\ModelManager.php at line 377   +
at ModelManager ->getIdentifierFieldNames (null)
in vendor\sonata-project\admin-bundle\Form\ChoiceList\ModelChoiceLoader.php at line 75   +
at ModelChoiceLoader ->__construct (object(ModelManager), null, 'name', null, array(), object(PropertyAccessor))
in vendor\sonata-project\admin-bundle\Form\Type\ModelType.php at line 113   +
at ModelType ->Sonata\AdminBundle\Form\Type\{closure} (object(OptionsResolver), null)
in vendor\symfony\symfony\src\Symfony\Component\OptionsResolver\OptionsResolver.php at line 859   +
at OptionsResolver ->offsetGet ('choice_loader')
in vendor\symfony\symfony\src\Symfony\Component\Form\Extension\Core\Type\ChoiceType.php at line 320   +
at ChoiceType ->Symfony\Component\Form\Extension\Core\Type\{closure} (object(OptionsResolver), null)
in vendor\symfony\symfony\src\Symfony\Component\OptionsResolver\OptionsResolver.php at line 965   +
at OptionsResolver ->offsetGet ('choice_list')
in vendor\symfony\symfony\src\Symfony\Component\OptionsResolver\OptionsResolver.php at line 791   +
at OptionsResolver ->resolve (array('label' => 'Countries', 'property' => 'name', 'multiple' => true, 'model_manager' => object(ModelManager)))
in vendor\symfony\symfony\src\Symfony\Component\Form\ResolvedFormType.php at line 156   +
at ResolvedFormType ->createBuilder (object(FormFactory), 'preferredCountries', array('label' => 'Countries', 'property' => 'name', 'multiple' => true, 'model_manager' => object(ModelManager)))
in vendor\symfony\symfony\src\Symfony\Component\Form\Extension\DataCollector\Proxy\ResolvedTypeDataCollectorProxy.php at line 89  +
at ResolvedTypeDataCollectorProxy ->createBuilder (object(FormFactory), 'preferredCountries', array('label' => 'Countries', 'property' => 'name', 'multiple' => true, 'model_manager' => object(ModelManager)))
in vendor\symfony\symfony\src\Symfony\Component\Form\FormFactory.php at line 114   +
at FormFactory ->createNamedBuilder ('preferredCountries', 'Sonata\AdminBundle\Form\Type\ModelType', null, array('label' => 'Countries', 'property' => 'name', 'multiple' => true, 'model_manager' => object(ModelManager)))
in vendor\symfony\symfony\src\Symfony\Component\Form\FormBuilder.php at line 106   +
at FormBuilder ->create ('preferredCountries', 'Sonata\AdminBundle\Form\Type\ModelType', array('label' => 'Countries', 'property' => 'name', 'multiple' => true, 'model_manager' => object(ModelManager)))
in vendor\symfony\symfony\src\Symfony\Component\Form\FormBuilder.php at line 269   +
at FormBuilder ->resolveChildren ()
in vendor\symfony\symfony\src\Symfony\Component\Form\FormBuilder.php at line 215   +
at FormBuilder ->getForm ()
in vendor\symfony\symfony\src\Symfony\Component\Form\FormFactory.php at line 40   +
at FormFactory ->create (object(InternshipType), object(Internship), array())
in vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Controller\Controller.php at line 282   +
at Controller ->createForm (object(InternshipType), object(Internship))
in src\IndexBundle\Controller\TraineeController.php at line 194   +
at TraineeController ->internshipsAction (object(Request))
at call_user_func_array (array(object(TraineeController), 'internshipsAction'), array(object(Request)))
in vendor\symfony\symfony\src\Symfony\Component\HttpKernel\HttpKernel.php at line 144   +
at HttpKernel ->handleRaw (object(Request), '1')
in vendor\symfony\symfony\src\Symfony\Component\HttpKernel\HttpKernel.php at line 64   +
at HttpKernel ->handle (object(Request), '1', true)
in vendor\symfony\symfony\src\Symfony\Component\HttpKernel\DependencyInjection\ContainerAwareHttpKernel.php at line 69   +
at ContainerAwareHttpKernel ->handle (object(Request), '1', true)
in vendor\symfony\symfony\src\Symfony\Component\HttpKernel\Kernel.php at line 185   +
at Kernel ->handle (object(Request))
in web\app_dev.php at line 30   +
</code>```

答:
I don't know if someone is still searching that, but, I've found that you need this to have the modelManager (at least in 2.7 version of symfony):

```<code>/** @var ModelManager $modelManager */
$modelManager = $this->get('sonata.admin.manager.orm');
$formType = new FormType($modelManager);

...
</code>```

byez

Body:
I would like to have good looking EntityType for multiple selection as Sonata does with sonata_type_model (ModelType).

The question would be, how can I use sonata_type_model outside SonataAdminBundle on my custom form?

I tried:

->add('countries', 'sonata_type_model', array(
    'label' => 'Countries',
    'property' => 'name',
    'multiple' => true
))

Also I tried:

use Sonata\AdminBundle\Form\Type\ModelType;

...

->add('countries', ModelType::class, array(
    'label' => 'Countries',
    'property' => 'name',
    'multiple' => true
))

But unfortunately I am getting an error:

Catchable Fatal Error: Argument 1 passed to
  Sonata\AdminBundle\Form\ChoiceList\ModelChoiceLoader::__construct()
  must implement interface
  Sonata\AdminBundle\Model\ModelManagerInterface, null given, called in
  C:\xampp\htdocs\trainingexperience_symfony\app\cache\dev\classes.php
  on line 18005 and defined

UPDATE

I followed an advice to define model_manager property inside form type options:

protected $modelManager;

function __construct(ModelManager $modelManager)
{
    $this->modelManager = $modelManager;
}

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('preferredCountries', ModelType::class, array(
            'label' => 'Countries',
            'property' => 'name',
            'multiple' => true,
            'model_manager' => $this->modelManager
        ));

    ...
}

I pass it from controller like:

/** @var ModelManager $modelManager */
$modelManager = $this->get('sonata.media.admin.media.manager');
$formType = new FormType($modelManager);

...

But now I get an error:

Class does not exist

500 Internal Server Error - ReflectionException

Stack Trace

in vendor\doctrine\common\lib\Doctrine\Common\Persistence\AbstractManagerRegistry.php at line 197   -

   $class = $this->getAliasNamespace($namespaceAlias) . '\\' . $simpleClassName;
        }
        $proxyClass = new \ReflectionClass($class);
        if ($proxyClass->implementsInterface($this->proxyInterfaceName)) {
            if (! $parentClass = $proxyClass->getParentClass()) {

at ReflectionClass ->__construct ('')
in vendor\doctrine\common\lib\Doctrine\Common\Persistence\AbstractManagerRegistry.php at line 197   +
at AbstractManagerRegistry ->getManagerForClass (null)
in vendor\sonata-project\doctrine-orm-admin-bundle\Model\ModelManager.php at line 272   +
at ModelManager ->getEntityManager (null)
in vendor\sonata-project\doctrine-orm-admin-bundle\Model\ModelManager.php at line 64   +
at ModelManager ->getMetadata (null)
in vendor\sonata-project\doctrine-orm-admin-bundle\Model\ModelManager.php at line 377   +
at ModelManager ->getIdentifierFieldNames (null)
in vendor\sonata-project\admin-bundle\Form\ChoiceList\ModelChoiceLoader.php at line 75   +
at ModelChoiceLoader ->__construct (object(ModelManager), null, 'name', null, array(), object(PropertyAccessor))
in vendor\sonata-project\admin-bundle\Form\Type\ModelType.php at line 113   +
at ModelType ->Sonata\AdminBundle\Form\Type\{closure} (object(OptionsResolver), null)
in vendor\symfony\symfony\src\Symfony\Component\OptionsResolver\OptionsResolver.php at line 859   +
at OptionsResolver ->offsetGet ('choice_loader')
in vendor\symfony\symfony\src\Symfony\Component\Form\Extension\Core\Type\ChoiceType.php at line 320   +
at ChoiceType ->Symfony\Component\Form\Extension\Core\Type\{closure} (object(OptionsResolver), null)
in vendor\symfony\symfony\src\Symfony\Component\OptionsResolver\OptionsResolver.php at line 965   +
at OptionsResolver ->offsetGet ('choice_list')
in vendor\symfony\symfony\src\Symfony\Component\OptionsResolver\OptionsResolver.php at line 791   +
at OptionsResolver ->resolve (array('label' => 'Countries', 'property' => 'name', 'multiple' => true, 'model_manager' => object(ModelManager)))
in vendor\symfony\symfony\src\Symfony\Component\Form\ResolvedFormType.php at line 156   +
at ResolvedFormType ->createBuilder (object(FormFactory), 'preferredCountries', array('label' => 'Countries', 'property' => 'name', 'multiple' => true, 'model_manager' => object(ModelManager)))
in vendor\symfony\symfony\src\Symfony\Component\Form\Extension\DataCollector\Proxy\ResolvedTypeDataCollectorProxy.php at line 89  +
at ResolvedTypeDataCollectorProxy ->createBuilder (object(FormFactory), 'preferredCountries', array('label' => 'Countries', 'property' => 'name', 'multiple' => true, 'model_manager' => object(ModelManager)))
in vendor\symfony\symfony\src\Symfony\Component\Form\FormFactory.php at line 114   +
at FormFactory ->createNamedBuilder ('preferredCountries', 'Sonata\AdminBundle\Form\Type\ModelType', null, array('label' => 'Countries', 'property' => 'name', 'multiple' => true, 'model_manager' => object(ModelManager)))
in vendor\symfony\symfony\src\Symfony\Component\Form\FormBuilder.php at line 106   +
at FormBuilder ->create ('preferredCountries', 'Sonata\AdminBundle\Form\Type\ModelType', array('label' => 'Countries', 'property' => 'name', 'multiple' => true, 'model_manager' => object(ModelManager)))
in vendor\symfony\symfony\src\Symfony\Component\Form\FormBuilder.php at line 269   +
at FormBuilder ->resolveChildren ()
in vendor\symfony\symfony\src\Symfony\Component\Form\FormBuilder.php at line 215   +
at FormBuilder ->getForm ()
in vendor\symfony\symfony\src\Symfony\Component\Form\FormFactory.php at line 40   +
at FormFactory ->create (object(InternshipType), object(Internship), array())
in vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Controller\Controller.php at line 282   +
at Controller ->createForm (object(InternshipType), object(Internship))
in src\IndexBundle\Controller\TraineeController.php at line 194   +
at TraineeController ->internshipsAction (object(Request))
at call_user_func_array (array(object(TraineeController), 'internshipsAction'), array(object(Request)))
in vendor\symfony\symfony\src\Symfony\Component\HttpKernel\HttpKernel.php at line 144   +
at HttpKernel ->handleRaw (object(Request), '1')
in vendor\symfony\symfony\src\Symfony\Component\HttpKernel\HttpKernel.php at line 64   +
at HttpKernel ->handle (object(Request), '1', true)
in vendor\symfony\symfony\src\Symfony\Component\HttpKernel\DependencyInjection\ContainerAwareHttpKernel.php at line 69   +
at ContainerAwareHttpKernel ->handle (object(Request), '1', true)
in vendor\symfony\symfony\src\Symfony\Component\HttpKernel\Kernel.php at line 185   +
at Kernel ->handle (object(Request))
in web\app_dev.php at line 30   +

Body:
I don't know if someone is still searching that, but, I've found that you need this to have the modelManager (at least in 2.7 version of symfony):

/** @var ModelManager $modelManager */
$modelManager = $this->get('sonata.admin.manager.orm');
$formType = new FormType($modelManager);

...

byez


问:
Can't Publish Because of Intellisense Errors
In VS 2015, I have a solution that builds and debugs just fine.  But, when I go to publish it, it won't let me because of 60 intellisense errors.

I've found a few threads like these:

Visual Studio 2015: Intellisense errors but solution compiles

Intellisense keeps showing errors while build is successful Visual Studio 2015

I've tried all the answers & suggestion, even in the comments.

What I've tried:

Go into the references of every project in the solution. Remove the reference to C#, and to all of the other projects.   Clean.  Rebuild (which of course failed.)  Then add them all back. Clean.  Rebuild.

Delete every .suo file within the solution.  Clean.  Rebuild.

Delete all of the bin and obj folders within the solution.  Clean.  Rebuild.

Do all of the above, but wait to do a clean and rebuild until all three steps had been done. Then clean & rebuild.

Updated every nuget package in the solution to the newest version.

Anyone else ever seen this and found a fix?

UPDATE:

The 60 errors are all over the place.  Here's just a sample:

答:
This question is getting a lot of views, and some stars. So I thought I would circle back to it and post the solution I found.

It turns out that my issue centered on TypeScript.  Another developer had installed in on this solution while using Visual Studio 2017. And when I tried to publish using Visual Studio 2015, it kept throwing the Intellisense errors and would not let me publish.

The only way we figured out how to get around this was for me to upgrade to VS 2017.  (I intended to anyway,  but this just hurried the process up a little.)  Once the upgrade was complete, the Intellisense errors went away and I was able to publish.

I hope this helps other people.


问:
Can anyone explain the difference between expression, ng-bind and ng-model?
I am very confuse between expression {{}}, ng-bind and ng-model. please explain with example if possible.</p>

答:
ng-bind and ng-model both are the inbuilt directives in Angular.

While ng-bind helps you to bind a value to innerHTML of an element, ng-model helps you bind the data to the interactive elements (i.e. <input>, <checkbox>, <textarea>), you got it..

Usage:

ng-bind

If you have
$scope.textFromComponent = "Superman" in your controller.

 binds this value within this span element.

{{ }}

The same behaviour can be achieved using {{}}.

These set of curly-brackets are called Interpolation directives and they work as a short-hand to ng-bind. While using them you no more need to write ng-bind rather you directly bind them. Like:

{{textFromComponent}}

ng-model

<input ng-model="textFromComponent" />

binds this value to the value property of your input element. This binds the value two-way which means if you make any changes to $scope.textFromComponent in your code, it will reflect on screen automatically. At the same time, if user makes any change to it ( since they are interactive elements, user can change them) the changed value will be passed to your code.

Body:
ng-bind and ng-model both are the inbuilt directives in Angular.

While ng-bind helps you to bind a value to innerHTML of an element, ng-model helps you bind the data to the interactive elements (i.e. <input>, <checkbox>, <textarea>), you got it..

Usage:

ng-bind

If you have
$scope.textFromComponent = "Superman" in your controller.

<span ng-bind="textFromComponent"></span> binds this value within this span element.

{{ }}

The same behaviour can be achieved using {{}}.

These set of curly-brackets are called Interpolation directives and they work as a short-hand to ng-bind. While using them you no more need to write ng-bind rather you directly bind them. Like:

<span>{{textFromComponent}}</span>

ng-model

<input ng-model="textFromComponent" />

binds this value to the value property of your input element. This binds the value two-way which means if you make any changes to $scope.textFromComponent in your code, it will reflect on screen automatically. At the same time, if user makes any change to it ( since they are interactive elements, user can change them) the changed value will be passed to your code.


问:
Bitbucket Pull Not working suddenly
When tried to pull the repo today, it say below error, but last several months it was working. Have tried with Bitbucket website, but no info about it. Is anyone in facing the same? Is Atalassian provided any work around for it?</p>

```<code> sudo git pull

Password for 'https://stutzen@bitbucket.org':
remote: Repositories on team accounts can only be accessed through a team member. Using a team password is not allowed.
</code>```

答:
This is due to changes in Bitbucket:

https://blog.bitbucket.org/2014/01/14/important-changes-are-coming-to-teams/

Clearly, the date kept getting pushed back, but this has been coming for a while.

There's a bit more detail at https://confluence.atlassian.com/bbkb/team-account-changes-454361799.html .

Title: Bitbucket Pull Not working suddenly

Body:
When tried to pull the repo today, it say below error, but last several months it was working. Have tried with Bitbucket website, but no info about it. Is anyone in facing the same? Is Atalassian provided any work around for it?

 sudo git pull

Password for 'https://stutzen@bitbucket.org':
remote: Repositories on team accounts can only be accessed through a team member. Using a team password is not allowed.


问:
React Native - Updating state upon pressing a button
I currently have two buttons (No, Yes)( component imported from native-base package) that when pressed should update the state with either 0 or 1 respectively and also toggle between true or false to notify if this field has been filled (by default, neither of the two will be pressed, hence set to false).

I have a handleOnClick() function bound to the "No" button with a debugger to test if I actually do hit it, but once inside this function, I'm not sure how to grab any info for associated components (i.e. the "No" text within the Text component) so I can perform logic to check if "No" or "Yes" was pressed.

If this was done in pure React, I know I can access certain data attributes that I add to DOM elements or traverse the DOM, but I'm not sure how to do this in React Native or if I'm able to add custom props to a built in component that I can then access.

```<code>class Toggle extends Component {
  constructor() {
    super()

    this.state = {
      selectedOption: '',
      isFilled: false
    }

    this.checkField = this.checkField.bind(this)
    this.handleOnClick = this.handleOnClick.bind(this)
  }

  checkField() {
    console.log(this)
    // debugger
  }

  handleOnClick(ev) {
    debugger
    console.log("I was pressed")
  }

  render() {
    const options = this.props.inputInfo.options //=> [0,1]
    const optionLabels = this.props.inputInfo.options_labels_en //=>["No","Yes"]

    return (
      <View style={{flexDirection: 'row'}}>
        <View style={styles.row} >
          <Button light full onPress={this.handleOnClick}><Text>No</Text></Button>
        </View>
        <View style={styles.row} >
          <Button success full><Text>Yes</Text></Button>
        </View>
      </View>
    )
  }
}
</code>```

答:
If you want to pass information into function, you can pass it when it is called. In your case, you can call your function from arrow function, like so:

```<code>      <View style={{flexDirection: 'row'}}>
        <View style={styles.row} >
          <Button light full onPress={() => this.handleOnClick('No')}>
            <Text>No</Text>
          </Button>
        </View>
        <View style={styles.row} >
          <Button success full><Text>Yes</Text></Button>
        </View>
      </View>
</code>```

And in your function

```<code>  handleOnClick(text) {
    debugger
    console.log(`${text} pressed`)
  }
</code>```

Body:
I currently have two buttons (No, Yes)( component imported from native-base package) that when pressed should update the state with either 0 or 1 respectively and also toggle between true or false to notify if this field has been filled (by default, neither of the two will be pressed, hence set to false).

I have a handleOnClick() function bound to the "No" button with a debugger to test if I actually do hit it, but once inside this function, I'm not sure how to grab any info for associated components (i.e. the "No" text within the Text component) so I can perform logic to check if "No" or "Yes" was pressed.

If this was done in pure React, I know I can access certain data attributes that I add to DOM elements or traverse the DOM, but I'm not sure how to do this in React Native or if I'm able to add custom props to a built in component that I can then access.

class Toggle extends Component {
  constructor() {
    super()

    this.state = {
      selectedOption: '',
      isFilled: false
    }

    this.checkField = this.checkField.bind(this)
    this.handleOnClick = this.handleOnClick.bind(this)
  }

  checkField() {
    console.log(this)
    // debugger
  }

  handleOnClick(ev) {
    debugger
    console.log("I was pressed")
  }

  render() {
    const options = this.props.inputInfo.options //=> [0,1]
    const optionLabels = this.props.inputInfo.options_labels_en //=>["No","Yes"]

    return (
      <View style={{flexDirection: 'row'}}>
        <View style={styles.row} >
          <Button light full onPress={this.handleOnClick}><Text>No</Text></Button>
        </View>
        <View style={styles.row} >
          <Button success full><Text>Yes</Text></Button>
        </View>
      </View>
    )
  }
}

Body:
If you want to pass information into function, you can pass it when it is called. In your case, you can call your function from arrow function, like so:

      <View style={{flexDirection: 'row'}}>
        <View style={styles.row} >
          <Button light full onPress={() => this.handleOnClick('No')}>
            <Text>No</Text>
          </Button>
        </View>
        <View style={styles.row} >
          <Button success full><Text>Yes</Text></Button>
        </View>
      </View>

And in your function

  handleOnClick(text) {
    debugger
    console.log(`${text} pressed`)
  }


问:
Dispatch and setState not working together, but are on their own
I have a DatePicker component, when I click on a new date it should set the change the date in the redux store, and also visibly UX-wise.

I'll put my code down below, for some reason in the handleChange function, with both the setState and the this.props.addFitler there firing off, the redux store updates correctly but the UX doesn't.
However if I comment out the this.props.addFilter dispatch function, the UX update correctly (and obviously the store doesn't).

Why aren't both of these working together? I've tried changing the order in which they're called, extracting each into another function, using mapDispatchToProps instead of calling the action creator directly, all to no avail.

DatePicker.js:

```<code>import DatePicker from 'react-datepicker';

class DatePick extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      date: moment()
    };
    this.handleChange = this.handleChange.bind(this);
  }
  handleChange(date) {
    const { dashboardName } = this.props;
    const { name } = this.props.column;
    this.props.addFilter(date, dashboardName, name);
    this.setState({date});
  }
  render() {
    return (
      <div style={{display: 'inline-block', fontWeight: 'bold'}}>
        <DatePicker
          dateFormat="DD/MM/YYYY"
          selected={this.state.date}
          onChange={this.handleChange} />
      </div>
    );
  }
}

const mapActionToProps = {
  addFilter
};

export default connect(null, mapActionToProps)(DatePick);
</code>```

The 'date' parameter that comes through in the handleChange function is a moment object just like the one used to set initialState, so that isn't the issue.

Additional info: If I console log before and after setState() it logs the initial state both times.

Has anyone ran into this problem or have any ideas? If you need to see my redux I can update the post with more code but I don't think that's the problem as it updates the store fine.

答: I found the solution, action creator calling is doing some synchronous operation and the whole UI thread is locked until it finishes whatever it's doing. Hence we can delay the call a little bit with the help of setTimeout and everything will go as expected</p>

Body:
I have a DatePicker component, when I click on a new date it should set the change the date in the redux store, and also visibly UX-wise.

I'll put my code down below, for some reason in the handleChange function, with both the setState and the this.props.addFitler there firing off, the redux store updates correctly but the UX doesn't.
However if I comment out the this.props.addFilter dispatch function, the UX update correctly (and obviously the store doesn't).

Why aren't both of these working together? I've tried changing the order in which they're called, extracting each into another function, using mapDispatchToProps instead of calling the action creator directly, all to no avail.

DatePicker.js:

import DatePicker from 'react-datepicker';

class DatePick extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      date: moment()
    };
    this.handleChange = this.handleChange.bind(this);
  }
  handleChange(date) {
    const { dashboardName } = this.props;
    const { name } = this.props.column;
    this.props.addFilter(date, dashboardName, name);
    this.setState({date});
  }
  render() {
    return (

        <DatePicker
          dateFormat="DD/MM/YYYY"
          selected={this.state.date}
          onChange={this.handleChange} />

    );
  }
}

const mapActionToProps = {
  addFilter
};

export default connect(null, mapActionToProps)(DatePick);

The 'date' parameter that comes through in the handleChange function is a moment object just like the one used to set initialState, so that isn't the issue.

Additional info: If I console log before and after setState() it logs the initial state both times.

Has anyone ran into this problem or have any ideas? If you need to see my redux I can update the post with more code but I don't think that's the problem as it updates the store fine.


问:
How to Display the Report Alias of an Interactive Report
Is there a way to display the Report Alias on a page, without having to go into the Saved Reports as the developer?

For example, I want to display on a page the direct URL to whichever interactive report the user is currently looking at (so they can bookmark directly to the report).

Normally, when asked for the direct link, I go into developer and grab the snippet and send them the direct link

What I would prefer to have is the user to be able to self serve - show the direct link on the report page itself, so they can copy it for later.

Any ideas how do this in ApEx 4.2?

答:
create a hidden item.. lets name it P1_REPORT

you may wish to create this on a global page

create a display only item for your link.. lets name it P1_LINK

Now we need to create a dynamic action to pass the appropriate alias to P1_REPORT. Once we have P1_REPORT populated we can pass it to the link.

Dynamic Action

event: After Refresh

type: region

region: [your interactive report]

true actions

true action #1: execute JavaScript code

Fire on page load = yes

code:

```<code>varSelected = $("apex_ir_SAVED_REPORTS option:selected" ).text();
$s('P1_REPORT', varSelected);
</code>```

apex 5 will require you to leverage a static id since you can have more than 1 IR per page, but this selector will work fine on 4.2

True action #2: Set Value

fire on load = yes

set type: pl/sql function body

code:

```<code>Declare
v_path varchar2(255):=null;
v_report varchar2(30):= :P1_REPORT;
Begin
   If v_report = '1. Primary Report' then
      v_path := 'ALIAS_1';
   Elsif v_report = 'some other report' then
      v_path := 'ALIAS_2';
   End if;

  Return '<a href="f?p=311:28:&APP_SESSION.:IR_REPORT_' || v_path || '">report link</a>';
End;
</code>```

page items to submit: P1_REPORT

affected element: item; P1_LINK

sent from my iPhone

Body:
create a hidden item.. lets name it P1_REPORT

you may wish to create this on a global page

create a display only item for your link.. lets name it P1_LINK

Now we need to create a dynamic action to pass the appropriate alias to P1_REPORT. Once we have P1_REPORT populated we can pass it to the link.

Dynamic Action

event: After Refresh

type: region

region: [your interactive report]

true actions

true action #1: execute JavaScript code

Fire on page load = yes

code:

varSelected = $("apex_ir_SAVED_REPORTS option:selected" ).text();
$s('P1_REPORT', varSelected);

apex 5 will require you to leverage a static id since you can have more than 1 IR per page, but this selector will work fine on 4.2

True action #2: Set Value

fire on load = yes

set type: pl/sql function body

code:

Declare
v_path varchar2(255):=null;
v_report varchar2(30):= :P1_REPORT;
Begin
   If v_report = '1. Primary Report' then
      v_path := 'ALIAS_1';
   Elsif v_report = 'some other report' then
      v_path := 'ALIAS_2';
   End if;

  Return '<a href="f?p=311:28:&APP_SESSION.:IR_REPORT_' || v_path || '">report link</a>';
End;

page items to submit: P1_REPORT

affected element: item; P1_LINK

sent from my iPhone


问:
BuildAsmmeta task failed unexpectedly
Anyone else run into this issue, or have any ideas on how I can start to investigate this error?

The "BuildAsmmeta" task failed unexpectedly.
  System.InvalidOperationException: Cannot start process because a file name has not been provided.
     at System.Diagnostics.Process.Start()
     at Microsoft.CompactFramework.Build.Tasks.BuildAsmmeta.Execute()
     at Microsoft.Build.BuildEngine.TaskEngine.ExecuteTask(ExecutionMode howToExecuteTask, Hashtable projectItemsAvailableToTask, BuildPropertyGroup projectPropertiesAvailableToTask, Boolean& taskClassWasFound)

This occurs when trying to build a Pocket PC (Compact Framework 2) application, using VS2005

This project builds without issue on my old Windows 8 box, but since updating to Windows 10 I haven't ever managed to get things working. It's possible (likely) I've missed installing something along the way

Any wisdom gratefully appreciated. I'd like to move away from Windows 8 at some point!

答:
The problem is in the BuildAsmmeta task, which is used to keep design time attributes of user controls in separate dlls.
I didn't need them so I focused on simply disabling the task...
One solution is to simply remove any xmta files from your project, if it is not a user control library.
Another option is to disable the task, by editing C:\Windows\Microsoft.NET\Framework\v2.0.50727\Microsoft.CompactFramework.Common.targets file.

Add some Condition  to the BuildAsmmeta tags by editing it like this:

```<code><Target Name="BuildAsmmeta" Condition="'$(BuildAsmmeta)' == 'true'">
<Target Name="CopyAsmmetaFilesToOutputDirectory" Condition="'$(BuildAsmmeta)' == 'true'">
</code>```

Don't forget to restart VS2005.
This way you can turn it on later by adding an environment variable BuildAsmmeta to the OS.

Title: BuildAsmmeta task failed unexpectedly

Body:
The problem is in the BuildAsmmeta task, which is used to keep design time attributes of user controls in separate dlls.
I didn't need them so I focused on simply disabling the task...
One solution is to simply remove any xmta files from your project, if it is not a user control library.
Another option is to disable the task, by editing C:\Windows\Microsoft.NET\Framework\v2.0.50727\Microsoft.CompactFramework.Common.targets file.

Add some Condition  to the BuildAsmmeta tags by editing it like this:

<Target Name="BuildAsmmeta" Condition="'$(BuildAsmmeta)' == 'true'">
<Target Name="CopyAsmmetaFilesToOutputDirectory" Condition="'$(BuildAsmmeta)' == 'true'">

Don't forget to restart VS2005.
This way you can turn it on later by adding an environment variable BuildAsmmeta to the OS.


问:
Powershell convert string to array
How do I change:

```<code>$Text = "Apple Pear Peach Banana"
</code>```

to

```<code>$Text = @("Apple", "Pear", "Peach", "Banana")
</code>```

I am planning to feed the array to a foreach loop. The input the user is prompted to enter fruit with a space between (I will use Read-Host for that). So then I need to convert a space-separated string to an array for the foreach loop.

Thank you...

答:
```<code>$text = $text -split " "
</code>```

will work, provided that none of your fruit names are two words that you want to keep together.

Title: Powershell convert string to array

Body:
How do I change:

$Text = "Apple Pear Peach Banana"

to

$Text = @("Apple", "Pear", "Peach", "Banana")

I am planning to feed the array to a foreach loop. The input the user is prompted to enter fruit with a space between (I will use Read-Host for that). So then I need to convert a space-separated string to an array for the foreach loop.

Thank you...

Body:
$text = $text -split " "

will work, provided that none of your fruit names are two words that you want to keep together.


问:
Mysql select one record from group having one of three conditions
Using MySQL. I need to extract one record per group of storeID + profitCenter according to the following conditions:

1) If group has a single active record (active=1), select that record

2) If group has no active records select the most recent (max(id))

3) If group has multiple active records, select the most recent active record

Sample table:
(blank lines added for clarity)

```<code> ID  | storeID | profitCenter | active
 --------------------------------------
 1   | X       | 1            |    1
 2   | X       | 1            |    0
 3   | X       | 1            |    0

 4   | X       | 2            |    0
 5   | X       | 2            |    1

 6   | X       | 3            |    0
 7   | X       | 3            |    0
 8   | X       | 3            |    0

 9   | X       | 4            |    1
10   | X       | 4            |    1
11   | X       | 4            |    0

12   | X       | 5            |    1

13   | X       | 6            |    0
</code>```

Desired result:

```<code> ID  | storeID | profitCenter | active
------------------------------------------
 1   | X       | 1            |    1
 5   | X       | 2            |    1
 8   | X       | 3            |    0
10   | X       | 4            |    1
12   | X       | 5            |    1
13   | X       | 6            |    0
</code>```

A single query would be great but I'm thinking I'll need to do this in a stored procedure due to its complexity. I would need to write the records to a new table so I can use that in joins and such. So far all I've really got is...

...A simple query to pull the "single" records like so....

```<code> SELECT * FROM table GROUP BY storeID, profitCenter HAVING count(*) = 1 AND active = 1
UNION
SELECT * FROM table GROUP BY storeID, profitCenter HAVING count(*) = 1 AND active = 0
</code>```

...which yields...

```<code> ID  | storeID | profitCenter | active
------------------------------------------
12   | X       | 5            |    1
13   | X       | 6            |    0
</code>```

Then I can do...

```<code> SELECT sum(active),tmult.* FROM
      (SELECT t.* FROM t LEFT JOIN
           (SELECT t.* FROM t GROUP BY storeID, profitCenter HAVING count(*) = 1 AND active = 1
      UNION
           SELECT t.* FROM t GROUP BY storeID, profitCenter HAVING count(*) = 1 AND active = 0) tsing
      ON t.id = tsing.id
      WHERE tsing.id IS NULL) tmult
 GROUP BY storeid, profitCenter
 HAVING sum(active)=1;
</code>```

...which gives the active record for each group that has only one active record:

```<code> ID  | storeID | profitCenter | active
 --------------------------------------
 1   | X       | 1            |    1
 5   | X       | 2            |    1
</code>```

It's the groups that have either no active records or multiple active records that I can't even begin to figure out.

Am I taking the right approach? Should I even be attempting this in SQL? I could write a script to do it but I was hoping to not have to go that route.

Any advice would be appreciated.

答:
I believe something like this should do it:

```<code> select
    ifnull(max(active_records.id), max(all_records.id)) id,
    all_records.store_id,
    all_records.profit_center,
    if(max(active_records.id) is null, 0, 1) active
from
    store all_records
    left outer join store active_records on all_records.id = active_records.id and active_records.active = 1
group by
    all_records.store_id,
    all_records.profit_center
;
</code>```

A full example with ddl and inserts is shown below:

```<code>create table store (
    id int,
    store_id varchar(64),
    profit_center int,
    active bit
);

insert into store values ( 1   , 'X'       , 1            ,    1);
insert into store values ( 2   , 'X'       , 1            ,    0);
insert into store values ( 3   , 'X'       , 1            ,    0);
insert into store values ( 4   , 'X'       , 2            ,    0);
insert into store values ( 5   , 'X'       , 2            ,    1);
insert into store values ( 6   , 'X'       , 3            ,    0);
insert into store values ( 7   , 'X'       , 3            ,    0);
insert into store values ( 8   , 'X'       , 3            ,    0);
insert into store values ( 9   , 'X'       , 4            ,    1);
insert into store values (10   , 'X'       , 4            ,    1);
insert into store values (11   , 'X'       , 4            ,    0);
insert into store values (12   , 'X'       , 5            ,    1);
insert into store values (13   , 'X'       , 6            ,    0);

select
    ifnull(max(active_records.id), max(all_records.id)) id,
    all_records.store_id,
    all_records.profit_center,
    if(max(active_records.id) is null, 0, 1) active
from
    store all_records
    left outer join store active_records on all_records.id = active_records.id and active_records.active = 1
group by
    all_records.store_id,
    all_records.profit_center
;

+ ------- + ------------- + ------------------ + ----------- +
| id      | store_id      | profit_center      | active      |
+ ------- + ------------- + ------------------ + ----------- +
| 1       | X             | 1                  | 1           |
| 5       | X             | 2                  | 1           |
| 8       | X             | 3                  | 0           |
| 10      | X             | 4                  | 1           |
| 12      | X             | 5                  | 1           |
| 13      | X             | 6                  | 0           |
+ ------- + ------------- + ------------------ + ----------- +
6 rows
</code>```

Body:
Using MySQL. I need to extract one record per group of storeID + profitCenter according to the following conditions:

1) If group has a single active record (active=1), select that record

2) If group has no active records select the most recent (max(id))

3) If group has multiple active records, select the most recent active record

Sample table:
(blank lines added for clarity)

 ID  | storeID | profitCenter | active
 --------------------------------------
 1   | X       | 1            |    1
 2   | X       | 1            |    0
 3   | X       | 1            |    0

 4   | X       | 2            |    0
 5   | X       | 2            |    1

 6   | X       | 3            |    0
 7   | X       | 3            |    0
 8   | X       | 3            |    0

 9   | X       | 4            |    1
10   | X       | 4            |    1
11   | X       | 4            |    0

12   | X       | 5            |    1

13   | X       | 6            |    0

Desired result:

 ID  | storeID | profitCenter | active
------------------------------------------
 1   | X       | 1            |    1
 5   | X       | 2            |    1
 8   | X       | 3            |    0
10   | X       | 4            |    1
12   | X       | 5            |    1
13   | X       | 6            |    0

A single query would be great but I'm thinking I'll need to do this in a stored procedure due to its complexity. I would need to write the records to a new table so I can use that in joins and such. So far all I've really got is...

...A simple query to pull the "single" records like so....

 SELECT * FROM table GROUP BY storeID, profitCenter HAVING count(*) = 1 AND active = 1
UNION
SELECT * FROM table GROUP BY storeID, profitCenter HAVING count(*) = 1 AND active = 0

...which yields...

 ID  | storeID | profitCenter | active
------------------------------------------
12   | X       | 5            |    1
13   | X       | 6            |    0

Then I can do...

 SELECT sum(active),tmult.* FROM
      (SELECT t.* FROM t LEFT JOIN
           (SELECT t.* FROM t GROUP BY storeID, profitCenter HAVING count(*) = 1 AND active = 1
      UNION
           SELECT t.* FROM t GROUP BY storeID, profitCenter HAVING count(*) = 1 AND active = 0) tsing
      ON t.id = tsing.id
      WHERE tsing.id IS NULL) tmult
 GROUP BY storeid, profitCenter
 HAVING sum(active)=1;

...which gives the active record for each group that has only one active record:

 ID  | storeID | profitCenter | active
 --------------------------------------
 1   | X       | 1            |    1
 5   | X       | 2            |    1

It's the groups that have either no active records or multiple active records that I can't even begin to figure out.

Am I taking the right approach? Should I even be attempting this in SQL? I could write a script to do it but I was hoping to not have to go that route.

Any advice would be appreciated.

Body:
I believe something like this should do it:

 select
    ifnull(max(active_records.id), max(all_records.id)) id,
    all_records.store_id,
    all_records.profit_center,
    if(max(active_records.id) is null, 0, 1) active
from
    store all_records
    left outer join store active_records on all_records.id = active_records.id and active_records.active = 1
group by
    all_records.store_id,
    all_records.profit_center
;

A full example with ddl and inserts is shown below:

create table store (
    id int,
    store_id varchar(64),
    profit_center int,
    active bit
);

insert into store values ( 1   , 'X'       , 1            ,    1);
insert into store values ( 2   , 'X'       , 1            ,    0);
insert into store values ( 3   , 'X'       , 1            ,    0);
insert into store values ( 4   , 'X'       , 2            ,    0);
insert into store values ( 5   , 'X'       , 2            ,    1);
insert into store values ( 6   , 'X'       , 3            ,    0);
insert into store values ( 7   , 'X'       , 3            ,    0);
insert into store values ( 8   , 'X'       , 3            ,    0);
insert into store values ( 9   , 'X'       , 4            ,    1);
insert into store values (10   , 'X'       , 4            ,    1);
insert into store values (11   , 'X'       , 4            ,    0);
insert into store values (12   , 'X'       , 5            ,    1);
insert into store values (13   , 'X'       , 6            ,    0);

select
    ifnull(max(active_records.id), max(all_records.id)) id,
    all_records.store_id,
    all_records.profit_center,
    if(max(active_records.id) is null, 0, 1) active
from
    store all_records
    left outer join store active_records on all_records.id = active_records.id and active_records.active = 1
group by
    all_records.store_id,
    all_records.profit_center
;

+ ------- + ------------- + ------------------ + ----------- +
| id      | store_id      | profit_center      | active      |
+ ------- + ------------- + ------------------ + ----------- +
| 1       | X             | 1                  | 1           |
| 5       | X             | 2                  | 1           |
| 8       | X             | 3                  | 0           |
| 10      | X             | 4                  | 1           |
| 12      | X             | 5                  | 1           |
| 13      | X             | 6                  | 0           |
+ ------- + ------------- + ------------------ + ----------- +
6 rows


问:
Positioning within a HTML form
I realize this is a very basic issue.

I am currently trying to create a website http://theviewbeyond.co.uk/.

I am currently adding a contact form to which I have created a picture to use as the background of the form, the issue is I cannot move the objects within the form such as text boxes to within the picture.

I have tried absolute positioning which doesn't seem to work either.

How can I do this ?

```<code>form {
margin: 0 auto;
width: 60%;
background-image: url("../IMG/contactpage1[2742].jpg");
background-size: cover;
</code>```

答:
set the picture to your background:</p>

```<code><div id="container" style='background-image:url("IMG/slidermockup[2710].jpg");'></div>
</code>```

Title: Positioning within a HTML form

Body:
I realize this is a very basic issue.

I am currently trying to create a website http://theviewbeyond.co.uk/.

I am currently adding a contact form to which I have created a picture to use as the background of the form, the issue is I cannot move the objects within the form such as text boxes to within the picture.

I have tried absolute positioning which doesn't seem to work either.

How can I do this ?

form {
margin: 0 auto;
width: 60%;
background-image: url("../IMG/contactpage1[2742].jpg");
background-size: cover;

Body:
set the picture to your background:

<div id="container" style='background-image:url("IMG/slidermockup[2710].jpg");'></div>


问:
C Source Code in Latex document
Can anyone recommend me a good template to include C source code with line numbering
in Latex? For example, taking the classical Hello world program, I would like to make it look as follows:

```<code>(1)   /* Hello World program */
(2)
(3)   #include<stdio.h>
(4)
(5)   main()
(6)   {
(7)    printf("Hello World");
(8)   }
</code>```

Typicall, I always used the verbatim environment, but I am wondering if there is a better and nicer way to do that.

Thanks so much
Richard

答: You might want to have a look at the listings package.  It is very flexible and easy to use.

ContentLicense: CC BY-SA 2.5

Title: C Source Code in Latex document

Body:
Can anyone recommend me a good template to include C source code with line numbering
in Latex? For example, taking the classical Hello world program, I would like to make it look as follows:

(1)   /* Hello World program */
(2)
(3)   #include<stdio.h>
(4)
(5)   main()
(6)   {
(7)    printf("Hello World");
(8)   }

Typicall, I always used the verbatim environment, but I am wondering if there is a better and nicer way to do that.

Thanks so much
Richard


问:
Need to do a match on a value with partial name of textfield with jquery and return results
I currently have a form set up where a user enters numbers, and based on the number entered, through jquery, a series of textboxes are displayed.

The code for the textbox display is as follows:

```<code>for(i=0;i<count;i++)
{

ch.innerHTML = ch.innerHTML +"<div style='width:120px;float:left;'>Left
Slide (size 6):</div><div style='float:left;width:100px;'> <input
type='text' class='txt' style='width:80px;margin-right:10px;font-size:14px !
important;' name='six"+ i+"'></div>";

}
</code>```

(there are several, from this example size 6, up through size 10.)

The jquery basically goes through and selects the value of all of the input textboxes, joins them and adds them to a hidden field on the form, which then gets submitted to the backend.

(I have ONLY one field to work with, and lots of information to pass through the one field.)

The code that does this part is as follows:

```<code>$(function() {
        $("#shineon").click(function(event) {
            var data = [];

            var form = $("form :input[type=text]");

            $.each(form, function(e, textBox) {

                if (e > 0) {
data.push($.trim(textBox.value));
 }

            });

            $("#mybond").val(data.join(" "));

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

What this returns is almost exactly what I need, the value of all textboxes that were dynamically generated.

It returns the input as follows:

```<code>textone texttwo textthree textfour
</code>```

However, I really need to join them in a more specific way - so that I capture all the values, but then based on a partial name match ("six") where my textfields are named as:  six1 six2 six3 and so on...

so that my input return looks like this:

```<code> six1 - textone texttwo
 six2 - textone texttwo
 six3 - textone texttwo
</code>```

Is there a way to accomplish this easily without destroying the code I have already written, which works perfectly?

答:
Get the name attribute from the element and concatenate it with the value:

```<code>data.push($.trim(textBox.getAttribute('name') + textBox.value));
</code>```

Body:
I currently have a form set up where a user enters numbers, and based on the number entered, through jquery, a series of textboxes are displayed.

The code for the textbox display is as follows:

for(i=0;i<count;i++)
{

ch.innerHTML = ch.innerHTML +"
Left
Slide (size 6):

 <input
type='text' class='txt' style='width:80px;margin-right:10px;font-size:14px !
important;' name='six"+ i+"'>
";

}

(there are several, from this example size 6, up through size 10.)

The jquery basically goes through and selects the value of all of the input textboxes, joins them and adds them to a hidden field on the form, which then gets submitted to the backend.

(I have ONLY one field to work with, and lots of information to pass through the one field.)

The code that does this part is as follows:

$(function() {
        $("#shineon").click(function(event) {
            var data = [];

            var form = $("form :input[type=text]");

            $.each(form, function(e, textBox) {

                if (e > 0) {
data.push($.trim(textBox.value));
 }

            });

            $("#mybond").val(data.join(" "));

        });
    });

What this returns is almost exactly what I need, the value of all textboxes that were dynamically generated.

It returns the input as follows:

textone texttwo textthree textfour

However, I really need to join them in a more specific way - so that I capture all the values, but then based on a partial name match ("six") where my textfields are named as:  six1 six2 six3 and so on...

so that my input return looks like this:

 six1 - textone texttwo
 six2 - textone texttwo
 six3 - textone texttwo

Is there a way to accomplish this easily without destroying the code I have already written, which works perfectly?

Body:
Get the name attribute from the element and concatenate it with the value:

data.push($.trim(textBox.getAttribute('name') + textBox.value));


问:
Is it possible to generate the original files back from the minified JS file generated by webpack
I have lost my original react JS code files. All I have left with now is the final production minified JS file, which was generated from the original files using webpack. Is there any way that I could somehow unminify or generate back the original files from the availalbe minified file? I don't have any source mapping available.</p>

答: No, there is no retained information about the old variable/methods names and so once you have minified, it can't be unminified back.</p>


问:
Displaying large amounts of photos from google Firebase
I am working on Building a IOS app for photographers do display and market their photos.

We are using Firebase and I need to figure out the best way to display a large amount of photos that are displayed from firebase. Photographers might have hundreds or thousands of photos on firebase and the user will scroll through and view all of them.

What is the best way to do this? Hosting? Storage? Database? What is this called?

Thank you!
Ryan

答:
Check out this video from Firebase : Writing a Cloud Storage Trigger.  Notice that she is using Storage.

In fact, watch as many of the Firebase videos over at Youtube as you can.

For now, Hosting is for static content that you can access directly from the web or from inside your app.  Hosting uses caching and will replicate your content to be closer to where it needs to be.  Soon you will be able to write dynamic content, but this is still more for web hosting.

Storage is for things like user uploads.  This provides access control using rules.  It uses buckets.

Database is for information.


问:
catching an error after trying to drop an existing column / checking a column exist before dropping it
I use sql server 2014.

I have couple stored procedures, one to drop a column table another to add a column table.
Following is the code to drop a column.
This is a generic procedure to delete any column in any table.

@Column and @Table are input for the stored procedure

The only way I could find to execute the statement has been to define a tsql string containing the sql instruction to execute with the table name and column name added to the command.

```<code>    DECLARE @tsql varchar (MAX)
    SET @tsql = 'ALTER TABLE [dbo].['+@Table+'] DROP COLUMN ' + @Column
    EXECUTE(@tsql)
</code>```

I'd like to return -1 if an error occur 2 otherwise as following :

```<code>    if @@ERROR <> 0
        BEGIN
            RETURN(-1)
        END
    ELSE
        BEGIN
            RETURN(2)
        END
</code>```

how to catch the error if something goes wrong while executing

```<code>    EXECUTE(@tsql)
</code>```

I tried to use @@ERROR but the execution went through without catching the error.

As an alternative what would be the way to check that a column exists if i am trying to drop a column which does not exist ?

Running the stored procedure I add the following Result: error 4924 "ALTER TABLE DROP COLUMN failed because column 'bla' does not exist in table 'part'."

In addition I d like to return a flag to confirm the change if any.

```<code>ALTER PROCEDURE [dbo].[DropColumn]
    -- Add the parameters for the stored procedure here
    @Table varchar(MAX)=NULL,
    @Column varchar(MAX)=NULL,
    @ColumnModified int OUTPUT
AS
    BEGIN TRY
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    Set @ColumnModified=0
    IF (@Table) IS NULL GOTO Help
    IF (@Column) IS NULL GOTO Help
    -- Insert statements for procedure here
    DECLARE @tsql varchar (MAX)
    SET @tsql = 'ALTER TABLE [dbo].['+@Table+'] DROP COLUMN ' + @Column
    EXECUTE(@tsql)
    if @@ERROR <> 0
        BEGIN
            RETURN(-1)
        END
    ELSE
        BEGIN
            RETURN(2)
        END
    Help:
        PRINT 'DropColumn'
        PRINT CHAR(13)
        PRINT 'usage:'
        PRINT CHAR(13)
        PRINT '@Table '
        PRINT CHAR(13)
        PRINT '@Column '
        PRINT CHAR(13)
        PRINT 'output @ColumnModified '
        PRINT CHAR(13)
        RETURN(-1)
    END TRY
    BEGIN CATCH
        SELECT
        ERROR_NUMBER() AS ErrorNumber
       ,ERROR_MESSAGE() AS ErrorMessage;
        RETURN(-1)
    END CATCH
</code>```

The post here How to check if a column exists in SQL Server table is a partial and undirect answer to my problem since it is peculiar to a specif table and column.
In stead of string valyue for tableName I have a variable (same for columnName).
How can I transpose the following code using @Column and @Table ?

```<code>IF COL_LENGTH('schemaName.tableName', 'columnName') IS NOT NULL
BEGIN
    -- Column Exists
END
</code>```

答:
Not sure that your "issue" is reproducible, but I have confirmed that a TRY CATCH block works:

```<code>BEGIN TRY

DECLARE @sql nvarchar(max);

SET @sql = 'ALTER TABLE [dbo].[SomeTable] DROP COLUMN NonExistentColumn'

EXECUTE(@sql);

END TRY

BEGIN CATCH

SELECT @@ERROR

END CATCH
</code>```

This code returned 4924 for me.   Which is not 0.

Body:
I use sql server 2014.

I have couple stored procedures, one to drop a column table another to add a column table.
Following is the code to drop a column.
This is a generic procedure to delete any column in any table.

@Column and @Table are input for the stored procedure

The only way I could find to execute the statement has been to define a tsql string containing the sql instruction to execute with the table name and column name added to the command.

    DECLARE @tsql varchar (MAX)
    SET @tsql = 'ALTER TABLE [dbo].['+@Table+'] DROP COLUMN ' + @Column
    EXECUTE(@tsql)

I'd like to return -1 if an error occur 2 otherwise as following :

    if @@ERROR <> 0
        BEGIN
            RETURN(-1)
        END
    ELSE
        BEGIN
            RETURN(2)
        END

how to catch the error if something goes wrong while executing

    EXECUTE(@tsql)

I tried to use @@ERROR but the execution went through without catching the error.

As an alternative what would be the way to check that a column exists if i am trying to drop a column which does not exist ?

Running the stored procedure I add the following Result: error 4924 "ALTER TABLE DROP COLUMN failed because column 'bla' does not exist in table 'part'."

In addition I d like to return a flag to confirm the change if any.

ALTER PROCEDURE [dbo].[DropColumn]
    -- Add the parameters for the stored procedure here
    @Table varchar(MAX)=NULL,
    @Column varchar(MAX)=NULL,
    @ColumnModified int OUTPUT
AS
    BEGIN TRY
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    Set @ColumnModified=0
    IF (@Table) IS NULL GOTO Help
    IF (@Column) IS NULL GOTO Help
    -- Insert statements for procedure here
    DECLARE @tsql varchar (MAX)
    SET @tsql = 'ALTER TABLE [dbo].['+@Table+'] DROP COLUMN ' + @Column
    EXECUTE(@tsql)
    if @@ERROR <> 0
        BEGIN
            RETURN(-1)
        END
    ELSE
        BEGIN
            RETURN(2)
        END
    Help:
        PRINT 'DropColumn'
        PRINT CHAR(13)
        PRINT 'usage:'
        PRINT CHAR(13)
        PRINT '@Table '
        PRINT CHAR(13)
        PRINT '@Column '
        PRINT CHAR(13)
        PRINT 'output @ColumnModified '
        PRINT CHAR(13)
        RETURN(-1)
    END TRY
    BEGIN CATCH
        SELECT
        ERROR_NUMBER() AS ErrorNumber
       ,ERROR_MESSAGE() AS ErrorMessage;
        RETURN(-1)
    END CATCH

The post here How to check if a column exists in SQL Server table is a partial and undirect answer to my problem since it is peculiar to a specif table and column.
In stead of string valyue for tableName I have a variable (same for columnName).
How can I transpose the following code using @Column and @Table ?

IF COL_LENGTH('schemaName.tableName', 'columnName') IS NOT NULL
BEGIN
    -- Column Exists
END

Body:
Not sure that your "issue" is reproducible, but I have confirmed that a TRY CATCH block works:

BEGIN TRY

DECLARE @sql nvarchar(max);

SET @sql = 'ALTER TABLE [dbo].[SomeTable] DROP COLUMN NonExistentColumn'

EXECUTE(@sql);

END TRY

BEGIN CATCH

SELECT @@ERROR

END CATCH

This code returned 4924 for me.   Which is not 0.


问:
TS2403: Subsequent variable declarations must have the same type. After NPM install
I've searched stack overflow for this issue, but am still unclear on why this is happening/how to fix.

I wanted Node Typings in my Typescript project so I entered this command:

```<code>npm install @types/node --save
</code>```

Which resulted in:

```<code>c:/xyz/node_modules/@types/node/index.d.ts(89,13)
error TS2403: Subsequent variable declarations must have the same type.
Variable 'require' must be of type 'Require', but here has type 'NodeRequire'.
</code>```

My machine had node version 7.0.3
The installed types was for version + @types/node@7.0.28

If I remove uninstall the typings my project compiles with no problems.

It appears as if the typings content is not correct per the error message! Fixing it is messy.  Any tips?

Here's the failing line of code in index.d.ts

Seems like the NodeRequire (interfaces) need to be bypassed in favor of Require.js?

This is the TSConfig file:

```<code>{
    "compilerOptions": {
        "module": "amd",
        "moduleResolution": "node",
        "target": "es5",
        "noImplicitAny": false,
        "jsx": "react",
        "sourceMap": false,
        "baseUrl": ".",
        "paths": {
            "OfficeFabric/*": [
                "node_modules/office-ui-fabric-react/lib-amd/*"
            ]
        }
    }
}
</code>```

I tried the Exclude suggestion below which didn't work.  Github says, if module resolution is NODE then exclude won't work anyway.

答:
Okay, finally found the root cause:  Node's index.d.ts file was conflicting with Require's index.d.ts file both were declaring a variable named require.  The way I found it was to rename require to nrequire then search the project for all instances of nrequire.  There are many solutions,

Rename the variable (will get wiped out on npm install or update).

In TypeScript use the --types option to use one or the other but not both.

Just remove the node typing.

Body:
I've searched stack overflow for this issue, but am still unclear on why this is happening/how to fix.

I wanted Node Typings in my Typescript project so I entered this command:

npm install @types/node --save

Which resulted in:

c:/xyz/node_modules/@types/node/index.d.ts(89,13)
error TS2403: Subsequent variable declarations must have the same type.
Variable 'require' must be of type 'Require', but here has type 'NodeRequire'.

My machine had node version 7.0.3
The installed types was for version + @types/node@7.0.28

If I remove uninstall the typings my project compiles with no problems.

It appears as if the typings content is not correct per the error message! Fixing it is messy.  Any tips?

Here's the failing line of code in index.d.ts

Seems like the NodeRequire (interfaces) need to be bypassed in favor of Require.js?

This is the TSConfig file:

{
    "compilerOptions": {
        "module": "amd",
        "moduleResolution": "node",
        "target": "es5",
        "noImplicitAny": false,
        "jsx": "react",
        "sourceMap": false,
        "baseUrl": ".",
        "paths": {
            "OfficeFabric/*": [
                "node_modules/office-ui-fabric-react/lib-amd/*"
            ]
        }
    }
}

I tried the Exclude suggestion below which didn't work.  Github says, if module resolution is NODE then exclude won't work anyway.

ContentLicense: CC BY-SA 4.0


问:
Get child data Microsoft Dynamics WebAPI
I am using the Microsoft Dynamics CRM WebAPI to access an on Premise version of Microsoft Dynamics CRM 2016.  I have two custom entities ccseq_ProductEvaluation and ccseq_ProductEvaluationArea.  ccseq_ProductEvaluation is the parent of ccseq_ProductEvaluationArea.  I am trying to build the url to retrieve the ccseq_ProductEvaluationArea records for a specific ccseq_ProductEvaluation record.  I have read the Dynamics API reference, but I have not been able to build the correct url.  Below is the current url I have tried.  What am I missing?

URL

```<code>https://mainurl.com/api/data/v8.0/ccseq_productevaluations?$expand=ccseq_productevaluationid
</code>```

ccseq_ProductEvaluation

ccseq_ProductEvaluationArea

1:N Relationship

答:
The query should read like this:

```<code>https://mainurl.com/api/data/v8.0/ccseq_productevaluations(915e89f5-29fc-e511-80d2-00155db07c77)?$select=ccseq_productname&$expand=ccseq_ccseq_productevaluation_ccseq_producteval($select=ccseq_evaluationarea)
</code>```

Here the guid should be replaced with the ID of the product evaluation record at hand.

Body:
I am using the Microsoft Dynamics CRM WebAPI to access an on Premise version of Microsoft Dynamics CRM 2016.  I have two custom entities ccseq_ProductEvaluation and ccseq_ProductEvaluationArea.  ccseq_ProductEvaluation is the parent of ccseq_ProductEvaluationArea.  I am trying to build the url to retrieve the ccseq_ProductEvaluationArea records for a specific ccseq_ProductEvaluation record.  I have read the Dynamics API reference, but I have not been able to build the correct url.  Below is the current url I have tried.  What am I missing?

URL

https://mainurl.com/api/data/v8.0/ccseq_productevaluations?$expand=ccseq_productevaluationid

ccseq_ProductEvaluation

ccseq_ProductEvaluationArea

1:N Relationship

Body:
The query should read like this:

https://mainurl.com/api/data/v8.0/ccseq_productevaluations(915e89f5-29fc-e511-80d2-00155db07c77)?$select=ccseq_productname&$expand=ccseq_ccseq_productevaluation_ccseq_producteval($select=ccseq_evaluationarea)

Here the guid should be replaced with the ID of the product evaluation record at hand.


问:
unix - how to sort on a specific key
How do I sort this output?

```<code>10.1.3.39:{ "range_start" : 96, "range_end" : 96 }
10.1.3.27:{ "range_start" : 33, "range_end" : 33 }
10.1.3.100:{ range_start" : 30, "range_end" : 30 }
10.1.2.233:{ "range_start" : 78, "range_end" : 78 }
10.1.4.239:{ "range_start" : 53, "range_end" : 53 }
10.1.2.161:{ "range_start" : 44, "range_end" : 44 }
</code>```

I want to sort this output by the range_start key

So, expected would be:

```<code>10.1.3.100:{ "range_start" : 30, "range_end" : 30 }
10.1.3.27:{ "range_start" : 33, "range_end" : 33 }
10.1.2.161:{ "range_start" : 44, "range_end" : 44 }
10.1.4.239:{ "range_start" : 53, "range_end" : 53 }
10.1.2.233:{ "range_start" : 78, "range_end" : 78 }
10.1.3.39:{ "range_start" : 96, "range_end" : 96 }
</code>```

答:
You can do a decorate, sort, undecorate pipe like so:

```<code>$ awk -F",|:" '{printf "%s\t%s\n", $3,$0}' file | sort -n | awk -F"\t" '{print $2}'
</code>```

Or, if using a \t or other unique delimiter, you can use cut:

```<code>$ awk -F",|:" '{printf "%s\t%s\n", $3,$0}' file | sort -n | cut -f 2
</code>```

Either case:

```<code>10.1.3.100:{ range_start" : 30, "range_end" : 30 }
10.1.3.27:{ "range_start" : 33, "range_end" : 33 }
10.1.2.161:{ "range_start" : 44, "range_end" : 44 }
10.1.4.239:{ "range_start" : 53, "range_end" : 53 }
10.1.2.233:{ "range_start" : 78, "range_end" : 78 }
10.1.3.39:{ "range_start" : 96, "range_end" : 96 }
</code>```

Change the \t to another delimiter if there are tabs in the text data.

Title: unix - how to sort on a specific key

Body:
How do I sort this output?

10.1.3.39:{ "range_start" : 96, "range_end" : 96 }
10.1.3.27:{ "range_start" : 33, "range_end" : 33 }
10.1.3.100:{ range_start" : 30, "range_end" : 30 }
10.1.2.233:{ "range_start" : 78, "range_end" : 78 }
10.1.4.239:{ "range_start" : 53, "range_end" : 53 }
10.1.2.161:{ "range_start" : 44, "range_end" : 44 }

I want to sort this output by the range_start key

So, expected would be:

10.1.3.100:{ "range_start" : 30, "range_end" : 30 }
10.1.3.27:{ "range_start" : 33, "range_end" : 33 }
10.1.2.161:{ "range_start" : 44, "range_end" : 44 }
10.1.4.239:{ "range_start" : 53, "range_end" : 53 }
10.1.2.233:{ "range_start" : 78, "range_end" : 78 }
10.1.3.39:{ "range_start" : 96, "range_end" : 96 }

Body:
You can do a decorate, sort, undecorate pipe like so:

$ awk -F",|:" '{printf "%s\t%s\n", $3,$0}' file | sort -n | awk -F"\t" '{print $2}'

Or, if using a \t or other unique delimiter, you can use cut:

$ awk -F",|:" '{printf "%s\t%s\n", $3,$0}' file | sort -n | cut -f 2

Either case:

10.1.3.100:{ range_start" : 30, "range_end" : 30 }
10.1.3.27:{ "range_start" : 33, "range_end" : 33 }
10.1.2.161:{ "range_start" : 44, "range_end" : 44 }
10.1.4.239:{ "range_start" : 53, "range_end" : 53 }
10.1.2.233:{ "range_start" : 78, "range_end" : 78 }
10.1.3.39:{ "range_start" : 96, "range_end" : 96 }

Change the \t to another delimiter if there are tabs in the text data.


答: CWEB had a nice C formatter.</p>

Title: C Source Code in Latex document

Body: CWEB had a nice C formatter.


问:
Does ArrayDeque implement the List interface, or Deque? Conflicting information from various sources
I'm currently taking an algorithms class online, and our textbook is Pat Morin's Open Data Structures.

In his discussion of ArrayDeque, Morin claims, "The ArrayDeque data structure allows for efficient addition and removal at both ends. This structure implements the List interface."  He then goes on to discuss a C++ implementation of the data structure, including the expected List methods:  get(i), set(i, x), add(i, x), and remove(i).

I found the author's treatment confusing, as I can't imagine how this implementation could be considered a Deque; it features insertion/deletion at any position, after all.

On the other hand, other resources indicate that ArrayDeque implements the Deque interface ("duh," right?).  In fact, this article claims, "the ArrayDeque is the array-based implementation of the Deque interface."  Furthermore, "the ArrayDeque, unlike the LinkedList, does not implement the List interface, and so we never think about using it for positional access."  This treatment makes perfect sense to me, and it seems to follow the consensus of the various articles I've found.

So is Morin's book just wrong, or am I missing something fundamental?

答:
Different implementations of array-based deques support different functionality, while using the same underlying structure. For example, in the Java Collections Framework, ArrayDeque only implements the Deque interface and does not support constant-time access by index.

Morin's implementation of ArrayDeque implements only the List interface. However, implementing the Deque interface with a List is straight-forward:

```<code>addFirst(x) { add(0, x); }
removeFirst() { return remove(0); }
addLast(x) { add(size, x); }
removeLast() { return remove(size - 1); }
</code>```

The performance guarantees for add and remove imply that each of these operations runs in constant time, making it an efficient deque.

So using the underlying structure of an array-based deque, it is possible to implement both the List and Deque interfaces, and different implementations make different choices in this.

Body:
Different implementations of array-based deques support different functionality, while using the same underlying structure. For example, in the Java Collections Framework, ArrayDeque only implements the Deque interface and does not support constant-time access by index.

Morin's implementation of ArrayDeque implements only the List interface. However, implementing the Deque interface with a List is straight-forward:

addFirst(x) { add(0, x); }
removeFirst() { return remove(0); }
addLast(x) { add(size, x); }
removeLast() { return remove(size - 1); }

The performance guarantees for add and remove imply that each of these operations runs in constant time, making it an efficient deque.

So using the underlying structure of an array-based deque, it is possible to implement both the List and Deque interfaces, and different implementations make different choices in this.


问:
ImportError: No module named urls
I have a django rest project which is built on Django1.7. I need to run it on Django 1.11. When i run

```<code>python manage.py migrate
</code>```

The error is:

```<code>ImportError: No module named urls
</code>```

on url.py line

```<code>url(r'^docs/', include('rest_framework_swagger.urls')),
</code>```

I have already made modifications in url.py file to avoid patterns. The url.py file look like

```<code>from django.conf.urls import include,url
from django.conf import settings
from django.conf.urls.static import static
from django.views.generic.base import TemplateView
from django.contrib import admin

admin.autodiscover()

urlpatterns = [

url(r'^grappelli/', include('grappelli.urls')),
url(r'^docs/', include('rest_framework_swagger.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'', include('gcm.urls')),
url(r'^', include('apps.account.urls')),
url(r'^', include('apps.vegetables.urls')),
url(r'^', include('apps.orders.urls')),
url(r'^', include('apps.listings.urls')),
url(r'^', include('apps.rating.urls')),
url(r'^', include('apps.faq.urls')),
url(r'^thank-you/$', TemplateView.as_view(template_name="thankyou.html"), name="thankyou"),
url(r'^/error/$', TemplateView.as_view(template_name="error.html"), name="error"),
url(r'^$', TemplateView.as_view(template_name="index.html"), name="home"),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

urlpatterns += [
'',
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {
    'document_root': settings.STATIC_ROOT})]
</code>```

How could i run it?

答:
In urls.py add this at the bottom,

```<code>urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT
</code>```

From Django 1.9 it does not support to add the URLs as a string, but it need to be imported as callable. So remove this from your urls.py.

```<code>urlpatterns += [ '', (r'^static/(?P<path>.*)$', 'django.views.static.serve', { 'document_root': settings.STATIC_ROOT})]
</code>```

Title: ImportError: No module named urls

Body:
I have a django rest project which is built on Django1.7. I need to run it on Django 1.11. When i run

python manage.py migrate

The error is:

ImportError: No module named urls

on url.py line

url(r'^docs/', include('rest_framework_swagger.urls')),

I have already made modifications in url.py file to avoid patterns. The url.py file look like

from django.conf.urls import include,url
from django.conf import settings
from django.conf.urls.static import static
from django.views.generic.base import TemplateView
from django.contrib import admin

admin.autodiscover()

urlpatterns = [

url(r'^grappelli/', include('grappelli.urls')),
url(r'^docs/', include('rest_framework_swagger.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'', include('gcm.urls')),
url(r'^', include('apps.account.urls')),
url(r'^', include('apps.vegetables.urls')),
url(r'^', include('apps.orders.urls')),
url(r'^', include('apps.listings.urls')),
url(r'^', include('apps.rating.urls')),
url(r'^', include('apps.faq.urls')),
url(r'^thank-you/$', TemplateView.as_view(template_name="thankyou.html"), name="thankyou"),
url(r'^/error/$', TemplateView.as_view(template_name="error.html"), name="error"),
url(r'^$', TemplateView.as_view(template_name="index.html"), name="home"),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

urlpatterns += [
'',
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {
    'document_root': settings.STATIC_ROOT})]

How could i run it?

Body:
In urls.py add this at the bottom,

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT

From Django 1.9 it does not support to add the URLs as a string, but it need to be imported as callable. So remove this from your urls.py.

urlpatterns += [ '', (r'^static/(?P<path>.*)$', 'django.views.static.serve', { 'document_root': settings.STATIC_ROOT})]


问:
Is there a logging facade for the .NET world?
I'm somewhat new to the .NET stack and I was wondering if there is an equivalent to slf4j for the .NET platform. For me, logging to a Facade and being able to swap out logging implementations as needed just makes sense. Furthermore, the wrapper APIs available in slf4j have saved me many times when I needed to use a third-party library that was coded against a single logging framework that I wasn't using.

Is there a project out there that acts as a facade between loggers like log4net, nLog and Enterprise Library? Are there wrappers that allow me to shortcut calls to those libraries and direct them to another library? Should I start out an open source project to do this myself? Is this question a duplicate because I don't know the right way to ask? Conversely, is the common way to do this using aspect orient programming?

答:
Update for .NET Core:

LibLog - https://github.com/damianh/LibLog - embedded logging facade, source code nuget package which is embedded into your project. Automatically detects and uses NLog, log4net, Serilog, LoupeLog

Microsoft: Microsoft.Extensions.Logging.Abstractions - https://github.com/aspnet/Logging. .NETCore supported

Common Logging - https://github.com/net-commons/common-logging. .NETCore supported since 3.4.1, not under active development


问:
How to Implement logging at the end of each job In talend?
I am new to Talend os.

However, I received a task:

Create file delimited .csv metadata (one for Lead & Opportunity).

Move files to your repository on the AWS server (the etl_process1 login).

Create two tables sfdc_leads_reporting_raw and sfdc_opp_reporting_raw.

Load the data from the files into the tables. Ensure the data types are correctly used when creating metadata schemas & tables.

Till step 4 I am done.

Now the problem is:

How to Implement logging at the end of each job to report the number of leads (count of distinct id in leads table) and number of opportunities created (count of opportunity id) by stages (how many converted, qualified, closed won, and dead)?

Help would be appreciated.

答:
You can get this data using global variables, in a subjob at the end of your job. Most components provide a global variable called tComponent_NB_LINE (or _NB_LINE_INSERTED for database components) that gives you the number of lines output by the component.
For instance tFileOutputDelimited_1_NB_LINE or tOracleOutput_1_NB_LINE_INSERTED.

Using these variables you can log into console or file.
Here is a simple example. If you have a tOracleOutput_1 in your job you can do:

```<code>tPostJob -- OnComponentOk -- tFixedFlowInput -- Main -- tLogRow
</code>```

Inside tFixedFlowInput you retrieve the variable

```<code>(Integer)globalMap.get("tOracleOutput_1_NB_LINE_INSERTED")`.
</code>```

If you need to log aggregated info, you can append a tAggregateRow to your output components, and use tSetGlobalVar to get count by certain criteria.

Body:
You can get this data using global variables, in a subjob at the end of your job. Most components provide a global variable called tComponent_NB_LINE (or _NB_LINE_INSERTED for database components) that gives you the number of lines output by the component.
For instance tFileOutputDelimited_1_NB_LINE or tOracleOutput_1_NB_LINE_INSERTED.

Using these variables you can log into console or file.
Here is a simple example. If you have a tOracleOutput_1 in your job you can do:

tPostJob -- OnComponentOk -- tFixedFlowInput -- Main -- tLogRow

Inside tFixedFlowInput you retrieve the variable

(Integer)globalMap.get("tOracleOutput_1_NB_LINE_INSERTED")`.

If you need to log aggregated info, you can append a tAggregateRow to your output components, and use tSetGlobalVar to get count by certain criteria.


问:
index to use for pivot
New to SQL.  I have an unindexed table of about 20 million records, that has one row per task, I need one row per job, with each job row containing the task and task dates.  I use a pivot to accomplish this which is working.  I am having some huge tempdb growth which is problemeatic.  I need help tuning this query.  When I look at the Execution plan I see about 80% is due to a table scan.  I figure indexing the source table would help, but I'm not sure how to index.

```<code>SELECT Job
    ,TSK_CD + 'F' AS TaskCode
    ,CAST(FORECAST_DATE AS SMALLDATETIME) AS TaskDate
FROM Task_Details AS FcstDateQuery
WHERE FORECAST_DATE IS NOT NULL

UNION

SELECT Job
    ,TSK_CD + 'A' AS TaskCode
    ,CAST(ACTUAL_DATE AS SMALLDATETIME) AS TaskDate
FROM Task_Details AS ActDateQuery
WHERE ACTUAL_DATE IS NOT NULL
) AS TaskDateQuery

PIVOT(MAX(TaskDate) FOR TaskCode IN (
            [Code1F]
            ,[Code1A]
            ,[Code2F]
            ,[Code2A]
            ,[Code3F]
            ,[Code3A]
                    <... a bunch of other task codes>

            )) AS Piv
</code>```

Source table has columns

```<code> Job
,TSK_CD
,FORECAST_DATE
,ACTUAL_DATE
</code>```

Resulting table has:

```<code>Job   Code1F   Code1A   Code2F  Code2A  Code3F   Code3A....
</code>```

Id be grateful on pointers on how to index the source table or improve the query.  The source table is static data (changes once a day via a push to me).  I use the query to build a target table.

答:
Covering index:

```<code>create nonclustered index ix_Task_Details__Job_Tsk_Cd_cover)
  on dbo.Task_Details (Job,Tsk_Cd)
    include (Forecast_Date,ActualDate)
</code>```

You might try conditional aggregation instead of pivot():

```<code>select
    Job
  , [Code1F] = max(case when Tsk_Cd='Code1' then ForeCast_Date end)
  , [Code1A] = max(case when Tsk_Cd='Code1' then Actual_Date end)
  , [Code2F] = max(case when Tsk_Cd='Code2' then ForeCast_Date end)
  , [Code2A] = max(case when Tsk_Cd='Code2' then Actual_Date end)
  , [Code3F] = max(case when Tsk_Cd='Code3' then ForeCast_Date end)
  , [Code3A] = max(case when Tsk_Cd='Code3' then Actual_Date end)
from dbo.Task_Details
group by Job
</code>```

Title: index to use for pivot

Body:
New to SQL.  I have an unindexed table of about 20 million records, that has one row per task, I need one row per job, with each job row containing the task and task dates.  I use a pivot to accomplish this which is working.  I am having some huge tempdb growth which is problemeatic.  I need help tuning this query.  When I look at the Execution plan I see about 80% is due to a table scan.  I figure indexing the source table would help, but I'm not sure how to index.

SELECT Job
    ,TSK_CD + 'F' AS TaskCode
    ,CAST(FORECAST_DATE AS SMALLDATETIME) AS TaskDate
FROM Task_Details AS FcstDateQuery
WHERE FORECAST_DATE IS NOT NULL

UNION

SELECT Job
    ,TSK_CD + 'A' AS TaskCode
    ,CAST(ACTUAL_DATE AS SMALLDATETIME) AS TaskDate
FROM Task_Details AS ActDateQuery
WHERE ACTUAL_DATE IS NOT NULL
) AS TaskDateQuery

PIVOT(MAX(TaskDate) FOR TaskCode IN (
            [Code1F]
            ,[Code1A]
            ,[Code2F]
            ,[Code2A]
            ,[Code3F]
            ,[Code3A]
                    <... a bunch of other task codes>

            )) AS Piv

Source table has columns

 Job
,TSK_CD
,FORECAST_DATE
,ACTUAL_DATE

Resulting table has:

Job   Code1F   Code1A   Code2F  Code2A  Code3F   Code3A....

Id be grateful on pointers on how to index the source table or improve the query.  The source table is static data (changes once a day via a push to me).  I use the query to build a target table.

Body:
Covering index:

create nonclustered index ix_Task_Details__Job_Tsk_Cd_cover)
  on dbo.Task_Details (Job,Tsk_Cd)
    include (Forecast_Date,ActualDate)

You might try conditional aggregation instead of pivot():

select
    Job
  , [Code1F] = max(case when Tsk_Cd='Code1' then ForeCast_Date end)
  , [Code1A] = max(case when Tsk_Cd='Code1' then Actual_Date end)
  , [Code2F] = max(case when Tsk_Cd='Code2' then ForeCast_Date end)
  , [Code2A] = max(case when Tsk_Cd='Code2' then Actual_Date end)
  , [Code3F] = max(case when Tsk_Cd='Code3' then ForeCast_Date end)
  , [Code3A] = max(case when Tsk_Cd='Code3' then Actual_Date end)
from dbo.Task_Details
group by Job