问:
Emitting events globally
What am trying to achieve is I would like to emit a custom event in angular2 globally and have multiple components listen to it so not just the parent-child pattern

In my event source component, I have

```<code>export class EventSourceComponent{

  @Output() testev = new EventEmitter();

  onbtnclick(){
    this.testev.emit("i have emitted an event")
  }
 }
</code>```

Now I would like other components to get this event

```<code>export class CmpTwoComponent{

    //here get the emitted event with data
  }
</code>```

How do I achieve the above?

答:
You could use a shared service for that.

```<code>export class EventSourceComponent{
    constructor(private sharedService : SharedService){}

      onbtnclick(){
        this.sharedService.testev.next("i have emitted an event")
      }
 }

export class CmpTwoComponent{

//here get the emitted event with data

   constructor(sharedService : SharedService){

      sharedService.testev.subscribe((event)=>{console.log(event)})
   }

}
</code>```

and then the sharedService would be

```<code>@Injectable()
export class SharedService{

   public testev = new Subject()

}
</code>```

Obviously, if you still need the Output so the parent component could be able to subscribe normally, you could add that too :

```<code>export class EventSourceComponent{

    @Output() testev = new EventEmitter();
    constructor(private sharedService : SharedService){}

      onbtnclick(){
        this.testev.emit("i have emitted an event")
        this.sharedService.testev.next("i have emitted an event")
      }
 }
</code>```

Title: Emitting events globally

Body:
What am trying to achieve is I would like to emit a custom event in angular2 globally and have multiple components listen to it so not just the parent-child pattern

In my event source component, I have

export class EventSourceComponent{

  @Output() testev = new EventEmitter();

  onbtnclick(){
    this.testev.emit("i have emitted an event")
  }
 }

Now I would like other components to get this event

export class CmpTwoComponent{

    //here get the emitted event with data
  }

How do I achieve the above?

Body:
You could use a shared service for that.

export class EventSourceComponent{
    constructor(private sharedService : SharedService){}

      onbtnclick(){
        this.sharedService.testev.next("i have emitted an event")
      }
 }

export class CmpTwoComponent{

//here get the emitted event with data

   constructor(sharedService : SharedService){

      sharedService.testev.subscribe((event)=>{console.log(event)})
   }

}

and then the sharedService would be

@Injectable()
export class SharedService{

   public testev = new Subject()

}

Obviously, if you still need the Output so the parent component could be able to subscribe normally, you could add that too :

export class EventSourceComponent{

    @Output() testev = new EventEmitter();
    constructor(private sharedService : SharedService){}

      onbtnclick(){
        this.testev.emit("i have emitted an event")
        this.sharedService.testev.next("i have emitted an event")
      }
 }


来源: stackexchange

问:
Django-- Deactivate User account instead of deleting it
I want to deactivate the User account instead of deleting it. I want to do something like user.is_active = False. I have a view to delete User profile and it works but now I need to change it to only deactivate.
Here is my view:

```<code>def delete_profile(request):
    user = User.objects.filter(id = request.user.profile.user_id)
    try:
        user.delete()
    except:
        messages.error(request,'Please try again.')
        return redirect('profile')

    messages.success(request, 'Profile successfully deleted.')
    return redirect('index')
</code>```

I tried User.is_active = False , it displays the success message but doesn't do anything. When I check the User in admin panel it will still have User marked as active.

Any Idea how I can achieve this? Thanks in advance

答:
You may need to set user.is_active = False and then save the user object.

```<code>def delete_profile(request):
    user = request.user
    user.is_active = False
    user.save()
    logout(request)
    messages.success(request, 'Profile successfully disabled.')
    return redirect('index')
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to deactivate the User account instead of deleting it. I want to do something like user.is_active = False. I have a view to delete User profile and it works but now I need to change it to only deactivate.
Here is my view:

def delete_profile(request):
    user = User.objects.filter(id = request.user.profile.user_id)
    try:
        user.delete()
    except:
        messages.error(request,'Please try again.')
        return redirect('profile')

    messages.success(request, 'Profile successfully deleted.')
    return redirect('index')

I tried User.is_active = False , it displays the success message but doesn't do anything. When I check the User in admin panel it will still have User marked as active.

Any Idea how I can achieve this? Thanks in advance

Body:
You may need to set user.is_active = False and then save the user object.

def delete_profile(request):
    user = request.user
    user.is_active = False
    user.save()
    logout(request)
    messages.success(request, 'Profile successfully disabled.')
    return redirect('index')


问:
XSD restricting the number of children for a partent element
So I am trying to define a schema for an XML file that we will be using in a program. There is an element that has children that defines the source language and any target languages for the entire file. There is always only 1 source language, and it must be the same in every translationUnit. There can be any number of targetLanguages, but every translationUnit must have the exact same targetLanguages, they can't be different.

Is there a way in XSD or another schema format to:

a) Require that the langLocale of the sourceSegment of each of the translationUnits is the same as the sourceLang in the jobLanguages element?

b) Require that the langLocale attribute of the targetSegment elements of each of the translationUnits match the langLocales of the targetLang elements of the jobLanguages element?

Essentially, each request sent with the XML has to be consistent throughout the entire document, some translationUnits cannot have a different source language or a different set of target languages.

Sample XML File:

```<code><?xml version="1.0" encoding="utf-8"?>
<translationBody>
    <translationJob>
        <jobLanguages>
            <sourceLang>en-US</sourceLang>
            <targetLang>ja-JP</targetLang>
            <targetLang>ko-KR</targetLang>
            <targetLang>es-ES</targetLang>
            <targetLang>de-DE</targetLang>
            <targetLang>fr-FR</targetLang>
            <targetLang>ru-RU</targetLang>
            <targetLang>zh-CN</targetLang>
            <targetLang>zh-TW</targetLang>
            <targetLang>ar-AA</targetLang>
        </jobLanguages>
        <translationUnit active="true" key="introText" notes="Notes for translator" lenRestriction="25">
            <sourceSegment langLocale="en-US">Some text for translation.</sourceSegment>
            <targetSegment langLocale="ja-JP">翻訳用テキスト</targetSegment>
            <targetSegment langLocale="ko-KR">번역을위한 일부 텍스트"</targetSegment>
            <targetSegment langLocale="es-ES">Algunos textos para traducción</targetSegment>
            <targetSegment langLocale="de-DE">Irgendein Text für Übersetzung</targetSegment>
            <targetSegment langLocale="fr-FR">Quelques textes pour la traduction</targetSegment>
            <targetSegment langLocale="ru-RU">Некоторый текст для перевода</targetSegment>
            <targetSegment langLocale="zh-CN">一些翻译文字</targetSegment>
            <targetSegment langLocale="zh-TW">一些翻譯文字</targetSegment>
            <targetSegment langLocale="ar-AA">بعض النصوص للترجمة</targetSegment>
        </translationUnit>
        <translationUnit active="true" key="headerText" notes="Notes for translator">
            <sourceSegment langLocale="en-US">New text for translation.</sourceSegment>
            <targetSegment langLocale="ja-JP"></targetSegment>
            <targetSegment langLocale="ko-KR"></targetSegment>
            <targetSegment langLocale="es-ES"></targetSegment>
            <targetSegment langLocale="de-DE"></targetSegment>
            <targetSegment langLocale="fr-FR"></targetSegment>
            <targetSegment langLocale="ru-RU"></targetSegment>
            <targetSegment langLocale="zh-CN"></targetSegment>
            <targetSegment langLocale="zh-TW"></targetSegment>
            <targetSegment langLocale="ar-AA"></targetSegment>
        </translationUnit>
        <translationUnit active="false" key="buttonText" notes="Text that is no longer active">
            <sourceSegment langLocale="en-US">New text for translation.</sourceSegment>
            <targetSegment langLocale="ja-JP"></targetSegment>
            <targetSegment langLocale="ko-KR"></targetSegment>
            <targetSegment langLocale="es-ES"></targetSegment>
            <targetSegment langLocale="de-DE"></targetSegment>
            <targetSegment langLocale="fr-FR"></targetSegment>
            <targetSegment langLocale="ru-RU"></targetSegment>
            <targetSegment langLocale="zh-CN"></targetSegment>
            <targetSegment langLocale="zh-TW"></targetSegment>
            <targetSegment langLocale="ar-AA"></targetSegment>
        </translationUnit>
    </translationJob>
