text:
Q: Excel interprets percentage inputs inconsistently I am inputting numbers into a cell that is formatted to display the number as percentage.
I desire to enter 10%, so I type "10" into the cell and hit Enter. The cell now displays 10% (great).
I desire to enter 0.2%, so I type "0.2" into the cell and hit Enter. However, now the cell displays 20%!
This behavior seems inconsistent. Is there are way to ensure it always behaves as the former?
If I type "0.2%" and hit Enter I get what I desire, but this is slightly tedious because I can't use the numpad for fast input. Also, there is a good chance I'll forget to add the "%" manually and input data incorrectly.

A: Please specify what version of Excel you are using.

*

*When I do what you describe in Excel 2013, I get the desired result;
i.e., if I enter "0.2", I get "0.20%".
If I enter ".2", without the leading zero, I get "20.00%".
So, if you made an error when typing your question,
and you typed ".2" when you got "20.00%",
then the answer is to always type the leading zero
when entering a value less than 1%.
This allows you to keep your hand on the numeric keypad.
But still has the drawback that you have to remember to do it every time,
and if you forget to do it, Excel will happily, quietly (with no warning)
give you the wrong answer.

*Another approach is not to format the cells as Percentage
until after you've done the data entry.
Leave them with the default format ("General"),
or format them as Number, if you prefer.
Enter the numbers you want,
e.g., "20", "17", "10", "7.2", "2", ".2", etc.
Then, when you're done, divide them all by 100 and format them as Percentage.
This should solve your problem if your workflow calls for a data entry phase,
followed by some sort of analysis / display phase
in which the percentages are unchanged.
If your workflow requires frequent updating of the percentages,
this might not be helpful.

How do you do the same arithmetic operation (e.g., divide by 100)
to a range of cells?
Here's a couple of ways.
(I'll assume that the numbers that you want to manipulate
are in cells A2:A100.)

*

*Pick a column that you aren't using; say, Q.
Enter =A2/100 in cell Q2 and drag/fill down to Q100.
Then copy cells Q2:Q100 and paste values into A2:A100.

*Pick a cell that you aren't using; say, Q17.
Enter 100 in cell Q17 and "Copy" it.
Then select cells A2:A100
and do "Paste" → "Paste Special" → "Divide".
In either case you will probably need to press Esc
to dismiss the selection.
You might then also want
to clear the cell(s) you used temporarily.
Both of these approaches have the issue
that blank cells will be turned into zeroes.
Ways of addressing this issue are discussed
in Display Blank when Referencing Blank Cell in Excel.

*Yet another approach is to maintain two columns in perpetuity.
Pick a column that you aren't using.
For example, if your percentage numbers are in Column P,
then you might choose Column Q (or AP).
Enter =Q2/100 in cell P2, format as Percentage,
and drag/fill down.
Then enter your raw data (i.e., the numbers ranging from 0 to 100)
into Column Q
(which you will have left as "General", or formatted as "Number").
Do all your edits in Column Q.
Hide the extra column when you want to print.

A: Excel has a setting for 'smart percentages' - if this is on, it tries to think for you.
If you enter 10, it thinks 'you probably don't mean 1000%, so it should be 10%'; if you enter .2, it thinks 'you probably don't mean 0.2%, so it should be 20%'.
Switch the setting to off, and the behavior is consistent for all entries (it will always multiply by 100 to show percentages, so 10 will give 1000%)


text:
Q: Today App Extension Playing for Video is working fine but when trying to play Audio is not working properly in ios swift In my Today App Extension video is playing properly but when trying to play Audio from url is not working.

*

*For Playing video from url Code is below working fine.
func playVideo() {

    let videoURL = NSURL(string: "http://jplayer.org/video/m4v/Big_Buck_Bunny_Trailer.m4v")
    let player = AVPlayer(url: videoURL! as URL)
    let playerViewController = AVPlayerViewController()
    playerViewController.player = player
    self.present(playerViewController, animated: true) {
        playerViewController.player!.play()
    }
}

