text:
Q: Use a queryset to display two filtered data in django? I have a table Documents and it has a field named type and the type has two data's namely - type1 & type2
Now my requirements is - i have a bootstrap tabs type1 & type2, and i need to display data accordingly on the template
Which is efficient way to do this ?
Using two variables

data = Documents.objects.filter(id=pk)
type1 = data.filter(type="type1")
type2 = data.filter(type="type2")

and then pass it to context
context = { "type1":type1,"type2":type2 }

Is there any other best way to do this ?

A: Seems like they really have to be different querysets since they are different sets of data to be rendered. Also assuming id is your primary key (which looks like it is), note that the usage of Documents.objects.filter(id=pk).filter(type=...) would just consider that 1 object with that pk, you might want to change it to Documents.objects.filter(type=...). Then you can make it a bit more dynamic by listing the possible types and then passing the filtered data to the template where the key is the type.
doc_types = ("type1", "type2")
context = {
    doc_type: Documents.objects.filter(type=doc_type)
    for doc_type in doc_types
}


text:
Q: Pickling wrapped partial functions I am trying to create a picklable decorator using partial functions. However, I keep getting pickling errors when trying to do that.
The first naïve example is as follows:
def decorator(func):
  def wrapper(**kwargs):
    return partial(func, **kwargs)
  return wrapper

@decorator
def decorated(x, y=1, z=2):
  return x+y+z

y5 = decorated(y=5)
pickle.dumps(y5)

Where partial is taken from functools.
A bit less naïve attempt involves adding @wraps one line above def wrapper. This doesn't help.
I'm not sure I understand how pickling really works.

A: The problem is in your decorator, not with partial.  A partial object should pickle just fine:
>>> from pickle import *
>>> from functools import *
>>> f = partial(pow, 2)
>>> p = dumps(f)
>>> g = loads(p)
>>> g(5)
32

So, this issue with your code is in the decorator.  It is not preserving the name of the original function.  Try this instead:
import pickle
from functools import *

def decorator(func):
    def wrapper(**kwargs):
        return partial(func, **kwargs)
    return wrapper

def decorated(x, y=1, z=2):
    return x+y+z

dd = decorator(decorated)

y5 = dd(y=5)
pickle.dumps(y5)