</translationBody>
</code>```

Current XSD:

```<code><xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:simpleType name="sourceString">
    <xs:annotation id="SourceStringDesc"><xs:documentation>This is a type setup to ensure that the length of the sourcString is greater than 0. Essentially, it is not ok to have a blank sourceSegment.</xs:documentation></xs:annotation>
    <xs:restriction base="xs:string">
      <xs:minLength value="1"/>
    </xs:restriction>
  </xs:simpleType>
  <xs:simpleType name="langString">
    <xs:annotation id="langStringDesc"><xs:documentation>This is a type setup to ensure that the length of the langString is greater than 0. Essentially, it is not ok to have a blank langString.</xs:documentation></xs:annotation>
    <xs:restriction base="xs:string">
      <xs:minLength value="1"/>
      <xs:pattern value="da-DK|ms-MY|it-IT|pt-BR|zh-CN|es-US|ko-KR|fr-CA|pt-PT|fr-FR|ja-JP|es-ES|de-DE|en-US|ru-RU|es-419|en-GB|zh-TW|tr-TR|nl-NL|th-TH|az-AZ-Cyrl|az-AZ-Latn|ba-RU|eu-ES|hmv|br-FR|bg-BG|my-BU|cal|ca-ES|ceb|ch|ny-MW|am-ET|zh-HK|zh-SG|bn|fr|fu|hr-HR|cs-CZ|ht|prs-AF|en|bal-IR|en-AU|eo|en-BZ|en-CA|en-CB|en-IE|en-JM|en-NZ|en-PH|en-ZA|en-CH|en-TT|en-ZW|et-EE|fo-FO|fa-IR|fj-FJ|sm-WS|fr-BE|nl|ar-DZ|mh|ar-AA|as-IN|ab|fy|fr-LU|ik|fr-MC|tet-ID|fr-CH|gd-GB|gl-ES|ka-GE|ar-IQ|ar-LY|ar-LB|ar-JO|ga-IE|lv-LV|ar-KW|he-IL|ar-MA|de-AT|sla-ME|de-LU|pau|de-CH|el-GR|kl-GL|grn|is-IS|es|ha-NG|hi-IN|id-ID|ia|ie|iu|zu-ZA|kk-KZ|jv-ID|kn-IN|ks|lo-LA|rw-RW|kg-CG|kok-IN|ku-TR|ln-CG|lt-LT|lb|mk-MK|mg-MG|mt-MT|mi-NZ|mn-MN|na-NR|nd-ZW|nb-NO|nn-NO|oc-FR|ps|pl-PL|qu-PE|ro-RO|rn|sg|sa-IN|sr-CY|sr-LA|sr-YU|st|sn|it-CH|ne-NP|pa-PA|ml-IN|yi|la|mo-MD|mr-IN|sk-SK|sl-SI|ar-OM|ar-QA|es-CU|ar-SA|apd-SD|ar-SY|sd|syr-TR|so-DJ|so-ET|tk-TM|so-KE|so-SO|dsb-DE|hsb-DE|es-AR|es-BO|es-CL|es-CO|es-CR|es-EC|es-SV|es-GT|es-HN|es-MX|es-NI|es-PA|es-PY|es-PE|es-PR|rm-CH|be-BY|so|sv|tt-RU|cy-GB|yi-IL|yo-NG|ta-IN|te-IN|ar-TN|bo|es-UY|es-VE|su|sw-KE|ss|sv-FI|sv-SE|tl-PH|tg-TJ|ts-ZA|tn-BW|uz-UZ-Latn|tn-ZA|tw|ug-CN|uk-UA|ur-IN|vi-VN|vo|xh-ZA|za|gu-IN|km-KH|zh-MO|or-IN|co-FR|de-LI|it|no|nl-BE|si-LK|de|pt|sq-AL|tz|nai|ti|ky|CHR|fil|nso-ZA|wo|fr-SN|ig|en-SG|ps-IR|to-TO|en-IN|ls|bs-BS-Cyrl|om-ET|hy-AM|dv-IN|fi-FI|hu-HU|es-DO|bs-BS-Latn|aa-ET|af-ZA|ar-BH|ar-EG|bn_IN|bn_BD|bi-VU|ar-AE|ar-YE"/>
    </xs:restriction>
  </xs:simpleType>
  <xs:element name="translationBody">
    <xs:annotation id="translationBodyDesc"><xs:documentation>This is the main body of the translation text. There are no allowed attributes or restrictions. There must be at least one translationUnit element.</xs:documentation></xs:annotation>
    <xs:complexType>
      <xs:sequence>
        <xs:element name="translationJob" maxOccurs="1" minOccurs="1">
          <xs:complexType>
           <xs:sequence>
             <xs:element name="jobLanguages" maxOccurs="1" minOccurs="1">
               <xs:annotation>
                 <xs:documentation>This element encapsulates the languages for the project. All the languages listed here should match the languages indicated in each translationUnit.</xs:documentation>
               </xs:annotation>
               <xs:complexType>
                 <xs:sequence>
             <xs:element name="sourceLang" maxOccurs="1" minOccurs="1" nillable="false">
               <xs:annotation>
                 <xs:documentation>This element encapsulates the source language of the project, and should match the source language of each translationUnit. There can and must be only 1 of these elements</xs:documentation>
               </xs:annotation>
               <xs:complexType>
                 <xs:simpleContent>
                   <xs:extension base="langString">
                   </xs:extension>
                 </xs:simpleContent>
               </xs:complexType>
             </xs:element>
             <xs:element name="targetLang" maxOccurs="unbounded" minOccurs="1" nillable="false">
               <xs:annotation>
                 <xs:documentation>This element encapsulates the target languages of the project. Each translationUnit should have each of these target languages, no exceptions. There must be at least 1 targetLanguage specified, but there is no limit as to how many targetLanguages there can be. Each target language must be unique, and the targetLanguage should not equal the sourceLanguage.</xs:documentation>
               </xs:annotation>
               <xs:complexType>
                 <xs:simpleContent>
                   <xs:extension base="langString">
                   </xs:extension>
                 </xs:simpleContent>
               </xs:complexType>
             </xs:element>
                 </xs:sequence>
               </xs:complexType>
               <xs:unique name="uniqueJobLangs">
                 <xs:selector xpath="*"/>
                 <xs:field xpath="@langString"/>
               </xs:unique>
             </xs:element>
        <xs:element name="translationUnit" maxOccurs="unbounded" minOccurs="1">
          <xs:annotation id="translationUnitDesc"><xs:documentation>This is the main unit for translation and comprises language combination(s). There should be only one sourceSegment element, and at least one targetSegment element. The langLocale attribute on each targetSegment element must be unique. In other words, there can only be one targetSegment per language. Also, no targetSegment can have the same langLocale as the sourceSegment. If no translation exists yet, targetSegments should be left blank, but they MUST be included in the file</xs:documentation></xs:annotation>
          <xs:complexType>
            <xs:sequence>
              <xs:element name="sourceSegment" maxOccurs="1" minOccurs="1" nillable="false">
                <xs:annotation id="sourceSegmentDesc"><xs:documentation>Text for translation is placed in this element. Must be 1 per translationUnit element. Cannot be null, also cannot be less than 1 character long.</xs:documentation></xs:annotation>
                <xs:complexType>
                  <xs:simpleContent>
                    <xs:extension base="sourceString">
                      <xs:attribute name="langLocale" use="required">
                        <xs:annotation id="langLocaleDesc"><xs:documentation>This is the language-locale combination for the source. All sourceString must have the same langLocale</xs:documentation></xs:annotation>
                        <xs:simpleType>
                          <xs:restriction base="xs:string">
                            <xs:annotation id="langRestrictionDesc"><xs:documentation>The available options for language locale combos are limited certain values based on our API. Please see Glyph Best Practices API Documentation for more details.</xs:documentation></xs:annotation>
                            <xs:pattern value="da-DK|ms-MY|it-IT|pt-BR|zh-CN|es-US|ko-KR|fr-CA|pt-PT|fr-FR|ja-JP|es-ES|de-DE|en-US|ru-RU|es-419|en-GB|zh-TW|tr-TR|nl-NL|th-TH|az-AZ-Cyrl|az-AZ-Latn|ba-RU|eu-ES|hmv|br-FR|bg-BG|my-BU|cal|ca-ES|ceb|ch|ny-MW|am-ET|zh-HK|zh-SG|bn|fr|fu|hr-HR|cs-CZ|ht|prs-AF|en|bal-IR|en-AU|eo|en-BZ|en-CA|en-CB|en-IE|en-JM|en-NZ|en-PH|en-ZA|en-CH|en-TT|en-ZW|et-EE|fo-FO|fa-IR|fj-FJ|sm-WS|fr-BE|nl|ar-DZ|mh|ar-AA|as-IN|ab|fy|fr-LU|ik|fr-MC|tet-ID|fr-CH|gd-GB|gl-ES|ka-GE|ar-IQ|ar-LY|ar-LB|ar-JO|ga-IE|lv-LV|ar-KW|he-IL|ar-MA|de-AT|sla-ME|de-LU|pau|de-CH|el-GR|kl-GL|grn|is-IS|es|ha-NG|hi-IN|id-ID|ia|ie|iu|zu-ZA|kk-KZ|jv-ID|kn-IN|ks|lo-LA|rw-RW|kg-CG|kok-IN|ku-TR|ln-CG|lt-LT|lb|mk-MK|mg-MG|mt-MT|mi-NZ|mn-MN|na-NR|nd-ZW|nb-NO|nn-NO|oc-FR|ps|pl-PL|qu-PE|ro-RO|rn|sg|sa-IN|sr-CY|sr-LA|sr-YU|st|sn|it-CH|ne-NP|pa-PA|ml-IN|yi|la|mo-MD|mr-IN|sk-SK|sl-SI|ar-OM|ar-QA|es-CU|ar-SA|apd-SD|ar-SY|sd|syr-TR|so-DJ|so-ET|tk-TM|so-KE|so-SO|dsb-DE|hsb-DE|es-AR|es-BO|es-CL|es-CO|es-CR|es-EC|es-SV|es-GT|es-HN|es-MX|es-NI|es-PA|es-PY|es-PE|es-PR|rm-CH|be-BY|so|sv|tt-RU|cy-GB|yi-IL|yo-NG|ta-IN|te-IN|ar-TN|bo|es-UY|es-VE|su|sw-KE|ss|sv-FI|sv-SE|tl-PH|tg-TJ|ts-ZA|tn-BW|uz-UZ-Latn|tn-ZA|tw|ug-CN|uk-UA|ur-IN|vi-VN|vo|xh-ZA|za|gu-IN|km-KH|zh-MO|or-IN|co-FR|de-LI|it|no|nl-BE|si-LK|de|pt|sq-AL|tz|nai|ti|ky|CHR|fil|nso-ZA|wo|fr-SN|ig|en-SG|ps-IR|to-TO|en-IN|ls|bs-BS-Cyrl|om-ET|hy-AM|dv-IN|fi-FI|hu-HU|es-DO|bs-BS-Latn|aa-ET|af-ZA|ar-BH|ar-EG|bn_IN|bn_BD|bi-VU|ar-AE|ar-YE"/>
                          </xs:restriction>
                        </xs:simpleType>
                      </xs:attribute>
                    </xs:extension>
                  </xs:simpleContent>
                </xs:complexType>
              </xs:element>
              <xs:element name="targetSegment" maxOccurs="unbounded" minOccurs="1" nillable="true">
                <xs:annotation id="targetSegmentDesc"><xs:documentation>This is the element that holds any translated text or is the place holder for translated text. It can be empty, but there must be at least one in each translationUnit. In other words, there must be at least one language combination in the file.</xs:documentation></xs:annotation>
                <xs:complexType>
                  <xs:simpleContent>
                    <xs:extension base="xs:string">
                      <xs:attribute name="langLocale" use="required">
                        <xs:annotation id="langLocaleDesc2"><xs:documentation>This is the language-locale combination for the source. All sourceString must have the same langLocale</xs:documentation></xs:annotation>
                        <xs:simpleType>
                          <xs:restriction base="xs:string">
                            <xs:annotation id="langRestrictionDesc2"><xs:documentation>The available options for language locale combos are limited certain values based on our API. Please see Glyph Best Practices API Documentation for more details.</xs:documentation></xs:annotation>
                            <xs:pattern value="da-DK|ms-MY|it-IT|pt-BR|zh-CN|es-US|ko-KR|fr-CA|pt-PT|fr-FR|ja-JP|es-ES|de-DE|en-US|ru-RU|es-419|en-GB|zh-TW|tr-TR|nl-NL|th-TH|az-AZ-Cyrl|az-AZ-Latn|ba-RU|eu-ES|hmv|br-FR|bg-BG|my-BU|cal|ca-ES|ceb|ch|ny-MW|am-ET|zh-HK|zh-SG|bn|fr|fu|hr-HR|cs-CZ|ht|prs-AF|en|bal-IR|en-AU|eo|en-BZ|en-CA|en-CB|en-IE|en-JM|en-NZ|en-PH|en-ZA|en-CH|en-TT|en-ZW|et-EE|fo-FO|fa-IR|fj-FJ|sm-WS|fr-BE|nl|ar-DZ|mh|ar-AA|as-IN|ab|fy|fr-LU|ik|fr-MC|tet-ID|fr-CH|gd-GB|gl-ES|ka-GE|ar-IQ|ar-LY|ar-LB|ar-JO|ga-IE|lv-LV|ar-KW|he-IL|ar-MA|de-AT|sla-ME|de-LU|pau|de-CH|el-GR|kl-GL|grn|is-IS|es|ha-NG|hi-IN|id-ID|ia|ie|iu|zu-ZA|kk-KZ|jv-ID|kn-IN|ks|lo-LA|rw-RW|kg-CG|kok-IN|ku-TR|ln-CG|lt-LT|lb|mk-MK|mg-MG|mt-MT|mi-NZ|mn-MN|na-NR|nd-ZW|nb-NO|nn-NO|oc-FR|ps|pl-PL|qu-PE|ro-RO|rn|sg|sa-IN|sr-CY|sr-LA|sr-YU|st|sn|it-CH|ne-NP|pa-PA|ml-IN|yi|la|mo-MD|mr-IN|sk-SK|sl-SI|ar-OM|ar-QA|es-CU|ar-SA|apd-SD|ar-SY|sd|syr-TR|so-DJ|so-ET|tk-TM|so-KE|so-SO|dsb-DE|hsb-DE|es-AR|es-BO|es-CL|es-CO|es-CR|es-EC|es-SV|es-GT|es-HN|es-MX|es-NI|es-PA|es-PY|es-PE|es-PR|rm-CH|be-BY|so|sv|tt-RU|cy-GB|yi-IL|yo-NG|ta-IN|te-IN|ar-TN|bo|es-UY|es-VE|su|sw-KE|ss|sv-FI|sv-SE|tl-PH|tg-TJ|ts-ZA|tn-BW|uz-UZ-Latn|tn-ZA|tw|ug-CN|uk-UA|ur-IN|vi-VN|vo|xh-ZA|za|gu-IN|km-KH|zh-MO|or-IN|co-FR|de-LI|it|no|nl-BE|si-LK|de|pt|sq-AL|tz|nai|ti|ky|CHR|fil|nso-ZA|wo|fr-SN|ig|en-SG|ps-IR|to-TO|en-IN|ls|bs-BS-Cyrl|om-ET|hy-AM|dv-IN|fi-FI|hu-HU|es-DO|bs-BS-Latn|aa-ET|af-ZA|ar-BH|ar-EG|bn_IN|bn_BD|bi-VU|ar-AE|ar-YE"/>
                          </xs:restriction>
                        </xs:simpleType>
                      </xs:attribute>
                    </xs:extension>
                  </xs:simpleContent>
                </xs:complexType>
              </xs:element>
            </xs:sequence>
            <xs:attribute name="active" use="required">
              <xs:annotation id="activeDesc"><xs:documentation>This indicates whether this translationUnit is active. If you do not want this to be translated or processed, set to false. Default should be true</xs:documentation></xs:annotation>
              <xs:simpleType>
                <xs:restriction base="xs:string">
                  <xs:enumeration value="true"/>
                  <xs:enumeration value="false"/>
                </xs:restriction>
              </xs:simpleType>
            </xs:attribute>
            <xs:attribute type="xs:string" name="key" use="required">
            <xs:annotation id="keyDesc"><xs:documentation>key is a required element. It should be a unique identifier for your string.</xs:documentation></xs:annotation>
            </xs:attribute>
              <xs:attribute type="xs:string" name="notes" use="required">
                <xs:annotation id="notesDesc"><xs:documentation>The notes attribute MUST be included, even if it is left blank (=""). Put any notes about context or information the translators should know. The notes will be presented to all langauges. At this time, we don't support langauge specific notes.</xs:documentation></xs:annotation>
              </xs:attribute>
            <xs:attribute name="lenRestriction" use="required">
              <xs:annotation id="lenRestrictionDesc"><xs:documentation>The notes attribute MUST be included, and cannot be left blank. The value should be 0 if no length restriction is desired. This attribute is used to tells the translator the maximum number of characters allowed for this string. If used, it must be an integer of 1 or greater. If used, the translator will be forced to validate the length or change their translation prior to delivery.</xs:documentation></xs:annotation>
              <xs:simpleType>
                <xs:restriction>
                  <xs:minInclusive value="0" />
                </xs:restriction>
              </xs:simpleType>
            </xs:attribute>
          </xs:complexType>
          <xs:unique name="uniqueLang">
            <xs:selector xpath="*"/>
            <xs:field xpath="@langLocale"/>
          </xs:unique>
          <xs:unique name="uniqueKey">
            <xs:selector xpath="*"></xs:selector>
            <xs:field xpath="@key"></xs:field>
          </xs:unique>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>