*but for Playing Audio from url in not working
func playAudio()

    var player:AVPlayer?
    var playerItem:AVPlayerItem?
    let url = URL(string: "https://s3.amazonaws.com/kargopolov/kukushka.mp3")
    let playerItem:AVPlayerItem = AVPlayerItem(url: url!)
    player = AVPlayer(playerItem: playerItem)

    let playerLayer=AVPlayerLayer(player: player!)
    playerLayer.frame=CGRect(x:0, y:0, width:100, height:100)
    self.view.layer.addSublayer(playerLayer)

    if player?.rate == 0 {
        player!.play()
    } else {
        player!.pause()
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to send emergency alerts from server to android app in realtime when app is closed? Using foreground service or by using other channel? Current Implentation:
When event is generated at server I am sending notifications to android app using FCM, some notification are with normal priority and some with high priority.
When notifications with high priority are sent to android app, app trigger custom alarms with sound to inform user about event.
It is working in android 5,6,7 without any issues.
Issue:
In phones with android 8+ I am facing issue of late notification due to Doze mode and App Stanby mode, so notifications are sent on time but received late on phone with delay of 20-25 minutes
What I have tried:
I have done all required settings like keeping Power saving disabled, Keep app rinning in background, Autostart enabled, Priority notification are enabled,
Also sending notifications with normal and high priority but still issue not resolved.
I have tried using foreground service but that remains active untill app is open, as soon as app is closed service stops.
How to send emergency alerts from server to android app in realtime even when app is closed? Using foreground service or by using other channel?


text:
Q: Connection via tracepath but not via telnet EDIT:
I have problems sending emails with Thunderbird. IMAP connection works without problems, but SMTP is not connecting. I have tried different settings:
No connection security (port 25), STARTTLS (port 587), but none is connecting to the server.
When I try to connect via telnet I get a timeout: telnet smtp.develman.de 25 resp. telnet smtp.develman.de 587
I have tried to connect via telnet with an online service and the connection was successfull: http://www.adminkit.net/telnet.aspx
Now I have installed wireshark to log the TCP traffic. I do not get any TCP SYN-ACK, only a TCP Retransmission.
I do not know, where the problem is. I also tried to disable clam av but without any success. My system is Archlinux.

A: Strange question from a fellow Archer...
It appears the site you mention is not accepting telnet connections. You may easily confirm that with nmap, or even with sites like http://ismyportopen.com/. You may do the same with e-mail ports, which you can find here. If the ports are closed, it becomes obvious why you can reach the site, but it does not act upon your requests.

A: I found the solution:
My router was blocking all smtp-server except smtp-servers configured as permitted servers in the router settings. I have added my smtp-server to the list and now it works.


text:
Q: Git Clone: Could not resolve branch/origin I'm new to Git and am trying to clone a repository on my local using Github Desktop.
However I get an error when I try to do this. If I check the log it ends with the error:

GetBranch`1|Could not resolve branch origin/drupal-dev-env

Googling this reveals nothing useful (to me, with my level of understanding).
Would anyone know what's going on?

A: It is possible the default branch of the remote repo is one which does not exist in the remote repo.
Try to clone that repo in command line, and see if you can list the branches actually fetched (even if the clone fail to checkout any branch) with:
git branch -avv


text:
Q: how can i return all the variables to to_html() at once?    def upload_file():
    if request.method == 'POST':
        print(request.files['file'])
        f = request.files['file']
        data_xls = pd.read_excel(f)
        df2 = data_xls.reset_index()
        p = df2.dropna(axis=1 , how='all')
        name_filter = df2[df2['Pensioner Name'].astype(str).str.match('^[a-zA-Z\s\.]*$')]
        cnic_filter = df2[df2['CNIC'].astype(str).str.match('^[\'][0-9+]{5}-[0-9+]{7}-[0-9]{1}[\']$')]
        wallet_filter = df2[df2['Wallet Account No'].astype(str).str.contains('^[0-9+]{8}$')]
        mobile_filter = df2[df2['Mobile Number'].astype(str).str.contains('^[3+][0-9+]{9}$')]

        filterf = df2[[name_filter , cnic_filter, wallet_filter,  mobile_filter]]
        filterf = pd.DataFrame(filterf)
        return filterf.to_html()

I am trying this but getting an error

ValueError: cannot copy sequence with size 62 to array axis with dimension 11

Please help i am new to pandas

A: I would parse it to JSON or XML.
It is easy to handle both in Python (https://www.w3schools.com/python/python_json.asp) and JS/PHP/Whatever.


text:
Q: Extract objects with specific date from custom object Array I have an ordered array of Availability object which is a class containing two attributes, startAt and endAt.
I'd like to extract from my availability array the objects from a specific day without taking into account the time.
I'd also like to use NSPredicate instead of "for" loop to do it.
Could you help me?
Thanks

A: for-in loop actually faster than NSPredicate for me, and easier since u can convert it to string or extract it for easy compare, but if u want then the format should be:
@"(%@ >= %@) AND (%@ <= %@)", dateForCompare, dayStart, dateForCompare, dayEnd where dayStart is the date to compare at 00:00:00, dayEnd is the date to compare at 23:59:59, tweak it base on your needs, u have to do this because a NSDate object contain exact date and time
Hope it help

A: if you are using timestamp(NSNumber) to store startAt and endAt then you can use predicate as bellow (to fetch all object whose start date is greter then current date)
NSPredicate *pred = [NSPredicate predicateWithFormat:@"startAt > %@", [NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]]];
NSArray *filteredArr = [yourArray filteredArrayUsingPredicate:pred];

and if you are using only date string then you can use
NSPredicate *pred = [NSPredicate predicateWithFormat:@"startAt = %@", @"your date string must be same as formate you saved in array"];

and if you are using only date string then you can use


text:
Q: Bootstrap apply nav-stacked if small screen Let's say we have a simple navigation bar like this:
http://getbootstrap.com/components/#nav-pills

Home

Profile

Messages

How can I add the class "nav-stacked" to it when the window or parent element is smaller than say 940px. Or even better: as soon as the navigation bar can't fit all elements in the same line anymore.
This would be pretty straight forward in javascript, but I'd like to see a pure css/html solution, but without adding @media queries to the bootstrap source code.

A: Found the solution. There is a class called "nav-justified". It simply stacks the navigation pills as soon as they don't fit into a single row anymore.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

Home

Profile

Messages

A: Try to add this CSS to your solution. Please check the result. Is it what you want to achieve?

@import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css');

@media (min-width: 768px) {
  .nav-justified > li {
    display: inline-block;
    width: auto;
  }
}

Home

Profile

Messages

Profile

Messages

Profile

Messages

Profile

Messages

Profile

Messages

Profile

Messages

Profile

Messages

Profile

Messages

Profile

Messages

Profile

Messages

Profile

Messages

Profile

Messages

Profile

Messages

Profile

Messages

Profile

Messages

Profile

Messages

Profile

Messages

Profile

Messages

Profile

Messages

Profile

Messages

Profile

Messages

Profile

Messages

Profile

Messages


text:
Q: Unable to assign a global variable to a drop down change event using Javascript I see that variations of this question has been asked several times before but none of the solutions seem to work for me unfortunately. I'm still a beginner in JavaScript hence I'm not sure what's happening here to debug this properly and what exactly to read up in the documentation.
Basically, I want to access and store the selected value of a drop down list inside a change event handler.
In my current approach, I am able to output the change event inside the event handler. But I cannot seem to assign it to a global variable outside of it, which I require for some other parts in my code.
Here is my MWE:
let dd = document.getElementById('dropDownMenu')
let dropDownChoice;

dd.addEventListener('change', function(e){
  dropDownChoice = e.target.value;
  console.log(dropDownChoice); // This outputs the selected item whenever the drop down is changed
});

console.log(dropDownChoice) // This does not output anything

A: It's not outputting anything becasue that line is executed before you make a selection. If you add a button and call a function by clicking it after you select, you will see that the value is there:
document.querySelector('button').addEventListener('click', () => console.log(dropDownChoice))


text:
Q: Caching/Etag for Static Action in Rails 4 Since Rails 4 removed page caching and action caching, I'm wondering what is the Rails 4 way to cache an action that has no variables and has only html in the view? Should I fragment cache the static html in the view? How do I set an etag/fresh_when when there is no model to set it to expire with? I'm struggling to find an example or convention to caching what should be the easiest page to cache.
One note is that while the view is completely static, the page still has a dynamic navbar depending on whether the user is signed in or not. How would you handle a static page like this without resorting to action caching since its been removed and the convention has been set not to use the gem version?
Example:
class HomesController < ApplicationController
  def index
  end
end

homes/index.html.erb

A bunch of normal html tags with no erb

Edit:
Based on @severin's answer and my own research, here is what I have come up with so far.
class HomesController < ApplicationController
  def index
    fresh_when(["some-identifier", current_user, flash])
  end
end

In addition, I'm using https://github.com/n8/bust_rails_etags to reset all etags after a deploy because the view may have changed between deploys. I think this covers the etag fairly well although I'm still curious whether fresh when will include some identifier about the view automatically and whether "some-idnetifier" is necessary? Is it going to be a problem that sometimes current_user and flash will be nil?
Now on the second point of fragment caching the static content. I'm assuming if I did:
cache "v1" do
  all my html
end

I'd have to remember to always change the cache identifier when the page is changed otherwise my app would serve stale content. Any way to automate this as well or is already handled by rails? It would be nice to just cache the last time the view was updated or something clever so I don't have to keep track on when my static content is changed.

A: You can set an etag/last modified at data without a model, check the documentation: http://api.rubyonrails.org/classes/ActionController/ConditionalGet.html#method-i-fresh_when
So you could do something like:
def index
  fresh_when(:etag => 'some_made_up_etag', :last_modified => a_long_time.ago, :public => true)
  render
end

Note: you don't need to provide an etag AND a last modified at timestamp, you could just provide an etag or only a last modified at timestamp.
In addition to this, I would also fragment cache the whole content of the view.
Or you could just continue using action-/page_caching using the official plugin/gem: https://github.com/rails/actionpack-page_caching

Some additions regarding the second part of your question:
Rails adds the content of the RAILS_CACHE_ID environment variable to all its cache keys (the etag and the fragment cache key in your example). The bust_rails_etags gem adds another environment variable that affects only the etags... So in your case you could just remove the bust_rails_etags gem and update the RAILS_CACHE_ID environment variable on all your deploys.
You can even automate the updating of the RAILS_CACHE_ID environment variable by adding something like this in config/environment.rb:
code_revision = # ... some piece of code that gets the current revision.
                # I'm using git and I use the following (crude) piece of
                # to get the current revision:
                # code_revision = `git log --pretty=format:%h -n1`.strip
ENV['RAILS_CACHE_ID'] = code_revision

This way, the current code revision is always added to all cache keys.


text:
Q: Disable ActiveMQ demo component Is it possible to disable the demo component of the Active MQ console? I have tried removing the following lines from jetty.xml but the /demolink still works.
<bean class="org.eclipse.jetty.webapp.WebAppContext">
    <property name="contextPath" value="/demo" />
    <property name="resourceBase" value="${activemq.home}/webapps/demo" />
    <property name="logUrlOnStart" value="true" />
</bean>

I am using Active MQ 5.5.1

A: In the end I deleted the folder webapps/demo, which has solved the problem.


text:
Q: Jenkins file with kubernenetes sonar build stage I am using Angular application for front end code, along with jenkins file docker image push into container registry after that we will deploy the code into the Kubernetes cluster.
stage('Deploy') {
        container('kubectl') {
          withCredentials([file(credentialsId: 'KUBE_CONFIG', variable: 'KUBE_CONFIG')]) {
            def kubectl
            echo 'deploy to deployment!'
              if(gitBranch == "master") {
                 kubectl = "kubectl --kubeconfig=${KUBE_CONFIG} --context=K8sCluster-testenv"
                echo 'deploy to testenv environment!'
                sh "${kubectl} apply -f ./infrastructure/testenv -n=testenv"
                messageInfo = "app is deployed to testenv"
              }

Now the question is, I need to add one more build stage to run sonar scanner to check the code quality after the successful deployment.
can you please someone help me with this.


text:
Q: will work out how far apart two letters are in the alphabet The program will then work out the difference between the positions of the two letters of the
alphabet, and display this to the screen. For example, the difference between "a" and "e" is 4. The
difference between "d" and "b" is 2. The difference between "c" and "c" is 0.
this is what I did but I don't know how to count the gap between the letters
SECTION .bss
SECTION .data
tMsg: db "fist letter",10
tLen: equ $-tMsg
Input: times 100 db 0
ok: db "ok"
oklen: equ $-ok
yMsg: db "Second letter",10
yLen: equ $-yMsg
SECTION .text
global _start

   _start:
   nop
   mov eax,4
   mov ebx,1
   mov ecx,tMsg
   mov edx,tLen
   int 80H

   mov eax,3
   mov ebx,0
   mov ecx,Input
   mov edx,100
   int 80H

   mov ax, [Input]
   mov bx, [ok]
   cmp ax, bx
   je y
   mov eax,1
   mov ebx,0
   int 80H

   y:
   mov eax,4
   mov ebx,1
   mov ecx,yMsg
   mov edx,yLen

   int 80H
   mov eax,1
   mov ebx,0
   int 80H

A: If you are still stuck, you question requires that you determine the distance between two characters. That brings with it a number of checks you must implement. Though your question is silent on whether you need to handle both uppercase and lowercase distances, unless you are converting everything to one case or the other, you will need to determine whether both characters are of the same case to make the distance within the alphabet between those two characters valid.
Since two characters are involved, you need a way of saving the case of the first for comparison with the case of the second. Here, and in all cases where a simple state is needed, just using a byte (flag) to store the state is about as simple as anything else. For example, a byte to hold 0 if the ASCII character is not an alpha character, 1 if the character is uppercase and 2 if the character is lowercase (or whatever consistent scheme you like)
That way, when you are done with the comparisons and tests, you can simply compare the two flags for equality. If they are equal, you can proceed to subtract one from the other to get the distance (swapping if necessary) and then output the number converting the number to ASCII digits for output.
To test if the character is an uppercase character, similar to isupper() in C, a short function is all that is needed:
; check if character isupper()
; parameters:
;   ecx - address holding character
; returns;
;   eax - 0 (false), 1 (true)
_isupr:

    mov eax, 1                  ; set return true

    cmp byte[ecx], 'A'          ; compare with 'A'
    jge _chkZ                   ; char >= 'A'

    mov eax, 0                  ; set return false
    ret

  _chkZ:
    cmp byte[ecx], 'Z'          ; compare with 'Z'
    jle _rtnupr                 ; <= is uppercase

    mov eax, 0                  ; set return false

  _rtnupr:
    ret

You can handle the storage for the local arrays and values you need in a couple of ways. You can either subtract from the current stack pointer to create temporary storage on the stack, or in a slightly more readable way, create labels to storage within the uninitialized segment (.bss) and use the labels as variable names. Your initialized variables go in the .data segment. For example, storage for the program could be:
section .bss

    buf     resb 32             ; general buffer, used by _prnuint32
    bufa    resb 8              ; storage for first letter line
    bufb    resb 8              ; storage for second letter line
    lena    resb 4              ; length of first letter line
    lenb    resb 4              ; length of second letter line
    nch     resb 1              ; number of digit characters in _prnuint32
    ais     resb 1              ; what 1st char is, 0-notalpha, 1-upper, 2-lower
    bis     resb 1              ; same for 2nd char

Rather than using numbers sprinkled through your syscall setups, declaring initialized labels for, e.g. stdin and stdout instead of using 0 and 1 make things more readable:
section .data

    bufsz:  equ 32
    babsz:  equ 8
    tmsg:   db "first letter : "
    tlen:   equ $-tmsg
    ymsg:   db "second letter: "
    ylen:   equ $-ymsg
    dmsg:   db "char distance: "
    dlen:   equ $-dmsg
    emsg:   db "error: not alpha or same case", 0xa
    elen:   equ $-emsg
    nl:     db 0xa
    stdin:  equ 0
    stdout: equ 1
    read:   equ 3
    write:  equ 4
    exit:   equ 1

Then for your reading your character input, you would have, e.g.
    mov     eax, write          ; prompt for 1st letter
    mov     ebx, stdout
    mov     ecx, tmsg
    mov     edx, tlen
    int 80h                     ; __NR_write

    mov     eax, read           ; read 1st letter line
    mov     ebx, stdin
    mov     ecx, bufa
    mov     edx, babsz
    int 80h                     ; __NR_read

    mov     [lena], eax         ; save no. of character in line

To then check the case of the character input, you could do:
    call    _isupr              ; check if uppercase
    cmp     eax, 1              ; check return 0-false, 1-true
    jne chkalwr                 ; if not, branch to check lowercase

    mov     byte[ais], 1        ; set uppercase flag for 1st letter

    jmp getb                    ; branch to get 2nd letter

  chkalwr:
    call    _islwr              ; check if lowercase
    cmp     eax, 1              ; check return
    jne notalpha                ; 1st letter not alpha char, display error

    mov     byte[ais], 2        ; set lowercase flag for 1st char

The notalpha: label just being a block to output an error in case the character isn't an alpha character or the case between the two characters don't match:
  notalpha:                     ; show not alpha or not same case error
    mov     eax, write
    mov     ebx, stdout
    mov     ecx, emsg
    mov     edx, elen
    int 80h                     ; __NR_write

    mov     ebx, 1              ; set EXIT_FAILURE

After you have completed input and classification of both characters, you now need to verify whether both character are of the same case, if so you need to compute the distance between the characters (swapping if necessary, or using an absolute value) and finally handle the conversion of the distance between them from a numeric value to ASCII digits for output. You can do something similar to the following:
  chkboth:
    mov     al, byte[ais]       ; load flags into al, bl
    mov     bl, byte[bis]
    cmp     al, bl              ; compare flags equal, else not same case
    jne notalpha

    mov     eax, write          ; display distance output
    mov     ebx, stdout
    mov     ecx, dmsg
    mov     edx, dlen
    int 80h                     ; __NR_write

    mov     al, byte[bufa]      ; load chars into al, bl
    mov     bl, byte[bufb]
    cmp     al, bl              ; chars equal, zero difference

    jns getdiff                 ; 1st char >= 2nd char

    push    eax                 ; swap chars
    push    ebx
    pop     eax
    pop     ebx

  getdiff:
    sub     eax, ebx            ; subtract 2nd char from 1st char
    call _prnuint32             ; output difference

    xor     ebx, ebx            ; set EXIT_SUCCESS
    jmp     done

Putting it altogether and including the _prnuint32 function below for conversion and output of the numeric distance between characters, you would have:
section .bss

    buf     resb 32             ; general buffer, used by _prnuint32
    bufa    resb 8              ; storage for first letter line
    bufb    resb 8              ; storage for second letter line
    lena    resb 4              ; length of first letter line
    lenb    resb 4              ; length of second letter line
    nch     resb 1              ; number of digit characters in _prnuint32
    ais     resb 1              ; what 1st char is, 0-notalpha, 1-upper, 2-lower
    bis     resb 1              ; same for 2nd char

section .data

    bufsz:  equ 32
    babsz:  equ 8
    tmsg:   db "first letter : "
    tlen:   equ $-tmsg
    ymsg:   db "second letter: "
    ylen:   equ $-ymsg
    dmsg:   db "char distance: "
    dlen:   equ $-dmsg
    emsg:   db "error: not alpha or same case", 0xa
    elen:   equ $-emsg
    nl:     db 0xa
    stdin:  equ 0
    stdout: equ 1
    read:   equ 3
    write:  equ 4
    exit:   equ 1

section .text

    global _start:
_start:

    mov     byte[ais], 0        ; zero flags
    mov     byte[bis], 0

    mov     eax, write          ; prompt for 1st letter
    mov     ebx, stdout
    mov     ecx, tmsg
    mov     edx, tlen
    int 80h                     ; __NR_write

    mov     eax, read           ; read 1st letter line
    mov     ebx, stdin
    mov     ecx, bufa
    mov     edx, babsz
    int 80h                     ; __NR_read

    mov     [lena], eax         ; save no. of character in line

    call    _isupr              ; check if uppercase
    cmp     eax, 1              ; check return 0-false, 1-true
    jne chkalwr                 ; if not, branch to check lowercase

    mov     byte[ais], 1        ; set uppercase flag for 1st letter

    jmp getb                    ; branch to get 2nd letter

  chkalwr:
    call    _islwr              ; check if lowercase
    cmp     eax, 1              ; check return
    jne notalpha                ; 1st letter not alpha char, display error

    mov     byte[ais], 2        ; set lowercase flag for 1st char

  getb:
    mov     eax, write          ; prompt for 2nd letter
    mov     ebx, stdout
    mov     ecx, ymsg
    mov     edx, ylen
    int 80h                     ; __NR_write

    mov     eax, read           ; read 2nd letter line
    mov     ebx, stdin
    mov     ecx, bufb
    mov     edx, babsz
    int 80h                     ; __NR_read

    mov     [lenb], eax         ; save no. of character in line

    call    _isupr              ; same checks for 2nd character
    cmp     eax, 1
    jne chkblwr

    mov     byte[bis], 1

    jmp chkboth

  chkblwr:
    call    _islwr
    cmp     eax, 1
    jne notalpha

    mov     byte[bis], 2

  chkboth:
    mov     al, byte[ais]       ; load flags into al, bl
    mov     bl, byte[bis]
    cmp     al, bl              ; compare flags equal, else not same case
    jne notalpha

    mov     eax, write          ; display distance output
    mov     ebx, stdout
    mov     ecx, dmsg
    mov     edx, dlen
    int 80h                     ; __NR_write

    mov     al, byte[bufa]      ; load chars into al, bl
    mov     bl, byte[bufb]
    cmp     al, bl              ; chars equal, zero difference

    jns getdiff                 ; 1st char >= 2nd char

    push    eax                 ; swap chars
    push    ebx
    pop     eax
    pop     ebx

  getdiff:
    sub     eax, ebx            ; subtract 2nd char from 1st char
    call _prnuint32             ; output difference

    xor     ebx, ebx            ; set EXIT_SUCCESS
    jmp     done

  notalpha:                     ; show not alpha or not same case error
    mov     eax, write
    mov     ebx, stdout
    mov     ecx, emsg
    mov     edx, elen
    int 80h                     ; __NR_write

    mov     ebx, 1              ; set EXIT_FAILURE

  done:
    mov     eax, exit           ; __NR_exit
    int 80h

; print unsigned 32-bit number to stdout
; arguments:
;   eax - number to output
; returns:
;   none
_prnuint32:
    mov     byte[nch], 0        ; zero nch counter

    mov     ecx, 0xa            ; base 10  (and newline)
    lea     esi, [buf + 31]     ; load address of last char in buf
    mov     [esi], cl           ; put newline in buf
    inc     byte[nch]           ; increment char count in buf

_todigit:                       ; do {
    xor     edx, edx            ; zero remainder register
    div     ecx                 ; edx=remainder = low digit = 0..9.  eax/=10

    or      edx, '0'            ; convert to ASCII
    dec     esi                 ; backup to next char in buf
    mov     [esi], dl           ; copy ASCII digit to buf
    inc     byte[nch]           ; increment char count in buf

    test    eax, eax            ; } while (eax);
    jnz     _todigit

    mov     eax, 4              ; __NR_write from /usr/include/asm/unistd_32.h
    mov     ebx, 1              ; fd = STDOUT_FILENO
    mov     ecx, esi            ; copy address in esi to ecx (addr of 1st digit)
                                ;  subtracting to find length.
    mov     dl, byte[nch]       ; length, including the \n
    int     80h                 ; write(1, string,  digits + 1)

    ret

; check if character islower()
; parameters:
;   ecx - address holding character
; returns;
;   eax - 0 (false), 1 (true)
_islwr:

    mov eax, 1                  ; set return true

    cmp byte[ecx], 'a'          ; compare with 'a'
    jge _chkz                   ; char >= 'a'

    mov eax, 0                  ; set return false
    ret

  _chkz:
    cmp byte[ecx], 'z'          ; compare with 'z'
    jle _rtnlwr                 ; <= is lowercase

    mov eax, 0                  ; set return false

  _rtnlwr:
    ret

; check if character isupper()
; parameters:
;   ecx - address holding character
; returns;
;   eax - 0 (false), 1 (true)
_isupr:

    mov eax, 1                  ; set return true

    cmp byte[ecx], 'A'          ; compare with 'A'
    jge _chkZ                   ; char >= 'A'

    mov eax, 0                  ; set return false
    ret

  _chkZ:
    cmp byte[ecx], 'Z'          ; compare with 'Z'
    jle _rtnupr                 ; <= is uppercase

    mov eax, 0                  ; set return false

  _rtnupr:
    ret

There are many ways to write the varying pieces and this is intended to fall more on the easier to follow side than the most efficient way it can be written side.
Example Use/Output
After you compile and link the code, e.g.
nasm -f elf -o ./obj/char_dist_32.o char_dist_32.asm
ld -m elf_i386 -o ./bin/char_dist_32 ./obj/char_dist_32.o

You can test with the inputs given in your question and others, e.g.
$ ./bin/char_dist_32
first letter : a
second letter: e
char distance: 4

$ ./bin/char_dist_32
first letter : d
second letter: b
char distance: 2

$ ./bin/char_dist_32
first letter : D
second letter: B
char distance: 2

$ ./bin/char_dist_32
first letter : a
second letter: Z
error: not alpha or same case

Look things over and let me know if you have further questions.

A: It's as simple as abs(c1 - c2).  You can subtract the ASCII codes; the +'a' part will cancel out.
Or if you want case-insensitive, force the chars to lower-case first with c1|=0x20.  See What is the idea behind ^= 32, that converts lowercase letters to upper and vice versa? (which also provides an efficient way to check if the inputs are alphabetic along with converting to lower case, resulting in a 0..25 position in the alphabet).
Printing out a number as a decimal ASCII string of digits is covered in How do I print an integer in Assembly Level Programming without printf from the c library? for the general case.  We can simplify if we can assume a 2-digit number, even moreso if we don't mind printing a leading zero.

Just for fun, let's see how simple we can make this.  Well maybe not always "simple", but compact and minimalist.  There's less code to understand, but some of the steps aren't the way I'd expect a beginner to do it.  (e.g. 2 chars in different positions of the same register, and using the AH:AL result of 8-bit DIV as a string.)
For starters we'll take both characters on the same line as part of the same read system call.  (Command line args are also simple, but more simple if you don't check argc and just crash if they aren't supplied.)
I left out printing prompts because that's boring and can be done if you want.
SYS__exit   equ 1
SYS_read   equ 3
SYS_write  equ 4

section .text          ; optional, already the default section
global _start
_start:
   sub  esp, 32        ; reserve some stack space.  I only ended up using 4 bytes

   mov  eax, SYS_read
   xor  ebx, ebx       ; ebx=0 = stdin
   mov  ecx, esp
   mov  edx, 4         ; long enough to get 2 chars and a newline with room to spare
   int  0x80           ; read(STDIN_FILENO, stackbuf, 4)

   movzx eax, word [ecx]  ; load both chars into AL and AH
   or    eax, 0x2020      ; force them both to lower case, operating on AL and AH at once
    ;;; if you want to check for non-alphabetic chars, add code here
   sub   al, ah           ; subtract ASCII codes
   jns  .done_abs         ; jump if result wasn't negative
    neg   al               ; AL = abx(al)
   .done_abs:

   movzx eax, al          ; clear AH
   mov   dl, 10
   div   dl               ; AL = diff/10 (leading digit)  AH = diff%10 (least significant digit)
   add   eax, `00\n`      ; 0..9 integer digits to ASCII codes and append a newline
   mov   [ecx], eax       ; store ASCII chars back into the same stack buffer

   mov   eax, SYS_write
   mov   ebx, 1           ; stdout
   ;mov  ecx, esp         ; still set
   mov   edx, 3           ; 2-digit number + newline, maybe including leading zero
   int   0x80             ; write(1, stackbuf, 3)

   mov   eax, SYS__exit
   xor   ebx, ebx
   int   0x80            ; _exit(0)

Fun fact: despite using partial registers, this mostly avoids partial-register stalls.  (Except for adding to EAX after div dl writes AX.)  If you were actually optimizing for performance, you'd use a multiplicative inverse. (https://codereview.stackexchange.com/questions/142842/integer-to-ascii-algorithm-x86-assembly)
Test cases:
$ nasm -felf32 -Worphan-labels char-diff.asm &&
 ld -melf_i386 -o char-diff char-diff.o

$ ./char-diff
ab
01
$ ./char-diff
Ax
23
$ ./char-diff
Aa
00
$ ./char-diff
Xa
23
$ ./char-diff
xA
23


text:
Q: How can I secure a Spyne web service with SSL? I'm trying to get a SOAP web service set up with Spyne.  So far, so good.  I have a web service,but not I need to secure the data in-flight with SSL.  Is there a way to attach a certificate to the Spyne app so my connection is encrypted?
Thank you!
I've looked at the help guides on Spyne.io and have not found the info I need about SSL.

A: You need to use either a reverse proxy setup (like nginx) that will terminate the SSL connection outside of the Python process (recommended) or you have to use OpenSSL (or similar) bindings to create an SSL socket for yourself.
You can use twisted's ssl capabilities via the WsgiApplication. Have a look: https://twisted.readthedocs.io/en/twisted-17.9.0/web/howto/using-twistedweb.html


text:
Q: MQ service process pointing to uninstalled instances We recently migrated our v8 mq to v9.1 on same server, after migrating we uninstalled the v8 packages. We realized after uninstalling that there are still '/opt/mqm/samp/bin/amqsclm' processes running that point to the uninstalled version directory (v9.1 was installed in a separate dir). I did update the services pertaining to those process to v9.1 installation directory but not sure how to restart those process without restarting the queue manager because the planned downtime window is a couple of weeks away.
I do not have much experience with mq service.
If I let those zombie processes keep running for a couple of weeks how will it impact my MQ service?
If I just kill those processes and start them immediately will it disturb any queue/qm activity?

A: The amqsclm program is not part of the queue manager. So it is safe to stop/restart it, that will not stop your queue manager.
It is a sample program for monitoring cluster queues and changing cluster workload balancing depending on whether the queue is opened or not:
Documentation of amqsclm


text:
Q: Is that possible to get customer attribute in custom grid? Here i m create one customer attribute.
Using custom module i want to change customer attribute.
Now i want that customer attribute column in my custom grid
in my custom table i m saving customer id.
So is it possible?

I want this attribute in my custom module grid

A: This is work for me
$collection = Mage::getModel("module/model")->getCollection();
        $attributeId = Mage::getResourceModel('eav/entity_attribute')->getIdByCode('customer', '[your attribute name]');
        $collection->getSelect()->join(array('l' => 'customer_entity_int'),
                'main_table.customer_ids = l.entity_id');
        $collection->getSelect()->where('l.attribute_id =?',$attributeId);
        $collection->load();


text:
Q: How To Display HTML Tags Saved In Database Using Symfony 2 and Twig I've managed to build a page that will display data from the database dynamically. However, this code which is saved in the database:

This is the content for the radio page.

Displays like this:

This is the content for the radio page.

The HTML tags aren't rendered. I understand that Symfony (for security purposes) renders any HTML code like this for security reasons. I want Symfony (obviously) to render these HTML tags. How can I achieve this just for this purpose only, so that Symfony still sanitises any HTML tag that is saved to the database elsewhere on the site?
For your information as well, this is the code that I am using to pull the data from the database:
    public function mainpageAction($slug)
{

    $content = $this->getDoctrine()
        ->getRepository('SiteMainBundle:Content')
        ->find($slug);

    if (!$content) {
        throw $this->createNotFoundException('No product found for slug '.$slug);
    }

    return $this->render('SiteMainBundle:Default:page.html.twig', array('content' => $content, 'slug' => $slug));
}

Also, just so I can learn more about Symfony, is the rendering of the HTML tags just the sole job of PHP or could it be rendered properly using Twig?
Many thanks!

A: If you want to do that, you need to use the raw filter in the twig template. Like described in the twig documentation, the raw filter marks the value as safe which means that in an environment with automatic escaping enabled this variable will not be escaped if raw is the last filter applied to it.
In your case, it's : {{ content | raw }}


text:
Q: Signalr hub get caller client from controller How can i get the caller client (the client which is requesting the current action) from controller.
something like the following:
  public class ChatController : EntityController
  {
      public void RegisterClientAsAvailable()
      {
          var hub=Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.GetHubContext<ChatHub>();

          var callingClient = hub.Clients.Caller;

//And I want to pass additional parameters(which the client doesnt know about them) from `EntityController (base)` to this method:

          hub.RegisterClient(base.UserId,Session["something"],callingClient);
          //OR:
          hub.SayHelloToClient(base.UserId,Session["something"],callingClient);
      }
  }


text:
Q: Ecto: Retrieve all executed changesets during a transaction For a given Ecto transaction, how to improve it to automatically add SQL inserts to log all changed values from executed changesets ? Here are unsuccessful tries:
Using Ecto.Multi:

*

*Ecto.Multi.to_list is not a solution since the multi can contain Ecto.Multi.run operations (these operations are needed in case of dependencies between operations: for example when creating an account with its first user, we need to inject the account id in the user changeset).

*Adding a final Ecto.Multi.run that is responsible to automatically inject audit events is not possible too since the changes_so_far parameter are the results from the previous operations and not the changesets.
Using Repo.transaction() with a anonymous function does not return any changeset.

A: From https://groups.google.com/forum/#!topic/elixir-ecto/5M6VA8fg364:
There's no such feature currently, and I'm not in favour of adding it - this can be already achieved today without any changes to the API.
If I were to create a system doing this I would most probably wrap the Ecto.Multi functions in my own that would add the additional tracking - for example:
defmodule MyApp.Multi do

  def insert(multi, name, changeset) do
    multi
    |> Ecto.Multi.insert(name, changeset)
    |> Ecto.Multi.insert({:log, name}, build_log(changeset))
  end
end

This will allow you to keep the nice API of Ecto.Multi, while allowing you to do additional operations easily.


text:
Q: getHeaders() to get source ip address We are currently using a managed package UI .
Upon clicking of Account in service console , user is directed to the managed package UI and not any VF Page .
How can I get the value of UI using getHeaders()
 map<String, String> mapHeaders = ApexPages.currentPage().getHeaders();

and
 X-Salesforce-SIP

How can this be accomplished?

A: Please find below getheader() can return this.
host= ApexPages.currentPage().getHeaders().get('Host');
referer=ApexPages.currentPage().getHeaders().gete('Referer');
useragent=ApexPages.currentPage().getHeaders().get('User-Agent');
chipersuite=ApexPages.currentPage().getHeaders().get('Chipersuite');
forward=ApexPages.currentPage().getHeaders().get('X-Salesforce-Forwarded-To');
salesforceip= ApexPages.currentPage().getHeaders().get('X-Salesforce-SIP');

Header information details can be found here


text:
Q: Angular 2-Way data binding with currency pipe I have an currency input field that has to display data in a 2-way binding context. In other words, data from the model must be able to update the value, and data from the user must also be able to update the value.
My first attempt was something like this:
<input type="text" [(ngModel)]="price | currency">

This works fine in a one-way context. But whenever the user tries to edit the input, we get an error, EX:
"InvalidPipeArgument: '$123.00 is not a number' for pipe 'CurrencyPipe'"

This error makes sense, as the pipe is trying to apply the filter on the input value again, but the value this time around is our currency string, not a number.
I thought about trying to do something like this:
<input type="text" [ngModel]="price" (ngModelChange)="price = $event.target.value">

But the value here is going to be the same currency string as before. I guess I need to do something like undo_currency_filter($event.target.value), but I don't see any way to do this without writing a custom, and probably error prone method.
What would be the best way to accomplish this task in Angular, preferably without having to write a custom method such as described above?

A: I've figured out how to solve this in a somewhat elegant manner.
There's really no way around undoing the currency pipe, and there's nothing built in that does this. However, undoing it isn't as difficult as I would have thought. All you really have to do to covert the currency string back to a number is to remove the extra characters added by the filter. This can be done with a RegEx like this:
Number(currency.replace(/[^0-9.-]+/g,""))

So my template is now:
<input [ngModel]="price | currency" (change)="price = Number(price.replace(/[^0-9.-]+/g,''))">

(I should probably put that in the component file, but this illustrates the solution all right).
I hope this can help someone running into a similar issue.


text:
Q: How to setup Eclipse Plugin Profiler I want to use the Eclipse Plugin Profiler to profile my applications. However, I am facing problems while installing it. I copied the unzipped folder of the profiler into the plugins folder in the root eclipse folder. However when i open eclipse, run->run configurations-> and click on profiler, i receive the following error:
"An error has occurred. See error log for more details.
ru/nlmk/eclipse/plugins/profiler/launch/ProfilerTab"
I think there is a problem in the location of the profiler dll, but i don't know where to put it.
How do i make this plugin work? thank you in advance

A: The right steps for installation are defined at http://eclipsecolorer.sourceforge.net/index_profiler.html, and the DLL should be in your bin folder of your JRE installation.


text:
Q: Jung VoltageScorer - Which vertices to use as 'sources' & 'sinks'? I would like to evaluate the Voltage Scores of a Graphs' Vertices in Jung using VoltageScorer. (http://jung.sourceforge.net/doc/api/edu/uci/ics/jung/algorithms/scoring/VoltageScorer.html)
The problem I encounter is that to do so I have to provide 'source' and 'sink' Vertices, but do not know which vertices I am supposed to use as 'sources' and which as 'sinks'.
One of the Constructor Summary in the Documentation is:
VoltageScorer(Hypergraph<V,E> g, Collection<V> sources, Collection<V> sinks)
          Creates an instance with the specified graph, source vertices
                           (each of whose 'voltages' are tied to 1), and sinks.

Can someone provide an explanation of how to determine which vertices are ought to be used as 'sources' and which as 'sinks'?
Thank you for your time.

A: This is not a question which can be answered a priori; as with most questions of the form "which algorithm/approach should I use?", the answer is "it depends".
For some social network data sets, there are clear choices for which vertices to use as 'sources' and which as 'sinks'.
For others, there may be no such obvious distinctions.  In which case, it may not be appropriate to use this algorithm.
One option in the latter case is to run the algorithm a number of times with random choices of sources and sinks, and give each vertex a score which is based on the aggregate scores from each run.


text:
Q: Is an ActorRef updated when the associated Actor is restarted by the supervisor? If I create an logging actor like so
val logger: ActorRef =
    actorSystem.actorOf(Props(new Logger()))

and the logger restarts due to an Exception, my logger stops writing to disk.
I had been sending messages logger ! msg
Am I correct in assuming that the ActorRef did not update when the supervisor restarted my logging actor?

A: ActorRef should be properly updated by Akka to point to the new instance of an actor. The docs clearly state that:

A reference pointing to a terminated actor does not compare equal to
  a reference pointing to another (re-created) actor with the same path.
  Note that a restart of an actor caused by a failure still means that
  it is the same actor incarnation, i.e. a restart is not visible for
  the consumer of the ActorRef.

Also here:

When actorOf() is called it assigns an incarnation of the actor
  described by the passed Props to the given path. An actor incarnation
  is identified by the path and a UID. A restart only swaps the Actor
  instance defined by the Props but the incarnation and hence the UID
  remains the same.
The lifecycle of an incarnation ends when the actor is stopped. At
  that point the appropriate lifecycle events are called and watching
  actors are notified of the termination. After the incarnation is
  stopped, the path can be reused again by creating an actor with
  actorOf(). In this case the name of the new incarnation will be the
  same as the previous one but the UIDs will differ. ...
An ActorRef always represents an incarnation (path and UID) not
  just a given path. Therefore if an actor is stopped and a new one with
  the same name is created an ActorRef of the old incarnation will not
  point to the new one.

That's one of the main advantages of using ActorRefs, otherwise it would be much more inconvenient to work with actors.
You need to check your supervisor strategy and make sure that the actor is actually restarted.
Default strategy is:
final val defaultStrategy: SupervisorStrategy = {
  def defaultDecider: Decider = {
    case _: ActorInitializationException ⇒ Stop
    case _: ActorKilledException         ⇒ Stop
    case _: Exception                    ⇒ Restart
  }
  OneForOneStrategy()(defaultDecider)
}

Thus if you get an Exception your actor will be restarted and ActorRef should be valid, but if you get other types of Throwable then it will be stopped and ActorRef will become invalid.


text:
Q: Validate enhanced Rich Text Field on PreSaveAction call on newform in SP 2010 List Form How to validate Enhanced Rich Text Field on PreSaveAction call in my SP 2010 list form's newform.aspx.
I tried with JavaScript but it didn't work.
I followed Marc's blog  here
But the issue is, once it's validated successfully, I delete the  text contents again and re-enter the text contents again and tried to validate and it failed!
Also the field needs to be mandatory field.

A: Try using this code
$("td.ms-formlabel h3.ms-standardheader nobr:contains('Field Name')").parent().parent().parent().find("div.ms-inputBox div.ms-rtestate-write").text()

Replace the 'Field Name' token with column display name


text:
Q: how to parse dynamic json object in Typescript I have a json object in my typescript which is returned from server side. One of the keys is dynamic. How do I parse and extract the value for that key.
Ex: serverResponse.detailsLMN.allList
Ex :serverResponse.detailsLMN.deleteList

In the above , 'LMN' is dynamic.
It can be serverResponse.detailsLMN.allList or serverResponse.detailsPQR.allList.
Assuming,
const temp = 'LMN' or 'PQR', how can I use temp to parse JSON object here.
Like :  serverResponse.details{temp}.allList

A: Not sure if I understood your question correctly. But try doing
let data = JSON.parse(serverResponse);

((JSON.stringify(serverResponse)).includes("LMN")) ? serverResponse.detailsLMN.allList
: serverResponse.detailsPQR.allList

^The above code is the same as the if statement. If you don't know the ES6 ternary conditional statement then here's a link:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
To parse, simply use JSON.parse(). To extract the value, since I can't see the format of the output, it's better to console.log(serverResponse) the whole response and then walk through the Object in Chrome console to see how to get to your specific value.


text:
Q: Select box style in Android 2.3 different from Android 4.2 I am working on a PhoneGap app in which clicking on a button generates a specific number of text boxes and select boxes based on user's input.
I tested the app on an AVD running Android 4.2. Everything was working fine and the selectboxes generated along with text boxes looked as the image below:

Now, I tested the same app in an AVD running android 2.3 which gave me the output shown here:
.
Clearly, the select box alone appears weird in Android 2.3 while the other controls like text box and buttons are absolutely fine.
I don't have any clue why this is happening. The app uses JQM and Cordova 2.5.0.
To give you  some ground on what I am trying to explain, I have added the code below which is my select box markup
    <select class="sel" data-theme="a" id="selectmenu0">
         <option value="1">option1</option>
         <option value="2">option2</option>
         <option value="3">option3</option>
    </select>

A: I resolved the issue myself. The problem was with the way I generated the markup. For some unknown reason, Android 2.3 expects the DOM to be built before navigating to the next page where the generated DOM will be inserted.
But in my case, On receiving the input from the user, I did the following operations

*

*I navigated to the target page

*Then, I built the select box markup

For some reason, Android 2.3 expects the above steps to be in reverse order. Only then, JQM applies it's styling to select box.

A: I had the same problem and solved it by setting the parameter 'data-native-menu' to false, like this:
<select id="yourSelectBox" data-native-menu="false"></select>

I think this is simpler.


text:
Q: How to compare a value with a list of values I am trying to perform an assertion where every instance of a region id matches the region id that's put through in the request. As an example, if in the request put in the number '736', then for each instance of region id within the response they should all be '736'. However when i perform at the asset, it states it's false and i beleive it is because the output is within a list so the == does not work. How can i get the request and each item in the list form the response to match?
Below is the code:
def hotelregionid = json.regions.hotels.regionId
assert hotelregionid != null
def hotelregionid_request = messageExchange.modelItem.testStep.testCase.testSuite.getPropertyValue("regionid")
assert hotelregionid.every {it == hotelregionid_request} -- this is where the assertion fails.

log.info hotelregionid
log.info hotelregionid_request

The error message it outputs is:
assert hotelregionid.every {it == hotelregionid_request} | | | false [[xxx,xxxx,xxxx,xxxx,xxx,xxx,xxx,xxx,xxx]]

The log.info provided when i comment out the assert is the same number which I will value as xxx.:
[[xxx, xxx, xxx, xxx, xxx,xxx,xxx]] - this is for hotelregionid
xxx - this is for hotelregionid_request
RAW RESPONSE:
{
    "xxx": [{
        "regionId": xxx,
        "xxx": [{
                "xxx": [{

                    "regionId": xxx

                }],

                "xxx": xxx
            },

            {
                "xxx": [{
                    "regionId": xxx
                }],
                "xxx": xxx
            }
        ]

    }]

Thank you

A: Here is the script assertion.
Note that define the expected value in the below variable.
EDIT: updated answer based on OP's full response here
//Change the value as needed
def expectedRegionId = 736
assert context.response, 'Response is null or empty'

def json = new groovy.json.JsonSlurper().parseText(context.response)

def sb = new StringBuffer()
json.regions.each { region ->
    assert region.regionId == expectedRegionId
    region.hotels.each { hotel ->
        assert hotel.regionId == expectedRegionId
    }
}

A: From your output, hotelregionid is a List of Lists
So you can use flatten to get it back to just a List of integers:
assert hotelregionid.flatten().every {it == hotelregionid_request}


text:
Q: A relation involving solutions of a quadratic equation Consider the following quadratic equation:
$$x^2 - (a + d) x + (a d - bc) = 0,$$
where $a, b, c, d \geq 0,$ and let $x_1 > 0, x_2 < 0$ be the solutions. I read in a book that since
$$x^2 - (a + d) x + (a d - bc) = \Big[x - \frac{a + d}{2}\Big]^2 - \Big[ \frac{(a - d)^2}{4} + ad - bc \Big],$$
and $\frac{a + d}{2}$ is nonnegative, then $x_1 > |x_2|$. Can someone explain me why is it true?

A: Hint Since we know the roots of the given quadratic (and that it is monic), we can also write it as
$$(x - x_1) (x - x_2) .$$

Additional hint On the other hand, expanding this expression and comparing like terms in $x$ in our two different ways of writing the polynomial gives $$a + d = x_1 + x_2 .$$


text:
Q: Serial Port Data Handling I have this code:
private void SerialPortDataReceived(object sender, SerialDataReceivedEventArgs e)
{
    while(_serialPort.BytesToRead > 0)
    {
       var count = _serialPort.BytesToRead;
       var bytes = new byte[count];
       _serialPort.Read(bytes, 0, count);
       AddBytes(bytes);
    }
}

Code is taken from Serial Port Polling and Data handling.
My question is about the While loop. When does "_serialPort.BytesToRead" update? Meaning, if the method above is an event driven method, and I use "_serialPort.Read", doesn't it clear all serial port buffer? If the answer is no, this code can create an endless loop, can't it?


text:
Q: How to calculate "undo" rotation except for parallel rotation Let's say we start with a vector $u = [0, 0, 1]$ which represents the positive z-axis.
Now, let's say we arbitrarily transform this vector via a rotation $z' = R \begin{bmatrix}0 \\ 0\\ 1 \end{bmatrix}$.
There are arbitrarily many rotations that can lead to the same $z'$.
I want to calculate a new rotation from $R$, $R_{undo}$, which inverts $R$ except it does not invert any portion of the rotation corresponding to a planar rotation around $z'$ (e.g. $z'$ is the normal vector of the plane of rotation).
For example, let's say in Euler angles with order zyx, $R = [90, 90, 0]$. Then, using the same zyx convention, $R_{undo} = [0, -90, 0]$, not $[-90, -90, 0]$.
How do we calculate $R_{undo}$ in general, for an arbitrary axis u?

A: It seems to me that your $R_{\text{undo}}$ is not very well defined, and that we should assume everything is in $\mathbb{R}^3$.
From your example, if $z'=Ru$ for some rotation $R$, it looks like you want $R_{\text{undo}}$ to be the unique rotation that maps $z'\mapsto u$ and fixes the plane spanned by the vectors $z'$ and $u$ (take a moment to think about what this means geometrically). But note that if $z'=-u$, it is not at all clear what $R_{\text{undo}}$ should do -- the vectors won't span a plane, and there is no "prefered direction" to bring $z'$ back to $u$ anymore.
So let's put this problem aside, and assume $z'\neq-u$. Then you can calculate $R_{\text{undo}}$ following the procedures in the answers to this question, which looks very much like yours:
Calculate Rotation Matrix to align Vector A to Vector B in 3d?


text:
Q: Почему метод не срабатывает корректно? Почему-то на платформе Stepik не проходит метод.
Пишет, что провален тест.
Не пойму, что не так делаю? Подскажите, пожалуйста.
Условие задачи:
Напишите программу, читающую из System.in текст в кодировке UTF-8, подсчитывающую в нем частоту появления слов, и в конце выводящую 10 наиболее часто встречающихся слов.
Словом будем считать любую непрерывную последовательность символов, состоящую только из букв и цифр. Например, в строке "Мама мыла раму 33 раза!" ровно пять слов: "Мама", "мыла", "раму", "33" и "раза".
Подсчет слов должен выполняться без учета регистра, т.е. "МАМА", "мама" и "Мама" — это одно и то же слово. Выводите слова в нижнем регистре.
Если в тексте меньше 10 уникальных слов, то выводите сколько есть.
Если в тексте некоторые слова имеют одинаковую частоту, т.е. их нельзя однозначно упорядочить только по частоте, то дополнительно упорядочите слова с одинаковой частотой в лексикографическом порядке.
Задача имеет красивое решение через стримы без циклов и условных операторов. Попробуйте придумать его.
    public static void main(String[] args) {
        HashMap<String, Integer> result = new HashMap<>();

        (new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8)))
                .lines()
                .flatMap(l -> Stream.of(l.split("[\\p{Punct}\\s]+")))
                .map(w -> w.toLowerCase())
                .forEach(w -> {
                    if (result.containsKey(w)) {
                        result.put(w, result.get(w) + 1);
                    } else {
                        result.put(w, 1);
                    }
                });

        result.entrySet()
                .stream()
                .sorted((e1, e2) -> {
                    if (e1.getValue() == e2.getValue()) {
                        return e1.getKey().compareTo(e2.getKey());
                    } else {
                        return e2.getValue().compareTo(e1.getValue());
                    }
                })
                .limit(10)
                .forEach(e -> System.out.println(e.getKey()));
    }

A: Вот более изящная версия:
public static void main(String[] args) throws IOException
    {
        try (Stream<String> lines = Files
                .lines(Paths.get("freq.txt")))
        {
                lines
                    .flatMap(l -> Stream.of(l.split("[\\p{Punct}\\s]+")))
                    .collect(Collectors.groupingBy(String::toLowerCase, Collectors.counting()))
                    .entrySet()
                    .stream()
                    .sorted((e1, e2) ->
                    {
                        if (e1.getValue().equals(e2.getValue()))
                        {
                            return e1.getKey().compareTo(e2.getKey());
                        } else
                        {
                            return e2.getValue().compareTo(e1.getValue());
                        }
                    })
                    .limit(10)
                    .forEach(e -> System.out.println(e.getKey()));
        }
    }

Может, она подойдет


text:
Q: How do you make the output of a `readfile` function into source for conduit? I am opening some .txt file via:
main :: IO ()
main = do
  xxs  <- TIO.readFile pathToFile
  return ()

The .txt file is of form
str_1 \n str_2 \n ... str_m

And I would like to make xxs into a source so that it might look like:
sourceList [str_1, str_2, ..., str_m]

Does the conduit API provide a way to do it without doing some string manipulation on xxs first, thus making it into the form [str_1, str_2, ..., str_m]?

A:
How do you make the output of a readfile function into source for conduit?

The source function for reading files already exists in the package conduit-extra in the form of sourceFile. You can also see various other combinators in that module like conduitFile, etc.


text:
Q: Counting binary digits in a list of excel cells I'm trying to make a formula that transforms a list decimal numbers to binary, then counts the number of appearances of ones at a certain position. I was trying to build an array formula that went something like this:
{=SUM(MID(DEC2BIN(A1:A10;10);9;1)}

This will return #VALUE. Is there a way to do this?
EDIT: examples added
Input       (Binary Equivalent)

  2             0000000010
  3             0000000101
  7             0000000111
  7             0000000111
  5             0000000101
  9             0000001001

 Outputs          Result
(digit to sum
from the right)

  1                 5
  2                 3
  3                 3
  4                 1

A: This was another way e.g. for the second digit from the right
=SUMPRODUCT(--ISODD(A1:A10/2))

Divide by 2^(n-1) where n is digit numbered from the right: the ISODD function ignores any fraction that results from the division.

A: =SUM(0+MID(DEC2BIN(--A1:A10,10),9,1))
array-entered.
Regards

A: If you are trying to count have many of the second digits are set in a range of numbers you can do this:
={SUM((MOD(A1:A10,4)>=2)+0)}

To understand this, let's look at some example data

Here I have some decimal numbers with their binary equivalents. In column C I have just extracted the 2nd digit (i.e. your MID(A1,9,1)). Then in column D I just take the modulo by 4. You can see that when the remainder is greater than 2, the second digit is set.
MOD(A1,4) basically divides the number by 4 and gives us the remainder (the numerator of the remainder if it was represented as a fraction over 4). With binary numbers, division by a power of two is just a right shift. Division by 4 is a right shift by 2 and the numbers that 'fall off' are the remainder. In this case it's the first two digits. They can be
00 | 0
01 | 1
10 | 2
11 | 3

so we see that the second digit is set only when the remainder is greater than 2.
Note the +0 in the original formula is to cast the boolean result of = to an integer so we can use SUM i.e. SUM({TRUE,FALSE}) doesn't work but SUM({TRUE,FALSE}+0) computes to SUM({1,0}) which does work.
To make this generic, let's assume you want to do it for the $E$1th digit:
=SUM((MOD(A1:A12,2^$E$1)>=2^($E$1-1))+0)

A: With bit operations it's not necessary to treat the number as a string.
{=SUM(BITAND(A1:A10;2^(C1-1))/2^(C1-1))}

Assuming the position you are looking for is stored in C1.


text:
Q: Installing node using npm fails with EACCES error I'm trying to install node on MacOS using the following command:
sudo npm install -g node

This yields the following output:
> node@12.6.0 preinstall /usr/local/lib/node_modules/node-darwin-x64/lib/node_modules/node-darwin-x64/lib/node_modules/node
> node installArchSpecificPackage

npm WARN registry Unexpected warning for https://registry.npmjs.org/: Miscellaneous Warning EACCES: EACCES: permission denied, open '/Users/bernhard/.npm/_cacache/tmp/5e859640'
npm WARN registry Using stale data from https://registry.npmjs.org/ due to a request error during revalidation.
npm ERR! path /Users/bernhard/.npm/_cacache/tmp/ef2c2113
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! syscall open
npm ERR! Error: EACCES: permission denied, open '/Users/bernhard/.npm/_cacache/tmp/ef2c2113'
npm ERR!  [OperationalError: EACCES: permission denied, open '/Users/bernhard/.npm/_cacache/tmp/ef2c2113'] {
npm ERR!   cause: [Error: EACCES: permission denied, open '/Users/bernhard/.npm/_cacache/tmp/ef2c2113'] {
npm ERR!     errno: -13,
npm ERR!     code: 'EACCES',
npm ERR!     syscall: 'open',
npm ERR!     path: '/Users/bernhard/.npm/_cacache/tmp/ef2c2113'
npm ERR!   },
npm ERR!   isOperational: true,
npm ERR!   stack: "Error: EACCES: permission denied, open '/Users/bernhard/.npm/_cacache/tmp/ef2c2113'",
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'open',
npm ERR!   path: '/Users/bernhard/.npm/_cacache/tmp/ef2c2113'
npm ERR! }
npm ERR!
npm ERR! The operation was rejected by your operating system.
npm ERR! It is likely you do not have the permissions to access this file as the current user
npm ERR!
npm ERR! If you believe this might be a permissions issue, please double-check the
npm ERR! permissions of the file and its containing directories, or try running
npm ERR! the command again as root/Administrator (though this is not recommended).
/usr/local/lib/node_modules/node-darwin-x64/lib/node_modules/node-darwin-x64/lib/node_modules/node/node_modules/node-bin-setup/index.js:27
        throw e;
        ^

Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/node-darwin-x64/lib/node_modules/node-darwin-x64/lib/node_modules/node/bin'
    at Object.mkdirSync (fs.js:764:3)
    at ChildProcess.<anonymous> (/usr/local/lib/node_modules/node-darwin-x64/lib/node_modules/node-darwin-x64/lib/node_modules/node/node_modules/node-bin-setup/index.js:24:10)
    at ChildProcess.emit (events.js:203:13)
    at maybeClose (internal/child_process.js:1021:16)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:283:5) {
  errno: -13,
  syscall: 'mkdir',
  code: 'EACCES',
  path: '/usr/local/lib/node_modules/node-darwin-x64/lib/node_modules/node-darwin-x64/lib/node_modules/node/bin'
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! node@12.6.0 preinstall: `node installArchSpecificPackage`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the node@12.6.0 preinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/bernhard/.npm/_logs/2019-07-21T16_20_19_759Z-debug.log

Running sudo npm cache clean before-hand does not make a difference. I checked the permissions on the _cacache folder and my user has full permissions to that folder.
Any ideas as to what may be causing this issue?

A: As other users mentioned, npm is essentially part of Node.js (and npm install -g node will instead install a global module called "node", which is not the same as the Node.js node executable).
My troubles began after I had to update node and when the (erroneous) npm command for doing that failed, I npm-uninstalled node so that I could re-install it. Node.js was, in fact, uninstalled by this point (at least partially - either that, or broken).
Re-installing Node.js by running the installer downloaded from the Node.js website fixed the issue. In future, I shall update Node.js using one of the recommended methods, like the one described in this post.


text:
Q: Simple jQuery slideshow repeats only one element I have 3 img tags and I want to have them in slideshow but somehow it does not work as expected. Only the child of the fade div repeats with the fadeIn method.
HTML:

Jquery:
$(function SlideShow(){
  $('.fade:first-child').appendTo('.fade');
    setInterval(function()
  {
    $('.fade:first-child').hide().appendTo('.fade').fadeIn(2000).end();
  },4000);
});

In addition I am trying to find a way, this function related with input text form to be appended together with the slideshow.
JavaScript :
var num=1;
text1 = "Picture One [TEXT]"
text2 = "Picture Two [TEXT]"
text3 = "Picture Three [TEXT]"

function textSlideShow()
{
num=num+1
if (num==3)
{num=1}
document.joe.burns.value=eval("text"+num)
}

JSFiddle:
http://jsfiddle.net/C3f6J/2/

A: I think you want to select the image here, not the div.fade like this.
$(function SlideShow(){
  $('.fade img:first-child').appendTo('.fade');
    setInterval(function()
  {
    $('.fade img:first-child').hide().appendTo('.fade').fadeIn(2000).end();
  },4000);
});

A: First, in you slideshow, you selector is wrong. You want to target the first-child of .fade. Just add a space :
$('.fade :first-child')

Then your CSS transition will mess with the fadeIn. Be more specific:
   transition:width .25s ease-in-out, height .25s ease-in-out, margin .25s ease-in-out;
  -webkit-transition:width .25s ease-in-out, height .25s ease-in-out, margin .25s ease-in-out;
  -moz-transition:width .25s ease-in-out, height .25s ease-in-out, margin .25s ease-in-out;
  -o-transition:width .25s ease-in-out, height .25s ease-in-out, margin .25s ease-in-out;
  -ms-transition:width .25s ease-in-out, height .25s ease-in-out, margin .25s ease-in-out;

After the transition, call your text slideshow function :
$('.fade :first-child').appendTo('.fade').hide().fadeIn(2000).end();
textSlideShow()

Also change you slideshow function to that :
function textSlideShow()
{
    num=num+1
    if (num>3) num=1;
    $('input[NAME=burns]').val(window['text'+num])
}

Everything work fine : http://jsfiddle.net/C3f6J/28/

A: I think you're trying to go to fast on this :
$('.fade:first-child').hide().appendTo('.fade').fadeIn(2000).end();

You're not selecting the image :
$('.fade img:first-child').hide().appendTo('.fade').fadeIn(2000).end();

This works better for me. Also, you're not calling your text function :
setInterval(function()
{
    $('.fade img:first-child').hide().appendTo('.fade').fadeIn(2000).end();
    textSlideShow(); // add this line to update your text
},4000);

And finally your text function doesn't properly handle cycling :
function textSlideShow()
{
    if (num==3)
    {
        num=1;
    }
    else{
        num=num+1;
    }
    document.joe.burns.value=eval("text"+num); // why not a table instead of an eval ?
}


text:
Q: Why version matching doesn't work in Maven? This is my pom.xml (fragment of it):
...
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    <version>[3.0,)</version>
</dependency>
...

This is what mvn tells me:
Couldn't find a version in [3.2.0.cr2, 3.2.0.ga, 3.3.1.ga] to match range [3.0,)

Why?

A: The old X.Y.Z.ga naming scheme used by Hibernate (see this page for the new JBoss conventions) is not following Maven's format and might not work well with the version comparison algorithm. Quoting the Version number rules:

The current implementation of DefaultArtifactVersion in the core of Maven expects that version numbers will have a very specific format:
<MajorVersion [> . <MinorVersion [> . <IncrementalVersion ] ] [> - <BuildNumber | Qualifier ]>

Where MajorVersion, MinorVersion, IncrementalVersion and BuildNumber are all numeric and Qualifier is a string. If your version number does not match this format, then the entire version number is treated as being the Qualifier.
If your version numbers do not match this scheme, you may face issues with

*

*version ranges (unfortunately there is nothing that the versions-maven-plugin can do to help you with your problems with version ranges and your version numbering scheme... well you could replace your version ranges with properties and use the update-properties goal)

*goals in this plugin that sort versions, for example update-properties (you can do things to help with these kinds of problems)

The algorithm is explained in details in Dependency Mediation and Conflict Resolution:

Default Version comparison definition
The default specification should be composed as follows:
<major>.<minor>.<revision>([ -<qualififer> ] | [ -<build> ])

where:

*

*the qualifier section is optional (and is SNAPSHOT, alpha-1, alpha-2)

*the build section is optional (and increments starting at 1 if specified)

*any '0' build or revision elements can be omitted.

*only one of build and qualifier can be given (note that the timestamped qualifier includes a build number, but this is not the same)

*the build number is for those that repackage the original artifact (eg, as is often done with rpms)

  For ordering, the following is done in order until an element is found that are not equal:

*

*numerical comparison of major version

*numerical comparison of minor version

*if revision does not exist, add ".0" for comparison purposes

*numerical comparison of revision

*if qualifier does not exist, it is newer than if it does

*case-insensitive string comparison of qualifier

*

*this ensures timestamps are correctly ordered, and SNAPSHOT is newer than an equivalent timestamp

*this also ensures that beta comes after alpha, as does rc

*if no qualifier, and build does not exist, add "-0" for comparison purposes

*numerical comparison of build

  Note also the proposed extension from a user in an rpm environment: Extending Maven 2.0 Dependencies

To sum up:

*

*3.2.0.cr2, 3.2.0.ga, 3.3.1.ga are treated as qualifier (i.e. they somehow become 0.0.0-3.2.0.cr2 etc)

*Knowing this, you can maybe fool Maven using a [0.0.0-3.0,) range.

*But this will match more versions than wanted (e.g. 2.x) so beware of unexpected side effects.

Actually, my recommendation is to not use version ranges at all, they are just bad for reproducible builds.
See also

*

*Dependency Version Ranges

*Improve default support for version schemes

A: Add repository to your pom.xml
Ex :
<repositories>
    <repository>
        <id>repo1</id>
        <name>repo1</name>
        <url>http://repo1.maven.org</url>
    </repository>
</repositories>


text:
Q: Stored Procedure in Orchard Hi We are working on a project and i am trying to call a stored procedure. I have searched for the solution but i didn't find any way that how to call a stored procedure so can any one please tell me how to execute stored procedure.

A: How ever finally i am using the below code to execute the stored procedure and get the result.
  using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Suppress))
        {
            // temporary scope for new connection and setting stored procedure, parameters, and return RecordName list
            using (SqlConnection cn = new SqlConnection(_settingsManager.LoadSettings().First().DataConnectionString))
            {
                if (cn.State == ConnectionState.Closed)
                {
                    cn.Open();
                }
                const string storedProcedure = "usp_spName";
                SqlCommand cmd = new SqlCommand(storedProcedure, cn);
                cmd.Parameters.AddWithValue("@IsVerified", "value");
                cmd.Parameters.AddWithValue("@page", "value");
                // for out put parameter
                cmd.Parameters.AddWithValue("@totalRows", 0);
                cmd.Parameters["@totalRows"].Direction = ParameterDirection.Output;
                cmd.CommandType = CommandType.StoredProcedure;
                IDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    // To Get The Values of the result
                    int id=Convert.ToInt32(reader["Id"].ToString());
                }
                reader.Close();
                try
                {
                    // To Get the Out Put Perameter
                    totalRecords = (int)cmd.Parameters["@totalRows"].Value;
                }
                catch
                {
                    totalRecords = 0;
                }
                cmd.Parameters.Clear();
                cmd.Dispose();
                cn.Close();
            }
        }

A: actually, I don't know about stored procedures, but you can call stored functions using code like examaple below. I'm new to C# and orchard, so may be my approach is not correct and good enough. At first you should get ISessionLocator object instance, using IOrchardServices, then create NHibernate ISession instance  and then IQuery/ISQLQuery with CreateSQLQuery().
here is example code of Services class
public class ExampleService {
    private readonly IOrchardServices _oServices;

    public EParamsServices(IOrchardServices oServices) {
         _oServices = oServices;
    }

    public float GetRegionPopulationDencity(int rId){

        //resolve ISession locator (you can do this using dependencies in ctor)
        ISessionLocator sl = _oServices.WorkContext.Resolve<ISessionLocator>();

        //create session
        ISession _session = sl.For(null);

        // create raw SQL query
        return _session.CreateSQLQuery(@"SELECT data.RegionDencity(:rId) as result")
                        .AddScalar("result", NHibernateUtil.Single)
                        .SetParameter<int>("rId", rId)
                        .List<float>()
                        .FirstOrDefault<float>();
    }

}

I think you can exec stored procs the same way, just change SQL code do exec yourProcName and ExecuteUpdate()  instead of List() method (I'm not sure in this part)
you also should add reference to NHibernate assembly to your project and add NHibernate & Orchard.Data to your using part.

A: You have to reference NHibernate and System.Data in your module , then you can use the below code
var cmd =  _transactionManager.GetSession().Connection.CreateCommand();

cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "MyStoredProcedure";

_transactionManager.GetSession().Transaction.Enlist(cmd);

cmd.ExecuteNonQuery();


text:
Q: How to Enforce SSL in Varnish 4 I am aiming to redirect clients to a SSL-version of a site using Varnish. In Varnish 3 this could be done by the following in the VCL:
sub vcl_recv {
    if ( (req.http.host ~ "^(?i)somesite.org" || req.http.host ~ "^(?i)www.somesite.org")
         && req.http.X-Forwarded-Proto !~ "(?i)https") {
        set req.http.x-Redir-Url = "https://www.somesite.org" + req.url;
        error 750 req.http.x-Redir-Url;
    }
}

sub vcl_error {
    if (obj.status == 750) {
        set obj.http.Location = obj.response;
        set obj.status = 302;
        return (deliver);
    }

Between Varnish versions 3 and 4 there were changes to the vcl requirements, these can be found in the varnish docs: https://www.varnish-cache.org/docs/4.0/whats-new/upgrading.html#changes-to-vcl.
My attempt at a Varnish 4 version of the redirect leads to a redirect loop. I am not entirely sure if it is this section of the the vcl which is incorrect, or if even the correct implementation would work with my current setup.
Either way, it would be useful to have a confirmed working ?Varnish 4 version of this. My attempt is:
sub vcl_recv {
    if ( (req.http.host ~ "^(?i)somesite.org" || req.http.host ~ "^(?i)www.somesite.org")
         && req.http.X-Forwarded-Proto !~ "(?i)https") {
        set req.http.x-Redir-Url = "https://www.somesite.org" + req.url;
        return (synth(750, req.http.x-Redir-Url));
  }
}

sub vcl_synth {
    if (resp.status == 750) {
        set resp.http.Location = resp.reason;
        set resp.status = 302;
        return (deliver);
    }

Is anyone familiar with this and able to spot if it is correct or incorrect?

A: Try the following for Varnish 4 while updating the TLD with your respective values:
sub vcl_recv {
        if ( (req.http.host ~ "^(?i)www.domain.com") && req.http.X-Forwarded-Proto !~ "(?i)https") {
                return (synth(750, ""));
        }
}

sub vcl_synth {
    if (resp.status == 750) {
        set resp.status = 301;
        set resp.http.Location = "https://www.domain.com" + req.url;
        return(deliver);
    }
}

You should be able keep the || statement and it should work (not tested):
sub vcl_recv {
        if ( (req.http.host ~ "^(?i)www.domain.com" || req.http.host ~ "^(?i)domain.com") && req.http.X-Forwarded-Proto !~ "(?i)https") {
                return (synth(750, ""));
        }
}


text:
Q: Problemas com consulta Ajax Estou tentando fazer uma consulta no banco sem dar refresh, então estou utilizo o Ajax, mas não está funcionando, não dá o refresh, nem retorna nada.
O código da página que deveria apresentar a consulta:

            <input placeholder="Busca por CPF" id="cpf" type="text" class="form-control">

            <button class="btn-floating btn-large waves-effect waves-light " type="button" id="buscar">search</button>

<form name="motorista" action="componentes/cad_motoca.php" method="POST">

        <input placeholder="Digite o nome do motorista" name="nome" type="text" class="validate">
        Motorista:

        <select name="disponibilidade" type="text" class="validate">
            <option value="" disabled selected></option>
            <option value="Ativo">Ativo</option>
            <option value="Inativo">Inativo</option>
        </select>
        Disponibilidade

        CPF:
        <input placeholder="Digite o CPF" name="cpf" type="text" class="validate">

        Carro:
        <input placeholder="Digite o carro" name="carro" type="text" class="validate">

        Data de Nascimento:
        <input placeholder="Digite a Data de Nascimento" name="data_nasc" type="text" class="validate">

        <select name="sexo" type="text" class="validate">
            <option value="" disabled selected></option>
            <option value="Masculino">Masculino</option>
            <option value="Feminino">Feminino</option>
        </select>
        Sexo

            <input type="submit" class="btn" value="Cadastrar">

</form>

O código de consulta ao banco:

<?php
    if(isset($_POST['cpf'])){
        echo "
";
            echo "
";
                echo "NOME	";
                echo "DISPONIBILIDADE	";
                echo "CARRO	";
                echo "CPF	";
                echo "DATA DE NASCIMENTO	";
                echo "SEXO	";
            echo "
";

            $strcon = mysqli_connect('localhost', 'root', '') or die('Erro ao conectar ao banco de dados');
            mysqli_select_db($strcon, 'uber');
            $sql = "SELECT nome, disponibilidade, carro, cpf, nascimento, sexo FROM tb_motorista WHERE cpf = $_POST[cpf]";
            $resultado = mysqli_query($strcon,$sql) or die("Erro ao retornar dados");

            while ($registro = mysqli_fetch_array($resultado)) {
                $nome = $registro['nome'];
                $disponibilidade = $registro['disponibilidade'];
                $carro = $registro['carro'];
                $cpf = $registro['cpf'];
                $nascimento = $registro['nascimento'];
                $sexo = $registro['sexo'];
                echo "
";
                    echo "".$nome."	";
                    echo "".$disponibilidade."	";
                    echo "".$carro."	";
                    echo "".$cpf."	";
                    echo "".$nascimento."	";
                    echo "".$sexo."	";
                echo "
";
            }
            mysqli_close($strcon);
        echo "
";
    }else{
        echo 'Digite o número do CPF para consultar';
    }
?>

O meu Footer:


text:
Q: Задать путь поиска классов через опцию -Xbootclasspath Для подгрузки внешней либы хочу использовать Xbootclasspath.
В Dokerfile это написал вот так, но при выполнении - создании образа, получаю ошибку.
Быть может у меня неправильный синтаксис?
RUN set -x \
    && $JAVA_HOME/bin/java -Xbootclasspath/a: App.jar \

Error: Could not find or load main class App.jar
Caused by: java.lang.ClassNotFoundException: App.jar

A: Чтоб запускать *.jar нужна опция -jar. В таком виде, как у вас сейчас параметр App.jar интерпретируется как имя класса.
Нужно так:
RUN set -x \
    && $JAVA_HOME/bin/java -Xbootclasspath/a: -jar App.jar


text:
Q: How to pass dropdownlist Id as parameter to javascript function? On the client side I need to call javascript function "changeSchool" with selector's Id as parameter, as soon user selects new option (school in this case). How to pass selector's Id to such javascript function?
Table in the view contains following drop down lists:
 @{
for (var i = 0; i < Model.StudentApplications.Count(); i++)
                {

                    ...
                    @Html.DropDownListFor(m => m.StudentApplications[i].SchoolId, Model.StudentApplications[i].SchoolList, new { onchange = "changeSchool(?);" })
                    ...

                }
              }

EDIT:
From the source code I can see that ids is generated: id="StudentApplications_0__SchoolId",
id="StudentApplications_1__SchoolId", ...
etc.

A: Perhaps?
onchange = "changeSchool(" + Model.StudentApplications[i].SchoolId + ");"


text:
Q: Are side-effects sometimes necessary when using KDB? Let's say I have a state variable s.
I've got a .z.ws hook that responds to websocket messages and runs:
.z.ws: {handleMsg x}

Do I have to declare s as global for handleMsg to be able to update s?
Ideally, what I'd want is something like:
s: handleMsg[s;x]

where handleMsg is a pure function (it doesn't affect any globals on the inside).
Should I declare s as global and then try to do this assignment inside the websocket callback?

A: You don't pre-declare variables as global in kdb, they're global if you make them global at any point (and if you reference them as a global).
q)func:{x+1}

/s is local and treated as such
q){s:func[1]}[]
2

/it is not a global
q)s
's

/this would make it global
q){`s set func[1]}[]
`s
/or
q){s::func[1]}[]

/now it's global
q)s
2

/but a local of the same name would take preference
q){s:func[100];s}[]
101
q)s
2

/you can force-reference the global if required
q){s:func[100];value `s}[]
2