The modification to use dd should allow the pickle logic to discover the underlying function by its name.  That is how pickles work.
To see the function name in the pickle, look at the dumps output:
>>> print pickle.dumps(y5)
cfunctools
partial
p0
(c__main__
decorated
p1
tp2
Rp3
(g1
(t(dp4
S'y'
p5
I5
sNtp6
b.

The word "decorated" needs to be findable, equal to the underlying function, and not be hidden by the decorator.  Remember, when functions get pickled, only their names get stored.  The actual contents of the function aren't in the pickle.
There are some workarounds, but they aren't pretty.  You can use __setstate__() to save both the function name and its source-code.  Then add a  __getstate__() method to restore the function by exec-ing its source.
Alternatively, you can extract the byte codes in the function object object and save those.  Upon a restore, compile the code object and exec it.
In short, your goal of using a decorator with the @ notation is directly at odds with how function pickling works.  In order to achieve your goal, you'll have to customize function pickling to have it save what the function does, not just its name.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting different paths in Red language I am trying to get different paths in Red language. If I cd to /myfolder and run following command:
/myfolder$ /path/to/red.exe /path/to/myscript.red

How can I get these 3 paths from code in script?
I tried:
system/options/path        ; Gives path/to/myscript
system/script/path         ; Gives none
call/output "pwd" outstr   ; Gives path/to/myscript
what-dir                   ; Gives path/to/myscript

I am able to get only one path. How can I get path of red.exe and path of current working directory (In Red language- not Rebol)?
Note: this is related to my question on Rebol at What-dir reporting own directory as current directory in Rebol

A: In Rebol (2 & 3), this is how you can get those three paths:
system/options/boot    ;; /path/to/red.exe
system/options/path    ;; /myfolder
system/script/path     ;; /path/to/myscript.red

At this moment only system/options/boot in Red matches what Rebol does here.

A: From the GUI Console:
boot             string!       {C:\ProgramData\Red\gui-console-2017-11-30-4300.exe}
home             none!         none
path             file!         %/C/ProgramData/Red/
script           none!         none
cache            file!         %/C/ProgramData/Red/

From the cli:
boot             string!       "C:\ProgramData\Red\console-2017-11-30-4430.
home             none!         none
path             file!         %/C/Users/Old%20Man/desktop/
script           none!         none
cache            file!         %/C/ProgramData/Red/

Using the GUI Console:
system/options/boot   ; Red binary
system/options/path   ; current dir
system/options/cache  ; Red default dir "home"

system/options/boot is a string!, so you'll have to convert it with:
to-red-file system/options/boot


text:
Q: Skips one input every time after a jmp So I have this code that is supposed to ask for 2 numbers and then make some operations with them, and after finishing one operation and outputting the answer, it should ask again for 2 numbers and an option until the user selects the option to exit. But for some reason, right after printing the result one time, the second time it skips one input.
segment .data

    prompt db "Please enter the first number: "
    promptLen equ $-prompt
    prompt2 db "Please enter the second number: "
    prompt2Len equ $-prompt2
    prompt3 db 10, "Your result is: "
    prompt3Len equ $-prompt3
    linefeed db 10
    menu1 db "Please chose what to do with the numbers: ", 10
    menu1Len equ $-menu1
    menu2 db "1. Add", 10
    menu2Len equ $-menu2
    menu3 db "2. Multiply", 10
    menu3Len equ $-menu3
    menu4 db "3. Divide", 10
    menu4Len equ $-menu4
    menu5 db "4. Nothing, exit.", 10
    menu5Len equ $-menu5
    menu6 db "5. Surprise me"
    menu6Len equ $-menu6
    menu7 db 10, "Selection: "
    menu7Len equ $-menu7

segment .bss

    Num1 resb 8
    Num2 resb 8
    uNum1 resd 1
    uNum2 resd 1
    choice resd 1
    uRes resd 1
    Result resb 8
    ResultLen resd 1

segment .text
    global _start

_start:
    call getNumbers
    call getMenuOption

    mov eax, [choice]
    cmp eax, 49
    je Addition
    cmp eax, 50
    je Multiply
    cmp eax, 51
    je Divide
    cmp eax, 52
    je exit
    cmp eax, 53
    je surprise

getNumbers:
    mov eax, 4
    mov ebx, 1
    mov ecx, prompt
    mov edx, promptLen
    int 80h

    mov eax, 3
    mov ebx, 0
    mov ecx, Num1
    mov edx, 8
    int 80h

    mov esi, Num1
    call dec2eax
    mov [uNum1], eax

    mov eax, 4
    mov ebx, 1
    mov ecx, prompt2
    mov edx, prompt2Len
    int 80h

    mov eax, 3
    mov ebx, 0
    mov ecx, Num2
    mov edx, 8
    int 80h

    mov esi, Num2
    call dec2eax
    mov [uNum2], eax
    ret

dec2eax:                            ; Arg ESI: ASCII-string (0x0A-terminated) with decimal digits
    xor eax,eax                     ; Result
    xor edx, edx                    ; Especially to clear the 32-bit-part of EDX

    .loop:
    mov dl, byte [esi]              ; Read digit
    cmp dl, 10                      ; End of string (SYS_READ - in certain cases not existent)?
    je .finish                      ; Yes: done
    lea eax, [eax*4+eax]            ; EAX = 5 * EAX ...
    add eax, eax                    ;   ... and EAX = 2 * EAX results in EAX = EAX * 10
    add esi, 1                      ; Increment pointer to string
    and dl, 0x0F                    ; Eliminate ASCII part of digit
    add eax, edx                    ; Add digit to result
    jmp .loop                       ; Next character

    .finish:
    ret                             ; Result: Converted unsigned integer in EAX

eax2dec:                            ; Arg EDI: Pointer to string that gets ASCII-characters
    mov ebx, 10                     ; Divisor
    xor ecx, ecx                    ; CX=0 (number of digits)

    .first_loop:
    xor edx, edx                    ; Attention: DIV applies also DX!
    div ebx                         ; DX:AX / BX = AX remainder: DX
    push dx                         ; LIFO
    inc cl                          ; Increment number of digits
    test eax, eax                   ; AX = 0?
    jnz .first_loop                 ; No: once more

    mov ebx, ecx                    ; Save strlen

    .second_loop:
    pop ax                          ; Get back pushed digit
    or al, 00110000b                ; AL to ASCII
    mov byte [edi], al              ; Save AL
    inc edi                         ; DI points to next character in string DECIMAL
    loop .second_loop               ; Until there are no digits left

    mov byte [edi], 0               ; End-of-string delimiter (ASCIZ)
    mov eax, ebx                    ; Return strlen in EAX
    ret

getMenuOption:
    mov eax, 4
    mov ebx, 1
    mov ecx, menu1
    mov edx, menu1Len
    int 80h

    mov eax, 4
    mov ebx, 1
    mov ecx, menu2
    mov edx, menu2Len
    int 80h

    mov eax, 4
    mov ebx, 1
    mov ecx, menu3
    mov edx, menu3Len
    int 80h

    mov eax, 4
    mov ebx, 1
    mov ecx, menu4
    mov edx, menu4Len
    int 80h

    mov eax, 4
    mov ebx, 1
    mov ecx, menu5
    mov edx, menu5Len
    int 80h

    mov eax, 4
    mov ebx, 1
    mov ecx, menu6
    mov edx, menu6Len
    int 80h

    mov eax, 4
    mov ebx, 1
    mov ecx, menu7
    mov edx, menu7Len
    int 80h

    mov eax, 3
    mov ebx, 0
    mov ecx, choice
    mov edx, 1
    int 80h

    ret

Addition:
    xor edx, edx
    mov eax, [uNum1]
    mov ebx, [uNum2]
    add eax, ebx
    mov [uRes], eax

    call printResult

    jmp _start

Multiply:
    xor edx, edx
    mov eax, [uNum1]
    mov ebx, [uNum2]
    mul ebx
    mov [uRes], eax

    call printResult

    jmp _start

Divide:
    xor edx, edx
    mov eax, [uNum1]
    mov ebx, [uNum2]
    div ebx
    mov [uRes], eax

    call printResult

    jmp _start

surprise:
    jmp _start

printResult:
    mov eax, [uRes]
    mov edi, Result
    call eax2dec
    mov [ResultLen], eax

    mov eax, 4
    mov ebx, 1
    mov ecx, prompt3
    mov edx, prompt3Len
    int 80h

    mov eax, 4
    mov ebx, 1
    mov ecx, Result
    mov edx, [ResultLen]
    int 80h

    mov eax, 4
    mov ebx, 1
    mov ecx, linefeed
    mov edx, 1
    int 80h

    ret

exit:
    mov eax, 1
    xor ebx, ebx
    int 80h

I would really appreciate someone pointing out what's wrong with it as I am very new to this programming language.
Edit: Here's what happens when I run the code.
./menu
Please enter the first number: 3
Please enter the second number: 5
Please chose what to do with the numbers:
1. Add
2. Multiply
3. Divide
4. Nothing, exit.
5. Surprise me
Selection: 1

Your result is: 8
Please enter the first number: Please enter the second number: 3
Please chose what to do with the numbers:
1. Add
2. Multiply
3. Divide
4. Nothing, exit.
5. Surprise me
Selection: 1

Your result is: 3
Please enter the first number: Please enter the second number: 3
Please chose what to do with the numbers:
1. Add
2. Multiply
3. Divide
4. Nothing, exit.
5. Surprise me
Selection: 1

Your result is: 3
Please enter the first number: Please enter the second number: ^C

So right after going through one jmp back to _start it skips one input, but if I take the "getMenuOption" out and just make it do one operation every time it works fine.

A: The problem seems to be that you read only one character at the end of getMenuOption. The newline charater that you enters after your menu choice is then kept in the input buffer until getNumbers is called, resulting in an automatic empty input for the first number.
A simple solution is to read more than one character in getMenuOption.


text:
Q: scikit-learn trying refit the model # Let's refit the model
np.random.seed(42)
x_train, x_test, y_train, _y_test = train_test_split(transformed_x,
                                                     y,
                                                     test_size=0.2)

model.fit(x_train, y_train)

TypeError                                 Traceback (most recent call last)
Input In [77], in <cell line: 7>()
      2 np.random.seed(42)
      3 x_train, x_test, y_train, _y_test = train_test_split(transformed_x,
      4                                                      y,
      5                                                      test_size=0.2)
----> 7 model.fit(x_train, y_train)

TypeError: BaseForest.fit() missing 1 required positional argument: 'y'

How to resolve this?


text:
Q: Should a Stack have a maximum size? I'm practicing my knowledge of ADTs by implementing some data structures, even if most already exist. With Stacks, a lot of books and other documentation I've read talk about the stack throwing an error when you try to add an element but the stack is full. In a java implementation (or any other), should I specifically keep track of a maximum stack size (from constructor), check to see if that size is reached, and throw an overflow exception if it is?
Or is not such a big deal?

A: Depends on the kind of stack, but usually, it doesn't matter about size if the stack is heap-allocated.
If your stack is really allocated on the stack, then you should keep it small.


text:
Q: Fix size of stackview to all screen sizes I have a stackview like this

I pinned the stackview like this:
Top: 200, Leading: 20, Trailing: 20, Bottom: 200

I want the stackview to be fixed to this size for every screen size, how do I achieve this?

A: Add leading, trailing, center vertically and aspect ratio 1:1 constraint to main StakeView.

Also, Add equal widths and equal heights constraint to each button.
Output :

A: Choose the Stack View and add Aspect Ration :

Then double click on the Aspect Ration around the Stack View and make the Multiplier 1:1 :

Then you can add Trailing and Leading constrains + Center Vertically in Safe Area.


text:
Q: How to use wildcard certificates in Kubernetes with nginx ingress and cert-manager? I am trying to deploy a React website together with an Express API on GKE. There should be multiple subdomains for both the website and the API, i.e.

*

*domain.com, a.domain.com, b.domain.com, ... -> React app

*api.domain.com, a.api.domain.com, b.api.domain.com -> Express API

The reasoning behind this is that the application is using cookie-based authentication, so the API and app need to be on the same subdomain (e.g. a.domain.com and api.a.domain.com).
Cert-manager and nginx ingress were deployed in the Kubernetes cluster with commands:
kubectl apply -f https://github.com/cert-manager/cert-manager/releases/download/v1.8.2/cert-manager.yaml
kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.5.1/deploy/static/provider/cloud/deploy.yaml

Everything works fine when I explicitly put all subdomains in the ingress and give each a separate TLS entry in the ingress. The certificates are successfully issued. But when using wildcards the certificates never get ready and when I try to open api.domain.com or domain.com it returns a "page not found" error.
# ingress.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ingress
  annotations:
    kubernetes.io/ingress.class: nginx
    kubernetes.io/tls-acme: "true"
    cert-manager.io/issuer: letsencrypt-production
spec:
  rules:
  - host: "*.domain.com"
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: react
            port:
              number: 80
  - host: wordpress.domain.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: wordpress
            port:
              number: 80
  - host: "*.api.domain.com"
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: api
            port:
              number: 9000
  tls:
  - hosts:
    - "*.domain.com"
    - domain.com
    secretName: certificate-wildcard-domain
  - hosts:
    - "wordpress.domain.com"
    secretName: certificate-wordpress-domain
  - hosts:
    - "*.api.domain.com"
    - api.domain.com
    secretName: certificate-api-domain

This is what is showing in the logs of the cert-manager pod:
 cert-manager/orders "msg"="Failed to determine the list of Challenge resources needed for the Order" "error"="no configured challenge solvers can be used for this challenge" "resource_kind"="Order" "resource_name"="certificate-api-domain-9wvd9-2527200272" "resource_namespace"="default" "resource_version"="v1"

I do not understand the problem, why certificates are not issued correctly for wildcard entries and the website is not reachable, while e.g. for wordpress.domain.com the certificates are issued successfully and the website can be reached.

A: Issuer/ClusterIssuer solvers(Try Upgrade from v0.10 to v0.11)
Update the apiVersion on all your backed up resources from certmanager.k8s.io/v1alpha1 to cert-manager.io/v1alpha2
Support for the deprecated spec.http01 or spec.dns01 fields in Issuer and ClusterIssuer have been removed. Any Issuer or ClusterIssuer objects must be converted to use the equivalent spec.solvers[].http01 or spec.solvers[].dns01 syntax. You can read more about the Issuer resource in the configuration documentation.
Any issuers that haven't been converted will result in the cert-manager pod being unable to find any solvers at the expected location. This will result in errors like the following: no configured challenge solvers can be used for this challenge.
Let's Encrypt issues wildcard certificates via ACMEv2 using the DNS-01 challenge. See ACME v2 Production Environment & Wildcard certificates for more technical information. Cert-manager.io: Docs: Configuration: ACME: DNS-01 contains details on the different options available on the Issuer resource's DNS01 challenge solver configuration.
Refer to No configured Challenge Solvers for ACME Prod only #2494 for more information, which may help to resolve your issue.


text: Q: Make multiple copies of the same report in PowerBI When i am trying to upload same report in PowerBI embedded it creates multiple copies. Can someone please let me know how to overwrite existing report when importing.


text:
Q: Is it better to purchase 1password from agilebits website or the app store? Is it better value to purchase 1password from the https://agilebits.com/ website or the app store?
They cost different amounts, does the app store version include all future versions of 1password?
Which is the best option for consumers based on the license terms of the Mac App store versus a third party license where you buy an app directly from the vendor?
(I have checked the agilebits.com website, but cannot find this information)

A: There are benefits to both sides:

*

*The Mac App Store's 1Password has iCloud syncing whereas the AgileBits store distribution method can't include iCloud syncing since an app must be distributed through the Mac App Store to use such Apple services.

*The AgileBits store's 1Password is updated more frequently since the updates don't have to go through Apple's approval system. This also means you can get beta updates that aren't on the Mac App Store due to Apple's guidelines on beta distribution.

A: http://learn.agilebits.com/1Password4/Mac/en/KB/where_to_purchase.html

Should I purchase on the Mac App Store or from your website?
To use iCloud syncing you should purchase on the Mac App Store, but
  ultimately the choice is a personal preference. Using the Mac App
  Store makes it easier since you don't need to keep track of a license
  key. On the other hand, purchasing from our website is also great
  since 1Password provides a great way to keep track of software license
  keys, and you will receive updates faster as we approve them directly.


text:
Q: Create object while still running code So I have some python code that creates objects like so:
paramToPassa = 'test'
paramToPassb = 'test2'
paramToPassc = 'test3'
paramToPassd = 'test4'
#... so on

objectToCreate = continuouslyRunningObject(paramToPassa, paramToPassb)
print('test')
objectToCreate2 = continouslyRunningObject(paramToPassc, paramToPassd)

The object instantiates with a while True: loop so it runs indefinitely after it's created (it does terminate eventually, but the time varies). The problem is I want to create objectToCreate2 simultaneously and have it also running at the same time as objectToCreate. Normally, the print statement is only called along with objectToCreate2 after the objectToCreate is finished running. Is there any way to do this easily or will I have to look into multi-threading/something of that nature? Thanks!
EDIT: Tried using Multiprocessing.Process to create objects like so...
a = Process(target=continouslyRunningObject, args=(paramToPassa, paramToPassb))
a.start()

but now I get the error 'TypeError: can't pickle _thread.lock objects'. Any ideas?


text:
Q: Change inner " and (, inconsistent behaviour Are there any plugins that patch the inconsistent behaviour of the c i <textobject>?
A common itch for me is the example specified in the title. Given the lines below and the assumption that the cursor is located at the first character of the line:
hello("stuff") -> c i " -> hello("")
hello('stuff') -> c i ' -> hello('')
hello( stuff ) -> c i (  -> hello( stuff )
First itch:
c i (/) works on none of the lines, unless the cursor is already located at or inside the parantheses.
Second itch:
c i "/' always work on their respective characters, as long as the cursor is located before or at the closing tag of the specified character.
Wrapping up:
As you see, there is a consistency. I've been letting it slip for some years now, but I wanna straighten it out. You may call me whiny, but working with parameters is something we all do lots of, and while it could be worse, it  could certainly be better. Is there a reason for this behaviour, and how do you get around it?

A: The trick is to prepend % to go inside the parentheses first: %ci(.
Found at selecting text inside paranthesis from outside the parenthesis in vim. Also, see why ci" and ci( ci{ behave differently, the same question as yours.


text:
Q: Constructing a table showing a directory listing works locally but not remotely I cannot get this to produce what I want server side, which supports PHP, because I can get PHP pages to echo and stuff. But locally it does exactly what I expect it to do. This is of course example code I found lying around on the internet that I modified to look for my specific directory, that is the only thing I changed.
It is supposed to check a directory for .html files and construct a table with each file in the table. It does this locally but on the remote server I'm trying to host the code on, just produces a blank page.
<?php
  $directory = "/pages/";
  $contents = scandir($directory);
    if ($contents) {
       foreach($contents as $key => $value) {
             if ($value == "." || $value == "..") {
                unset($key);
             }
       }
    }
        echo "
";
    foreach($contents as $k => $v) {
      echo "
link text
";
    }
        echo "
";

?>

A: User l'L'l pointed me in the right direction. error_reporting(E_ALL); helped me figure out what was wrong. the directory was a bit more complicated because i am using a subdomain for testing. and thought all i needed was "/pages/" as the directory.


text:
Q: Calling button with jQuery won't receive JSON response I'm new to JSON, but what I'm trying to do, is when I click my button on my HTML page, the console should display the content.
This works when I'm NOT wrapping the $.getJSON in a function but I can't figure out what the problem is when I'm calling it from a button.
I want to keep the call asynchronous, so I don't know if I'm doing it wrong or if there's a better way.
Heres my JS code
 $(document).ready(function(){
  $("button").click(function(){
    $.getJSON('https://mysite', function(data) {
        var i;
        for(i = 0; i < data.files.length; i++){
          console.log(data.files[i].title);
          var path = data.files[i].path;
          console.log(path);
          document.getElementById("getMedia").innerHTML = 'https://mysite' + path;
          }
        });
      });
});

This is the HTML
   <form action="" enctype="multipart/form-data" method="post">
        <button type="submit" class="btn btn-default" id="getfiles">Submit</button>
   </form>

I also tried changing the call of the click of the button to $("#getfiles").click(function() but that did not work either.

A: My guess would be that your page is submitting and refreshing. Try adding the event parameter to your function call and then run the method event.preventDefault(); to prevent the default submission behavior of the browser.
$(document).ready(function (){
    $("button").click(function (event) {
        event.preventDefault(); // <-- Add this line

        $.getJSON('https://mysite', function(data) {
            /* ... */
        });
    });
});

A: As you are using the button type="submit" this actually submits the form. The normal behavior then is that the pages refresh. Remove the type="submit" like below.
<button class="btn btn-default" id="getfiles">Submit</button>

In this case, you can leave the click handler as it.


text:
Q: Invoke one PowerShell script from Another PowerShell script with passing arguments I want to invoke test1.ps1 from test2.ps1. And I want to pass arguments from test2.ps1 to test1.ps1 while invoking.

A: PS C:\> gc .\test2.ps1
.\test1.ps1 'foo'
Write-Host 'bar'
PS C:\> gc .\test1.ps1
$a = $ARGS[0] -split ''
[array]::Reverse($a)
Write-Host ($a -join '')
PS C:\> .\test2.ps1
oof
bar


text:
Q: Get properties for single dbid fails to return data status 202 this issue is happening since today morning. Same code/endpoint used yesterday and was working perfectly.
example:
'https://developer.api.autodesk.com/modelderivative/v2/::urn::/metadata/:::guid:/properties?objectid=3981'

keeps returning 202 status code even after 20 retries in some tries it returns 504 as well.
Update 1: currently its 202 in endless retires.
Update 2: (possible workaround)

*

*Tried the Following: downloaded and reuploaded the model to a different bim 360 project (works) - same file

*Reuploaded the same file as a revision on the the original file (works)

Currently I am happy it works, but need to know what is the cause of this issue, to prevent it in the future.
Any insights would be much appreciated.


text:
Q: How to make text slide in and out of the page I need to achieve same effect as slide in and out effect like on this page :https://pangrampangram.com/products/neue-machina

A: create a div inside a another div make the child div bigger than parent div once it get done you can make the child scrolling by left or right attribute in css.
`<html data-test-id="brave-new-tab-page" dir="ltr">

        .parent
        {
            width: 500px;
            height: 100px;
            overflow: hidden;
            position: absolute;
        }
        .child
        {
            width: 1347px;
            font-size: 76px;
            position: absolute;
        }

        test test test test test test test tesenter code heret test test

        let position = 0;
        document.addEventListener('DOMContentLoaded',  () =>
        {
            setInterval(() =>
            {
                let child = document.getElementsByClassName('child')[0]
                child.setAttribute('style', 'left:-' + position + 'px')
            if ( position > ( 1347 - 500 ) )
                position = 0

            position ++
        }, 5)
    }, false);
</script>

`


text:
Q: Not able to run kubectl on remote using python I am trying to run kubectl commands on a remote server from local, but seems it is trying to run on localhost when all other commands(ls, date) I am able to run on remote.
command = 'kubectl get pod -n namespace'
stdin,stdout,stderr=ssh.exec_command(command)

Error:
The connection to the server localhost:8080 was refused - did you specify the right host or port?

Any idea how to run kubectl on remote to connect to a pod and run some command there inside the pod?

A: Check if you are ssh connection is non-root user, this error comes when you try to execute the kubectl commands as non-root user.
Solutions:

*

*Add sudo as prefix to the commands. This will solve the issue with current user itself.

*Make the ssh connection with root user.


text:
Q: Can Google Sheets pull a number from a table based on a different number I'm using google sheets to make calculations for a game I'm playing. I've made a table that shows how many materials are needed to build a building, and which materials I need to make those materials. The problem is that the base materials vary based on how many buildings I've made. The way I go around this is using the sum function. So:
Sum(P38:P42)
It's annoying to have to select the right range every time though. Is there a way for google sheets to calculate which row of the table I need from the number on the left? For instance, in table:
1|20
2|20
3|125
4|450
5|625

If I just want the sum of 2 to 4, how can I make it so that I just have to enter 2 and 4 in two cells to get the sum of 20+125+450?
Sorry if I worded it in a weird way, all help appreciated.

A: try:
=SUM(INDIRECT("B"&D1&":B"&D2))


text:
Q: Mix post date with post meta value using WP_Query Finding any way to push old posts into the WP_Query using custom fields.
For example I have 10 posts in this year, and want to republish 2 posts from the past to custom rss feed.
So the posts must be ordered by post date and value in the post meta for old posts:
new post - (post date: 2018-11-11)
new post - (post date: 2018-11-10)
old post - (post date: 2017-05-01, post-meta date: 2018-11-09)
new post - (post date: 2018-11-08)

I try to order by 2 values in WP_Query but it is not working
<?php
   add_filter('pre_get_posts', function($query) {
        if($query->is_main_query() && $query->is_feed()) {
            $query->set('posts_per_rss', 3);
            $query->set('post_type', 'post');
            $query->set('post_status', 'publish');

            $query->set('meta_query', [
                'relation' => 'OR',
                'push_clause' => [
                    'key' => 'is-push',
                    'compare' => 'EXISTS'
                ],
                'exclude_clause' => [
                    'key' => 'is-exclude',
                    'compare' => 'NOT EXISTS'
                ]
            ]);

            $query->set('orderby', ['push_clause' => 'DESC']);
        }
    });

Is there any way to implement this using WP_Query?
Update:
I've written pure sql query, working sorting as I want
SELECT SQL_CALC_FOUND_ROWS wp_posts.post_title, wp_posts.post_date, m.*, IFNULL(m.meta_value, wp_posts.post_date) as d
FROM wp_posts
LEFT JOIN wp_postmeta m ON (wp_posts.ID = m.post_id AND m.meta_key = 'is-push')
WHERE wp_posts.post_status = 'publish' AND wp_posts.post_type = 'post'
ORDER BY
     d DESC
LIMIT 10

A: Finally I've decided to use custom sql query with get_results method.
$query = "SELECT SQL_CALC_FOUND_ROWS p.*, IFNULL(m2.meta_value, p.post_date_gmt) as zen_date
            FROM {$wpdb->posts} p
            LEFT JOIN {$wpdb->postmeta} m1 ON (p.ID = m1.post_id AND m1.meta_key = 'is-exclude')
            LEFT JOIN {$wpdb->postmeta} m2 ON (p.ID = m2.post_id AND m2.meta_key = 'is-push')
            WHERE p.post_type = 'post' AND p.post_status = 'publish' AND m1.post_id IS NULL
            GROUP BY p.ID ORDER BY zen_date DESC LIMIT 0, 50";

$posts = $wpdb->get_results($query, OBJECT);

foreach($posts as $post) {
    setup_postdata($post);

    // do something
}

If somebody suggests something better, I'll be glad to accept that answer.


text:
Q: How to change the names of the x values in a boxplot Sorry if this is very basic, but I am quite new to this. I am creating boxplots for some survey data in R using boxplot(). I  notice it automatically arranges the x groups in alphabetical order, which doesn't suit my needs. In my data frame I changed the names to have an 'a' or 'b' at the beginning. This puts them in the order I want but then the label isn't neat. I would like to be able to override the x labels from the data frame with my own labels OR decide the order of the values along the x axis. Basically I just want 'Riparian' to come first, then 'Floodplain'. I have a number of other boxplots to do as well, some will have more than 2 values on the x axis.
This is the data and the code without trying to override the labels
data
Script
boxplot(tot_sp ~ hab, data = mydata, xlab= "Habitat Type", ylab = "Total # Species")
title("Bird Search: Total Species")

boxplot

Some other scripts I have tried, none have worked.
boxplot(tot_sp ~ hab, data = mydata, axis(1, at=seq(1, 2), labels = labels.name),
        xlab= "Habitat Type", ylab = "Total # Species")

boxplot(tot_sp ~ hab, data = mydata, 'labels',{'Riparian', 'Floodplain'}, at=NULL,
        xlab= "Habitat Type", ylab = "Total # Species")

boxplot(tot_sp ~ hab, data = mydata, xtix = {'Riparian', 'Floodplain'}, xtixloc = [1, 2],
        xlab= "Habitat Type", ylab = "Total # Species")

Thanks very much for your help!

A: Here's a stab in the dark:
mydata$hab <- factor(mydata$hab, levels=c("Riparian", "Floodplain")

boxplot(tot_sp ~ hab, data = mydata,
        xlab= "Habitat Type", ylab = "Total # Species")

Example of reordering with iris data-set:
df <- iris
df$Species <- factor(df$Species, levels=c("virginica", "setosa", "versicolor"))
boxplot(Sepal.Length ~ Species, df)


text: Q: JavaFX.Пересечение границ фигур Делается симуляция индикатора кругового обзора(радара). Есть отображение точек с затуханием и треугольник,который в виде сектора вращается,имитируя луч обзора.Необходимо,чтобы при пересечении границ треугольника и точки - точка появлялась на радаре.При вызове метода у треугольника  getBoundsInParent().intersects(Bounds bounds),то пересечение считается по прямоугольнику вокруг фигуры,а не по реальным границам.Как сделать,чтобы брались реальные границы фигуры?


text:
Q: Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead I want to make a component that will hold a material-ui grid.
There is a codesandbox that I made here: codesanbox
This is the container component. AllCards.js
// All the required imports here

const exer = [
  {
    imageurl: "https://media1.giphy.com/media/26tPtg8M3i6DPSSt2/200w.gif",
    imagealt: "react-gif",
    title: "Elongacion de columna",
    body: "Este es un ejercicio que sirve para estirar los lumbares.",
    firstButtonText: "Ver",
    secondButtonText: "Ayuda"
  },
  {
    imageurl: "https://media1.giphy.com/media/26tPtg8M3i6DPSSt2/200w.gif",
    imagealt: "react-gif",
    title: "Elongacion de cuadriceps",
    body: "Este es un ejercicio que sirve para estirar los cuadriceps.",
    firstButtonText: "Ver"
  }
];

function AllCards() {
  const [exercises, setExercises] = useState(null);

  useEffect(() => {
    setExercises(exer);
  }, [exercises]);

  let ret = exercises ? <CardGrid cards={exercises} /> : null;
  return ret;
}

export default AllCards;

And this is the CardGrid.js component
const CardGrid = props => {
  const classes = useStyles();
  const { cards } = props;

  return (
    <div className={classes.root}>
      <Grid container spacing={3} justify="space-evenly" alignItems="center">
        {cards.map((currentCard, ind) => (
          <Grid key={ind} item xs>
            <CardItem card={currentCard} />
          </Grid>
        ))}
      </Grid>
    </div>
  );
};

My CardItem.js component
const CardItem = props => {

  let ret = null;
  if (props.card) {
    console.log("ITEM PROPS", props);
    ret = ( <Card . . . )
  // return { ret };     <-- THIS IS WRONG
     return ret          <-- SHOLD BE LIKE THIS
};

I have the following error
Error: Objects are not valid as a React child (found: object with keys {card}). If you meant to render a collection of children, use an array instead.
    in CardItem (at CardGrid.js:49)

SOLVED:
In CardItem.js I am returning { ret }
It should be return ret

A: On your sandbox example, you have import CardItem from "./CardGrid"; in top of your code within CardGrid.js. I'm assuming that you wanted to say import CardItem from "./CardItem";
Then, I believe your component needs to be able to hold ForwardRefs and this guide will help you with that. https://material-ui.com/guides/composition/

A: As Thomas pointed out, you were importing CardItem from the wrong file. Also, inside CardItem you were using a prop called card but also creating a new variable called card to return the component, which causes a naming collision and tries to render an object which is disallowed.
If you change the variable name it seems to work.
Fork here


text:
Q: Primary keys in MySQL I am trying to create a table from an existing table. Will the primary keys from the existing table transfer over to the new table?
create table B as select column1, column2, column3 from A.
In table A, the primary keys are column1 and column2.

A:
CREATE TABLE ... SELECT does not automatically create any indexes for you. This is done intentionally to make the statement as flexible as possible. If you want to have indexes in the created table, you should specify these before the SELECT statement:
mysql> CREATE TABLE bar (UNIQUE (n)) SELECT n FROM foo;

Documentation


text:
Q: How to I cut a wav file based on time segments? I have a wav file that I need to split up using the following list:
[0.89, 1.38, 1.945, 2.93, 3.435, 4.47, 5.435, 6.035, 6.67, 7.665, 8.48]

I want to create an array of smaller wav files that are the following segments from the original wav file:
0.89 to (1.38 - 0.05)
1.38 to (1.945 - 0.05)

Is there a way to do that? I've googled it but it seems like the wave library only does it for bytes, not the timing.

A: From the wave module documentation:
Wave_read.getsampwidth()
Returns sample width in bytes.

Wave_read.getframerate()
Returns sampling frequency.

Using those you should be able to calculate the bytes per second of your file.


text:
Q: ReactJS - JavaScript: How to zoom on customized marker after click on it Usig google-map-react, how do I zoom on a customized marker after I click on it?
I am able to click on the marker but it is not zooming after the click.
Below a snippet of code for the most important parts:
GoogleMap.js
import React, { Component } from 'react';
import GoogleMapReact from 'google-map-react';

const markerStyle = {
    position: 'absolute'
};

function CustomMarker({ lat, lng, onMarkerClick }) {
    return (

    );
}
function MapClick({ center, zoom, data }) {
    function handleMarkerClick() {
        console.log('Click');
    }
}

class BoatMap extends Component {
    constructor(props) {
        super(props);
        this.state = {
            buttonEnabled: true,
            buttonClickedAt: null,
            progress: 0,
            ships: [],
            type: 'All'
        };
    }

// Operations.......

render() {
    return (

            <GoogleMapReact
                bootstrapURLKeys={{ key: 'My_KEY' }}
                center={{
                    lat: 42.4,
                    lng: -71.1
                }}
                zoom={8}
                defaultZoom={zoom}
                defaultCenter={center}
            >
                {/* Rendering all the markers here */}
                {this.state.ships.map((ship) => (
                    <Ship ship={ship} key={ship.CALLSIGN} lat={ship.LATITUDE} lng={ship.LONGITUDE} />
                ))}

                {/* Trying to focus on the marker after clicking on it */}
                {data.map((item, idx) => {
                return <CustomMarker  onMarkerClick={handleMarkerClick} key={idx} lat={item.lat} lng={item.lng} />
                })}

            </GoogleMapReact>

    );
}
}

ShipTracker.js is where I detect the correct click event:
const Ship = ({ ship }) => {
    const shipName = ship.NAME;
    const company = shipCompanyMap[shipName];

    function handleMarkerClick() {
        console.log('marker clicked');
    }

    const shipImage = companyImageMap[company];
    return (

            {/* Render shipImage image */}

    );
};
export { Ship };

What I have done so far:
what I tried so far:
1) I came across this source and that was useful to understand how to create a marker but unfortunately I was not able to solve the problem.
2) In my case I use google-map-react instead of google-map. I know that the procedure is similar, but for some reasons I might be missing something.
3) After digging more into the problem I came across this source and it was very useful but still I could not fix the problem.

A: I'm not sure but you can try to get instance of map throw ref
like
<GoogleMapReact ref={this.map}

and then use it in handler
function handleMarkerClick(marker) {
    this.map.panTo(marker.coordinates);
}


text:
Q: Unrecognized selector when adding an object to NSMutableArray I have a singleton class with a NSMutableArray property to which I want to add objects and remove objects. For some reason I am getting:
-[__NSDictionaryI setObject:forKey:]: unrecognized selector sent to instance 0x1edf24c0

exception when trying to add to it. Here is the relevant code for the interface of the singleton:
//outbox item is the type of objects to be held in the dictionary
@interface OutboxItem : NSObject
@property (nonatomic, assign) unsigned long long size;
@end

@interface GlobalData : NSObject
@property (nonatomic, copy) NSMutableDictionary *p_outbox;
+ (GlobalData*)sharedGlobalData;
@end

The implementation of the singleton:
@implementation GlobalData
@synthesize  p_outbox;
static GlobalData *sharedGlobalData = nil;
+ (GlobalData*)sharedGlobalData {
    if (sharedGlobalData == nil) {
        sharedGlobalData = [[super allocWithZone:NULL] init];
        sharedGlobalData.p_outbox = [[NSMutableDictionary alloc] init];
    }
    return sharedGlobalData;
}

+ (id)allocWithZone:(NSZone *)zone {
    @synchronized(self)
    {
        if (sharedGlobalData == nil)
        {
            sharedGlobalData = [super allocWithZone:zone];
            return sharedGlobalData;
        }
    }
    return nil;
}
- (id)copyWithZone:(NSZone *)zone {
    return self;
}
@end

And here is the code that throws the exception:
GlobalData* glblData=[GlobalData sharedGlobalData] ;
OutboxItem* oItem = [OutboxItem alloc];
oItem.size = ...;//some number here
[glblData.p_outbox setObject:oItem forKey:...];//some NSString for a key

Am I missing something very obvious??

A: The problem is with your property:
@property (nonatomic, copy) NSMutableDictionary *p_outbox;

The copy semantics of the property result in a copy of the dictionary being made when you assign a value to the property. But the copy method for a dictionary always returns an immutable NSDictionary, even when called on an NSMutableDictionary.
To solve this problem you must create your own setter method for the property:
// I'm a little unclear what the actual name of the method will be.
// It's unusual to use underscores in property names. CamelCase is the standard.
- (void)setP_outbox:(NSMutableDictionary *)dictionary {
    p_outbox = [dictionary mutableCopy];
}

A: Your
@property (nonatomic, copy) NSMutableDictionary *p_outbox;

is creating a copy of that object which you assign to it.
As you are assigning a NSMutableDictionary to it, it's creates a copy of NSMutableDictionary object which is NSDictionary which is not a mutable copy.
So change it to
For Non ARC
@property (nonatomic, retain) NSMutableDictionary *p_outbox;

For ARC
@property (nonatomic, strong) NSMutableDictionary *p_outbox;


text:
Q: what is the difference between web service and website look at this scenario :  in my app I get the form in html of a website
that form displays customer info
now I can parse the form and get customer info
Or I can use a web service (SOAP or whatever) and get the same information
What is the difference?

A: Web service is a solution to integrate systems and comunications between different applications. Your app is a way to interact with this Service.

A: On a general level, a website is displayed to a user in a browser making it consist of GET request through HTTP/HTTPS.  A webservice is one that responds to more than just GET requests (eg. POST, PUT, DELETE). This means that a user can interact with data remotely.  Like adding your post to stackoverflow.com, that meant you sent a POST request where stackoverflow can store the data contained in this post in some remote location, like a database.


text:
Q: How "return false" can optimize your scripts So i'm reading this https://code.tutsplus.com/tutorials/10-ways-to-instantly-increase-your-jquery-performance--net-5551, #9, reproduced below, I don't totally understand, can someone explain to me (in a different way than how it's been explained below)?

*Return False
You may have noticed whenever your functions don't return false, you jump to the top of the page.When dealing with longer pages, this result can be quite annoying.

So, instead of
$('#item').click (function () {
  // stuff here
});

Write
$('#item').click (function () {
  // stuff here
  return false;
});

A: .click(...) is an alias for .on("click", ...).
As described in the jQuery documentation for .on():

Returning false from an event handler will automatically call event.stopPropagation() and event.preventDefault(). A false value can also be passed for the handler as a shorthand for function(){ return false; }. So, $( "a.disabled" ).on( "click", false ); attaches an event handler to all links with class "disabled" that prevents them from being followed when they are clicked and also stops the event from bubbling.

This is a feature (one of many) jQuery adds for convenience.
As for performance, I'm not sure this increases it in any meaningful way.

That article in general is mainly "stuff I heard on the internet". I doubt the author truly understands the why's of the various tips they give.

For example, if you are caching selects (#6) then you're not going to get much out of preferring ids over classes for selections (#4).
Another example is #3 which is basically saying "don't use jQuery". Using anything in jQuery is going to cause a microscopic decrease in performance but that's the trade off you agree to when you decide to use jQuery at all. The point of jQuery isn't so much about improving performance, it's about improving convenience.

A: The following is mostly true if #item is an anchor element with an href, which most likely looks something like <a href="#" id="item">
return false in the event handler is equivalent to event.preventDefault() and event.stopPropagation(), which prevents the default execution of the native action, in this case going to the # hypertext reference and also stops the event from bubbling up.

CSS Tricks has a good explanation ( as compared to event.preventDefault() ):

The difference is that return false; takes things a bit further in that it also prevents that event from propagating (or "bubbling up") the DOM. The you-may-not-know-this bit is that whenever an event happens on an element, that event is triggered on every single parent element as well. So let's say you have a box inside a box. Both boxes have click events on them. Click on the inner box, a click will trigger on the outer box too, unless you prevent propagation.


text:
Q: For $G=\mathbb{Z}^2\rtimes \mathbb{Z}$, $Spec(\mathbb{Z}G)$=? Let $G$ be the group $\mathbb{Z}^2\rtimes_{\sigma} \mathbb{Z}=\langle y,z\rangle\rtimes_{\sigma}\langle x\rangle$, where $\sigma(x)=\begin{pmatrix}a, b\\c,d\end{pmatrix}\in SL_2(\mathbb{Z})$, which means that we have relations $xyx^{-1}=y^az^c, xzx^{-1}=y^bz^d$. Then we can form the group ring $R=\mathbb{Z}G$, note that since $G$ is a polycyclic-by-finite group, $R$ is a left Noetherian ring.
I am interested in what a general prime ideal $\wp$ in $R$ looks like, so I want to ask the following question:
What does Spec(R) generally look like? Especially when $\sigma(x)=\begin{pmatrix}1,0\\1,1\end{pmatrix}$ or $ ~ \sigma(x)=\begin{pmatrix}2,1\\1,1\end{pmatrix}$

A: The natural map $\mathbb{Z} \to \mathbb{Z}G$ has central image and therefore induces a map between prime spectra $Spec(\mathbb{Z}G) \to Spec(\mathbb{Z})$. The preimage of the ideal generated by $(p)$ under this map is in a natural bijection with $Spec( kG )$ where $k = \mathbb{F}_p$ if $p$ is a prime number and $k = \mathbb{Q}$ if $p = 0$. So $Spec( \mathbb{Z}G )$ is the disjoint union of various prime spectra $Spec( kG )$, where $k$ is a field.
A prime $P$ of $kG$ is said to be faithful if $G$ embeds into the group of units of $kG/P$, or equivalently, if $G \cap (1 + P) = 1$.
If a prime of $kG$ is unfaithful, then $P^\dagger := G \cap (1 + P)$ is a non-trivial normal subgroup of $G$, and $P$ is completely determined by its image inside $k[G / P^\dagger]$, which is then a faithful prime of this smaller group ring. Thus it is enough to understand the faithful primes of $kG$.
James Roseblade published a paper in 1978 called "Prime ideals in group rings of polycyclic groups", which appeared in the Proceedings of the London Mathematical Society (I can send you a copy if you like). Although he did not completely settle the problem of classifying the faithful prime ideals in group rings $kG$ of polycyclic-by-finite groups $G$ over fields $k$, he made some serious breakthroughs in this paper.
I'd like to draw your attention to Theorem E, which says:
Let $A$ be the Zalesskii subgroup of the polycyclic group $G$. If $G$ is orbitally sound, then any faithful prime ideal of a group algebra $kG$ is controlled by $A$.
Being controlled by $A$ for a prime ideal $P$ means that $P$ is generated by its intersection with $kA$ and is therefore completely determined by an ideal in a smaller group ring. The Zalesskii subgroup $A$ is defined by the property that it contains the largest finite normal subgroup $F$ of $G$ and that $A/F$ is the centre of the Fitting (largest normal nilpotent) subgroup of $G/F$. Being orbitally sound is a technical condition that I won't go into here.
In particular, if $G$ happens to be torsion-free and nilpotent then $F$ is trivial and $A$ is just the centre of $G$, and then Roseblade's Theorem E essentially says that every faithful prime of $kG$ is controlled by the centre of $G$. This happens for example when $G = \mathbb{Z}^2 \rtimes \mathbb{Z}$ as in your question and when $\sigma$ is the matrix $\begin{pmatrix} 1 & 1 \\ 0 & 1\end{pmatrix}$.


text:
Q: Combining multiple Django Views/Templates I am working on a website. On the Homepage, I want to show the posts in the center and show famous tags on the right side of the page. Now, posts and tags are two different apps and their views/tempaltes are calculated/generated in two separate functions.
How can I show what I want on my Homepage keeping my mind that its two different views being called. As far as I understand, I can only call a single view to show my homepage.
This must be possible but I am unable to understand this. Any help will be much appreciated.

A: I think you need to create a custom template tag that in this case called: Inclusion tags

A: You can look into writing a custom template tag for the tags. That way the tag logic can stay in the right application.

A: It depends how these different apps render the templates. If they just render the template without extending from a base template you could simply use AJAX to load all the content into your homepage.
If not, then there is no other way than writing a custom solution for this. This could be an extension to your views, a custom template tag as already mentioned or something else according to what exactly you need.


text:
Q: Как отправить вложение по вебхуку в discord? у меня есть файл UidUtil (взял тут), UidPlayerBuilder (взял тут) и UidPlayer (взял тут) которые вместе позволяют отправить сообщение в discord по вебхуку, вот пример
UidPlayerBuilder dm = new UidPlayerBuilder.Builder()
                .withUsername("никнейм бота")
                .withContent("Тут сообщение которое придёт по вебхуку")
                .withAvatarURL("аваарка бота")
                .withDev(false) // испольвозвание /tts сообщений
                .build();
        scr.sendMessage(dm);

вот, можно как-нибуть отправить вместе с сообщением вложение в виде картинки?


text:
Q: Meteor on Windows: meteor command outputs nothing I installed the MSI file from win.meteor.com
I reboot the computer, and open up CMD and type meteor create app but nothing happens. It doesn't say the command was undefined, so I don't know what's wrong here.
I am using windows 7 64-bit home.

A: I have discovered an issue with node fibers (on windows) and have a tentative fix - at least it fixed the problem for me, and I would be interested to see if that also fixes it for others.
Ultimately the problem was apparently sudden death due stack overflow and access violation. The root cause however was that the thread locals were not correctly being switched on a fiber switch.

A: you should check the environment path
add Meteor root directory to PATH
like this

PATH: ...;d:\Meteor;d:\Meteor\bin
METEOR_PATH: d:\Meteor
NODE_PATH: d:\Meteor\lib\node_modules

A: I have this issue too..
METEOR_PATH = C:\Program Files (x86)\Meteor\
NODE_PATH = C:\Program Files (x86)\Meteor\lib\node_modules
PATH = C:\Program Files (x86)\VMware\VMware vSphere CLI\Perl\site\bin;C:\Program Files (x86)\VMware\VMware vSphere CLI\Perl\bin;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Enterprise Vault\EVClient\;C:\Program Files (x86)\Heroku\bin;C:\Program Files (x86)\git\cmd;C:\Program Files\Java\jre6\bin\;C:\Program Files\Sublime Text 2;C:\Program Files (x86)\Meteor\;C:\Program Files (x86)\Meteor\bin

When you I run the meteor command, it does open meteor.js in node (if I add console.log('xxx') to meteor.js I see output), but the script finishes with no output.


text:
Q: Make Python module callable need some help making the below a callable object for another script e.g scrape.run()
I'm not sure where to start any pointers?
scrape.py
from clint.textui import puts, colored
import subprocess, sys
from datetime import datetime
from time import sleep as sleep
today = datetime.now().strftime("%H:%M:%S")
multimon_ng = subprocess.Popen("rtl_fm -A lut -s 22050  -f 148.81250M | multimon-ng -t raw -a FLEX -f alpha /dev/stdin",
 stdout=subprocess.PIPE,
 stderr=subprocess.PIPE,
 shell=True)
while True:
 try:
  nextline = multimon_ng.stdout.readline()
  if not nextline:
   pass
  else:
   try:
    flex, mdate, mtime, bitrate, other, capcode, o2, msg = nextline.split(" ", 7)
   except ValueError:
    print "invalid line", nextline
   else:
    puts(colored.yellow(capcode), newline=False)
    puts(" [", newline=False)
    puts(colored.green(mdate + " " + str(datetime.now().strftime('%H:%M'))), newline=False)
    puts(" ]", newline=False)
    puts(msg)
 except KeyboardInterrupt:
    print "exit"
 multimon_ng.poll()

A: Add this to the bottom of the script.
if __name__ == "__main__":
    function_you_wish_to_call_here()

Anything under the if statement will run when you call the script directly.


text:
Q: I want to display a simple 'hello' message over the server using django in vscode but it says page not found I want to display a simple hello in the server but receiving an error as Page not found.
here are my code:
Analytic_web.urls.py
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path(r'jas/', include('website.urls')),
    path('admin/', admin.site.urls),
]

website.urls.py:
from django.urls import path
from . import views

urlpatterns = [
    path(r'jas/', views.home, name='home'),
]

views.py:
from django.shortcuts import render
from django.http import HttpResponse

def home(request):
    return render(request, '/templates/website/home.html' )

home.html:

Helllllllloooooooooowwwwwwwwwwwww

A: in website.urls.py, try :
path('', views.home, name='home'),

instead of this
path(r'jas/', views.home, name='home'),

and in Analytic_web.urls.py, try :
path('jas/', include('website.urls')),

instead of this
path(r'jas/', include('website.urls')),

hope this would help.


text:
Q: AutoFac Autowiring Conventions StructureMap has the ability to apply conventions when scanning. Thus IFoo => Foo, without explicit registration.
Is something simular available in AutoFac? Looked around and just can't find anything helpfull.
Thanks,

A: For Autofac versions from v2
The new scanning features in Autofac2 will imo remove some of the need for registration-by-convention. Lets say that Foo lives in Plugins.dll:
var assembly = Assembly.Load("Plugins");
builder.RegisterAssemblyTypes(assembly)
       .AsImplementedInterfaces();

This registration will pick up Foo and register it as IFoo.
For Autofac versions less than v2
You can use the ContainerBuilder.RegisterTypesMatching. Here's an example:
var builder = new ContainerBuilder();
builder.RegisterTypesMatching(type => type.IsAssignableFrom(typeof(IFoo)));
var container = builder.Build();

var foo = container.Resolve<Foo>();

A: Peter, what he means is default convention scanning that is available in StructureMap. It automatically binds IX and X where X is a class that implements interface IX. It works like this:
public override void Process(Type type, Registry registry)
{
    if (!type.IsConcrete()) return;

    Type pluginType = FindPluginType(type);
    if (pluginType != null && Constructor.HasConstructors(type))
    {
        registry.AddType(pluginType, type);
        ConfigureFamily(registry.For(pluginType));
    }
}

public virtual Type FindPluginType(Type concreteType)
{
    string interfaceName = "I" + concreteType.Name;
    Type[] interfaces = concreteType.GetInterfaces();
    return Array.Find(interfaces, t => t.Name == interfaceName);
}

I would also like to know if Autofac supports a similar thing. StructureMap lets you define your own IRegistrationConvention's. This is one example of a convention.


text:
Q: Symfony 6 - CAS Bundle I am using Symfony 6 and I should use CAS bundle for my app because we use SSO system. So, can I install the following bundle while I use Symfony 6 because there is no CAS bundle for Symfony6:
https://github.com/ecphp/cas-bundle
I asked Symfony Community and I got recieved this message:

Unfortunately, I've never worked with CAS protocol before, so don't
use those bundles myself. But let me give you some hints. First of
all, I see that the bundle you linked https://github.com/ecphp/ca...
does not support Symfony 6 yet, though there's an issue about it:
https://github.com/ecphp/ca... - feel free to follow it to know when
that issue is closed. Also, if you have time - feel free to help with
upgrading that bundle and make it compatible with Symfony 6 and send a
PR - that may have a good side effect, because even if the bundle is
slow on reviewing/merging your PR - you will be able to use your
fork in your project while PR is not merged yet. Other options - you
may want to take a look at GitHub search:
https://github.com/search?o... - probably you will find that is still
maintained. If no luck - you may want to use low-level tools that are
used in those bundles to write the implementation yourself - take a
look at composer.json file to see what libs are used behind the scene
in those bundles that might help you. Or, another option - downgrade
your project to Symfony 5.4. Basically, Symfony 5.4 == 6.0, but in
Symfony 6.0 just dropped all the legacy code since 5.x version.
Though, it might work and you will be able to install that bundle, but
keep in mind that if the bundle is dead and nobody will add Symfony 6
support there - you won't be able to upgrade to the newer version at
some point.

Do you have any idea about this issue?
Thanks all :)

A: It seems there is a CAS bundle for Symfony 6.
Take a look to
https://packagist.org/packages/l3/cas-guard-bundle
https://packagist.org/packages/l3/cas-bundle


text:
Q: How do I delete availability tests after moving Applications Insights to another resource group? I moved applications insights from one resource group to another one. After moving I still can see availability tests in AI although I didn´t mark them for the move. Now I can´t do anything with them - disable, delete, edit.
When I try to delete test I get notification that availability test was deleted. But it was not. When I try to disable it I get notification: Failed to update availabity test. Updating availability test "webtest-appservice" failed with error:
{
    "error": {
        "code": "ResourceNotFound",
        "message": "The Resource 'microsoft.insights/webtests/webtest-appservice-xxxxx-ain' under resource group 'xxx-rsg' was not found. For more details please go to https://aka.ms/ARMResourceNotFoundFix"
    }
}

Is there a way to delete them?

A: Please try to use the Web Tests - Delete rest api.
On that page, there is a green button "Try it", just click it, and provide any necessary parameters.


text:
Q: Material ui and reactjs,  with ref : doesn't work I have a problem to recover the value of input with  when I transform an input into TextField
That's the code that works :
<form onSubmit={(e) => this.goToNextStep(e)}>
  <input type="text" className="form-control" placeholder="Name" pattern="[A-Za-z-]{1,}" required ref={(input) => {this.nameInput = input}} />
  <RaisedButton label="GO" color="primary" primary={true} type="submit" />
</form>

And the goToNextStep function :
goToNextStep = event{
event.preventDefault;
const name = this.nameInput.value;
console.log(name);
}

So with this, when I submit, I get the name back.
But with  when I submit, I don't get the name back.
That's the code that doesn't works :
<form onSubmit={(e) => this.goToNextStep(e)}>
  <TextField ref={(input) => {this.nameInput = input}} floatingLabelText="Name" pattern="[A-Za-z-]{1,}" required />
  <RaisedButton label="GO" color="primary" primary={true} type="submit" />
</form>

Do you know why it doesn't work ?
How to  make it good ?
Thanks for help :)

A: You got ref to a component instance, not a real <input>
<TextField ref={(input) => {this.nameInput = input}} floatingLabelText="Name" pattern="[A-Za-z-]{1,}" required />

Read more about it in docs. Unfortunately, I don't see a way to pass ref callback to TextField component.


text:
Q: Visual Studio + Cordova Remotebuild failed Error: 65 until today I could easily build iOS apps from my Windows-PC with remotebuild to my Mac and build it on the connected iPad on my Mac. But now i updated all devices (Mac, iPad) and suddenly it stopped working. When i want to build in Visual Studio i get this message:

Severity  Code    Description Project File    Line    Suppression State
  Error       Remote build error from the build server Build failed with error Error code 65 for command: xcodebuild with args: -xcconfig,/Users/grafikschulung/.taco_home/remote-builds/taco-remote/builds/877/cordovaApp/platforms/ios/cordova/build-debug.xcconfig,-project,memoxx.xcodeproj,ARCHS=armv7 arm64,-target,memoxx,-configuration,Debug,-sdk,iphoneos,build,VALID_ARCHS=armv7 arm64,CONFIGURATION_BUILD_DIR=/Users/grafikschulung/.taco_home/remote-builds/taco-remote/builds/877/cordovaApp/platforms/ios/build/device,SHARED_PRECOMPS_DIR=/Users/grafikschulung/.taco_home/remote-builds/taco-remote/builds/877/cordovaApp/platforms/ios/build/sharedpch: {1} Katalog C:\Users\m.hüttl\Documents\Visual Studio 2015\Projects\Katalog - Kopie\Katalog\MDAVSCLI 1

When I copy the project-folder to my Mac and import it into xCode and choose a development-team and build it from xCode it works perfect...

A: I believe until Cordova CLI is updated for Visual Sudio with the Xcode 8 changes you will have this issue.  Darryl Pogue did write a hook if you want to follow his instructions on his site which might fix the development team issue you are having.
There are a couple other suggestions on the following Stack Overflow page that might give you other options such as changing settings in the Xcode project.
Code Sign Error on Xcode 8 and iOS 10 Cordova Project


text:
Q: Can't add a New filter to Magento Magento's Total Ordered Report I'm trying to add a new filter to Magento's Total Ordered Report (i.e. Reports > Sales > Orders from the admin panel).
The filter I want is "Order Type" and can be either "Delivery" or "Collection"
I was able to add the filter to the Report form by rewriting the Mage_Sales_Block_Adminhtml_Report_Filter_Form_Order class.
<?php
class Holy_Reports_Block_Sales_Adminhtml_Report_Filter_Form_Order extends Mage_Sales_Block_Adminhtml_Report_Filter_Form_Order
{
    protected function _prepareForm()
    {
        parent::_prepareForm();
        $form = $this->getForm();
        $htmlIdPrefix = $form->getHtmlIdPrefix();
        /** @var Varien_Data_Form_Element_Fieldset $fieldset */
        $fieldset = $this->getForm()->getElement('base_fieldset');

        if (is_object($fieldset) && $fieldset instanceof Varien_Data_Form_Element_Fieldset) {

            $fieldset->addField('order_type', 'select', array(
                'name'       => 'order_type',
                'options'    => array("delivery"=>"Delivery", "collection"=>"Collection"),
                'label'      => Mage::helper('reports')->__('Order Type'),
            ));

        }

        return $this;
    }
}

But when I run the report it does not filter the results by the Order Type.
I've tried to add the filter to the collection with $this->_addCustomFilter($resourceCollection, $filterData->getData('order_type')); by re-writing Mage_Adminhtml_Block_Report_Sales_Sales_Grid
<?php
class Holy_Reports_Block_Adminhtml_Report_Sales_Sales_Grid extends Mage_Adminhtml_Block_Report_Sales_Sales_Grid
{
    protected function _prepareCollection()
    {
        parent::_prepareCollection();

        $filterData = $this->getFilterData();

        $storeIds = $this->_getStoreIds();

//        $orderType = $filterData->getData('order_type');

        $resourceCollection = Mage::getResourceModel($this->getResourceCollectionName())
            ->setPeriod($filterData->getData('period_type'))
            ->setDateRange($filterData->getData('from', null), $filterData->getData('to', null))
            ->addStoreFilter($storeIds)
            ->setAggregatedColumns($this->_getAggregatedColumns());

//        $resourceCollection->$filterData->getData('order_type');
//        $resourceCollection->addFieldToFilter($filterData->getData('order_type'));
//        $this->_addOrderStatusFilter($resourceCollection, $filterData);
//        parent::getCollection()->addFieldToFilter('fulfillment_store_id', $filterData->getData('order_type'));
//        $this->_addCustomFilter($resourceCollection, $filterData);
        $this->_addCustomFilter($resourceCollection, $filterData->getData('order_type'));

        $this->getCollection()->setColumnGroupBy($this->_columnGroupBy);
        $this->getCollection()->setResourceCollection($resourceCollection);

        return parent::_prepareCollection();
    }
}

I'm using xDebug and can see that my class re-writes are working, it seems to be that my PHP logic is wrong.


text:
Q: Can an extended use case have a relationship with another actor Is the below valid use case diagram? Can the extended use case be associated with another actor than the base use case?

A: Short answer is: yes
Yet you need to be careful. The association to use case shows actor involved in the use case (not necessarily initiating it).
The given example is absolutely fine.
You could also achieve the same result by using UC specialization in case of opening a folder for a new patient rather than existing one.


text:
Q: Modulus/Remainder function for non-integers rem gives this:
Prelude> rem 9 8
1

I wanted something like this:
Prelude> nonIntRem 9.1 8
1.0999999999999996

I implemented it like this:
nonIntRem x y = x - (y * (fromIntegral $ truncate (x/y)))

My questions are:

*

*Does something like this already exist in a standard Haskell library? I'd prefer to use a standard function, and I may have missed it.

*If not, is there a more standard name for this function in other languages? Maybe fmod, but the behavior for negatives in this case is not like mod, but like rem. If there is no standard name, can you think of a better name for this function?

*It seems to work properly, but if you notice a problem with this function, I'd like to know about it.

A: The function you're after is mod' from Data.Fixed.


text:
Q: Convert combinational loops into latches Can you recommend an algorithm that convert any cyclic combinational logic into an acyclic combinational logic plus latches?
Thank you

A: This is a rather open-ended question and can be a very hard problem in its general form. This is more of a CAD problem and has little to do with Verilog. Just creating an acyclic combinational logic graph from a cyclic combinational logic graph is easy: find a cycle and break it by inserting a latch. Continue until there is no cycles left.
However, you should also define some sort of functional correctness and equivalence and preserve it after the conversion. By adding latches to the circuit you are changing the relative timing of signals (aka synchronous distance) and the resulting graph may be functionally different than the original graph.
A classic algorithm called retiming tries to move latches that already exist to satisfy/minimize the clock cycle time.
A sketch of algorithm that I can think which preserve the synchronous distance is the following: add n latches at primary inputs and run an enhanced retiming algorithm in which you add extra constraints to preserve the synchronous distance of equal-distance nodes from the primary inputs. These nodes are the inputs of combinational gates and primary outputs. For example, the sequential distance of two inputs a and b of an AND gate should always remain the same from all primary inputs, i.e. in the path from each input i to a you should see the same number of latches that you would see from i to b.
With these added constraints retiming would tell you if it can move the latches to satisfy the clock-cycle time (which in this case can be a very large number, i.e. bigger than your longest cycle). If n is enough, retiming algorithm should be able to put the latches to break all the cycles. You can iterate the algorithm on different values of n to get an answer.


text:
Q: Terraform to setup AWS Codepipline Notification Rule I have already setup AWS Codepipeline and notification rules manually. On that manual setup pipeline, I have set 4 events to trigger notification on SNS:

*

*State Execution:

*

*Succeeded

*Failed

*Pipeline Execution:

*

*Succeeded

*Failed

Now, I am trying to do the same thing with Terraform. But, unable to find the resource in Terraform registry.
How can I find out the Terraform resource to create the Codepipeline Notification Rules?

A: The CP notifications are set using aws_codestarnotifications_notification_rule.
For exactly how to set event_type_ids  up you have to refer to AWS docs:

*

*Events for notification rules on pipelines


text:
Q: ASP.Net membership for sql server compact database for ASP.Net MVC 3 project When we start ASP.Net MVC 3 Starter Site Project in WebMatrix.
We get asp.net membership tables pre-installed in SDF (SQL Compact) db.
Now, if we want to create them in new SQL CE 4.0 DB, what is the procedure?
i dont want to use starter site.

A: What about ASP.NET Universal Providers?
Pretty sure it will be default on next ASP.NET version.

A: The Starter Site is not an MVC application. It's a Web Pages application. The Starter Site is designed to show you how to use security and membership in a Web Pages application, but more detailed instructions can be found here: Adding Security and Membership


text:
Q: how to set the value of Input from state ( React app) hope you're doing well!
I am looking to set the value of Input from the state that i receive from props! I could set all the information from "profile" state in the placeholder but when putting it in the value field it doesn't show anything
here's my code and the form i use :
                        <Form
                            name="basic"
                            wrapperCol={{ span: 24 }}
                            onFinish={onUpdate}
                            onFinishFailed={onFinishFailed}>
                            <FormItem>
                                <Input prefix={<ContactsTwoTone />} placeholder={profile.name} />
                            </FormItem>

                            <FormItem name="email"
                                rules={[
                                    {
                                        type: 'email',
                                        message: 'The input is not valid E-mail!',
                                    }
                                ]}
                            >
                                <Input value={profile.email} name="name" prefix={<MailTwoTone />} placeholder={profile}  />
                            </FormItem>
                            <FormItem name="mobile" value={profile.mobile} >
                                <Input value={profile.mobile} name="mobile" prefix={<PhoneTwoTone />} placeholder={profile.mobile} />
                            </FormItem>
                            <FormItem name="addres">
                                <Input name="addres" prefix={<HomeTwoTone />} placeholder={profile.addres} />
                            </FormItem>
                            <FormItem name="description">
                                <Input.TextArea name="description" placeholder="description" rows={4} prefix={<ContainerTwoTone />} />
                            </FormItem>
                            <FormItem>
                                <Button className="width-100" type="primary" htmlType="submit" onClick={onUpdate} >Update</Button>
                            </FormItem>

                        </Form> ```

the useEffect function and the declaration of state :

const [visible, setVisible] = useState(false);
const FormItem = Form.Item;
const [profile, setProfile] = useState({});

useEffect(() => {
    setProfile(props.profile);

},[props.profile] );
const showDrawer = () => {
    setVisible(true);
};

A:
I am looking to set the value of Input from the state that i receive
from props!

If you're just looking to set the input from state, here is a simple example of that.
Solution and Demo
https://codesandbox.io/s/trusting-swanson-1q0ftq
import { useState } from "react";

const initialValue = "John";

const App = () => {
  const [name, setName] = useState(initialValue);

  console.log("render");
  console.log("state: ", name);

  const handleChange = (event) => {
    const value = event.target.value;
    setName(value);
  };

  return (

Form

Type in the input...

      <form>
        <input type="text" onChange={handleChange} value={name} />
      </form>

state: {name}

  );
};

export default App;

Regarding the rest of your question and the example code, it looks like you may be thinking that props should inform some new state based on your useEffect.
However, useEffect runs every time the prop is updated, and when the prop is updated React already triggers a re-render. We can use the new value in our component already, so we don't need to mess with useEffect or state. This would be redundant and unnecessary.
You seem to essentially be asking about how to pass props into your form. Below is an example with editable profile section that is used to manage the profile state. The form section simply reads the values from state and displays the profile information. This illustrates the desired behavior you're describing. The form is just a component that receives the profile state passed down as props.
The profile fields rely on state for their values. The form component relies on props based on that state.
Example Passing Props to Component
https://codesandbox.io/s/damp-fire-sbxmoz
import { useState } from "react";

const initialProfile = {
  firstName: "John",
  lastName: "Doe"
};

const Form = ({ firstName, lastName }) => (

Form

Values based on profile...

    <form>
      <input
        label="First Name"
        type="text"
        name="firstName"
        value={firstName}
      />
      <input label="Last Name" type="text" name="lastName" value={lastName} />
    </form>

);

const App = () => {
  const [profileFields, setProfileFields] = useState(initialProfile);

  const { firstName, lastName } = profileFields;

  console.log("render, profile fields: ", profileFields);

  const handleChange = (event) => {
    const { name, value } = event.target;
    setProfileFields(() => {
      return {
        ...profileFields,
        [name]: value
      };
    });
  };

  return (

      <Form firstName={firstName} lastName={lastName} />

Profile

Type to edit profile fields...

      <form>
        <input
          label="First Name"
          type="text"
          onChange={handleChange}
          name="firstName"
          value={firstName}
        />
        <input
          label="Last Name"
          type="text"
          onChange={handleChange}
          name="lastName"
          value={lastName}
        />
      </form>

  );
};

export default App;

Explanation
You can type in the profile fields to see how the form values are updated via props. Typing in the top form won't update values because these are read-only and "set from props".
You might not want a read-only form, but this is just based on your example. You can pass your profile data as props to whatever component needs it.
I think the idea I'm hoping to communicate here is to think about a "single source of truth" for your profile data (your state) and decide where you want that to live versus what other components need to access it.
Hopefully that helps.

A: Try to log them out and see if they are doing what they are supposed to.

const SomeInput = (props) => {
  const { name, placeholder, value } = props;
  console.log(`${name} placeholder: ${placeholder} value: ${value}`);
  return(
    <input placeholder={placeholder} value={value}/>
  );
};

const App = () => {
  const [state,setState] = React.useState('foo');

  console.log(`App state: ${state}`);

  return(

      <SomeInput name={'input1'} placeholder={state}/>
      <SomeInput name={'input2'} value={state}/>

  );
};

ReactDOM.render(<App/>,document.getElementById("root"));


text:
Q: Android prevent keyboard from closing Is it possible to prevent the user from closing the soft keyboard. In other words, keyboard to be available on the screen (at all times) while my activity is visible. Is this possible? If so, how would you accomplish it?

A: This should force the keyboard to show regardless of focus :
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(yourViewObject.getWindowToken(), 0);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);

A: You need to override the onKeyUp() and onKeyDown() methods like below,
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK)
    {
        ((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput
                (InputMethodManager.SHOW_FORCED,InputMethodManager.HIDE_IMPLICIT_ONLY);
    }
    return super.onKeyUp(keyCode, event);
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK)
    {
        ((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput
                (InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
    }
    return super.onKeyDown(keyCode, event);
}

You can also try in either way, by using OnEditorActionListener, have a look at following code,
EditText txtMyEdit = (EditText) findViewById(R.id.txtEdit);
txtMyEdit.setOnEditorActionListener(new OnEditorActionListener()
{
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
    {
        if (actionId == EditorInfo.IME_ACTION_DONE)
        {
            // your additional processing...
            return true;
        }
        else
        {
            return false;
        }
    }
});


text:
Q: Variables in CSS / Codeigniter? Hey, I'm trying to set variables in my CSS so that I can allow subscribers to customize the colors of their page. I'd rather have as many files on my static server as possibly.
Is there a good / easy way to do this?  Should I just have a CSS file containing all the editable parameters in a CSS file inside the application?
Walker

A: There are a few different ways you could do this:

*

*Use PHP to output your CSS file that contains all the editable CSS values (make sure you remember to set the mime type of the file to text/css).

*Alternatively, you could tell the web server to parse CSS files for PHP code (Apache in the example below).

This goes in your site's .htaccess file (tells the server to look for PHP in CSS files):
AddType application/x-httpd-php .css

This goes at the very top of your CSS file so browsers treat it as a CSS file:
<?php Header ("Content-type: text/css");?>


text:
Q: Hibernate 4, alternative way for implement UserType I need to implement the UserType interface for use a custom type in hibernate.
I seen that the UserType is deprecated in hibernate 4, so there are other way to do it or it can't be done?
Of course I searched on Google and in Stackoverflow but i not found nothing that help me.
Thanks for all.

A: Thanks to Thomas's comments I have implemented the interface provided by Hibernate that is CompositeUserType.
It allow the use of your custom type in the HQL. I haven't noticed a drop of performance while I gained the semplicity to have the enum mapped automatically.
You need only read this doc https://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html/ch06.html#types-custom


text:
Q: Percentage calculation in Pivot Table I need calculate the uptime of each system.
I have the downtime of each issue, date and system information.
I can get the total uptime of each month..
How can I calculate the uptime % of each month in Pivot table?
The uptime % = (Total Uptime - Total downtime)/Total Uptime * 100%
Please kindly help.
Ivan

A: I assume your date format is in number form (i.e. 6/3/2015) for example, then you can create a helper column "Month", using formula =TEXT(A1,"mmm")(Assuming your date is in column A).
You can create a pivot table from this new set of data that include your data and the new helper column.
Place the "Month" in row labels, downtime data in values labels. This will give you a compilation of total downtime for each month.
From there, you can copy the data from the pivot table into new sheet and add in the input for the total uptime of each month that you already have. After that, all you need to do is just use simple addition / subtraction / multiplication to  perform the uptime % =formula.


text:
Q: changing value of QueryString I got the error in Query String. My project was written by ms visual studio 2003. Please see my code below
NAME1 + NAME2 + NAME3 PARA TEST

System tried to get the customer value at PageOne like below
Request.QueryString("Customer").ToString

The value is
NAME1   NAME2   NAME3 PARA TEST

The plus sign is replaced by space. Please share me how to fix this.

A: URL's are subject to URL encoding and decoding.  And unfortunately for your URL, in this encoding scheme a + represents a literal space.  You can fix this issue by encoding the URL yourself so that the browser knows that you have literal + signs in your parameter that should be preserved, like:

A: Try Url decoding in the URL - More info here - HttpServerUtility.UrlDecode Method (String)


text:
Q: Why does Hapi bomb when creating cookies? Setting a simple cookie with Hapi.
return h.redirect('http://localhost:3000/handle-login').state('tester', { authToken, refreshToken })
It breaks.
Error: Invalid cookie value: [object Object]
    at exports.Definitions.internals.Definitions.internals.Definitions.format...

refreshToken and authToken are just strings.
Seems this is a common issue with Hapi
https://github.com/hapijs/hapi/issues?utf8=%E2%9C%93&q=%22Invalid+cookie+value%22
But no real solutions other than disabling some error configs in the server (sounds like a bad idea to me)
How can I make Hapi happy with simple cookie handling?

A: If you are storing a cookie as a JSON, you need to set the encoding attribute when you configure the server:
server.state('tester', {
    ttl: null,
    isSecure: true,
    isHttpOnly: true,
    encoding: 'base64json',
    clearInvalid: true,
    strictHeader: true
});


text:
Q: ¿Cómo haría para sacar datos de dentro de un array JSON en java? En este json, me gustaría conseguir sacar de results, del id PC todos los games:
https://api.rawg.io/api/platforms?key=bf61e2970a4d4af8b77dac08fbc273f4
{
   "count":51,
   "next":"https://api.rawg.io/api/platforms?key=bf61e2970a4d4af8b77dac08fbc273f4&page=2",
   "previous":null,
   "results":[
      {
         "id":4,
         "name":"PC",
         "slug":"pc",
         "games_count":446263,
         "image_background":"https://media.rawg.io/media/games/588/588c6bdff3d4baf66ec36b1c05b793bf.jpg",
         "image":null,
         "year_start":null,
         "year_end":null,
         "games":[
            {
               "id":3498,
               "slug":"grand-theft-auto-v",
               "name":"Grand Theft Auto V",
               "added":17407
            },
            {
               "id":3328,
               "slug":"the-witcher-3-wild-hunt",
               "name":"The Witcher 3: Wild Hunt",
               "added":16143
            },
            {
               "id":4200,
               "slug":"portal-2",
               "name":"Portal 2",
               "added":15229
            },
            {
               "id":5286,
               "slug":"tomb-raider",
               "name":"Tomb Raider (2013)",
               "added":13629
            },
            {
               "id":5679,
               "slug":"the-elder-scrolls-v-skyrim",
               "name":"The Elder Scrolls V: Skyrim",
               "added":13210
            },
            {
               "id":4291,
               "slug":"counter-strike-global-offensive",
               "name":"Counter-Strike: Global Offensive",
               "added":13119
            }
         ]
      }
  }

EDIT(Este seria el codigo que estoy intentando utilizar, pero me da error en el JSONObject["object"]):
JSONObject json = readJsonFromUrl("https://api.rawg.io/api/platforms?key=bf61e2970a4d4af8b77dac08fbc273f4");

        JSONObject jsonobject1 = json.getJSONObject("object");
//      JSONObject jsresults = jsonobject.getJSONObject("results");
//      JSONObject js0 = jsresults.getJSONObject("0");
//      JSONObject jsgames = js0.getJSONObject("games");
//      System.out.println(jsgames.get("name"));

        JSONArray arr = jsonobject1.getJSONArray("results");
        for (int i = 0; i < arr.length(); i++) {
            String post_id = arr.getJSONObject(i).getString("0");
            System.out.println(post_id);
        }

A: Puedes obtener los juegos de PC, de manera simple usando una combinación de getJSONArray y getJSONObject dependiendo del tipo de objeto que sea la clave en el json. Finalmente puedes iterar los juegos de PC con un simple for:
JSONArray gamesPC = json.getJSONArray( "results" )
        .getJSONObject( 0 )
        .getJSONArray( "games" );

for (int i = 0; i < gamesPC.length(); i++) {
    JSONObject game = gamesPC.getJSONObject( i );
    System.out.println(game.toString(4));

    // Alternativamente usa esto para imprimir solo el nombre
    System.out.println(game.getString("name"));
}

A: Para obtener el nombre de los games:
JSONObject json = readJsonFromUrl("https://api.rawg.io/api/platforms?key=bf61e2970a4d4af8b77dac08fbc273f4");
        //convert json results to array
        JSONArray jsonArray = json.getJSONArray("results");
        //from jsonArray name PC get games names
        JSONObject jsonObject = jsonArray.getJSONObject(0);
        //get games names
        JSONArray jsonArray2 = jsonObject.getJSONArray("games");
        //iterate over jsonArray2 and print names
        for (int i = 0; i < jsonArray2.length(); i++) {
            System.out.println(jsonArray2.getJSONObject(i).getString("name"));
        }

Para ver las consolas y sus juegos:
JSONObject json = readJsonFromUrl("https://api.rawg.io/api/platforms?key=bf61e2970a4d4af8b77dac08fbc273f4");
        //convert json results to array
        JSONArray jsonArray = json.getJSONArray("results");
        //iterate over array
        for (int i = 0; i < jsonArray.length(); i++) {
            System.out.println(jsonArray.getJSONObject(i).get("name"));
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            JSONArray jsonArray2 = jsonObject.getJSONArray("games");
            //iterate over jsonArray2 and print names
            for (int j = 0; j < jsonArray2.length(); j++) {
                System.out.println("---"+jsonArray2.getJSONObject(j).getString("name"));
            }
        }


text:
Q: A record correct? I have domain in one company, with an specific NS entries, but I don't want changes the NS entries.
The server is in another company with public IP.
If I want to point from my domain to the server, is enough with adding an A record into the domain company, that A entry would point to my public IP.
Is that OK?
How long it takes the changes?
How can I trace the A record propagation?

A: Use your domain companies tools to create an A record that points to the public IP address of your server. The changes can take quite some time perhaps up to 72 hours for global coverage but would generally be less. You can try tools like this to see how your A record is propagating.

A: Adding a new A record for a new domain (host) should propagate quite quickly.  Initial queries will go to your nameserver rather than caches.  Changes to that domain will depend on the TTL for the domain.
There may be some delay with synchronizing the nameservers, but many setups use notify.  This will speed things up.
The main problem will be possible negative caching.  This should not be much of a problem, as noone should have been looking for the domain.


text:
Q: Local branch shows unstaged changes and untracked files without apparent reason Recently I started to work on a big project, I just cloned the repository, the main branch is called dev all the pull requests are merged into that branch.
I haven't done any work on the repo, but for some reason when I do git status it shows changes I don't have any idea. I do this in order to clean my git status:
git add . && git reset --hard HEAD
This way I just remove all those local changes that appeared magically and to make sure my dev branch is up to date with remote I just make a git pull
However this is happening repeatedly, so this is becoming annoying. Today I checked there are some unstaged changes and looking to the remote dev branch I can see that those changes were committed today. I think that for some reason git is synchronizing the dev branch with my local dev branch and showing changes as local changes.
Any idea why this could be happening?

A: The reason why this is happening is that you're seeing automatically generated files from your IDE.
This is very normal. What you need to do is simply add these files to .gitignore and
git add .gitignore && git commit -m "Update gitignore" on dev if you have permissions.
If you don't have permissions, create a branch:
git checkout -b gitignore

add the automatically generate files to .gitignore and commit these changes
git add .gitignore && git commit -m "Update .gitignore"

Once you create another feature branch from dev, just go to that feature branch and
git merge gitignore

However, note that the above solution will only work to files that have not been tracked yet. If your files are tracked, as you did, by staging them, then:
After adding each file to .gitignore, what you need to do is:
git update-index --assume-unchanged <file>

Or else, .gitignore will not be able to ignore these files after they've been tracked.


text:
Q: SVD of (2,1,-2) not ok I'm trying to find the SVD of
$$
\begin{pmatrix}
2&1&-2\\
\end{pmatrix}
$$
I found $$\Sigma , u$$
But on the V matrix I got
$$
\begin{pmatrix}
-\frac{2}{3}&&\frac{1}{\sqrt{2}}&&\frac{-1}{\sqrt{5}} \\
-\frac{1}{3}&&0&&\frac{2}{\sqrt{5}} \\
\frac{2}{3}&&\frac{1}{\sqrt{2}}&&0 \\
\end{pmatrix}
$$
While Wolfram Alpha gives :
result
I checked the eigenvectors on wolfram alpha as well and they are correct:
$$
\begin{pmatrix}
-2&&1&&-1\\
-1&&0&&2\\
2&&1&&0\\
\end{pmatrix}
$$
I realized that the 3rd collumn of V (the one from wolfram alpha) is obtained by doing the cross product of the first two eigenvectors , why is that ?

A: A singular value decomposition of a $1\times 3$ matrix can be written almost "by inspection":
$$ \begin{pmatrix} 2 & 1 & -2 \end{pmatrix} = U \Sigma V^* $$
where $U,V$ are unitary (in this case, orthogonal) matrices and $\Sigma$ is a rectangular diagonal matrix with the required singular values on the diagonal:
$$ \Sigma = \begin{pmatrix} \lambda & 0 & 0 \end{pmatrix} $$
Since $U$ is a $1\times 1$ unitary matrix, actually $U = (1)$ is just the $1\times 1$ identity.  $\Sigma$ is a $1\times 3$ matrix of equal Euclidean norm to $\begin{pmatrix} 2 & 1 & -2 \end{pmatrix}$, so $\Sigma = \begin{pmatrix} 3 & 0 & 0 \end{pmatrix}$.
The requirement that $V$ be unitary (or orthogonal) does not uniquely specify its entries.  So long as:
$$ \begin{pmatrix} 3 & 0 & 0 \end{pmatrix} V^* = \begin{pmatrix} 2 & 1 & -2 \end{pmatrix} $$
it will meet the definition of a singular value decomposition, and from this we see that only the first column of $V$ (top row of $V^*$) is determined:
$$ V^* = \begin{pmatrix} \frac{2}{3} & \frac{1}{3} & -\frac{2}{3} \\
{-} & {-} & {-} \\ {-} & {-} & {-} \end{pmatrix} $$
The bottom two rows of $V^*$ can be filled in with any pair of unit vectors that make up an orthonormal basis for $\mathbb{R}^3$ together with the top row shown.  Therefore it is not surprising that the third row might be the cross-product of the first two rows (since the third row will be determined, up to sign, by the first two rows).

A: Problem
Detailed instructions for computing the SVD abound on Math Stack Exchange. For example: SVD and the columns, SVD -obligation of normalization, how SVD is calculated in reality, Pseudo-inverse of a matrix that is neither fat nor tall?.
This problem is straightforward. Let the target matrix be the covector
$$
\mathbf{A} = \left[ \begin{array}{ccr}
 2 & 1 & -2
\end{array} \right]
$$
Find the singular value decomposition
$$
 \mathbf{A} = \mathbf{U} \, \Sigma \, \mathbf{V}^{*}
$$
Methods
The first link presents a table showing two paths for finding the SVD for a matrix $\mathbf{A} \in \mathbb{C}^{m \times n}_{\rho}$:
$$
\begin{array}{lll}
%
 \text{Operation} &
\text{Row space first} & \text{Column space first} \\\hline
%
  \text{1. Construct product matrix}  &
  \mathbf{W} = \mathbf{A}^{*} \mathbf{A} &
  \mathbf{W} = \mathbf{A} \, \mathbf{A}^{*} \\
%
  \text{2. Solve for eigenvalues}  &
  \sigma = \tilde{\lambda} \left( \mathbf{W} \right) &
  \sigma = \tilde{\lambda} \left( \mathbf{W} \right) \\
%
  \color{blue}{\text{3. Solve for eigenvectors }} w_{k},\  k=1, \rho  &
  \left( \mathbf{W} - \lambda_{k} \mathbf{I}_{n} \right) w_{k} = \mathbf{0} &
  \left( \mathbf{W} - \lambda_{k} \mathbf{I}_{m} \right) w_{k} = \mathbf{0} \\
%
  \text{4. Assemble domain matrix}  &
  \mathbf{V}_{k} = \frac{w_{k}}{\lVert w_{k} \rVert_{2}} &
  \mathbf{U}_{k} = \frac{w_{k}}{\lVert w_{k} \rVert_{2}} &
\\
%
  \text{5. Compute complementary domain matrix}  &
  \mathbf{U}_{k} = \sigma_{k}^{-1} \mathbf{A} \mathbf{V}_{k} &
  \mathbf{V}_{k} = \sigma_{k}^{-1} \mathbf{A}^{*} \mathbf{U}_{k} &
\\
%
\end{array}
$$
The two product matrices to wrok with are
$$
\mathbf{A} \mathbf{A}^{*} =
\left[
\begin{array}{c}
  9 \\
\end{array}
\right]
\qquad
\mathbf{A}^{*} \mathbf{A} =
\left[
\begin{array}{rrr}
  4 &  2 & -4 \\
  2 &  1 & -2 \\
 -4 & -2 &  4 \\
\end{array}
\right].
$$
Solution
The product matrix $\mathbf{A} \mathbf{A}^{*}$ is much easier to work with!
Singular values
The eigenvalue is
$$
 \lambda \left( \mathbf{A}\mathbf{A}^{*} \right) = 9
$$
which implies the singular value is
$$
 \sigma = \sqrt{\lambda \left( \mathbf{A}\mathbf{A}^{*} \right)} = 3
$$
The matrix of singular values is
$$
 \mathbf{S} =
\left[
\begin{array}{c}
  3
\end{array}
\right]
$$
There is no need for $0$ padding, so
$$
 \Sigma = \mathbf{S}
$$
Matrix $\mathbf{U}$
The eigenvector is already normalized and represents the first column
$$
\mathbf{U} =
\color{blue}{\left[
\begin{array}{c}
  1
\end{array}
\right]}
$$
Coloring distinguishes $\color{blue}{range}$ space vectors from $\color{red}{null}$ space vectors.
Column space
$$
\begin{align}
 \color{blue}{\mathcal{R}\left(\mathbf{A}\right)}
&=
\text{span} \left\{ \,
\color{blue}{\left[
\begin{array}{c}
  1
\end{array}
\right]}
\, \right\} \\
%
 \color{red}{\mathcal{N}\left(\mathbf{A}^{*}\right)}  &=
\left\{ 0 \right\}
\end{align}
$$
Matrix $\mathbf{V}$
$$
  \mathbf{V}_{1}
= \frac{1}{\sigma} \mathbf{A}^{*} \mathbf{U}_{k}
= \frac{1}{3}
\color{blue}{\left[
\begin{array}{r}
  2 \\ 1 \\ -2
\end{array}
\right]}
$$
For the $\color{red}{null}$ space vectors, we have options. We could call upon the process of Gram and Schmidt. Or we could eyeball the problem to find any $\color{red}{null}$ space vector, and use the cross product to find the missing vector.
Choosing the latter, we select
$$
\color{red}{\mathbf{V}_{2}} = \frac{1}{\sqrt{2}}
\color{red}{\left[
\begin{array}{r}
  1 \\ 0 \\ 1
\end{array}
\right]}
$$
The missing vector is then
$$
\color{blue}{\left[
\begin{array}{r}
  2 \\ 1 \\ -2
\end{array}
\right]}
\times
\color{red}{\left[
\begin{array}{r}
  1 \\ 0 \\ 1
\end{array}
\right]}
=
\color{red}{\left[
\begin{array}{r}
  1 \\ -4 \\ -1
\end{array}
\right]}
$$
Final assembly
$$
\begin{align}
 \mathbf{A} &= \mathbf{U} \, \Sigma \mathbf{V}^{*}
% U
\\ &=
\color{blue}{\left[
\begin{array}{c}
  1
\end{array}
\right]}
% Sigma
\left[
\begin{array}{c}
  3
\end{array}
\right]
% V*
\left[
\begin{array}{ccc}
  % c1
\frac{1}{3}
\color{blue}{\left[
\begin{array}{r}
  2 \\ 1 \\ -2
\end{array}
\right]}
  % c2
\frac{1}{\sqrt{2}}
\color{red}{\left[
\begin{array}{r}
  1 \\ 0 \\ 1
\end{array}
\right]}
  % c3
\frac{1}{3\sqrt{2}}
\color{red}{\left[
\begin{array}{r}
  1 \\ -4 \\ -1
\end{array}
\right]}
\end{array}
\right]
%
\\ &=
 \left[ \begin{array}{ccr}
 2 & 1 & -2
\end{array} \right]
%
\end{align}
$$