</code>```

答:
At first sight it certainly looks as if this can be done with key/keyref.

At the level of translationJob, define a key with selection=jobLanguages/sourceLang, field=".", and a corresponding keyref with selection translationUnit/sourceSegment, field=@langLocale.

Then define a second key with selection=jobLanguages/targetLang (field="."), and a corresponding keyRef with selection=translationUnit/targetSegment, field=@langLocale.

Body:
So I am trying to define a schema for an XML file that we will be using in a program. There is an element that has children that defines the source language and any target languages for the entire file. There is always only 1 source language, and it must be the same in every translationUnit. There can be any number of targetLanguages, but every translationUnit must have the exact same targetLanguages, they can't be different.

Is there a way in XSD or another schema format to:

a) Require that the langLocale of the sourceSegment of each of the translationUnits is the same as the sourceLang in the jobLanguages element?

b) Require that the langLocale attribute of the targetSegment elements of each of the translationUnits match the langLocales of the targetLang elements of the jobLanguages element?

Essentially, each request sent with the XML has to be consistent throughout the entire document, some translationUnits cannot have a different source language or a different set of target languages.

Sample XML File:

<?xml version="1.0" encoding="utf-8"?>
<translationBody>
    <translationJob>
        <jobLanguages>
            <sourceLang>en-US</sourceLang>
            <targetLang>ja-JP</targetLang>
            <targetLang>ko-KR</targetLang>
            <targetLang>es-ES</targetLang>
            <targetLang>de-DE</targetLang>
            <targetLang>fr-FR</targetLang>
            <targetLang>ru-RU</targetLang>
            <targetLang>zh-CN</targetLang>
            <targetLang>zh-TW</targetLang>
            <targetLang>ar-AA</targetLang>
        </jobLanguages>
        <translationUnit active="true" key="introText" notes="Notes for translator" lenRestriction="25">
            <sourceSegment langLocale="en-US">Some text for translation.</sourceSegment>
            <targetSegment langLocale="ja-JP">翻訳用テキスト</targetSegment>
            <targetSegment langLocale="ko-KR">번역을위한 일부 텍스트"</targetSegment>
            <targetSegment langLocale="es-ES">Algunos textos para traducción</targetSegment>
            <targetSegment langLocale="de-DE">Irgendein Text für Übersetzung</targetSegment>
            <targetSegment langLocale="fr-FR">Quelques textes pour la traduction</targetSegment>
            <targetSegment langLocale="ru-RU">Некоторый текст для перевода</targetSegment>
            <targetSegment langLocale="zh-CN">一些翻译文字</targetSegment>
            <targetSegment langLocale="zh-TW">一些翻譯文字</targetSegment>
            <targetSegment langLocale="ar-AA">بعض النصوص للترجمة</targetSegment>
        </translationUnit>
        <translationUnit active="true" key="headerText" notes="Notes for translator">
            <sourceSegment langLocale="en-US">New text for translation.</sourceSegment>
            <targetSegment langLocale="ja-JP"></targetSegment>
            <targetSegment langLocale="ko-KR"></targetSegment>
            <targetSegment langLocale="es-ES"></targetSegment>
            <targetSegment langLocale="de-DE"></targetSegment>
            <targetSegment langLocale="fr-FR"></targetSegment>
            <targetSegment langLocale="ru-RU"></targetSegment>
            <targetSegment langLocale="zh-CN"></targetSegment>
            <targetSegment langLocale="zh-TW"></targetSegment>
            <targetSegment langLocale="ar-AA"></targetSegment>
        </translationUnit>
        <translationUnit active="false" key="buttonText" notes="Text that is no longer active">
            <sourceSegment langLocale="en-US">New text for translation.</sourceSegment>
            <targetSegment langLocale="ja-JP"></targetSegment>
            <targetSegment langLocale="ko-KR"></targetSegment>
            <targetSegment langLocale="es-ES"></targetSegment>
            <targetSegment langLocale="de-DE"></targetSegment>
            <targetSegment langLocale="fr-FR"></targetSegment>
            <targetSegment langLocale="ru-RU"></targetSegment>
            <targetSegment langLocale="zh-CN"></targetSegment>
            <targetSegment langLocale="zh-TW"></targetSegment>
            <targetSegment langLocale="ar-AA"></targetSegment>
        </translationUnit>
    </translationJob>
</translationBody>

Current XSD:

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:simpleType name="sourceString">
    <xs:annotation id="SourceStringDesc"><xs:documentation>This is a type setup to ensure that the length of the sourcString is greater than 0. Essentially, it is not ok to have a blank sourceSegment.</xs:documentation></xs:annotation>
    <xs:restriction base="xs:string">
      <xs:minLength value="1"/>
    </xs:restriction>
  </xs:simpleType>
  <xs:simpleType name="langString">
    <xs:annotation id="langStringDesc"><xs:documentation>This is a type setup to ensure that the length of the langString is greater than 0. Essentially, it is not ok to have a blank langString.</xs:documentation></xs:annotation>
    <xs:restriction base="xs:string">
      <xs:minLength value="1"/>
      <xs:pattern value="da-DK|ms-MY|it-IT|pt-BR|zh-CN|es-US|ko-KR|fr-CA|pt-PT|fr-FR|ja-JP|es-ES|de-DE|en-US|ru-RU|es-419|en-GB|zh-TW|tr-TR|nl-NL|th-TH|az-AZ-Cyrl|az-AZ-Latn|ba-RU|eu-ES|hmv|br-FR|bg-BG|my-BU|cal|ca-ES|ceb|ch|ny-MW|am-ET|zh-HK|zh-SG|bn|fr|fu|hr-HR|cs-CZ|ht|prs-AF|en|bal-IR|en-AU|eo|en-BZ|en-CA|en-CB|en-IE|en-JM|en-NZ|en-PH|en-ZA|en-CH|en-TT|en-ZW|et-EE|fo-FO|fa-IR|fj-FJ|sm-WS|fr-BE|nl|ar-DZ|mh|ar-AA|as-IN|ab|fy|fr-LU|ik|fr-MC|tet-ID|fr-CH|gd-GB|gl-ES|ka-GE|ar-IQ|ar-LY|ar-LB|ar-JO|ga-IE|lv-LV|ar-KW|he-IL|ar-MA|de-AT|sla-ME|de-LU|pau|de-CH|el-GR|kl-GL|grn|is-IS|es|ha-NG|hi-IN|id-ID|ia|ie|iu|zu-ZA|kk-KZ|jv-ID|kn-IN|ks|lo-LA|rw-RW|kg-CG|kok-IN|ku-TR|ln-CG|lt-LT|lb|mk-MK|mg-MG|mt-MT|mi-NZ|mn-MN|na-NR|nd-ZW|nb-NO|nn-NO|oc-FR|ps|pl-PL|qu-PE|ro-RO|rn|sg|sa-IN|sr-CY|sr-LA|sr-YU|st|sn|it-CH|ne-NP|pa-PA|ml-IN|yi|la|mo-MD|mr-IN|sk-SK|sl-SI|ar-OM|ar-QA|es-CU|ar-SA|apd-SD|ar-SY|sd|syr-TR|so-DJ|so-ET|tk-TM|so-KE|so-SO|dsb-DE|hsb-DE|es-AR|es-BO|es-CL|es-CO|es-CR|es-EC|es-SV|es-GT|es-HN|es-MX|es-NI|es-PA|es-PY|es-PE|es-PR|rm-CH|be-BY|so|sv|tt-RU|cy-GB|yi-IL|yo-NG|ta-IN|te-IN|ar-TN|bo|es-UY|es-VE|su|sw-KE|ss|sv-FI|sv-SE|tl-PH|tg-TJ|ts-ZA|tn-BW|uz-UZ-Latn|tn-ZA|tw|ug-CN|uk-UA|ur-IN|vi-VN|vo|xh-ZA|za|gu-IN|km-KH|zh-MO|or-IN|co-FR|de-LI|it|no|nl-BE|si-LK|de|pt|sq-AL|tz|nai|ti|ky|CHR|fil|nso-ZA|wo|fr-SN|ig|en-SG|ps-IR|to-TO|en-IN|ls|bs-BS-Cyrl|om-ET|hy-AM|dv-IN|fi-FI|hu-HU|es-DO|bs-BS-Latn|aa-ET|af-ZA|ar-BH|ar-EG|bn_IN|bn_BD|bi-VU|ar-AE|ar-YE"/>
    </xs:restriction>
  </xs:simpleType>
  <xs:element name="translationBody">
    <xs:annotation id="translationBodyDesc"><xs:documentation>This is the main body of the translation text. There are no allowed attributes or restrictions. There must be at least one translationUnit element.</xs:documentation></xs:annotation>
    <xs:complexType>
      <xs:sequence>
        <xs:element name="translationJob" maxOccurs="1" minOccurs="1">
          <xs:complexType>
           <xs:sequence>
             <xs:element name="jobLanguages" maxOccurs="1" minOccurs="1">
               <xs:annotation>
                 <xs:documentation>This element encapsulates the languages for the project. All the languages listed here should match the languages indicated in each translationUnit.</xs:documentation>
               </xs:annotation>
               <xs:complexType>
                 <xs:sequence>
             <xs:element name="sourceLang" maxOccurs="1" minOccurs="1" nillable="false">
               <xs:annotation>
                 <xs:documentation>This element encapsulates the source language of the project, and should match the source language of each translationUnit. There can and must be only 1 of these elements</xs:documentation>
               </xs:annotation>
               <xs:complexType>
                 <xs:simpleContent>
                   <xs:extension base="langString">
                   </xs:extension>
                 </xs:simpleContent>
               </xs:complexType>
             </xs:element>
             <xs:element name="targetLang" maxOccurs="unbounded" minOccurs="1" nillable="false">
               <xs:annotation>
                 <xs:documentation>This element encapsulates the target languages of the project. Each translationUnit should have each of these target languages, no exceptions. There must be at least 1 targetLanguage specified, but there is no limit as to how many targetLanguages there can be. Each target language must be unique, and the targetLanguage should not equal the sourceLanguage.</xs:documentation>
               </xs:annotation>
               <xs:complexType>
                 <xs:simpleContent>
                   <xs:extension base="langString">
                   </xs:extension>
                 </xs:simpleContent>
               </xs:complexType>
             </xs:element>
                 </xs:sequence>
               </xs:complexType>
               <xs:unique name="uniqueJobLangs">
                 <xs:selector xpath="*"/>
                 <xs:field xpath="@langString"/>
               </xs:unique>
             </xs:element>
        <xs:element name="translationUnit" maxOccurs="unbounded" minOccurs="1">
          <xs:annotation id="translationUnitDesc"><xs:documentation>This is the main unit for translation and comprises language combination(s). There should be only one sourceSegment element, and at least one targetSegment element. The langLocale attribute on each targetSegment element must be unique. In other words, there can only be one targetSegment per language. Also, no targetSegment can have the same langLocale as the sourceSegment. If no translation exists yet, targetSegments should be left blank, but they MUST be included in the file</xs:documentation></xs:annotation>
          <xs:complexType>
            <xs:sequence>
              <xs:element name="sourceSegment" maxOccurs="1" minOccurs="1" nillable="false">
                <xs:annotation id="sourceSegmentDesc"><xs:documentation>Text for translation is placed in this element. Must be 1 per translationUnit element. Cannot be null, also cannot be less than 1 character long.</xs:documentation></xs:annotation>
                <xs:complexType>
                  <xs:simpleContent>
                    <xs:extension base="sourceString">
                      <xs:attribute name="langLocale" use="required">
                        <xs:annotation id="langLocaleDesc"><xs:documentation>This is the language-locale combination for the source. All sourceString must have the same langLocale</xs:documentation></xs:annotation>
                        <xs:simpleType>
                          <xs:restriction base="xs:string">
                            <xs:annotation id="langRestrictionDesc"><xs:documentation>The available options for language locale combos are limited certain values based on our API. Please see Glyph Best Practices API Documentation for more details.</xs:documentation></xs:annotation>
                            <xs:pattern value="da-DK|ms-MY|it-IT|pt-BR|zh-CN|es-US|ko-KR|fr-CA|pt-PT|fr-FR|ja-JP|es-ES|de-DE|en-US|ru-RU|es-419|en-GB|zh-TW|tr-TR|nl-NL|th-TH|az-AZ-Cyrl|az-AZ-Latn|ba-RU|eu-ES|hmv|br-FR|bg-BG|my-BU|cal|ca-ES|ceb|ch|ny-MW|am-ET|zh-HK|zh-SG|bn|fr|fu|hr-HR|cs-CZ|ht|prs-AF|en|bal-IR|en-AU|eo|en-BZ|en-CA|en-CB|en-IE|en-JM|en-NZ|en-PH|en-ZA|en-CH|en-TT|en-ZW|et-EE|fo-FO|fa-IR|fj-FJ|sm-WS|fr-BE|nl|ar-DZ|mh|ar-AA|as-IN|ab|fy|fr-LU|ik|fr-MC|tet-ID|fr-CH|gd-GB|gl-ES|ka-GE|ar-IQ|ar-LY|ar-LB|ar-JO|ga-IE|lv-LV|ar-KW|he-IL|ar-MA|de-AT|sla-ME|de-LU|pau|de-CH|el-GR|kl-GL|grn|is-IS|es|ha-NG|hi-IN|id-ID|ia|ie|iu|zu-ZA|kk-KZ|jv-ID|kn-IN|ks|lo-LA|rw-RW|kg-CG|kok-IN|ku-TR|ln-CG|lt-LT|lb|mk-MK|mg-MG|mt-MT|mi-NZ|mn-MN|na-NR|nd-ZW|nb-NO|nn-NO|oc-FR|ps|pl-PL|qu-PE|ro-RO|rn|sg|sa-IN|sr-CY|sr-LA|sr-YU|st|sn|it-CH|ne-NP|pa-PA|ml-IN|yi|la|mo-MD|mr-IN|sk-SK|sl-SI|ar-OM|ar-QA|es-CU|ar-SA|apd-SD|ar-SY|sd|syr-TR|so-DJ|so-ET|tk-TM|so-KE|so-SO|dsb-DE|hsb-DE|es-AR|es-BO|es-CL|es-CO|es-CR|es-EC|es-SV|es-GT|es-HN|es-MX|es-NI|es-PA|es-PY|es-PE|es-PR|rm-CH|be-BY|so|sv|tt-RU|cy-GB|yi-IL|yo-NG|ta-IN|te-IN|ar-TN|bo|es-UY|es-VE|su|sw-KE|ss|sv-FI|sv-SE|tl-PH|tg-TJ|ts-ZA|tn-BW|uz-UZ-Latn|tn-ZA|tw|ug-CN|uk-UA|ur-IN|vi-VN|vo|xh-ZA|za|gu-IN|km-KH|zh-MO|or-IN|co-FR|de-LI|it|no|nl-BE|si-LK|de|pt|sq-AL|tz|nai|ti|ky|CHR|fil|nso-ZA|wo|fr-SN|ig|en-SG|ps-IR|to-TO|en-IN|ls|bs-BS-Cyrl|om-ET|hy-AM|dv-IN|fi-FI|hu-HU|es-DO|bs-BS-Latn|aa-ET|af-ZA|ar-BH|ar-EG|bn_IN|bn_BD|bi-VU|ar-AE|ar-YE"/>
                          </xs:restriction>
                        </xs:simpleType>
                      </xs:attribute>
                    </xs:extension>
                  </xs:simpleContent>
                </xs:complexType>
              </xs:element>
              <xs:element name="targetSegment" maxOccurs="unbounded" minOccurs="1" nillable="true">
                <xs:annotation id="targetSegmentDesc"><xs:documentation>This is the element that holds any translated text or is the place holder for translated text. It can be empty, but there must be at least one in each translationUnit. In other words, there must be at least one language combination in the file.</xs:documentation></xs:annotation>
                <xs:complexType>
                  <xs:simpleContent>
                    <xs:extension base="xs:string">
                      <xs:attribute name="langLocale" use="required">
                        <xs:annotation id="langLocaleDesc2"><xs:documentation>This is the language-locale combination for the source. All sourceString must have the same langLocale</xs:documentation></xs:annotation>
                        <xs:simpleType>
                          <xs:restriction base="xs:string">
                            <xs:annotation id="langRestrictionDesc2"><xs:documentation>The available options for language locale combos are limited certain values based on our API. Please see Glyph Best Practices API Documentation for more details.</xs:documentation></xs:annotation>
                            <xs:pattern value="da-DK|ms-MY|it-IT|pt-BR|zh-CN|es-US|ko-KR|fr-CA|pt-PT|fr-FR|ja-JP|es-ES|de-DE|en-US|ru-RU|es-419|en-GB|zh-TW|tr-TR|nl-NL|th-TH|az-AZ-Cyrl|az-AZ-Latn|ba-RU|eu-ES|hmv|br-FR|bg-BG|my-BU|cal|ca-ES|ceb|ch|ny-MW|am-ET|zh-HK|zh-SG|bn|fr|fu|hr-HR|cs-CZ|ht|prs-AF|en|bal-IR|en-AU|eo|en-BZ|en-CA|en-CB|en-IE|en-JM|en-NZ|en-PH|en-ZA|en-CH|en-TT|en-ZW|et-EE|fo-FO|fa-IR|fj-FJ|sm-WS|fr-BE|nl|ar-DZ|mh|ar-AA|as-IN|ab|fy|fr-LU|ik|fr-MC|tet-ID|fr-CH|gd-GB|gl-ES|ka-GE|ar-IQ|ar-LY|ar-LB|ar-JO|ga-IE|lv-LV|ar-KW|he-IL|ar-MA|de-AT|sla-ME|de-LU|pau|de-CH|el-GR|kl-GL|grn|is-IS|es|ha-NG|hi-IN|id-ID|ia|ie|iu|zu-ZA|kk-KZ|jv-ID|kn-IN|ks|lo-LA|rw-RW|kg-CG|kok-IN|ku-TR|ln-CG|lt-LT|lb|mk-MK|mg-MG|mt-MT|mi-NZ|mn-MN|na-NR|nd-ZW|nb-NO|nn-NO|oc-FR|ps|pl-PL|qu-PE|ro-RO|rn|sg|sa-IN|sr-CY|sr-LA|sr-YU|st|sn|it-CH|ne-NP|pa-PA|ml-IN|yi|la|mo-MD|mr-IN|sk-SK|sl-SI|ar-OM|ar-QA|es-CU|ar-SA|apd-SD|ar-SY|sd|syr-TR|so-DJ|so-ET|tk-TM|so-KE|so-SO|dsb-DE|hsb-DE|es-AR|es-BO|es-CL|es-CO|es-CR|es-EC|es-SV|es-GT|es-HN|es-MX|es-NI|es-PA|es-PY|es-PE|es-PR|rm-CH|be-BY|so|sv|tt-RU|cy-GB|yi-IL|yo-NG|ta-IN|te-IN|ar-TN|bo|es-UY|es-VE|su|sw-KE|ss|sv-FI|sv-SE|tl-PH|tg-TJ|ts-ZA|tn-BW|uz-UZ-Latn|tn-ZA|tw|ug-CN|uk-UA|ur-IN|vi-VN|vo|xh-ZA|za|gu-IN|km-KH|zh-MO|or-IN|co-FR|de-LI|it|no|nl-BE|si-LK|de|pt|sq-AL|tz|nai|ti|ky|CHR|fil|nso-ZA|wo|fr-SN|ig|en-SG|ps-IR|to-TO|en-IN|ls|bs-BS-Cyrl|om-ET|hy-AM|dv-IN|fi-FI|hu-HU|es-DO|bs-BS-Latn|aa-ET|af-ZA|ar-BH|ar-EG|bn_IN|bn_BD|bi-VU|ar-AE|ar-YE"/>
                          </xs:restriction>
                        </xs:simpleType>
                      </xs:attribute>
                    </xs:extension>
                  </xs:simpleContent>
                </xs:complexType>
              </xs:element>
            </xs:sequence>
            <xs:attribute name="active" use="required">
              <xs:annotation id="activeDesc"><xs:documentation>This indicates whether this translationUnit is active. If you do not want this to be translated or processed, set to false. Default should be true</xs:documentation></xs:annotation>
              <xs:simpleType>
                <xs:restriction base="xs:string">
                  <xs:enumeration value="true"/>
                  <xs:enumeration value="false"/>
                </xs:restriction>
              </xs:simpleType>
            </xs:attribute>
            <xs:attribute type="xs:string" name="key" use="required">
            <xs:annotation id="keyDesc"><xs:documentation>key is a required element. It should be a unique identifier for your string.</xs:documentation></xs:annotation>
            </xs:attribute>
              <xs:attribute type="xs:string" name="notes" use="required">
                <xs:annotation id="notesDesc"><xs:documentation>The notes attribute MUST be included, even if it is left blank (=""). Put any notes about context or information the translators should know. The notes will be presented to all langauges. At this time, we don't support langauge specific notes.</xs:documentation></xs:annotation>
              </xs:attribute>
            <xs:attribute name="lenRestriction" use="required">
              <xs:annotation id="lenRestrictionDesc"><xs:documentation>The notes attribute MUST be included, and cannot be left blank. The value should be 0 if no length restriction is desired. This attribute is used to tells the translator the maximum number of characters allowed for this string. If used, it must be an integer of 1 or greater. If used, the translator will be forced to validate the length or change their translation prior to delivery.</xs:documentation></xs:annotation>
              <xs:simpleType>
                <xs:restriction>
                  <xs:minInclusive value="0" />
                </xs:restriction>
              </xs:simpleType>
            </xs:attribute>
          </xs:complexType>
          <xs:unique name="uniqueLang">
            <xs:selector xpath="*"/>
            <xs:field xpath="@langLocale"/>
          </xs:unique>
          <xs:unique name="uniqueKey">
            <xs:selector xpath="*"></xs:selector>
            <xs:field xpath="@key"></xs:field>
          </xs:unique>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>


问:
HTML form - PHP not inserting into Database correctly
i'm only tring to make a form work.
Its a similar for than i am fillin now: question, text, tags.

Fine,

this is when i print the form

```<code>function imprimir_formulario_pregunta(){
    $html = '<form id="pregunta" name ="pregunta" method="post" action="preguntas.php">';
    $html .= '<h2>Pregunta</h2>';

    $html .= '<input name="q" id="q" type="text" value=" "></input>';
    $html .= '<h2>Explica tu duda</h2>';
    $html .= '<textarea name="texto" id="texto" /
                    ></textarea>';
    $html .= '<h2>Etiquetas (separadas por comas)</h2>';
    $html .= '<input name="tags" id="tags"/>';
    $html .= '<input name="responde_a" style="display:none;" id="responde_a" value="0"/>';

    $html .= '<button name="pregunta" id="pregunta" type="submit" >Publicar</button>';

    $html .= '</form>';

    echo $html;

}
</code>```

this is when i recive data

```<code>if(isset($_POST['pregunta'])){
    $p_title = $_POST['q'];
    $p_text = $_POST['texto'];
    $p_et = $_POST['etiquetas'];
    $p_resp = $_POST['responde_a'];
    post_pregunta($p_title,$p_text, $p_et, $p_resp);
</code>```

this is when i process data

```<code>function obtener_id_pregunta($p,$t){
    $consulta = mysql_query("SELECT * FROM preguntas WHERE pregunta='$p' && texto='$t'");
    while($item = mysql_fetch_array($consulta)){
        return $item['id'];
    }
}

function    post_pregunta($a,$t,$et,$r){
    mostrar_notificacion("hemos entrado");
    //// ******
    if($a != '' && $t != ''){
        $b = $a;
        guardar_pregunta($b,$t,$r);
        $id = obtener_id_pregunta($b,$t);
        $temp = new etiqueta(0, '');
        $basura = $temp->guardar_etiquetas($et, $id, $_SESSION['id']);

    }else
        mostrar_notificacion("hemos salido $a $t");
}

function guardar_pregunta($p,$t,$r){
    $id_tmp = $_SESSION['id'];
    $insert = "INSERT INTO preguntas (pregunta,texto,id_usuario,fecha,responde_a) VALUES ('$p','$t','$id_tmp',NOW(),'$r')";
    $qry = mysql_query($insert);
    if(mysql_affected_rows())
    {
        mostrar_notificacion("La pregunta $p ($t)($r) se guardo");
        return true;
    }
    else
    {
        mostrar_notificacion("Error Ingresando datos");
        return false;
    }
    return false;
}
</code>```

Result:

I get the insert in the database done, but the 'q' field has a '' value....

Notes:
It looses the value in the step ** because it enters in the condition, but it doesn't in the next one wich is the same question...

Please tell me you have my answer, been too long on this.. and i need it done this week for class

Thanks in advance

答:
@Toni Michel Caubet: I rewrote your code a little to make it more readable and should be slightly easier to debug as well. Please heed the /* comments */. I've left a lot of the work up to you with just some guides here and there.

Receive data:

```<code>if(isset($_POST['pregunta']))
{
    $p_title = $_POST['q'];
    $p_text  = $_POST['texto'];
    $p_et    = $_POST['tags'];
    $p_resp  = $_POST['responde_a'];

    /* Never trust user input, validate the data you're retrieving */

    /* Keep variable names the same, or risk confusing yourself later */
    post_pregunta($p_title, $p_text, $p_et, $p_resp);
}
</code>```

Process data:

```<code>function post_pregunta($p_title, $p_text, $p_et, $p_resp)
{
    mostrar_notificacion("hemos entrado");

    /* You should handle validation like this after initially receiving post
       data, the ideal would be to validate the data in a central location
       and then only pass the valid data on to other functions to avoid
       having to recheck everything.
    */
    if($p_title != '' && $p_text != '')
    {
        guardar_pregunta($p_title, $p_text, $p_resp);
        $id = obtener_id_pregunta($p_title, $p_text);
        $temp = new etiqueta(0, '');
        $basura = $temp->guardar_etiquetas($p_et, $id, $_SESSION['id']);
    }
    else
    {
        mostrar_notificacion("hemos salido $p_title $p_text");
    }
}

function obtener_id_pregunta($p_title, $p_text)
{
    /* This query may also be susceptible to SQL injection */
    $consulta = mysql_query("SELECT id FROM preguntas WHERE pregunta='" . $p . "' AND texto='" . $t . "'");
    while($item = mysql_fetch_array($consulta))
    {
        return $item['id'];
    }
}

function guardar_pregunta($p_title, $p_text, $p_resp)
{
    $id_tmp = $_SESSION['id'];

    /* This query is susceptible to SQL injection not least because there's
       no data validation. */
    $insert = "INSERT INTO preguntas (pregunta, texto, id_usuario, fecha, responde_a) VALUES ('$p_title', '$p_text', '$id_tmp', NOW(), '$p_resp')";
    $qry = mysql_query($insert);
    if(mysql_affected_rows())
    {
        mostrar_notificacion("La pregunta $p_title ($p_text)($p_resp) se guardo");
        return true;
    }
    else
    {
        mostrar_notificacion("Error Ingresando datos");
        return false;
    }
    return false;
}
</code>```

Print form:

```<code>function imprimir_formulario_pregunta()
{
    $html  = '<form id="preguntas" name="preguntas" method="post" action="preguntas.php">' . "\n";
    $html .= '    <div>' . "\n";
    $html .= '        <h2>Pregunta</h2>' . "\n";
    $html .= '        <input name="q" id="q" type="text" />' . "\n";
    $html .= '    </div>' . "\n";
    $html .= '    <div>' . "\n";
    $html .= '        <h2>Explica tu duda</h2>' . "\n";
    $html .= '        <textarea name="texto" id="texto"></textarea>' . "\n";
    $html .= '    </div>' . "\n";
    $html .= '    <div>' . "\n";
    $html .= '        <h2>Etiquetas (separadas por comas)</h2>' . "\n";
    $html .= '        <input name="tags" id="tags" />' . "\n";
    $html .= '    </div>' . "\n";
    $html .= '    <div>' . "\n";
    $html .= '        <input name="responde_a" style="display:none;" id="responde_a" value="0" />' . "\n";
    $html .= '        <button name="pregunta" id="pregunta" type="submit">Publicar</button>' . "\n";
    $html .= '    </div>' . "\n";
    $html .= '</form>' . "\n";

    echo $html;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
i'm only tring to make a form work.
Its a similar for than i am fillin now: question, text, tags.

Fine,

this is when i print the form

function imprimir_formulario_pregunta(){
    $html = '<form id="pregunta" name ="pregunta" method="post" action="preguntas.php">';
    $html .= '
Pregunta
';

    $html .= '<input name="q" id="q" type="text" value=" "></input>';
    $html .= '
Explica tu duda
';
    $html .= '<textarea name="texto" id="texto" /
                    ></textarea>';
    $html .= '
Etiquetas (separadas por comas)
';
    $html .= '<input name="tags" id="tags"/>';
    $html .= '<input name="responde_a" style="display:none;" id="responde_a" value="0"/>';

    $html .= '<button name="pregunta" id="pregunta" type="submit" >Publicar</button>';

    $html .= '</form>';

    echo $html;

}

this is when i recive data

if(isset($_POST['pregunta'])){
    $p_title = $_POST['q'];
    $p_text = $_POST['texto'];
    $p_et = $_POST['etiquetas'];
    $p_resp = $_POST['responde_a'];
    post_pregunta($p_title,$p_text, $p_et, $p_resp);

this is when i process data

function obtener_id_pregunta($p,$t){
    $consulta = mysql_query("SELECT * FROM preguntas WHERE pregunta='$p' && texto='$t'");
    while($item = mysql_fetch_array($consulta)){
        return $item['id'];
    }
}

function    post_pregunta($a,$t,$et,$r){
    mostrar_notificacion("hemos entrado");
    //// ******
    if($a != '' && $t != ''){
        $b = $a;
        guardar_pregunta($b,$t,$r);
        $id = obtener_id_pregunta($b,$t);
        $temp = new etiqueta(0, '');
        $basura = $temp->guardar_etiquetas($et, $id, $_SESSION['id']);

    }else
        mostrar_notificacion("hemos salido $a $t");
}

function guardar_pregunta($p,$t,$r){
    $id_tmp = $_SESSION['id'];
    $insert = "INSERT INTO preguntas (pregunta,texto,id_usuario,fecha,responde_a) VALUES ('$p','$t','$id_tmp',NOW(),'$r')";
    $qry = mysql_query($insert);
    if(mysql_affected_rows())
    {
        mostrar_notificacion("La pregunta $p ($t)($r) se guardo");
        return true;
    }
    else
    {
        mostrar_notificacion("Error Ingresando datos");
        return false;
    }
    return false;
}

Result:

I get the insert in the database done, but the 'q' field has a '' value....

Notes:
It looses the value in the step ** because it enters in the condition, but it doesn't in the next one wich is the same question...

Please tell me you have my answer, been too long on this.. and i need it done this week for class

Thanks in advance

Body:
@Toni Michel Caubet: I rewrote your code a little to make it more readable and should be slightly easier to debug as well. Please heed the /* comments */. I've left a lot of the work up to you with just some guides here and there.

Receive data:

if(isset($_POST['pregunta']))
{
    $p_title = $_POST['q'];
    $p_text  = $_POST['texto'];
    $p_et    = $_POST['tags'];
    $p_resp  = $_POST['responde_a'];

    /* Never trust user input, validate the data you're retrieving */

    /* Keep variable names the same, or risk confusing yourself later */
    post_pregunta($p_title, $p_text, $p_et, $p_resp);
}

Process data:

function post_pregunta($p_title, $p_text, $p_et, $p_resp)
{
    mostrar_notificacion("hemos entrado");

    /* You should handle validation like this after initially receiving post
       data, the ideal would be to validate the data in a central location
       and then only pass the valid data on to other functions to avoid
       having to recheck everything.
    */
    if($p_title != '' && $p_text != '')
    {
        guardar_pregunta($p_title, $p_text, $p_resp);
        $id = obtener_id_pregunta($p_title, $p_text);
        $temp = new etiqueta(0, '');
        $basura = $temp->guardar_etiquetas($p_et, $id, $_SESSION['id']);
    }
    else
    {
        mostrar_notificacion("hemos salido $p_title $p_text");
    }
}

function obtener_id_pregunta($p_title, $p_text)
{
    /* This query may also be susceptible to SQL injection */
    $consulta = mysql_query("SELECT id FROM preguntas WHERE pregunta='" . $p . "' AND texto='" . $t . "'");
    while($item = mysql_fetch_array($consulta))
    {
        return $item['id'];
    }
}

function guardar_pregunta($p_title, $p_text, $p_resp)
{
    $id_tmp = $_SESSION['id'];

    /* This query is susceptible to SQL injection not least because there's
       no data validation. */
    $insert = "INSERT INTO preguntas (pregunta, texto, id_usuario, fecha, responde_a) VALUES ('$p_title', '$p_text', '$id_tmp', NOW(), '$p_resp')";
    $qry = mysql_query($insert);
    if(mysql_affected_rows())
    {
        mostrar_notificacion("La pregunta $p_title ($p_text)($p_resp) se guardo");
        return true;
    }
    else
    {
        mostrar_notificacion("Error Ingresando datos");
        return false;
    }
    return false;
}

Print form:

function imprimir_formulario_pregunta()
{
    $html  = '<form id="preguntas" name="preguntas" method="post" action="preguntas.php">' . "\n";
    $html .= '    <div>' . "\n";
    $html .= '        <h2>Pregunta</h2>' . "\n";
    $html .= '        <input name="q" id="q" type="text" />' . "\n";
    $html .= '    </div>' . "\n";
    $html .= '    <div>' . "\n";
    $html .= '        <h2>Explica tu duda</h2>' . "\n";
    $html .= '        <textarea name="texto" id="texto"></textarea>' . "\n";
    $html .= '    </div>' . "\n";
    $html .= '    <div>' . "\n";
    $html .= '        <h2>Etiquetas (separadas por comas)</h2>' . "\n";
    $html .= '        <input name="tags" id="tags" />' . "\n";
    $html .= '    </div>' . "\n";
    $html .= '    <div>' . "\n";
    $html .= '        <input name="responde_a" style="display:none;" id="responde_a" value="0" />' . "\n";
    $html .= '        <button name="pregunta" id="pregunta" type="submit">Publicar</button>' . "\n";
    $html .= '    </div>' . "\n";
    $html .= '</form>' . "\n";

    echo $html;
}


问:
How to implement auto increment column value alphabetical?
I have a table tbl_login and I want my column id to be auto increment and alphabetical also. Please help me. Thanks in advance.

```<code>ID      Name    Pass
101A    Mohan   1234
102B    Madan   4321
103C    Ram     12334
</code>```

答:
Very Nice question.

i) This id can be generated upto how much digit ?like 10,000 or 1,00,000 or more

ii) You should throw little more example randomly start from 101 .specially throw few example from 4 digit and few from 5 digits.

iii)how you are going to implement it.Like will you insert single row or you will insert bulk rows. Implemented SCRIPT can be optimize and change according to requirement once requirement is clear.