So you're in complete control over what's global, what isn't, when you're referencing a local and when you're referencing a global.


text:
Q: Fastest way to mix arrays in numpy? a= array([1,3,5,7,9])
b= array([2,4,6,8,10])

I want to mix pair of arrays so that their sequences insert element by element
Example: using a and b, it should result into
c= array([1,2,3,4,5,6,7,8,9,10])

I need to do that using pairs of long arrays (more than one hundred elements) on thousand of sequences. Any smarter ideas than pickling element by element on each array?
thanks

A: c = np.empty(len(a)+len(b), dtype=a.dtype)
c[::2] = a
c[1::2] = b

(That assumes a and b have the same dtype.)
You asked for the fastest, so here's a timing comparison (vstack, ravel and empty are all numpy functions):
In [40]: a = np.random.randint(0, 10, size=150)

In [41]: b = np.random.randint(0, 10, size=150)

In [42]: %timeit vstack((a,b)).T.flatten()
100000 loops, best of 3: 5.6 µs per loop

In [43]: %timeit ravel([a, b], order='F')
100000 loops, best of 3: 3.1 µs per loop

In [44]: %timeit c = empty(len(a)+len(b), dtype=a.dtype); c[::2] = a; c[1::2] = b
1000000 loops, best of 3: 1.94 µs per loop

With vstack((a,b)).T.flatten(), a and b are copied to create vstack((a,b)), and then the data is copied again by the flatten() method.
ravel([a, b], order='F') is implemented as asarray([a, b]).ravel(order), which requires copying a and b, and then copying the result to create an array with order='F'.  (If you do just ravel([a, b]), it is about the same speed as my answer, because it doesn't have to copy the data again.  Unfortunately, order='F' is needed to get the alternating pattern.)
So the other two methods copy the data twice.  In my version, each array is copied once.

A: This'll do it:
vstack((a,b)).T.flatten()

array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])

A: Using numpy.ravel:
>>> np.ravel([a, b], order='F')
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])


text:
Q: "for all" in datalog Given a set of facts of the form is_member(country, organisation), I have the following query to write in datalog:

Return all countries who belong to all of the organisations of which Denmark is a member of.

I want to do something like
member_all_Denmarks_organisations(Country):-
    ¬( is_member('Denmark', Organization),
       ¬is_member(Country, Organization)
     ).
In other words, 'for every organization that Denmark is member of, Country is a member of it too'. But datalog does not allow negated predicates which contain non-instantiated variables, so this doesn't work.
How can I proceed? And in general, when wanting to express a 'for all' statement, how to do so in datalog?

A: We are going to take the following alternative equivalent definition:

Return all countries who not fail to belong to some organisation that Denmark is a member of.

Of course, you can only express this in a dialect of Datalog with negation.
The following should do:
organisation_of_denmark(org) :- is_member('Denmark', org).

// a country c is disqualified if there is some organisation org
// of which Denmark is a member but c isn't
disqualified_country(c) :- organisation_of_denmark(org), country(c), ¬is_member(c, org).

// we are only interested in countries that are not excluded by the previous rule
mmember_all_Denmarks_organisations(c) :- country(c), ¬disqualified_country(c).

// in case there is no unary predicate identifying all countries
// the best we can do is the following (knowing well that then the above
// will only work for countries that are members of at least one organisation)
country(c) :- is_member(c, _).

This is precisely what you wrote also, only with intermediate relations included that
capture some of your sub-formulas and with the atom country(c) included to act as
a guard or a domain for the outer-most complementation.

A: The problem is a case of expressing the following proposition P in Datalog:
P(x) := for all y, p(y) => q(x,y)
In Datalog, given database DB with, say, 2 columns and x in 1st column, this can be expressed as:
P(x):- DB(x,_), ¬disqualified(x).
disqualified(x):- DB(x,_), p(y), ¬q(x,y).

The trick is to create your own disqualified() predicate.
DB(x,_) is there just to instantiate x before it appears in a negated predicate.

In the specific Denmark case:
P(x) =: 'x is member of all Denmark's organisations'
p(y) =: is_member('Denmark', y)
q(x,y) =: is_member(x,y)
DB =: is_member()