iv) Test my script.First thoroughly test it from any number between 101 to 921

Just change the value of @input

```<code>DECLARE @Input INT = 127--change here
DECLARE @Output VARCHAR(10) = ''
    ,@TempOutput VARCHAR(10) = ''
DECLARE @Base INT = 100
    ,@z INT = 26
    ,@Rem INT
DECLARE @Tempinput INT = @Input

WHILE (
        @Tempinput > 0
        AND @input > @Base + @z
        )
BEGIN
    SET @TempOutput = ''

    IF (@Tempinput > @Base)
    BEGIN
        SET @Rem = @Tempinput % @Base
    END

    IF (
            (@Rem % @z) = 0
            AND (@Rem / @z) > 1
            )
    BEGIN
        SET @Tempinput = (@Rem / @z) - 1
        SET @Rem = @Rem % @z

        PRINT '23'
    END
    ELSE
    BEGIN
        IF (@Rem > @z)
        BEGIN
            SET @Tempinput = @Rem / @z
            SET @Rem = @Rem % @z

            PRINT @Tempinput
        END
        ELSE
        BEGIN
            SET @Rem = @Tempinput % @z
            SET @Tempinput = @Tempinput / @z
        END
    END

    IF (
            @Rem > 0
            AND @Rem <= @z
            )
        SET @TempOutput = CHAR(@Rem + 64)
    ELSE IF (@Rem = 0)
        SET @TempOutput = 'Z'
    SET @Output = @TempOutput + @Output
END

IF (@input <= @Base + @z)
    SET @Output = CHAR((@input % @Base) + 64)

SELECT cast(@Input AS VARCHAR(10)) + @Output
</code>```

Body:
I have a table tbl_login and I want my column id to be auto increment and alphabetical also. Please help me. Thanks in advance.

ID      Name    Pass
101A    Mohan   1234
102B    Madan   4321
103C    Ram     12334

Body:
Very Nice question.

i) This id can be generated upto how much digit ?like 10,000 or 1,00,000 or more

ii) You should throw little more example randomly start from 101 .specially throw few example from 4 digit and few from 5 digits.

iii)how you are going to implement it.Like will you insert single row or you will insert bulk rows. Implemented SCRIPT can be optimize and change according to requirement once requirement is clear.

iv) Test my script.First thoroughly test it from any number between 101 to 921

Just change the value of @input

DECLARE @Input INT = 127--change here
DECLARE @Output VARCHAR(10) = ''
    ,@TempOutput VARCHAR(10) = ''
DECLARE @Base INT = 100
    ,@z INT = 26
    ,@Rem INT
DECLARE @Tempinput INT = @Input

WHILE (
        @Tempinput > 0
        AND @input > @Base + @z
        )
BEGIN
    SET @TempOutput = ''

    IF (@Tempinput > @Base)
    BEGIN
        SET @Rem = @Tempinput % @Base
    END

    IF (
            (@Rem % @z) = 0
            AND (@Rem / @z) > 1
            )
    BEGIN
        SET @Tempinput = (@Rem / @z) - 1
        SET @Rem = @Rem % @z

        PRINT '23'
    END
    ELSE
    BEGIN
        IF (@Rem > @z)
        BEGIN
            SET @Tempinput = @Rem / @z
            SET @Rem = @Rem % @z

            PRINT @Tempinput
        END
        ELSE
        BEGIN
            SET @Rem = @Tempinput % @z
            SET @Tempinput = @Tempinput / @z
        END
    END

    IF (
            @Rem > 0
            AND @Rem <= @z
            )
        SET @TempOutput = CHAR(@Rem + 64)
    ELSE IF (@Rem = 0)
        SET @TempOutput = 'Z'
    SET @Output = @TempOutput + @Output
END

IF (@input <= @Base + @z)
    SET @Output = CHAR((@input % @Base) + 64)

SELECT cast(@Input AS VARCHAR(10)) + @Output


答:
You should show the code that didn't work. From your description though, you're doing a few things wrong.

First, .filter() always returns a queryset, not an instance. To get an instance, you should use .get().

Secondly, User is the class; the instance is user.

Thirdly, you have no reason to do a query here at all. request.user is already the User instance. There is no need to take that user, get its profile, ask the profile for the user ID, then do another query to get back the user you started with. Just use the user you already have.

Finally, never, ever do a blank except, as that will catch all sorts of unexpected errors and hide anything that could be going wrong. Only catch exceptions you actually know how to deal with. In this case, there is nothing specific you need to handle; if anything unexpected goes wrong, let Django report that error normally.

```<code>def delete_profile(request):
    user = request.user
    user.is_active = False
    user.save()
    messages.success(request, 'Profile successfully disabled.')
    return redirect('index')
</code>```

Title: Django-- Deactivate User account instead of deleting it

Body:
You should show the code that didn't work. From your description though, you're doing a few things wrong.

First, .filter() always returns a queryset, not an instance. To get an instance, you should use .get().

Secondly, User is the class; the instance is user.

Thirdly, you have no reason to do a query here at all. request.user is already the User instance. There is no need to take that user, get its profile, ask the profile for the user ID, then do another query to get back the user you started with. Just use the user you already have.

Finally, never, ever do a blank except, as that will catch all sorts of unexpected errors and hide anything that could be going wrong. Only catch exceptions you actually know how to deal with. In this case, there is nothing specific you need to handle; if anything unexpected goes wrong, let Django report that error normally.

def delete_profile(request):
    user = request.user
    user.is_active = False
    user.save()
    messages.success(request, 'Profile successfully disabled.')
    return redirect('index')


问:
Integer division optimization MSVC C++
I'm trying to reduce the CPU usage of a portion of my code, taking 40% of the CPU power. The portion is this one:

```<code>void CalibrationFunction(cv::Mat* pMatSrc, cv::Mat* pMatDst,
                         cv::Mat* pBlack, cv::Mat* pWhite, INT32 nRadioFactor)
{
  if (pMatSrc && pMatDst && pMatSrc->data && pMatDst->data)
  {
    for (int i = 0; i < pMatSrc->size[0]; i++)
    {
      UINT16* pBlackVal = (UINT16*)(pBlack->data + i*pBlack->step[0]);
      UINT16* pWhiteVal = (UINT16*)(pWhite->data + i*pWhite->step[0]);
      UINT16* pData = (UINT16*)(pMatSrc->data + i*pMatSrc->step[0]);
      INT32 nDif;
      UINT16 un16Value;
      for (int j = 0; j < pMatSrc->size[1]; j++)
      {
        nDif = (*pData) - (*pBlackVal);
        un16Value = (UINT16)min(65535, (max(0, nDif) * nRadioFactor / max(1, (*pWhiteVal))));
        pBlackVal++;
        pWhiteVal++;
        pData++;

        int i0 = 0, i1 = j, i2 = i;
        *(UINT16*)(pMatDst->data + i0 * pMatDst->step[0] + i1 * pMatDst->step[1] + i2 * pMatDst->step[2]) = un16Value;
      }
    }
  }
}
</code>```

Multithreading is already implemented: 8 threads are used.

I looked at SIMD with integer arithmetic operation, but as there is an integer division, it seems this is not the way to proceed. I looked at optimized integer division libraries, but they all seem to only be effective when all the integers are divided by the same denominator, which is not the case here.

Does someone have a lead to follow? I'm very open to exotic solution (compile the code in another language and call it from the current solution, etc), the only restriction is this has to stay a MSVC project, using MSVC compiler.

I've seen that Intel implemented integer division with SMID, maybe I should compile this piece of code with the Intel compiler, and call the generated binary from the current solution (I have an Intel compiler), but this solution would only work on my computer and would be, in my opinion, "too custom".

EDIT

I finally managed to use SIMD however. The trick was, for the division, to cast the vector of 8 integers of 16 bits into 2 vectors of four float of 32 bits, and then I could divide them, because there are some function to divide floats in SIMD. After the division, recast in order to have 16 bits integer results.
The new function, using SIMD, is 6 times faster, which is enough at this moment. I keep in mind all your remarks, as they could be helpful if this portion of my solution become again a bottleneck.

EDIT 2

As requested, here is the new code:

```<code>void CalibrationRadioSIMD(UINT16* pBlackVal, UINT16* pWhiteVal, UINT16* pData, UINT16* pResult, int size, int nRadioFactor = 2)
{

    for (int hop = 0; hop < 100; hop++) {
        UINT16* pResultTmp = pResult;
        UINT16* pDataTmp = pData;
        UINT16* pBlackValTmp = pBlackVal;
        UINT16* pWhiteValTmp = pWhiteVal;
        __m128i radio;

        radio.m128i_i32[0] = nRadioFactor;
        radio.m128i_i32[1] = nRadioFactor;
        radio.m128i_i32[2] = nRadioFactor;
        radio.m128i_i32[3] = nRadioFactor;
        for (int j = 0; j < size / 8; j++)
        {
            //
            // nDif = max(0, (*pData) - (*pBlackVal));
            //
            // 1/ Loads 128-bit value
            //    Address p must be 16-byte aligned.
            //    For the unaligned version, see _mm_loadu_si128.
            __m128i reg_a = _mm_load_si128((__m128i*)pDataTmp);
            __m128i reg_B = _mm_load_si128((__m128i*)pBlackValTmp);
            __m128i reg_white = _mm_load_si128((__m128i*)pWhiteValTmp);
            pDataTmp += 8;
            pBlackValTmp += 8;
            pWhiteValTmp += 8;

            // 2/ Subtracts the 8 unsigned 16-bit integers of b from the 8 unsigned 16-bit integers of a and saturates.
            __m128i reg_diff = _mm_subs_epu16(reg_a, reg_B);

            /////////////////////////////////////////////////////////////////////////////

            // unpack your vector of 8 x 16 bit unsigned shorts into two vectors of 32 bit unsigned ints, :
            __m128i xlo = _mm_unpacklo_epi16(reg_diff, _mm_set1_epi16(0));
            __m128i xhi = _mm_unpackhi_epi16(reg_diff, _mm_set1_epi16(0));

            // This instruction multiplies two sets of 32-bit signed integers.
            __m128i mullo = _mm_mullo_epi32(xlo, radio);
            __m128i mulhi = _mm_mullo_epi32(xhi, radio);

            // convert each of these vectors to float
            __m128 ylo = _mm_cvtepi32_ps(mullo);
            __m128 yhi = _mm_cvtepi32_ps(mulhi);

            // Meme question que pour xlo et xhi
            __m128i i32_whitelo = _mm_unpacklo_epi16(reg_white, _mm_set1_epi16(0));
            __m128i i32_whitehi = _mm_unpackhi_epi16(reg_white, _mm_set1_epi16(0));

            __m128 f32_white_lo = _mm_cvtepi32_ps(i32_whitelo);
            __m128 f32_white_hi = _mm_cvtepi32_ps(i32_whitehi);

            __m128 f32_res_lo = _mm_div_ps(ylo, f32_white_lo);
            __m128 f32_res_hi = _mm_div_ps(yhi, f32_white_hi);

            // Reconvertir en entier 16 bits

            __m128i n32_res_lo = _mm_cvtps_epi32(f32_res_lo);
            __m128i n32_res_hi = _mm_cvtps_epi32(f32_res_hi);

            // Put result into result vector
            UINT16* f32_res_lo_i16 = (UINT16*)&n32_res_lo;
            UINT16* f32_res_hi_i16 = (UINT16*)&n32_res_hi;
            int l = 0;
            for (int k = 0; k < 4; k++) {
                *(pResultTmp + k + 0) = *(f32_res_lo_i16 + l);
                *(pResultTmp + k + 4) = *(f32_res_hi_i16 + l);
                l += 2;
            }
            pResultTmp += 8;

        }
    }
}
</code>```

答:
I don't recommend that you go down the SIMD route until you've eliminated any memory related performance issues.

What I mean is, glancing through the code, I think the performance of your code might be limited by unnecessary waits on memory rather than computations.

Benchmark

First off, establish a reproducible way of benchmarking your code. I'm assuming you've already done this considering you're saying it's using 40% of your CPU time. Measure the runtime of this code and nothing else, do it 5 times and record the fastest time. That's the best of 5 value and it should get you pretty far.

The best of N approach to measuring runtimes is good under the assumption that any slowdowns are caused by random other things happening on the computer. This can be other programs doing background work for example. The idea is that the fastest runtime you record is the least affected by random outside noise.

Help the compiler

The next step is to do simple code transformations such as moving memory reads outside of loops that don't have to be in loops. I know this sounds like overdoing it and that it might seem like the compiler should be able to figure it out. The fact is though, that the compiler often doesn't.

What I mean is to change code like this

```<code>UINT16* pBlackVal = (UINT16*)(pBlack->data + i*pBlack->step[0]);
</code>```

into this

```<code>// Before first loop:
UINT16* blackData = (UINT16*) pBlack->data;
yourType blackStep = (yourType) pBlack->step[0];

...

UINT16* pBlackVal = (UINT16*)(blackData + i*blackStep);
</code>```

to avoid generating any code that would chase pointers to data that could be evicted from the cache. The same goes for pMatSrc->size[0] and pWhite->step[0] etc. Especially do it for (*pData) in nDif = (*pData) - (*pBlackVal);.

This is a general recommendation in any code that might be performance sensitive, don't blindly assume that the compiler will solve your problems, especially when it comes to memory reads/writes.

Incrementing variables using prefix notation instead of postfix COULD help, but I suspect compilers are smart enough here. But why chance it? The reason is that if you use prefix, the previous value of the variable does not have to be remembered, since the prefix increment notation increments the value BEFORE it can be used instead of after. I might be a bit too picky here though. :)

You can use tools to inspect cache misses to determine if these transformations help. See for example https://msdn.microsoft.com/en-us/library/bb385772.aspx.

Memory patterns

Next, I recommend that you look through your memory read patterns to see if you could store your data in memory in a way that would make it more cache friendly.

The first thing that comes to mind here, since you're doing effectively 2D arrays with your matrices, is that you must iterate over your matrix to match the data layout, otherwise you'll destroy performance.

What I mean is that if you store the matrix

```<code>a b c
d e f
g h i
</code>```

like this in memory

```<code>abcdefghi
</code>```

then you should iterate like this

```<code>for r in [0, rowLength-1]
    for c in [0, columnLength-1]
        // do thing with data[rowLength * r + c] here
</code>```

i.e. you iterate over every column in a row before skipping to the next row. If you do it the otherway around, you program will run super slow.

If you are already doing this or not is unclear. It depends on the values of pMatDst->step[1] and pMatDst->step[2]. Make sure the inner loop jumps the shortest distance possible through the array, basically, so you want pMatDst->step[1] to be much smaller than pMatDst->step[2].

What you want to do is to read memory linearly. The memory systems in computers are great at prefetching data and caching it to make that fast. The best is of course to not read memory at all if you can help it. Also try to do all you need do with a piece of memory after reading it before moving on to the next thing instead of reading it over and over again.

Links

To learn more about how memory use and layouts affect performance, I recommend reading the "Pitfalls of Object Oriented Programming" presentation (hope this works http://harmful.cat-v.org/software/OO_programming/_pdf/Pitfalls_of_Object_Oriented_Programming_GCAP_09.pdf).

Another great resource is Mike Acton's talk on data oriented design at CppCon https://www.youtube.com/watch?v=rX0ItVEVjHc, albeit a bit less specific.

Title: Integer division optimization MSVC C++

Body:
I'm trying to reduce the CPU usage of a portion of my code, taking 40% of the CPU power. The portion is this one:

void CalibrationFunction(cv::Mat* pMatSrc, cv::Mat* pMatDst,
                         cv::Mat* pBlack, cv::Mat* pWhite, INT32 nRadioFactor)
{
  if (pMatSrc && pMatDst && pMatSrc->data && pMatDst->data)
  {
    for (int i = 0; i < pMatSrc->size[0]; i++)
    {
      UINT16* pBlackVal = (UINT16*)(pBlack->data + i*pBlack->step[0]);
      UINT16* pWhiteVal = (UINT16*)(pWhite->data + i*pWhite->step[0]);
      UINT16* pData = (UINT16*)(pMatSrc->data + i*pMatSrc->step[0]);
      INT32 nDif;
      UINT16 un16Value;
      for (int j = 0; j < pMatSrc->size[1]; j++)
      {
        nDif = (*pData) - (*pBlackVal);
        un16Value = (UINT16)min(65535, (max(0, nDif) * nRadioFactor / max(1, (*pWhiteVal))));
        pBlackVal++;
        pWhiteVal++;
        pData++;

        int i0 = 0, i1 = j, i2 = i;
        *(UINT16*)(pMatDst->data + i0 * pMatDst->step[0] + i1 * pMatDst->step[1] + i2 * pMatDst->step[2]) = un16Value;
      }
    }
  }
}

Multithreading is already implemented: 8 threads are used.

I looked at SIMD with integer arithmetic operation, but as there is an integer division, it seems this is not the way to proceed. I looked at optimized integer division libraries, but they all seem to only be effective when all the integers are divided by the same denominator, which is not the case here.

Does someone have a lead to follow? I'm very open to exotic solution (compile the code in another language and call it from the current solution, etc), the only restriction is this has to stay a MSVC project, using MSVC compiler.

I've seen that Intel implemented integer division with SMID, maybe I should compile this piece of code with the Intel compiler, and call the generated binary from the current solution (I have an Intel compiler), but this solution would only work on my computer and would be, in my opinion, "too custom".

EDIT

I finally managed to use SIMD however. The trick was, for the division, to cast the vector of 8 integers of 16 bits into 2 vectors of four float of 32 bits, and then I could divide them, because there are some function to divide floats in SIMD. After the division, recast in order to have 16 bits integer results.
The new function, using SIMD, is 6 times faster, which is enough at this moment. I keep in mind all your remarks, as they could be helpful if this portion of my solution become again a bottleneck.

EDIT 2

As requested, here is the new code:

void CalibrationRadioSIMD(UINT16* pBlackVal, UINT16* pWhiteVal, UINT16* pData, UINT16* pResult, int size, int nRadioFactor = 2)
{

    for (int hop = 0; hop < 100; hop++) {
        UINT16* pResultTmp = pResult;
        UINT16* pDataTmp = pData;
        UINT16* pBlackValTmp = pBlackVal;
        UINT16* pWhiteValTmp = pWhiteVal;
        __m128i radio;

        radio.m128i_i32[0] = nRadioFactor;
        radio.m128i_i32[1] = nRadioFactor;
        radio.m128i_i32[2] = nRadioFactor;
        radio.m128i_i32[3] = nRadioFactor;
        for (int j = 0; j < size / 8; j++)
        {
            //
            // nDif = max(0, (*pData) - (*pBlackVal));
            //
            // 1/ Loads 128-bit value
            //    Address p must be 16-byte aligned.
            //    For the unaligned version, see _mm_loadu_si128.
            __m128i reg_a = _mm_load_si128((__m128i*)pDataTmp);
            __m128i reg_B = _mm_load_si128((__m128i*)pBlackValTmp);
            __m128i reg_white = _mm_load_si128((__m128i*)pWhiteValTmp);
            pDataTmp += 8;
            pBlackValTmp += 8;
            pWhiteValTmp += 8;

            // 2/ Subtracts the 8 unsigned 16-bit integers of b from the 8 unsigned 16-bit integers of a and saturates.
            __m128i reg_diff = _mm_subs_epu16(reg_a, reg_B);

            /////////////////////////////////////////////////////////////////////////////

            // unpack your vector of 8 x 16 bit unsigned shorts into two vectors of 32 bit unsigned ints, :
            __m128i xlo = _mm_unpacklo_epi16(reg_diff, _mm_set1_epi16(0));
            __m128i xhi = _mm_unpackhi_epi16(reg_diff, _mm_set1_epi16(0));

            // This instruction multiplies two sets of 32-bit signed integers.
            __m128i mullo = _mm_mullo_epi32(xlo, radio);
            __m128i mulhi = _mm_mullo_epi32(xhi, radio);

            // convert each of these vectors to float
            __m128 ylo = _mm_cvtepi32_ps(mullo);
            __m128 yhi = _mm_cvtepi32_ps(mulhi);

            // Meme question que pour xlo et xhi
            __m128i i32_whitelo = _mm_unpacklo_epi16(reg_white, _mm_set1_epi16(0));
            __m128i i32_whitehi = _mm_unpackhi_epi16(reg_white, _mm_set1_epi16(0));

            __m128 f32_white_lo = _mm_cvtepi32_ps(i32_whitelo);
            __m128 f32_white_hi = _mm_cvtepi32_ps(i32_whitehi);

            __m128 f32_res_lo = _mm_div_ps(ylo, f32_white_lo);
            __m128 f32_res_hi = _mm_div_ps(yhi, f32_white_hi);

            // Reconvertir en entier 16 bits

            __m128i n32_res_lo = _mm_cvtps_epi32(f32_res_lo);
            __m128i n32_res_hi = _mm_cvtps_epi32(f32_res_hi);

            // Put result into result vector
            UINT16* f32_res_lo_i16 = (UINT16*)&n32_res_lo;
            UINT16* f32_res_hi_i16 = (UINT16*)&n32_res_hi;
            int l = 0;
            for (int k = 0; k < 4; k++) {
                *(pResultTmp + k + 0) = *(f32_res_lo_i16 + l);
                *(pResultTmp + k + 4) = *(f32_res_hi_i16 + l);
                l += 2;
            }
            pResultTmp += 8;

        }
    }
}

Body:
I don't recommend that you go down the SIMD route until you've eliminated any memory related performance issues.

What I mean is, glancing through the code, I think the performance of your code might be limited by unnecessary waits on memory rather than computations.

Benchmark

First off, establish a reproducible way of benchmarking your code. I'm assuming you've already done this considering you're saying it's using 40% of your CPU time. Measure the runtime of this code and nothing else, do it 5 times and record the fastest time. That's the best of 5 value and it should get you pretty far.

The best of N approach to measuring runtimes is good under the assumption that any slowdowns are caused by random other things happening on the computer. This can be other programs doing background work for example. The idea is that the fastest runtime you record is the least affected by random outside noise.

Help the compiler

The next step is to do simple code transformations such as moving memory reads outside of loops that don't have to be in loops. I know this sounds like overdoing it and that it might seem like the compiler should be able to figure it out. The fact is though, that the compiler often doesn't.

What I mean is to change code like this

UINT16* pBlackVal = (UINT16*)(pBlack->data + i*pBlack->step[0]);

into this

// Before first loop:
UINT16* blackData = (UINT16*) pBlack->data;
yourType blackStep = (yourType) pBlack->step[0];

...

UINT16* pBlackVal = (UINT16*)(blackData + i*blackStep);

to avoid generating any code that would chase pointers to data that could be evicted from the cache. The same goes for pMatSrc->size[0] and pWhite->step[0] etc. Especially do it for (*pData) in nDif = (*pData) - (*pBlackVal);.

This is a general recommendation in any code that might be performance sensitive, don't blindly assume that the compiler will solve your problems, especially when it comes to memory reads/writes.

Incrementing variables using prefix notation instead of postfix COULD help, but I suspect compilers are smart enough here. But why chance it? The reason is that if you use prefix, the previous value of the variable does not have to be remembered, since the prefix increment notation increments the value BEFORE it can be used instead of after. I might be a bit too picky here though. :)

You can use tools to inspect cache misses to determine if these transformations help. See for example https://msdn.microsoft.com/en-us/library/bb385772.aspx.

Memory patterns

Next, I recommend that you look through your memory read patterns to see if you could store your data in memory in a way that would make it more cache friendly.

The first thing that comes to mind here, since you're doing effectively 2D arrays with your matrices, is that you must iterate over your matrix to match the data layout, otherwise you'll destroy performance.

What I mean is that if you store the matrix

a b c
d e f
g h i

like this in memory

abcdefghi

then you should iterate like this

for r in [0, rowLength-1]
    for c in [0, columnLength-1]
        // do thing with data[rowLength * r + c] here

i.e. you iterate over every column in a row before skipping to the next row. If you do it the otherway around, you program will run super slow.

If you are already doing this or not is unclear. It depends on the values of pMatDst->step[1] and pMatDst->step[2]. Make sure the inner loop jumps the shortest distance possible through the array, basically, so you want pMatDst->step[1] to be much smaller than pMatDst->step[2].

What you want to do is to read memory linearly. The memory systems in computers are great at prefetching data and caching it to make that fast. The best is of course to not read memory at all if you can help it. Also try to do all you need do with a piece of memory after reading it before moving on to the next thing instead of reading it over and over again.

Links

To learn more about how memory use and layouts affect performance, I recommend reading the "Pitfalls of Object Oriented Programming" presentation (hope this works http://harmful.cat-v.org/software/OO_programming/_pdf/Pitfalls_of_Object_Oriented_Programming_GCAP_09.pdf).

Another great resource is Mike Acton's talk on data oriented design at CppCon https://www.youtube.com/watch?v=rX0ItVEVjHc, albeit a bit less specific.


答:
There is no pattern in Angular that allows to achieve what you ask for.

The best option that I can think of for you would be to create a custom service. Make some service that you inject into AppComponent (therefore having a single instance of the service). In the Service you can have whatever logic you want.

Title: Emitting events globally


问:
What is the fastest way to create new model and set properties in C#?
I was wondering which of these two ways to instantiate a class/model, and set properties in C#, is the fastest and uses fewer resources.

Say class TestClass has a string property called Info.

```<code>var instantiatedClass = new TestClass();
instantiatedClass.Info = "Information";
</code>```

or

```<code>var instantiatedClass = new TestClass {
    Info = "Information"
}
</code>```

Of course, I want to know which is the fastest, when you have to set say 10+ properties.
The above was just for illustrating.

Thank you

(Please comment if anything in this post could be better)

答:
Second snippet is just syntactic sugar. Behind the scenes, its all same for a compiler as it generates almost same IL code.

So it does not matter what code is used, end result (in terms of performance) will remain the same.

First snippet IL code

```<code>.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       20 (0x14)
  .maxstack  2
  .locals init ([0] class SO.TestClass instantiatedClass)
  IL_0000:  nop
  IL_0001:  newobj     instance void SO.TestClass::.ctor()
  IL_0006:  stloc.0
  IL_0007:  ldloc.0
  IL_0008:  ldstr      "Information"
  IL_000d:  callvirt   instance void SO.TestClass::set_Info(string)
  IL_0012:  nop
  IL_0013:  ret
} // end of method Program::Main
</code>```

Second code snippet IL code

```<code>.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       20 (0x14)
  .maxstack  3
  .locals init ([0] class SO.TestClass instantiatedClass)
  IL_0000:  nop
  IL_0001:  newobj     instance void SO.TestClass::.ctor()
  IL_0006:  dup
  IL_0007:  ldstr      "Information"
  IL_000c:  callvirt   instance void SO.TestClass::set_Info(string)
  IL_0011:  nop
  IL_0012:  stloc.0
  IL_0013:  ret
} // end of method Program::Main
</code>```

Body:
I was wondering which of these two ways to instantiate a class/model, and set properties in C#, is the fastest and uses fewer resources.

Say class TestClass has a string property called Info.

var instantiatedClass = new TestClass();
instantiatedClass.Info = "Information";

or

var instantiatedClass = new TestClass {
    Info = "Information"
}

Of course, I want to know which is the fastest, when you have to set say 10+ properties.
The above was just for illustrating.

Thank you

(Please comment if anything in this post could be better)

Body:
Second snippet is just syntactic sugar. Behind the scenes, its all same for a compiler as it generates almost same IL code.

So it does not matter what code is used, end result (in terms of performance) will remain the same.

First snippet IL code

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       20 (0x14)
  .maxstack  2
  .locals init ([0] class SO.TestClass instantiatedClass)
  IL_0000:  nop
  IL_0001:  newobj     instance void SO.TestClass::.ctor()
  IL_0006:  stloc.0
  IL_0007:  ldloc.0
  IL_0008:  ldstr      "Information"
  IL_000d:  callvirt   instance void SO.TestClass::set_Info(string)
  IL_0012:  nop
  IL_0013:  ret
} // end of method Program::Main

Second code snippet IL code

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       20 (0x14)
  .maxstack  3
  .locals init ([0] class SO.TestClass instantiatedClass)
  IL_0000:  nop
  IL_0001:  newobj     instance void SO.TestClass::.ctor()
  IL_0006:  dup
  IL_0007:  ldstr      "Information"
  IL_000c:  callvirt   instance void SO.TestClass::set_Info(string)
  IL_0011:  nop
  IL_0012:  stloc.0
  IL_0013:  ret
} // end of method Program::Main


答:
You need to save it too: </p>

```<code>user.is_active = False
user.save()
</code>```

Body:
You need to save it too:

user.is_active = False
user.save()


问:
Sending multiple params through selector?
I want to use a selector to get to my controller and pass 2 values, the sender and a number.

Issue is that i get the crash:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[CDCFaderController changeView:]: unrecognised selector sent to instance 0x109db6f40'

The code makes sense to me so not sure why, anyone able to help?

```<code>[self.viewController performSelector:@selector(changeView:) withObject:self withObject:[NSNumber numberWithInteger: channel.channelNumber]];
</code>```

Receiver:

```<code>- (void)changeView:(UIButton *)sender chanToPush:(NSNumber*)channel
</code>```

答:
Use as this

```<code>[self performSelector:@selector(changeView:chanToPush:) withObject:self withObject:[NSNumber numberWithInteger: channel.channelNumber]];

- (void)changeView:(UIButton *)sender chanToPush:(NSNumber*)channel
{
    NSLog(@"channel is --%@",channel);
}
</code>```

OR

```<code>[self performSelector:@selector(changeView:) withObject:[NSNumber numberWithInteger: channel.channelNumber]];

- (void) changeView:(NSNumber *)num
{ //
}
</code>```

Body:
I want to use a selector to get to my controller and pass 2 values, the sender and a number.

Issue is that i get the crash:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[CDCFaderController changeView:]: unrecognised selector sent to instance 0x109db6f40'

The code makes sense to me so not sure why, anyone able to help?

[self.viewController performSelector:@selector(changeView:) withObject:self withObject:[NSNumber numberWithInteger: channel.channelNumber]];

Receiver:

- (void)changeView:(UIButton *)sender chanToPush:(NSNumber*)channel

Body:
Use as this

[self performSelector:@selector(changeView:chanToPush:) withObject:self withObject:[NSNumber numberWithInteger: channel.channelNumber]];

- (void)changeView:(UIButton *)sender chanToPush:(NSNumber*)channel
{
    NSLog(@"channel is --%@",channel);
}

OR

[self performSelector:@selector(changeView:) withObject:[NSNumber numberWithInteger: channel.channelNumber]];

- (void) changeView:(NSNumber *)num
{ //
}


问:
Validation in .net MVC
I need to check whether all fields are filled while clicking insert button.
This is my view:

```<code><body>

    <form name="form1">
        <h2>MEDICATION</h2>
        <div class="med">
            ```
 Patient code       <input type="text" id="pat" name="ptcode" size="25" value="" />                                ICD10  <input style="width:85px;height:30px;" type="text" name="icd10" value="">    <button style="height:30px;width:59px;" name="search" onclick="openicd()";>search</button>

Medication         @Html.DropDownListFor(Model => Model.medication, Model.medication,"Select Medication", new { style = "width:200px; height :30px" })   <button style="height:30px;"onclick="openmedication()";>search</button>            Prescription Date  <input type="date" class="sizetestdate" name="testdate" style="width:140px;height:30px;" value="">

Strength           @Html.DropDownListFor(Model => Model.strength, Model.strength, "Select Strength", new { style = "width:200px; height :30px" })                    Start Date         <input type="date" class="sizetestdate" name="testdate" style="width:140px;height:30px;" value="">   End Date  <input type="date" class="sizetestdate" name="testdate" style="width:140px;height:30px;" value="">

Form               @Html.DropDownListFor(Model => Model.form, Model.form, "Select form", new { style = "width:200px; height :30px" })                    Renewal Date       <input type="date" class="sizetestdate" name="testdate" style="width:140px;height:30px;" value=""> Days Supply <input type="text" style="width:85px;height:30px;" name="supply" value="">

Route              @Html.DropDownListFor(Model => Model.route, Model.route, "Select route", new { style = "width:200px; height :30px" })                    Pharmacy           @Html.DropDownListFor(Model => Model.pharmacy, Model.pharmacy, "Select Pharmacy", new { style = "width:200px; height :30px" })

Dose               @Html.DropDownListFor(Model => Model.dosage, Model.dosage, "Select Dose", new { style = "width:200px; height :30px" })
```
        </div>
    </form>
    <hr />
    <div class="wrapper">
        <button class="button" style="height:30px;" id="a" >Insert</button>      <button class="button" style="height:30px;" id="b">Update</button>      <button class="button" style="height:30px;" id="c">Delete</button>

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

答:
```<code>The best way is adding model Validations in Models
i don't know how your model look like assuming

public class Meditation
{
  [Required]
  public int id{get;set}

  [Required]
  public int name{get;set;}

}
 using System.ComponentModel.DataAnnotations; should be added

or you can simply use required in form

<input type="text" style="width:85px;height:30px;" name="supply" value="" required>

  @Html.DropDownListFor(Model => Model.dosage, Model.dosage, "Select Dose", new { style = "width:200px; height :30px", @required="true"})
</code>```

Title: Validation in .net MVC

Body:
I need to check whether all fields are filled while clicking insert button.
This is my view:

    <form name="form1">

MEDICATION

 Patient code       <input type="text" id="pat" name="ptcode" size="25" value="" />                                ICD10  <input style="width:85px;height:30px;" type="text" name="icd10" value="">    <button style="height:30px;width:59px;" name="search" onclick="openicd()";>search</button>

Medication         @Html.DropDownListFor(Model => Model.medication, Model.medication,"Select Medication", new { style = "width:200px; height :30px" })   <button style="height:30px;"onclick="openmedication()";>search</button>            Prescription Date  <input type="date" class="sizetestdate" name="testdate" style="width:140px;height:30px;" value="">

Strength           @Html.DropDownListFor(Model => Model.strength, Model.strength, "Select Strength", new { style = "width:200px; height :30px" })                    Start Date         <input type="date" class="sizetestdate" name="testdate" style="width:140px;height:30px;" value="">   End Date  <input type="date" class="sizetestdate" name="testdate" style="width:140px;height:30px;" value="">

Form               @Html.DropDownListFor(Model => Model.form, Model.form, "Select form", new { style = "width:200px; height :30px" })                    Renewal Date       <input type="date" class="sizetestdate" name="testdate" style="width:140px;height:30px;" value=""> Days Supply <input type="text" style="width:85px;height:30px;" name="supply" value="">

Route              @Html.DropDownListFor(Model => Model.route, Model.route, "Select route", new { style = "width:200px; height :30px" })                    Pharmacy           @Html.DropDownListFor(Model => Model.pharmacy, Model.pharmacy, "Select Pharmacy", new { style = "width:200px; height :30px" })

Dose               @Html.DropDownListFor(Model => Model.dosage, Model.dosage, "Select Dose", new { style = "width:200px; height :30px" })

    </form>

        <button class="button" style="height:30px;" id="a" >Insert</button>      <button class="button" style="height:30px;" id="b">Update</button>      <button class="button" style="height:30px;" id="c">Delete</button>


问:
Unable to build gRPC ManagedChannel with scala
I try to create a gRPC client. For

```<code>val channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext(true).build
</code>```

I get this compile time error

```<code>Error:(18, 87) value build is not a member of ?0
    val channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext(true).build
</code>```

gRPC is built for Java. My project is multi-module maven project, where for protobuf files and generated code is in a separate module.

答:
I managed to solve this issue by adding redundant casting</p>

```<code> val channel = ManagedChannelBuilder
    .forAddress(host, port)
    .usePlaintext(true)
    .asInstanceOf[ManagedChannelBuilder[_]].build
</code>```

Body:
I try to create a gRPC client. For

val channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext(true).build

I get this compile time error

Error:(18, 87) value build is not a member of ?0
    val channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext(true).build

gRPC is built for Java. My project is multi-module maven project, where for protobuf files and generated code is in a separate module.

Body:
I managed to solve this issue by adding redundant casting

 val channel = ManagedChannelBuilder
    .forAddress(host, port)
    .usePlaintext(true)
    .asInstanceOf[ManagedChannelBuilder[_]].build