text:
Q: Shiny App - take user input into user defined function and download resulting files I am trying to build my first Shiny app.
I have a user defined function which takes generates encryption keys. I'd like to make it in to a Shiny app.
I had a go as below.
The first bit of the UI works in that it asks for text input for the users name (this should be used to label the output files) - and I managed to get an action button which the user could then click to in theory run the code to make the encryption keys.
library(shiny)

# Define UI for ODK Encryption app ----

# Define UI for application that draws a histogram
ui <- fluidPage(

  # Application title
  titlePanel("Make ODK Encryption Keys"),

  # Sidebar with a slider input for number of bins
  sidebarLayout(
    sidebarPanel(
      textInput("name",
                  "Enter your name:"),
      actionButton(inputId = "input_action", label = "Generate Keys")

    ),

    mainPanel(

    )
  )
)

I feel that there ?should be something in mainPanel to give a link for the outputted key files or alternatively they could just automatically get downloaded?
Then within the server section I
1) Take the sys-date-time as a seed
2) Take the name (as inputted above) and link that to the sys-date to make a file name for the eventual keys
3) Then I define my function (create.key.pair)
- This takes the sys-date-time (set in 1 above) and uses that and openSSL to generate a public and private key. It labels these files using the name inputted in point 2 (which should take the input from the sidebar section of the UI in the shiny app)
#Make the Key

server <- function(input, output) {
  observeEvent(input$button, {
    key_seed <- round(as.numeric(Sys.time()),0)
    key_name <- paste(name,Sys.Date(),sep="_")
    create.key.pair<-function(keynumber)
    {
      folder<-paste("ODK.KEY",key_name,sep=".")                      #make a folder name
      system(paste("mkdir",folder,sep=" "))                           #create the folder

      name.private.key<-paste("ODK.PRIVATE.KEY.",key_name,".pem",sep = "") #make a name for the keys
      name.public.key<-paste("ODK.PUBLIC.KEY.",key_name,".pem",sep = "")

      keygen.private<-paste("openssl genrsa -out ",folder,"/",name.private.key," 2048",sep="") #create the system call
      system(command = keygen.private) #create the private key

      keygen.public<-paste("openssl rsa -in ",folder,"/",name.private.key," -inform PEM -out ",folder,"/",name.public.key," -outform PEM -pubout",sep="")

      system(command = keygen.public) #create the private key
    }
    create.key.pair(key_seed)
  })
}

shinyApp(ui, server)

I need some guidance on whether
A) I need to add something within mainPanel to show/download the outputted files
B) The code within the server section should work
I can't currently tell if my error is in A or B just that it doesnt generate keys (whereas my R script version of this works just fine)
First time using Shiny so any help gratefully accepted.

A: If I fix some slight bugs it's working the same way in shiny and as a usual R script:

*

*input$input_action and input$name

*adding key_name to your function

Also, do not load your function in observeEvent as this will cause your app to reload the function every time someone clicks the actionButton. You can instead load it once prior to your app start.
Your code is then:
library(shiny)

create.key.pair<-function(keynumber, key_name)
{
    folder<-paste("ODK.KEY",key_name,sep=".")                      #make a folder name
    system(paste("mkdir",folder,sep=" "))                           #create the folder

    name.private.key<-paste("ODK.PRIVATE.KEY.",key_name,".pem",sep = "") #make a name for the keys
    name.public.key<-paste("ODK.PUBLIC.KEY.",key_name,".pem",sep = "")

    keygen.private<-paste("openssl genrsa -out ",folder,"/",name.private.key," 2048",sep="") #create the system call
    system(command = keygen.private) #create the private key

    keygen.public<-paste("openssl rsa -in ",folder,"/",name.private.key," -inform PEM -out ",folder,"/",name.public.key," -outform PEM -pubout",sep="")

    system(command = keygen.public) #create the private key
}

# Define UI for ODK Encryption app ----

# Define UI for application that draws a histogram
ui <- fluidPage(

    # Application title
    titlePanel("Make ODK Encryption Keys"),

    # Sidebar with a slider input for number of bins
    sidebarLayout(
        sidebarPanel(
            textInput("name",
                      "Enter your name:"),
            actionButton(inputId = "input_action", label = "Generate Keys")

        ),

        mainPanel(

        )
    )
)

#Make the Key

server <- function(input, output) {
    observeEvent(input$input_action, {

        key_seed <- round(as.numeric(Sys.time()),0)
        key_name <- paste(input$name,Sys.Date(),sep="_")
        create.key.pair(key_seed, key_name)
    })
}

shinyApp(ui, server)


text:
Q: content assist is not available at current location error if I use ctrl+space for the views declared inside  I am using eclipse Juno in ubuntu 12.04 environment for android app development. I am facing one very strange problem with eclipse. Whenever I press CTRL+SPACE I get error saying

content assist is not available at current location

This is only happening when I use CTRL+SPACEfor the views declared inside <android.support.v4.widget.DrawerLayout> tag.
I googled a lot, but dint find working solution. Some people responded that

Here you using, android.support.v4.widget.DrawerLayout and hence the
  issue

here
Please check my xml file below:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <!-- The main content view -->

        <GridView
            android:id="@+id/gridView1"
            android:layout_width="match_parent"

            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:gravity="center"
            android:layout_centerInParent="true"
            android:columnWidth="50dp"
            android:fitsSystemWindows="true"
            android:horizontalSpacing="10dp"
            android:numColumns="2"
            android:rowHeight="50dp"
            android:background="#000000"
            android:stretchMode="columnWidth"
            android:verticalSpacing="10dp" >
        </GridView>
    <!-- The navigation drawer -->

    <LinearLayout
        android:id="@+id/drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#f4f4f4"
        android:orientation="vertical" >

        <ExpandableListView
            android:id="@+id/drawer_list1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/blue_gray_back"
            android:cacheColorHint="#00000000"
            android:groupIndicator="@android:color/transparent" />
    </LinearLayout>

</android.support.v4.widget.DrawerLayout>

Now If I remove
 <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
 </android.support.v4.widget.DrawerLayout>

everything works perfectly. all the attributes of the GridView are showing in suggestion by pressing CTRL+SPACE. So I figured out the problem is occurring due to  <android.support.v4.widget.DrawerLayout>.
How can I resolve this issue, because I must have to use above tab in xml?

redpajama_set_name: RedPajamaStackExchange


text:
Q: AngularJS disabled select input behaviour not same as native HTML It seems that when an input or select is disabled in angularjs, the model value remains the same. My problem is that this is not the same as native form behaviour in HTML, and that I have to invoke some extra behaviour via an ng-change scope method in order to get the proper behaviour, which is for the value to be set to null if the input or select input is disabled.
Here is my example:

    <select ng-disabled="disableIt" ng-model="data">
        <option>1</option>
        <option>2</option>
    </select>
    <input type="text" ng-model="textData" ng-disabled="disableIt" />

    <input type="checkbox" ng-model="disableIt"/>

    Select Data: {{selectData}}

    Text Data: {{textData}}

You can test it out on jsfiddle here: http://jsfiddle.net/9wbtnhno/1/
The desired result is for the textData and selectData models to be null when disabled.


text:
Q: Implementing Laugerre's method in python I'm writing a python module for mathematics, and I've tried to create a basic implementation
of Laguerre's Method, without using external libraries such as numpy or scipy.
Laguerre's method is an algorithm for finding roots of polynomials ( i.e : intersection with the x axis ) , and it's further elaborated in
Wikipedia: https://en.wikipedia.org/wiki/Laguerre%27s_method
Here is what I came up with:
def laguerre_method(f_0: Callable, f_1: Callable, f_2: Callable, x0: float, n: float, epsilon: float = 0.00001):
    xk = x0
    while abs(f_0(xk)) > epsilon:
        G = f_1(xk) / f_0(xk)
        H = G ** 2 - f_2(xk) / f_0(xk)
        root = cmath.sqrt((n - 1) * (n * H - G ** 2))
        d = max(abs(G + root), abs(G - root))
        a = n / d
        xk -= a
    return xk

f_0 is the original function, f_1 is its derivative, and f_2 is the second derivative.
x0 is a guess we start from.  Epsilon represents how close to 0 the y value of a point should be, to be considered a root.
n represents the power of the polynomial, i.e, for x^3 + 3x + 5, the power is 3.
For some reason, the method works as expected when the initial value ( x0 ) is positive, and even with small negative numbers, but it fails with bigger negative values, showing math domain error or OverflowError: (34, 'Result too large') , or ZeroDivisionError: float division by zero
For example, let's define a function, its derivative, and its second derivative with lambdas:
 f_0 = lambda n: 2 * n ** 3 - 5 * n ** 2 - 23 * n - 10
 f_1 = lambda n: 6 * n ** 2 - 10 * n - 23
 f_2 = lambda n: 12 * n - 10

The code works for these inputs:
print(laguerre_method(f_0, f_1, f_2, 6, 3))

print(laguerre_method(f_0, f_1, f_2, -1, 3))

And outputs approximately 5.0 and -2.0 respectively, which are the corresponding roots.
However it fails with this input for example:
print(laguerre_method(f_0, f_1, f_2, -7, 3))

The algorithm is detailed in Wikipedia.
Keep in mind this is not the finished implementation, and that I know I've probably made a stupid error, so expect stupidity from my side.

A: This line:
d = max(abs(G + root), abs(G - root))

Should be:
d = max([G + root, G - root], key=abs)


text:
Q: Python hashlib & decode() on a Bytes Object I'm not understanding something about hashlib. I'm not sure why I can decode a regular byte object, but can't decode a hash that's returned as a byte object. I keep getting this error:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xad in position 1: invalid start byte
Here's my test code that's producing this error. The error is on line 8 (h2 = h.decode('utf-8'))
import hashlib

pw = 'wh@teV)r'
salt = 'b7u2qw^T&^#U@Lta)hvx7ivRoxr^tDyua'
pwd = pw + salt
h = hashlib.sha512(pwd.encode('utf-8')).digest()
print(h)
h2 = h.decode('utf-8')
print(h2)

If I don't hash it, it works perfectly fine...
>>> pw = 'wh@teV)r'
>>> salt = 'b7u2qw^T&^#U@Lta)hvx7ivRoxr^tDyua'
>>> pwd = pw + salt
>>> h = pwd.encode('utf-8')
>>> print(h)
b'wh@teV)rb7u2qw^T&^#U@Lta)hvx7ivRoxr^tDyua'
>>> h2 = h.decode('utf-8')
>>> print(h2)
wh@teV)rb7u2qw^T&^#U@Lta)hvx7ivRoxr^tDyua

So I'm guessing I'm not understanding something about the hash, but I have no clue what I'm missing.

A: In the second example you're just encoding to UTF-8 and then decoding the result straight back.
In the first example, on the other hand, you're encoding to UTF-8, messing about with the bytes, and then trying to decode it as though it's still UTF-8. Whether the resulting bytes are still valid as UTF-8 is purely down to chance (and even if it is still valid UTF-8, the Unicode string it represents will bear no relation to the original string).


text:
Q: Submitting multiple variables with one input foreach($rates as $item){
    if ($item->disabled == false){
        echo '<input type="radio" name="rate" id="membership" required="yes" message="Please select your membership type."  value="' . $item->rate . '"><input type="hidden" name="membership" value="' . $item->membership . '" >';
    }
}

This is probably pretty simple, but the issue that I'm having is that I can't get $item->membership to submit with $item->rate. For example when somebody selects the '125' rate, it should also submit 'Student' or whatever. When I do submit the form though, it submits the last $item->membership in the series instead of the one that is tied to it's rate... Any help would be appreciated, I'm sure I'm overthinking this.
Thanks

A: Because they all have the same name attribute, so they set the same variable multiple times and thus the last one is what you always get. Try giving all the hidden inputs unique names, so you can get the membership you want. HTML forms aren't smart enough to pick only the hidden input next to the radio button, they all get posted.

A: When you submit an form, hidden field and radio button are independent elements regardless how you wrap them together.
Here is my solution to pass multiple variables for each radio button
view:
<form method="post" action="your_post_file.php" >
    <?php $i = 1;  foreach($rates as $item){?>
        <input type="radio" name="rates[]" value="<?php echo $i?>" /><?php echo $item->rate?>
        <input type="hidden" name="rate<?php echo $i?>" value="<?php echo $item->rate?>" />
        <input type="hidden" name="membership<?php echo $i?>" value="<?php echo $item->member_id?>" />
    <?php $i++;}?>

    <input type="submit" />
</form>

on the your_post_file.php
if(isset($_POST['rates'])){
            if(is_array($_POST['rates'])){

                $index = $_POST['rates'][0]; //return the index of selected radio button

                $rate =  $_POST['rate' . $index];
                $membership_id =  $_POST['membership' . $index];

                //print out the result
                var_dump($rate);
                var_dump($membership_id);

            }
        }

Bingo, you get what you want, even you want more the value for each rate, just add more hidden field with same given format, such as first name, last name, or anything else.


text:
Q: C++ Hexadecimal Multiplication Segmentation Fault Let me first start by saying I do not have access to debuggers and I'm using Nano as my editor
Currently, with my calculator, I am beating my head against a brick wall(segmentation fault). I've tried going through my pointers to discover what my problem is, but my lack of experience/knowledge has only gotten me so far. Let me explain what works so far in my program. Currently, I am able to store hexadecimal numbers in a linked list and add them together. The problem comes from my multiplication method.Somehow leftNode is becoming NULL midway through the multiplication method throwing a segmentation fault. I'm wondering at what point does leftNode become NULL?
Multiplication Method:
LList Calculator::multiply(LList& left, LList& right) {
    LList prodSum;
    listnode *leftNode = (left.next());
    int zeros = 0;
    for(;;) {
        if(leftNode == NULL) break;
        int lval = leftNode->data;
        LList curList;
        for(int i = 0; i < zeros; i++) {
            curList.insertTail(0);
        }
        right.reset();
        listnode *rightNode = (right.next());
        int carry = 0;
        while(rightNode != NULL) {
            int rval = rightNode->data;
            int product = lval * rval + carry;
            carry = product / 16;
            product %= 16;
            curList.insertTail(product);
            rightNode = (right.next());
        }
        while(carry) {
            curList.insertTail(carry % 16);
            carry /= 16;
        }
        prodSum = *add(prodSum, curList);
        leftNode = (left.next()); // eventually causes a segmentation fault
        leftNode->data << endl;
        ++zeros;
    }

    return prodSum;
}

Classes related to multiplication:
class listnode {
    public:
        element data;
        listnode * next;
};

class LList {
    private:
        listnode * head;
        listnode * tail;
        listnode * view;

    public:
        LList();
        ~LList();
        void read();
        listnode* next();
        void reset();
        void print();
        void insertTail(element val);
        void clean();

        element deleteHead();
};

class Calculator {
    public:
        Calculator();
        //inline LList* add(LList& left, LList& right); works
        inline LList multiply(LList& left, LList& right);
};

Calculator::Calculator() {

};

Other methods related to traversing nodes:
listnode* LList::next() {
    listnode* temp = view;
    if(temp != NULL)
        view = view->next;

    if(view == NULL) {
    }
    return temp;
};

void LList::reset() {
    view = head;
}

LList::LList(){
    head = NULL;
    view = NULL;
};

void LList::insertTail(element val) {
    listnode * temp;
    temp = new listnode;
    temp -> data = val;
    temp -> next = NULL;

    if(head == NULL) {
        head = temp;
        view = head;
    }
    else
        tail -> next = temp;
    tail = temp;
};

void LList::clean() {
    while(head != NULL)
        deleteHead();
};

element LList::deleteHead() {
    listnode * temp;
    temp = head;
    head = head -> next;
    delete temp;
    return temp -> data;
};

LList::~LList(){
    delete head;
};

A: it's me again.
One exception occurs after the line you marked: // eventually causes a segmentation fault, there seems to be a partially-formed line for sending leftNode->data to cout, but on the final iteration through left's nodes, leftNode = (left.next()); will set leftNode to NULL, so a dereference here might be causing the fault.
One other problem is that no copy constructor or assignment operator is defined for LList, so this line: prodSum = *add(prodSum, curList); will give prodSum a set of list nodes that will be deleted right after.
However, LList's destructor only seems to delete the head node, not the whole list, so there's a grab-bag of invalid and valid going on.
Also, multiply returns prodSum, so the lack of a copy constructor will make something similar happen.
I'm including a version of your code that seems to work.  I had to make my own add function, just because I don't see it here.
I made the destructor delete all of the LList's nodes.
I marked the default copy constructor and assignment operator =delete because the default implementations do the wrong thing.
In order to pass LList objects around by value, I added a move constructor and a move assignment operator.  These pass allocated nodes from one object to another, and only one object is allowed to keep one set of nodes, so you don't have to worry about double-destruction.
#include <iostream>
#include <string>

typedef int element;

class listnode {
    public:
        element data;
        listnode * next;
};

class LList {
        listnode *head, *tail, *view;
    public:
        LList() { head = view = tail = NULL; }
        LList(LList&& src) : head(src.head), tail(src.tail), view(src.view) { src.head = src.tail = src.view = nullptr; }
        LList(const LList&) = delete;
        ~LList() { clean(); }
        LList& operator = (LList&& src) {
            clean();
            /* OK here */
            head = src.head;
            tail = src.tail;
            view = src.view;
            src.head = src.tail = src.view = nullptr;
            return *this;
        }
        LList& operator = (const LList&) = delete;
        listnode* next() {
            listnode* temp = view;
            if(temp) view = view->next;
            return temp;
        }
        void reset() { view = head; }
        void print();
        void insertTail(element val) {
            listnode* temp = new listnode;
            temp->data = val;
            temp->next = NULL;

            if(!head) { view = head = temp; }
            else      { tail->next = temp;  }
            tail = temp;
        }
        void clean() { while(head) deleteHead(); }

        element deleteHead() {
            listnode*  temp = head;
            head = head->next;
            const element data = temp->data;
            delete temp;
            return data;
        }
};

LList add(LList& left, LList& right) {
    LList sum;
    int carry = 0;
    left.reset();
    right.reset();
    for(;;) {
        const listnode* leftNode = left.next();
        const listnode* rightNode = right.next();
        if(!leftNode && !rightNode) break;
        if(leftNode) carry += leftNode->data;
        if(rightNode) carry += rightNode->data;
        sum.insertTail(carry % 16);
        carry /= 16;
    }
    if(carry) sum.insertTail(carry);
    return sum;
}

LList multiply(LList& left, LList& right) {
    LList prodSum;
    listnode *leftNode = left.next();
    int zeros = 0;
    for(;;) {
        if(!leftNode) break;
        int lval = leftNode->data;
        LList curList;
        for(int i = 0; i < zeros; i++) {
            curList.insertTail(0);
        }
        right.reset();
        listnode *rightNode = right.next();
        int carry = 0;
        while(rightNode) {
            int rval = rightNode->data;
            int product = lval * rval + carry;
            carry = product / 16;
            product %= 16;
            curList.insertTail(product);
            rightNode = right.next();
        }
        while(carry) {
            curList.insertTail(carry % 16);
            carry /= 16;
        }
        prodSum = add(prodSum, curList);
        leftNode = left.next(); // eventually causes a segmentation fault
        //std::cout << leftNode->data << std::endl;
        ++zeros;
    }
    return prodSum;
}

LList string_to_list(std::string hex_string) {
    LList list;
    for(size_t i=hex_string.length()-1; i+1; --i) {
        char c = hex_string[i] | 0x20;
        if     (c >= '0' && c <= '9') list.insertTail(c - '0');
        else if(c >= 'a' && c <= 'f') list.insertTail(c - 'a' + 10);
    }
    return list;
}

std::string list_to_string(LList& list) {
    std::string hex_string;
    list.reset();
    for(;;) {
        listnode* node = list.next();
        if(!node) return hex_string;
        static const char digits[] = "0123456789abcdef";
        hex_string = digits[node->data] + hex_string;
    }
}

int main() {
    //LList list = string_to_list("1234aBcd");
    //std::string s = list_to_string(list);
    //std::cout << s << '\n';

    LList left = string_to_list("111");
    LList right = string_to_list("333");
    LList prod = multiply(left, right);
    std::cout << list_to_string(prod) << '\n';
}


text:
Q: OpenSearch Amazon S3 Plugin Does Not Appear in OpenSearch Dashboard I want to use my Amazon S3 bucket as a snapshot repository for my OpenSearch installation on MacOS.
I installed the S3 plugin by going to Docker Desktop and clicking on the Open in Terminal link for the opensearch node. In the terminal I entered ./bin/opensearch-plugin install repository-s3. I did not encounter any errors.
I then opened the OpenSearch Dashboards and the plugin was not listed in the OpenSearch plugins menu.
How can I troubleshoot and fix this issue?


text:
Q: routing to a view without passing variables - laravel I'm new to Laravel.
In the question.blade view I receive two variables from a controller as follows :

*

*@foreach ($answer as $answers)

*{{$post->body}}
Sometimes I want to be routed to this question.blade view but without passing one or both of the variables.
I noticed if I want for example to normally be linked to this view to view its contents , I receive this error :
Undefined variable: answer (View: D:\wamp\www\xxxxxxx\resources\views\Question.blade.php)
Is there a way to tell a blade to only expect variables when the user is routed by a specific controller=>method, while not expect variables when the user is routed by another method?
I hope this is clear :)

A: Simple way is to just check if desired variable does exist:
@if (isset($answers))
    @foreach ($answers as $answer)
        ...
    @endforeach
@endif

{{ isset($post) ? $post->body : '' }}

A: for the part of the view which have variable data , you may separate it as a partial blade view file . then you check if it is exists. or count the array .
@if(count($array))
    <div class="col-xs-12" style="margin: auto;">
        @include('partials.myview')
    </div>
@endif

Better to give the variable or array empty value to avoid errors for whatever reason .


text:
Q: Alglib minnlc returns answer out of constraints I am trying to implement a simple minimisation under a quadratic inequality constraint and a linear equality constraint as well as lower and upper bounds. My problem is as follow:
min: x1*(-0.00498) + x2*0.05656
u.c. :

*

*x1^2 * 0.00001048 + 2*x1*x2*0.001431 + x2^2*0.6737996 <= 0.0084050

*x1 + x2 = 1.0

*0 < x1 < 0.9

*0 < x2 < 0.9

Once implemented in F# using Alglib it seems that the constraints are not respected. Neither the sum x1+x2 is equal to 1.0 nor the variance is below 0.0084. Though lower and upper bound are respected, my objective function with x2 is improved (lower) than with x0. I believe I have an issue with my formulation of the constraints, but I can't see which one.
l
let nsfunc2_jac(x:float[]) (fi:float[])(jac:float[,])=
   fi.[0] <- -(x.[0]*-0.00498+x.[1]*0.05656)
   fi.[2] <- x.[0]+x.[1]+x.[2]-1.0
   fi.[1] <- x.[0]*x.[0]*0.00001048 + 2.0*x.[0]+x.[1]*0.001431 + x.[1]*x.[1]*0.6737996-0.0084050
   jac.[0,0] <- -0.00498
   jac.[0,1] <- 0.05656
   jac.[2,0] <- 1.0
   jac.[2,1] <- 1.0
   jac.[1,0] <- 2*x.[0]*0.00001048 + 2*x[1]*0.001431
   jac.[1,1] <- 2*x.[0]*0.001431 + 2+x[1]*0.6737996

let mutable state2 = new alglib.minnlcstate()
let mutable rep2 = new alglib.minnlcreport()
let mutable nrep = new alglib.ndimesional_rep(func2)
let x0 = [|0.8999, 0.1001|]
alglib.minnlccreate(2,x0, &state2)
alglib.minnlcsetalgoaul(state2, 1000.0, 15.0)
alglib.minnlsetcond(state2, 0.000001,10.0)
alglib.minnlcsetscale(state2, [|1.0,1.0|])
alglib.minnlcsetprecexactlowrank(state2, 5.0)
alglib.minnlcsetnlc(state2, 1,1)
alglib.minnlcsetbc(state2, [|0.0,0.0|], [|0.9,0.9|])

alglib.minnlcoptimize(state2, jac, nrep, None)
let x2, rep = alglib.minnlcresults(state2)
let var = x2.[0]*x2.[0]*0.00001048 + 2.0*x2.[0]+x2.[1]*0.001431 + x2.[1]*x2.[1]*0.6737996
printfn "Variance: %s" var.ToString()

I get Var = 0.53 well above the 0.0084050 target. In fact, after the first iteration both my equality and my inequality constraints are broken and the algorithm never comes back within the range.
More worisome, I receive an answer TerminationType = 1 -> OK


text:
Q: dk.brics.automaton gets into infinite looping when given regex "a.b"? I am wondering what metacharacters does dk.brics.automaton support.
Does it even not support . operator? When I give a.b to it, it gets into infinite loop until Err: OutOfMemory.
Is there any alternative to get the same purpose as .?
If you have ideas of which operators does dk.brics.automaton support, please help list them here.

A: According to the grammar (http://www.brics.dk/automaton/doc/dk/brics/automaton/RegExp.html), that should work.  Perhaps some of your code would help.


text:
Q: HTTP Response splitting in case of java Is HTTP Response splitting possible in below case:
String requestFilename = request.getParameter("name");

response.addHeader("content-disposition", "attachment; filename=" + requestFilename);

I am directly appending the unsanitized request parameter to the reponse header.
My Question is that by using CRLF characters can we insert our own header into response.
So far i have tried \r\n and %0D%0A but they do not work.
Is response.addHeader() immune to such attacks?
Can someone explain it to me how this attack can be executed?

A: Whether http response splitting is possible in your case will depend on the servlet container that is hosting the code.
For example, Tomcat guards against common security vunerabilities, with the CORS Filter dealing with response splitting (at least for the incoming request).
Tomcat also filters the values written to the response - see Http11OutputBuffer (line 383), which prevents corrupt values being returned to the client should they somehow end up as a header value.
Never say never, but if you're using an upto date version of popular web-server like Tomcat, you should be safe from well known vunerabilities like response splitting.


text:
Q: x86 live image on a x64 processor I have a live image of ubuntu, and I will be using it for programming. It came with a book, and the book mentions that it has to be used on a x86 based-processor. I have an AMD64 processor, so my question is will this difference affect any of my programming if I run the image on VM because I think the book might dive into ASM. I also read that AMD64 is x86-64, so is it okay ?

A: Yes it'll run.
A proper modern VM ought to run assembly language for the architectures in question with no issue.
Your VM software would have an option for running a 32 bit OS anyway.
In any case, x64 has support for pure x64 and combined 32 and 64 bit operations under long mode, and 16 and 32 bit operations under legacy mode. Your processor is probably frighteningly backward compatible.


text:
Q: Fix User permission (UID changed) I changed the UID of an user, (cos I was having problems with file permission), now this user can access or see any file...
any ideas how to fix?
I executed
usermod -u UID username
 with the old UID but it saying that uid exist...
any ideas how to solve?
thank you!

A: Add the -o option and it will allow using non-unique/duplicate UID
usermod -o -u UID username

Also quite a few other things you could try for debugging.
usermod --help

for a full list


text:
Q: Modify request URI in spring mvc I have a spring mvc based application. I want to modify the request URI before it reaches controller. For example, RequestMapping for controller is "abc/xyz" but the request coming is "abc/1/xyz". I want to modify incoming request to map it to controller.
Solution1: Implement interceptor and modify incoming request URI. But the problem here is that as there is no controller matching the URI pattern "abc/1/xyz", it does not even goes to interceptor.(I might be missing something to enable it if its there)
Get around for  it could be to have both of URI as request mapping for controller.
What other solutions could be there? Is there a way to handle this request even before it comes to spring. As in handle it at filter in web.xml, i am just making it up.

A: You could write a servlet Filter which wraps the HttpServletRequest and returns a different value for the method getRequestURI. Something like that:
public class RequestURIOverriderServletFilter implements Filter {

    public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
        chain.doFilter(new HttpServletRequestWrapper((HttpServletRequest) request) {
            @Override
            public String getRequestURI() {
                 // return what you want
            }
        }, response);
    }

    // ...

 }

The servlet filter configuration must be added into the web.xml.
But sincerly, there is probably other way to solve your problems and you should not do this unless you have very good reasons.

A: in order to achieve this you should replace every place that affected when you calling uri.
the place that not mentioned is INCLUDE_SERVLET_PATH_ATTRIBUTE which is internally is accessed when going deeper.
public class AuthFilter implements Filter {

private final Logger logger = LoggerFactory.getLogger(AuthFilter.class);
private final String API_PREFIX = "/api";

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String requestURI = httpRequest.getRequestURI();
    if (requestURI.startsWith(API_PREFIX)) {
        String redirectURI = requestURI.substring(API_PREFIX.length());
        StringBuffer redirectURL = new StringBuffer(((HttpServletRequest) request).getRequestURL().toString().replaceFirst(API_PREFIX, ""));
        filterChain.doFilter(new HttpServletRequestWrapper((HttpServletRequest) request) {
            @Override
            public String getRequestURI() {
                return redirectURI;
            }

            @Override
            public StringBuffer getRequestURL() {
                return redirectURL;
            }

            @Override
            public Object getAttribute(String name) {
                if(WebUtils.INCLUDE_SERVLET_PATH_ATTRIBUTE.equals(name))
                    return redirectURI;
                return super.getAttribute(name);
            }
        }, response);

    } else {
        filterChain.doFilter(request, response);
    }
}
}

A: You can use a URL Re-Write which are specifically meant for this purpose i.e. transform one request URI to another URI based on some regex.


text:
Q: Permissions Needed To Attach AdventureWorks Database I am trying to add the AdventureWorks database in MS SQL Server Management Studio (SSMS) 2008 R2. As a new person to this area, or noob, this seemingly simple task has caused me much hardship and grief.
Initially I have tried: Right clicking on Databases, 'attach'... which immediately gets me the error:
Cannot show requested dialog.
Additional information:
Parameter name: nColIndex Actual value was -1. (Microsoft.SqlServer.GridControl)

So I've looked up other ways to add this database. I realise that there are many questions similar to the one I will ask below. I have tried their solutions to no avail, including:

*

*Running SSMS as administrator (right clicking on program, and 'Run as Administrator'...). I do the same process as above, and get the same error as above.

*Running an SQL script (by writing the script after clicking 'New Query'),
EXEC sp_attach_db    @dbname = 'DBName',
             @filename1='F:\AdventureWorks2008_Data.mdf',
             @filename2='F:\AdventureWorks2008_Log.ldf'

With (2), I get the error:
Msg 262, Level 14, State 1, Line 1
CREATE DATABASE permission denied in database 'master'.

Based on some websites (like this), the error is caused when there's a Permissions issue. But as I understand, I am an administrator.
The server I log onto is the local one, so the Server name is the same as my User name (through Windows Authentication), plus "\SQLEXPRESS".
Why can't I add the AdventureWorks database? What am i doing wrong? How can I get it working?

A: You have not given your admin user the correct permissions yet. You must explicitally tell SQL Server that this user is trusted. Running the program as an admin gives the program itself the highest level of permissions, but does nothing for the authentication process when executng a query.
To add your administrator account as a SQL Administrator:

*

*Open 'SQL Server Surface Area Configuration'  (Under Start -> MS SQL Server -> Configuration Tools)

*Click "Add New Administrator"

*Move the user from the left to the right, then save changes.
In 2008 and later, follow the instructions given here.

A: If you did not add your account to the sysadmin role during installation of SQL Server you will need to try and do that now. There are two options you can use with SQL Server 2008 R2:

*

*Easiest way I have found is to follow the method discussed in my answer here. This method does not work on any higher versions of SQL Server. Illustration is below.

*Your other option is to start SQL Server service in single-user mode. You can find those instructions in BOL here.

Using PsExec:

*

*Open command prompt (as administrator) to the directory where you downloaded PsExec.exe. Type in the command PsExec.exe -i -s cmd.exe.

*You can enter the command whoami to show that anything you open from this command prompt will open as the system account now.

*Simply type in ssms.exe to Open SSMS (SQL Server Management Studio) as the system account. You should have access now as a member of sysadmin to add your account to the sysadmin fixed server role.


text:
Q: Colouring Graphs: Identifying Chromatic Number So I'm asked to find the chromatic number for the given graph by colouring the vertices using the minimum number of required colours. My attempt at doing so is below but I was wondering if someone could confirm whether I coloured it correctly? Are there any vertices that should be a different colour/should there be more or less colours used? Did I misplace any colours?
I was also wondering if there is some rule or formula to figure out the chromatic number for a graph?
I'd appreciate some help or confirmation.
Link to graph:
https://imgur.com/a/1UVydLo

A: Nodes $8, 14, 15$ form a triangle. Therefore it is not possible to color the graph with less than $3$ colors. Since you used $3$ colors and no two adjacent nodes have the same color, your coloring is correct.


text:
Q: FileNotFoundError: [Errno 2] No such file or directory: 'credentials.json' So i am making an assistant in python with the module pyttsx3 and i have this error. Here is the code:
from __future__ import print_function
import datetime
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import os
import pyttsx3
import speech_recognition as sr
from datetime import date
import time
import webbrowser
import random
from google_images_download import google_images_download

invis_RBT = pyttsx3.init()
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')

def SearchImagesInBrowserAssistantOption():
    response = google_images_download.googleimagesdownload()
    run_again = "Y"
    while run_again == "y" or run_again == "Y":
        invis_RBT.say("Please enter the keyword(s) to search for. Please note, multiple keywords should be separated  with a comma : ")
        invis_RBT.runAndWait()
        search = input("Please enter the keyword(s) to search for. Please note, multiple keywords should be separated  with a , : \n")
        absolute_image_paths = response.download({"keywords": "Google Image Search", "limit": 1})
        run_again = input("Perform another search? Y or N:")
        invis_RBT.say("Perform Another serach?  ")
        invis_RBT.runAndWait()
    print("Bye!")

def DriveToSiteAssistantOption():
    try:
        invis_RBT.say("Listening.... (try typing: 'drive me to and the site name. Like in stagram or linked in.') ")
        invis_RBT.runAndWait()
        DriveMeTo = input("Where do you want me to drive you? Please type the site (only name) correct \n with the correct uppercase letters e.t.c:   ")
        invis_RBT.say(f"Redirecting to {DriveMeTo}.....")
        webbrowser.open(f'https://www.{DriveMeTo}.com/')
        invis_RBT.runAndWait()
        time.sleep(1)
        invis_RBT.say("Are we good now?")
        invis_RBT.runAndWait()

    except:
        invis_RBT.say("Error. Could not complete process.")

def SendEmailAssistantOption():
    # If modifying these scopes, delete the file token.pickle .
    # if you run this for the firs
    # t time it will take you to gmail to choose your account
    SCOPES = ["https://www.googleapis.com/auth/gmail.readonly"]

    def speak(text):
        engine = pyttsx3.init()
        voices = engine.getProperty('voices')
        engine.setProperty('voice', voices[1].id)
        rate = engine.getProperty('rate')

        engine.setProperty('rate', rate - 20)

        engine.say(text)
        engine.runAndWait()

    speak("Welcome to mail service")

    def get_audio():
        r = sr.Recognizer()
        with sr.Microphone() as source:
            r.pause_threshold = 1
            r.adjust_for_ambient_noise(source, duration=1)
            audio = r.listen(source)
            said = ""

        try:
            said = r.recognize_google(audio)
            print(said)

        except:
            speak("Didn't get that")

        return said.lower()

    def authenticate_gmail():
        """Shows basic usage of the Gmail API.
        Lists the user's Gmail labels.
        """
        creds = None

        # The file token.pickle stores the user's
        # access and refresh tokens, and is
        # created automatically when the authorization
        # flow completes for the first
        # time.
        if os.path.exists('token.pickle'):
            with open('token.pickle', 'rb') as token:
                creds = pickle.load(token)

        # If there are no (valid) credentials available,
        # let the user log in.
        if not creds or not creds.valid:
            if creds and creds.expired and creds.refresh_token:
                creds.refresh(Request())
            else:
                flow = InstalledAppFlow.from_client_secrets_file(
                    'credentials.json', SCOPES)
                creds = flow.run_local_server(port=0)

            # Save the credentials for the next run
            with open('token.pickle', 'wb') as token:
                pickle.dump(creds, token)

        service = build('gmail', 'v1', credentials=creds)
        return service

    def check_mails(service):

        # fetching emails of today's date
        today = (date.today())

        today_main = today.strftime('%Y/%m/%d')

        # Call the Gmail API
        results = service.users().messages().list(userId='me',
                                                  labelIds=["INBOX", "UNREAD"],
                                                  q="after:{0} and category:Primary".format(today_main)).execute()
        # The above code will get emails from primary
        # inbox which are unread
        messages = results.get('messages', [])

        if not messages:

            # if no new emails
            print('No messages found.')
            speak('No messages found.')
        else:
            m = ""

            # if email found
            speak("{} new emails found".format(len(messages)))

            speak("if you want to read any particular email just type read ")
            speak("and for not reading type leave ")
            for message in messages:

                msg = service.users().messages().get(userId='me',
                                                     id=message['id'], format='metadata').execute()

                for add in msg['payload']['headers']:
                    if add['name'] == "From":

                        # fetching sender's email name
                        a = str(add['value'].split("<")[0])
                        print(a)

                        speak("email from" + a)
                        text = input()

                        if text == "read":

                            print(msg['snippet'])

                            # speak up the mail
                            speak(msg['snippet'])

                        else:
                            speak("email passed")

    SERVICE2 = authenticate_gmail()
    check_mails(SERVICE2)

def PrintCurrentTimeAssistantOption():
    t = time.localtime()
    current_time = time.strftime("%H:%M:%S", t)
    invis_RBT.say("Current time is: " + current_time)
    invis_RBT.runAndWait()
    print("Current time is: " + current_time)
    invis_RBT.runAndWait()

def RockPaperScissorsAssistantOption():
    while True:
        user_action = input("Enter a choice (rock, paper, scissors): ")
        possible_actions = ["rock", "paper", "scissors"]
        computer_action = random.choice(possible_actions)
        print(f"\nYou chose {user_action}, computer chose {computer_action}.\n")

        if user_action == computer_action:
            print(f"Both players selected {user_action}. It's a tie!")
            invis_RBT.say("It's a draw!")
            invis_RBT.runAndWait()
        elif user_action == "rock":
            if computer_action == "scissors":
                print("Rock smashes scissors! You win!")
                invis_RBT.say("You won!")
                invis_RBT.runAndWait()
            else:
                print("Paper covers rock! You lose.")
                invis_RBT.say("You lost.")
                invis_RBT.runAndWait()
        elif user_action == "paper":
            if computer_action == "rock":
                print("Paper covers rock! You win!")
                invis_RBT.say("You win!")
                invis_RBT.runAndWait()
            else:
                print("Scissors cuts paper! You lose.")
                invis_RBT.say("You lost!")
                invis_RBT.runAndWait()
        elif user_action == "scissors":
            if computer_action == "paper":
                print("Scissors cuts paper! You win!")
                invis_RBT.say("You won!")
                invis_RBT.runAndWait()
            else:
                print("Rock smashes scissors! You lose.")
                invis_RBT.say("You lost.")
                invis_RBT.runAndWait()
        invis_RBT.say("Do you wish to play again?")
        invis_RBT.runAndWait()
        play_again = input("Play again? (y/n): ")
        if play_again.lower() != "y":
            invis_RBT.say("Okay, we had fun. See you net time!")
            invis_RBT.runAndWait()
            break

invis_RBT.say("Hello. i am your new personal assistant, Mr invis. Select option: emails, drivetosite, tellthetime, rockpaperscissors, searchanimage")
invis_RBT.runAndWait()
print("Hello. i am your new personal assistant, Mr invis. Select option: emails, drivetosite, tellthetime, rockpaperscissors, searchanimage")
invis_RBT.runAndWait()
SelectOption = input("Type here:   ")
if SelectOption == "drivetosite":
    DriveToSiteAssistantOption()
elif SelectOption == "emails":
    SendEmailAssistantOption()
elif SelectOption == "tellthetime":
    PrintCurrentTimeAssistantOption()
elif SelectOption == "rockpaperscissors":
    RockPaperScissorsAssistantOption()
elif SelectOption == "searchanimage":
    SearchImagesInBrowserAssistantOption()
else:
    print("Sorry, i do not understand your option.")
    invis_RBT.say("Sorry, but i do not understand you option.")

I read that this has to do with Google API. I tried to install some things but it does not work.
I installed client_secrets and i also put it in the current directory, it does not work. Do i have to install somehing else? In the google API console i created a new crendetial, I download it and i still have the same error. Thanks for your time, please answer and if you can answer, please tell me with images what to do and what to download -if the error can be fixed-. Thanks!

A: Mostly it will be the path error, make sure if have the required file in proper place


text:
Q: Seeing contents of war file without extracting I created a simple web application and deployed in Tomcat using the admin console of Tomcat. Now, this war files gets stored in tomcat location under webapps directory.
Is there a way to see the contents of this war without extracting? I know we can see the contents of war file by extracting  using jar -xvf ; however is there any tool/mechanism by which to see the contents of war files without extracting it?
Thanks for your time!

A: A little late to the party, but you can use 7-zip or other similar software to view the contents of the .war
With 7-zip:
Right click on file.war -> Open archive

A: The t option to the command line jar program will list the contents of a jar (or war) file, e.g.:
$ jar tf the-file.war


text:
Q: How to make a device available for a Bluetooth connection in Windows I am developing an application that involves creating a Bluetooth connection between an Android device and a Windows 10/11 device. Getting the Android section working was pretty straight forward thanks to the detailed documentation, but not so much on desktop.
I want to get the local Bluetooth MAC address of my Windows device and then make it available from connection by the Android device which will use that MAC address to connect directly without needing to go through the discovery process.
I would like to use Java for the Windows application if possible. All I can find is from Oracle explaining it using the core Bluetooth API, but this seems to be removed from current versions of Java as the javax.bluetooth package isn't found. I'm using OpenJDK 17.0.2. Any similar stackoverflow questions I could find are extremely old and mention using this javax.bluetooth package which no longer exists.
Can anyone explain how we work with Bluetooth in Java in 2022? Are there any other languages that it is much easier to work with in you would reccommend over Java?


text:
Q: Plotting longitude and latitude on a map and create line for each subset (every row in DataFarame) I worked a lot on my data set to make it like following.
I know how to plot each latitude and longitude in folium as below. I have no idea how to
plot line (Polygone) between each pairs of latitude and longitude of my data set in each row. As we see each row is combination of latitude and longitude.
The code is for showing each point( lat and long) on the map.
Notice:
I didn't write this code for the provided DataFrame. it is for a data frame with a column named "start_station_latitude" and other column start_station_longitude.

import matplotlib.pyplot as plt

#installation
# Create a world map to show distributions of users
import folium
from folium.plugins import MarkerCluster
#empty map
world_map= folium.Map(tiles="CartoDB dark_matter")
marker_cluster = MarkerCluster().add_to(world_map)
#for each coordinate, create circlemarker of user percent
for i in range(len(trip_counts_10)):
        lat = trip_counts_10.iloc[i]['start_station_latitude']
        long = trip_counts_10.iloc[i]['start_station_longitude']

        radius=5
        popup_text = """Users : {}<br>"""
        popup_text = popup_text.format(trip_counts_10.iloc[i]['start_station_name'])

        folium.CircleMarker(location = [lat, long], radius=radius, popup= popup_text, fill =True).add_to(marker_cluster)

plt.savefig('x', dpi=300)
#show the map
world_map
#tiles="CartoDB dark_matter"
#cartodbpositron

        lan0     lan1       lan2           long0      long1      long2
    59.915667   59.913796   59.922539   10.777567   10.735802   10.704541
    59.929853   59.919463   59.910356   10.711515   10.743829   10.705106
    ....

I also wrote the code below to get a list of each row, But I don't know what I should do the next.
import geopandas as gpd
from shapely.geometry import Polygon

Row_list = []
for index, rows in indices_df.iterrows():
    my_list =[rows.lan0, rows.lan1, rows.lan2,rows.long0, rows.long1, rows.long2]
    Row_list.append(my_list)
print(Row_list)
    #polygon_geom = Polygon(zip(lon_point_list, lat_point_list))

A: I'm not sure I understood your question perfectly. How I understand it, you have a df with three latitudes and three longitudes on every row and you want to draw a line throug these three points. If that is what you mean, you could try this:
folium.PolyLine(points).add_to(world_map)

Here points is a list of tuples with latitude and longitude. You could make this list like this:
mid_i = int(len(my_list)/2)
points = [(my_list[i], my_list(mid_i + i]) for i in range(mid_i)]

If you would want the line to be closed, you just add the first point to the end of this list.
points.append(points[0])

See this page for more info.
Also, I think you made some questionable design choises. Discussing these is not really the point of this answer but I would advise you to never use the name lan for latitude, that makes no sense.


text:
Q: Extend the $grid-breakpoints map-merge variable through project variables file In the Bootstrap _variables.scss file there is some code setting the breakpoint sizes
$grid-breakpoints: () !default;
// stylelint-disable-next-line scss/dollar-variable-default
$grid-breakpoints: map-merge(
  (
    xs: 0,
    sm: 576px,
    md: 768px,
    lg: 992px,
    xl: 1200px
  ),
  $grid-breakpoints
);

@include _assert-ascending($grid-breakpoints, "$grid-breakpoints");
@include _assert-starts-at-zero($grid-breakpoints);

And I'm wondering if there is a way to add a new size to this list through a scss file outside of Bootstrap (since Bootstrap is through npm  and will be overriden on update)
The size I'm trying to add is xxl: 1490px


text:
Q: VB.Net - Add Handler to object of unknown type? I am trying to create a Sub that can take an object and add a load of event handlers for it, but the object can be any one of N types that all have these events. How can I do this? If I just have it as an Object as below AddHandler complains that the event does not exist for Object.
Can this be done?
Sub addHandlers(ByVal inputObject as object)
    AddHandler inputObject.MouseDown, AddressOf HandleClick
    AddHandler inputObject.MouseUp, AddressOf HandleMouseUp
End Sub

EDIT: Each of these objects is an instance of a class that inherits a different class (usually a control) that already has these events.
Thanks for any help,
Sam.

A: You probably just want to make inputObject a type that has all of these members. For example, if your using WinForms, it would be Control:
Sub addHandlers(ByVal inputObject As Control)
    AddHandler inputObject.MouseDown, AddressOf HandleClick
    AddHandler inputObject.MouseUp, AddressOf HandleMouseUp
End Sub

Or if WPF, use UIElement:
Sub addHandlers(ByVal inputObject As UIElement)
    AddHandler inputObject.MouseDown, AddressOf HandleClick
    AddHandler inputObject.MouseUp, AddressOf HandleMouseUp
End Sub

Now any control that is of that type can be passed into addHandlers.
EDIT:
If there is no common type between all of them, you could use reflection:
Sub addHandlers(ByVal inputObject As Object)
    Dim type = inputObject.GetType()
    Dim handleClickDel = New MouseEventHandler(AddressOf HandleClick)
    Dim handleUpDel = New MouseEventHandler(AddressOf HandleMouseUp)
    type.GetEvent("MouseDown").AddEventHandler(inputObject, handleClickDel)
    type.GetEvent("MouseUp").AddEventHandler(inputObject, handleUpDel)
End Sub

The delegate type must still match though. This feels a bit clunky to me, though. If possible, try creating different overloads for addHandlers as needed, and using base types to avoid creating many of them. If own the code of the types that can be passed in as inputOjbect, use an interface.

A: If they don't all inherit from the same type, you will likely need to implement an interface on each of them in order to give them commonality.
and then use the interface definition of an event and implement it on the existing events for each object.
Interface:
Public Interface MyInterface
      Event PropertyChanged(ByVal sender As Object, ByVal e As EventArgs)
End Interface

Object with the event:
Public WhateverClass
    Implements MyInterface

    Public Event PropertyChanged(ByVal sender As Object, ByVal e As EventArgs) Implements IMyInterface

End Class

Class that needs the handler:
  Public Class SomeOtherClass
      Public Sub AddHandlers (ByVal inputObject as MyInterface)
         AddHandler inputObject.PropertyChanged, AddressOf PropertyChanged

      End Sub

      Public Sub PropertyChanged(ByVal sender as Object, ByVal e as EventArgs)
        'Do Stuff
      End Sub
  End Class


text:
Q: Scrolling issue with lightning-record-edit-form and input-field (picklist) drop menu I came across this GitHub issue https://github.com/salesforce-ux/design-system/issues/587 where it is discussed about the scrolling issues with using lightning-combobox inside a modal.
The resolution was to use menu-alignment=auto but that attribute cannot be set for an input-field for rendering a picklist field.
Does anyone have a workaround for fixing the scrolling issue here?
How to reproduce:

*

*Setup multiple picklist fields on Account object, with each containing 30+ values.

*Create an LWC using code below.

                <button class="slds-button slds-button_icon slds-modal__close slds-button_icon-inverse" title="Close">
                    <svg class="slds-button__icon slds-button__icon_large" aria-hidden="true">
                        <use xlink:href="/assets/icons/utility-sprite/svg/symbols.svg#close"></use>
                    </svg>
                    Close
                </button>

Modal Header

                <lightning-record-edit-form object-api-name="Account" class="publish-form">
                    <lightning-messages></lightning-messages>

                    <lightning-input-field field-name="Name"></lightning-input-field>
                    <lightning-input-field field-name="Description"></lightning-input-field>
                    <lightning-input-field field-name="Industry"></lightning-input-field>
                    <lightning-input-field field-name="Type"></lightning-input-field>
                    <lightning-input-field field-name="Custom_Field1__c"></lightning-input-field>
                    <lightning-input-field field-name="Custom_Field2__c"></lightning-input-field>
                    <lightning-input-field field-name="Custom_Field3__c"></lightning-input-field>
                    <lightning-input-field field-name="Custom_Field4__c"></lightning-input-field>
                    <lightning-input-field field-name="Custom_Field5__c"></lightning-input-field>
                </lightning-record-edit-form>

                <button class="slds-button slds-button_neutral">Cancel</button>
                <button class="slds-button slds-button_brand">Save</button>


text:
Q: Insert 2 records at once asp.net I'm trying to add a records into two tables at once, the ID of the 1st record is a foreign key in the second one, also one of the columns in the second tables is in the quirt string. the thing is I couldn't add the records and I don't know why
Table one is: Customer
customer ID
customer name
customer email
customer addres
customer phone

Table two is: Order
Order id
order date
order details< contain Product id
customer id

This is the aspx markup:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
    ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
    SelectCommand="SELECT [ProductID], [Prod_name], [Prod_price], [prod_description], [prod_photo] FROM [Products] WHERE ([ProductID] = @ProductID)">
    <SelectParameters>
        <asp:QueryStringParameter Name="ProductID" QueryStringField="ProdPass"
            Type="Int32" />
    </SelectParameters>
</asp:SqlDataSource>
<asp:FormView HorizontalAlign="Center" ID="FormView1" runat="server" DataKeyNames="ProductID"
DataSourceID="SqlDataSource1"
onpageindexchanging="FormView1_PageIndexChanging">
    <ItemTemplate>

                    <asp:Image ID="Image1" runat="server" Height="348px"
                        ImageUrl='<%# Bind("prod_photo","~\ppp\{0}") %>' style="margin-left: 0px"
                        Width="290px" />

                    <asp:Label ID="Label3" runat="server"
                        style="font-weight: 700; font-family: 'Century Gothic'; font-size: large"
                        Text='<%# Eval("Prod_name") %>'></asp:Label>

                    <asp:Label ID="Label1" runat="server" CssClass="style30"
                        Text='<%# Eval("Prod_name") %>'></asp:Label>

                    <asp:Label ID="Label2" runat="server" CssClass="style30"
                        Text='<%# Eval("Prod_price") %>'></asp:Label>

                    <asp:DropDownList ID="ddlQuantity" runat="server" Width="50px">
                        <asp:ListItem Value="1" Text="1" Selected="True"></asp:ListItem>
                        <asp:ListItem Value="2" Text="2" ></asp:ListItem>
                        <asp:ListItem Value="3" Text="3" ></asp:ListItem>
                        <asp:ListItem Value="4" Text="4" ></asp:ListItem>
                        <asp:ListItem Value="5" Text="5" ></asp:ListItem>
                        <asp:ListItem Value="6" Text="6" ></asp:ListItem>
                        <asp:ListItem Value="7" Text="7"></asp:ListItem>
                        <asp:ListItem Value="8" Text="8"></asp:ListItem>
                        <asp:ListItem Value="9" Text="9"></asp:ListItem>
                        <asp:ListItem Value="10" Text="10"></asp:ListItem>
                    </asp:DropDownList>

                    <asp:LinkButton ID="LinkButton1" runat="server" Font-Names="Century Gothic"
                        Font-Underline="False" ForeColor="Gray" onclick="LinkButton1_Click">Order</asp:LinkButton>

    </ItemTemplate>
</asp:FormView>

<asp:Label ID="lblMessage" runat="server"></asp:Label>

<asp:SqlDataSource ID="SqlDataSource2" runat="server"
    ConnectionString="<%$ ConnectionStrings:SHOPUREConnectionString %>"

    SelectCommand="SELECT Order_product.Quantity, Order_product.ProductID, [Order].OrderID, [Order].OrderDate, [Order].Orderdetails, [Order].CustomerID AS Expr1, Customer.* FROM Order_product INNER JOIN [Order] ON Order_product.OrderID = [Order].OrderID INNER JOIN Customer ON [Order].CustomerID = Customer.CustomerID WHERE ProductID=@ProductID " InsertCommand="INSERT INTO [Customer] ([CusomerName],[C_address],[C_phone],[C_email]) VALUES (@CusomerName, @C_address, @C_phone, @C_email);
 INSERT INTO [Order] ([OrderDetails],[CustomerID]) VALUES (@OrderDetails,@@Identity);
" oninserted="SqlDataSource2_Inserted">
    <InsertParameters>
        <asp:Parameter Name="CusomerName" />
        <asp:Parameter Name="C_address" />
        <asp:Parameter Name="C_phone" />
        <asp:Parameter Name="C_email" />
        <asp:Parameter Name="OrderDetails" />
    </InsertParameters>
    <SelectParameters>
        <asp:QueryStringParameter Name="ProductID" QueryStringField="ProdPass" />
    </SelectParameters>
</asp:SqlDataSource>
<asp:FormView DefaultMode="Insert" ID="FormView2" runat="server" DataSourceID="SqlDataSource2">
    <InsertItemTemplate>
        Quantity:

        <asp:DropDownList ID="ddlQuantity" runat="server"
            SelectedValue='<%# Bind("Quantity") %>' Width="50px">
            <asp:ListItem Text="1" Value="1"></asp:ListItem>
            <asp:ListItem Text="2" Value="2"></asp:ListItem>
            <asp:ListItem Text="3" Value="3"></asp:ListItem>
            <asp:ListItem Text="4" Value="4"></asp:ListItem>
            <asp:ListItem Text="5" Value="5"></asp:ListItem>
            <asp:ListItem Text="6" Value="6"></asp:ListItem>
            <asp:ListItem Text="7" Value="7"></asp:ListItem>
            <asp:ListItem Text="8" Value="8"></asp:ListItem>
            <asp:ListItem Text="9" Value="9"></asp:ListItem>
            <asp:ListItem Text="10" Value="10"></asp:ListItem>
        </asp:DropDownList>

        OrderDate:

        <asp:Label ID="Label4" runat="server" Text='<%# Eval("OrderDate", "{0:g}") %>'></asp:Label>

Orderdetails:
        <asp:TextBox ID="OrderdetailsTextBox" runat="server"
            Text='<%# Bind("Orderdetails") %>' />

        CustomerName:
        <asp:TextBox ID="CustomerNameTextBox" runat="server"
            Text='<%# Bind("CustomerName") %>' />

        C_address:
        <asp:TextBox ID="C_addressTextBox" runat="server"
            Text='<%# Bind("C_address") %>' />

        C_phone:
        <asp:TextBox ID="C_phoneTextBox" runat="server" Text='<%# Bind("C_phone") %>' />

        C_email:
        <asp:TextBox ID="C_emailTextBox" runat="server" Text='<%# Bind("C_email") %>' />

        <asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True"
                CommandName="Insert" Text="Insert" />


text:
Q: Residue Theorem Integral of $\frac{1}{\sinh(x)-1}$ I need help with the integral: $$\int_{-\infty}^\infty\frac{x}{\sinh(x)-1}dx,$$ and I (unfortunately) have to use contour integration techniques. I know how to do the integral $$\int_{-\infty}^\infty\frac{1}{\sinh(x)}dx,$$ so using a similar strategy, I tried integrating $$f(z):=\frac{z}{\sinh(z)-1}$$ around a box of width $2R$ and height $\pi $ centered at the origin. However, $\frac{1}{\sinh(x)-1}$ has poles at $z_n=\ln(2\pm\sqrt{2})+2\pi i n,$ for $n\in\mathbb{N}$, and so we must make $\epsilon$ bumps around $\log(2\pm\sqrt{2})$. However, around these bumps,
$$\int_{C_\epsilon}f(z)dz=\int_0^\pi\frac{2\log(1\pm\sqrt{2})+2\epsilon e^{-i\theta}}{\log(1\pm \sqrt{2})[e^{\epsilon e^{i\theta}}-e^{-\epsilon e^{-\theta}}]-1}\cdot -i\epsilon e^{-i\theta}d\theta$$
Does this simplify? I'm not sure how to tackle this. I also thought about making a substitution $x\mapsto \ln(x)$ at the very beginning, but the integration bounds that I get confuse me (I get from $-\infty +i\pi$ to $\infty$).

A: DETERMINING CONVERGENCE
We are asked to evaluate the integral $I$ given by
$$I=\int_{-\infty}^\infty \frac{x}{\sinh(x)-1}\,dx\tag1$$
We denote the denominator of the integrand in $(1)$ by $g(x)=\sinh(x)-1$.  For $x\in \mathbb{R}$, it is easy to show that $g(x)$ has a single root $x_0-=\log(1+\sqrt 2)$.
Then, from the prosthaphaeresis identity
$$\begin{align}
g(x)&=\sinh(x)-1\\\\
&=\sinh(x)-\sinh(x_0)\\\\
&=2\cosh\left(\frac{x+x_0}{2}\right)\sinh\left(\frac{x-x_0}{2}\right)
\end{align}$$
we find that $g(x)=O\left(x-x_0\right)$ as $x\to x_0$.

Hence, we conclude that the integral in $(1)$ fails to exist.

CAUCHY-PRINCIPAL VALUE
However, the Cauchy Principal Value of $(1)$ does exist and is expressed as
$$\begin{align}\text{PV}\left(\int_{-\infty}^\infty \frac{x}{\sinh(x)-1}\,dx\right)&=\lim_{\varepsilon\to 0^+}\left(\int_{-\infty}^{x_0-\varepsilon} \frac{x}{\sinh(x)-1}\,dx\\+\int_{x_0+\varepsilon}^\infty \frac{x}{\sinh(x)-1}\,dx\right)\tag2
\end{align}$$
In the next section, we use contour integration to evaluate $(2)$.

EVALUATION OF THE CAUCHY PRINCIPAL VALUE
Let $f(z)=\frac{z^2}{\sinh(z)-1}$, $z\in \mathbb{C}$.  The poles of $f(z)$ are simple and located at $z_n=x_0+i2n\pi$ and $z'_n=-x_0+i(2n+1)\pi$.
Let $J$ be the integral
$$J=\oint_C f(z)\,dz$$
where $C$ is the contour comprised of the six line segments $(i)$ from $-R$ to $z_0-\varepsilon$, $(ii)$ from $z_0+\varepsilon$ to $R$, $(iii)$ from $R$ to $R+i2\pi$, $(iv)$ from $R+in\pi$ to $z_1+\varepsilon$, $(v)$ from $z_1-\varepsilon$ to $-R+i2\pi$, and $(vi)$ from $-R+i2\pi$ to $-R$ and the two semicircular arcs $(i)$ $z_0+\varepsilon e^{i\phi}$, from $\phi=\pi$ to $\phi=0$ and (ii) $z_1+\varepsilon e^{i\phi}$, from $\phi=2\pi$ to $\phi=\pi$.

APPLYING THE RESIDUE THEOREM
The contour $C$ encloses only the simple pole at $z'_0=-x_0+i\pi$.  Therefore, the reside theorem guarantees that for $R>|z_0'|$
$$\begin{align}
\oint_C f(z)\,dz&=2\pi i \text{Res}\left(f(z), z=z'_0\right)\\\\
&=2\pi i \lim_{z\to z'_0}\left(\frac{z^2(z-z'_0)}{\sinh(z)-1}\right)\\\\
&=2\pi i \lim_{z\to z'_0}\frac{z^2}{\cosh(z)}\\\\
&=2\pi i \frac{(z'_0)^2}{\cosh(z'_0)}\\\\
&=2\pi i \frac{(x_0+i\pi)^2}{-\sqrt 2}\\\\
&=-\frac{i\pi}{\sqrt 2}(2(x_0+i\pi)^2)\tag3
\end{align}$$

EXPRESSING THE INTEGRAL OVER $C$
We also have as $R\to \infty$ and $\varepsilon \to 0^+$
$$\begin{align}
\lim_{R\to\infty\\\varepsilon\to 0^+}\oint_C f(z)\,dz&= \text{PV}\left(\int_{-\infty}^{\infty}\frac{x^2}{\sinh(x)-1}\,dx\right)-\text{PV}\left(\int_{-\infty}^{\infty}\frac{(x+i2\pi)^2}{\sinh(x)-1}\,dx\right)\\\\
&-i\pi \frac{z_0^2}{\cosh(z_0)}-i\pi\frac{z_1^2}{\cosh(z_1)}\\\\
&=-i4\pi \text{PV}\left(\int_{-\infty}^{\infty}\frac{x}{\sinh(x)-1}\,dx\right)\\\\
&+4\pi^2\text{PV}\left(\int_{-\infty}^{\infty}\frac{1}{\sinh(x)-1}\,dx\right)\\\\
&-\frac{i\pi }{\sqrt 2}(z_0^2+(z_0+i2\pi)^2)\tag4
\end{align}$$

CONCLUSION
Equating $(3)$ and $(4)$ we find that
$$\bbox[5px,border:2px solid #C0A000]{\text{PV}\left(\int_{-\infty}^\infty \frac{x}{\sinh(x)-1}\,dx\right)=\frac{\pi^2}{2\sqrt 2}}$$

A: I think rewriting the problem with an appropriate substitution will turn it into a much more standard application of the residue theorem. Rewriting the integral using the definition of $\sinh(x)$, we have that
$$\int_{-\infty}^{\infty} \frac{x}{\sinh(x) - 1}dx = \int_{-\infty}^{\infty} \frac{x}{\frac{1}{2}(e^x - e^{-x}) - 1}dx.$$
Making the substitution $u = e^x$, we then have the relationships $\ln(u) = x$ and $du = e^xdx = u dx$. Our domain's bounds also change under this substitution, so our integral becomes
$$\int_{-\infty}^{\infty} \frac{x}{\frac{1}{2}(e^x - e^{-x}) - 1}dx = \int_0^{\infty} \frac{\ln(u)}{\frac{1}{2}(u-u^{-1})-1}\frac{du}{u} = \int_0^{\infty} \frac{\ln(u)}{\frac{1}{2}(u^2-1)-u}du.$$
From here, you can extend to $\mathbb{C}$ and pick the appropriate branch of the logarithm  to proceed. EDIT: I actually tried to write the integral out but all my attempts and online integral calculators couldn't solve it. Looking at its graph, I'm now mildly convinced it might actually diverges, but I'd love to see if anyone can take this further or prove that rigorously.


text:
Q: HTML, CSS, JS responsive dropdown menu First, I'd like to apologize for my mistakes in grammar.
My problem is that I made a responsive dropdown menu in HTML with CSS and with JavaScript, but when I make the webpage smaller than 600px, everything works except the dropdown part. It shows all the main parts of the menu, here there are "Kezdőlap", "Rajzok", "Festmények" etc. But it does not show "Fekete-fehér grafikák" and so all. So, the ul > li > ul > li parts that I mean. When it is smaller than 600px width.
I have to make this code better, to show everything. So, here is the HTML part:

Kezdőlap

            Rajzok

Fekete-fehér grafikák

Színes képek

Negatív rajzok

            Festmények

Fekete-fehér

Színes

Kapcsolat

Inspiráció

Egyéb alkotások

☰

I have a CSS code (it is not the full, but I guess you can understand my problem) which looks like this:
@media (max-width:600px) {
    nav li:not(:first-child) {display: none;}
    nav li.ikon {float: right; display: inline-block;}
    nav ul.kibont {position: relative;}
    nav ul.kibont li.ikon {position: absolute; right: 0; top: 0;}
    nav ul.kibont li {float: none; display: block;}
    nav ul.kibont li a {display: block; text-align: left;}
}

and the JS:
function myFunction()
{
     document.getElementsByClassName("menu")[0].classList.toggle("kibont");
}

A: You're hiding any li that isn't first in the list with
nav li:not(:first-child) {display: none;}

So you'll need to change that if you want the other lis to show.


text:
Q: Unable to call getLifecycle() method in AppCompatActivity I am trying to test the android architecture components and have included the libraries for the same in the app.
Going through the sample code in google documentation it has a method getLifecycle() that is being passed to another class. But I'm not able to call that method from the main activity that extends AppCompatActivity. The auto suggestion wont show up the method. Am I missing something?

A: Do you have Support Library 26.1.0 or later in your gradle file? Because as stated here:

Fragments and Activities in Support Library 26.1.0 and later already
  implement the LifecycleOwner interface.

If you have the corresponding support library, the AppCompatActivity should have the getLifecycle() method available.


text:
Q: mysql str_to_date warning does not show the row number I'm importing data from .csv file to Mysql db using "LOAD DATA LOCAL INFILE" query. .csv contains foll:
ID | Name | Date | Price

 1. 01 | abc  | 13-02-2013 | 1500
 2. 02 | nbd  | blahblahbl | 1000
 3. 03 | kgj  | 11-02-2012 | 3444

My Mysql Table contains following columns:
Id INTEGER
NAME Varchat(100)
InsertionTimeStamp Date
Price INTEGER

MySQL query to load .csv data to the table above :
LOAD DATA LOCAL INFILE 'UserDetails.csv' INTO TABLE userdetails
FIELDS TERMINATED BY ','
IGNORE 1 LINES
 (Id,Name,InsertionTimeStamp,Price)
 set InsertionTimeStamp = str_to_date(@d,'%d-%m-%Y');

The above query shows warning as
"Incorrect datetime value : 'blahblahbl' for function str_to_date"
where as if I remove the set InsertionTimeStamp = str_to_date(@d,'%d-%m-%Y');from the query, the warning message includes the row number in the below :
Data truncated for column 'Date' at row 2

Why is the warning message not including the Row Number when I use
set InsertionTimeStamp = str_to_date(@d,'%d-%m-%Y')

I want to capture the row number.


text:
Q: The system cannot infer the transport information from xxxx url I have been trying to configure a simple pass through proxy using wso2 esb, which points to a REST service in https port.
I had tried doing the same using my development machine (Windows 7) and it is successful.
But when I try repeating the same in production server, in RHEL, I get The system cannot infer the transport information error in system log.
Things Tried

*

*Created passthrough proxy service pointing to https://some.domain.in/something/something.

*Tried CURL to https://some.domain.in/something/something and its shows the response properly

*Imported certificate from the site to client-truststore.jks. Same was done locally and it worked.

*in axis2.xml, edited <parameter name="HostnameVerifier">AllowAll</parameter>under https transporter

Error Message

*

*When clicked in test in configuration console, I got the following message, Invalid address

*CURL the proxy service URL, and got Empty response

*Checked system logs and saw below logs

Am I missing out something?

A: I could see in the wso2-error-logs following messages
ERROR {org.apache.synapse.transport.passthru.TargetHandler} -  I/O
error: handshake alert:  unrecognized_name
javax.net.ssl.SSLProtocolException: handshake alert:  unrecognized_name

Then I realised that I was using java 1.6 locally but 1.7 in production.
And in Java 1.7 there are some changes in SSL handling
The JDK 7 release supports
the Server Name Indication (SNI) extension in the JSSE client. SNI,
described in RFC 4366 enables TLS clients to connect to virtual
servers.

In order to bypass this, I added JAVA_OPTS="-Djsse.enableSNIExtension=false" in wso2server.sh and restarted.
This solved my problem.
Not sure if this is the correct way though
This url helped me finally


text:
Q: How to concatenate I18n.t() strings in content_for() helper? I'd like to concatenate the strings from my localization file "admin.titles.index" and "%{model_name}" (which takes from activerecord.models.harddisk).
I tried with:
<% title = I18n.t("admin.titles.index") + I18n.t("%{model_name}",
           model_name: admin.model_name,
           pluralized_model_name: admin.model_name.pluralize)%>

<% content_for(:title, title) %>

But I get an error message:
translation missing: de.%{model_name}

How can I fix that?

A: You need to provide a translation for a string, that you pass in I18n.t. As long as you don't have a translation for "%{model_name}" you'll get the error message.
In your case, you can just concatenate the string from localization with your model name:
<% title = I18n.t("admin.titles.index") + admin.model_name %>

Otherwise, you need to provide a translation for model_name in yml file. For example:
en:
  model_name: "English %{model_name}"
de:
  model_name: "German %{model_name}"

and then use it as
I18n.t("admin.titles.index") + I18n.t("model_name", model_name: admin.model_name)


text:
Q: ZF2 "Zend\Form\Element\Time" gives wrong message I've got the following element in my form but on submit it keeps giving the message "The input does not appear to be a valid date". It's not a date it's a Time element. I've got no filters applied to it.
    $this->add(array(
        'name' => 'starttime',
        'type' => 'Zend\Form\Element\Time',
        'options' => array(
            'label' => _("Start time"),
            'format' => 'H:i:s'
        ),
        'attributes' => array(
            'min' => '00:00:00',
            'max' => '23:59:59',
            'step' => 60 * 15, // seconds; default step interval is 60 seconds
        )
    ));

What am i doing wrong?

A: Try to edit "step" like : 60 and not 60*15
This input is considered like a "date format" you can change the default error message if you prefer : "The input does not appear to be a valid time"


text:
Q: How do I reverse a list in VB.NET? I have:
clientWB.Sheets(getClientSheetNames("currMonth").ToArray).Copy(After:=devWB.Sheets(1))

Function: getClientSheetNames("currMonth") returns a list of String.
I want to select the sheets in reverse order, so I did:
clientWB.Sheets(getClientSheetNames("currMonth").Reverse().ToArray).Copy(After:=devWB.Sheets(1))

But it gives an error:

getClientSheetNames("currMonth").Reverse() => Expression does not produce a value

What am I doing wrong? How should I correct it?

A: Have you tried a switcheroo on your calls?
getClientSheetNames("currMonth").ToArray.Reverse()

A: List(Of T).Reverse is a sub, so it will return nothing (see here). You have to do the reverse first, for example like this:
Dim myList As New List(Of String)
myList = getClientSheetNames("currMonth")
myList.Reverse()
clientWB.Sheets(myList.ToArray).Copy(After:=devWB.Sheets(1))


text:
Q: How can I highlight the table column? In my table I have STUDENTID, FULLNAME, SEX, COURSE & SUBJECT. I used combobox to search for all the 'Male' or 'Female' in my table. For example, I choose 'Male' I want all the Male column or cell will be highlighted with any colors. Only the 'SEX' column will be highlighted. How can I do it on javascript?

function searchForSex() {
  var input, filter, table, tr, td, i;
  input = document.getElementById("txtSearch");
  filter = input.value.toUpperCase();
  table = document.getElementById("tblStudent");
  tr = table.getElementsByTagName("tr");

  for (i = 0; i
 -1) {
        tr[i].style.backgroundColor = "red";
      }
    }
  }
}
Search:
<select id="txtSearch">

  <option value="Male">Male</option>
  <option value="Female">Female</option>
</select>

<button onclick="searchForSex()">Search</button>

 ID:

<input type="text" id="txtProdName">

 FULL Name:

<input type="text" id="txtProdName">

 SEX:

<select id="cboSex">
  <option value="Male">Male</option>
  <option value="Female">Female</option>
</select>

 COURSE:

<input type="text" id="txtCourse">

 SUBJECT:

<input type="text" id="txtSubject">

<button onclick="insertValueTable()">Save</button>
<button>Cancel</button>

  ID
  FULL NAME
  SEX
  COURSE
  SUBJECT

A: You could do it like this for example.
And on another note: searchForSex is a pretty interesting function name.

function searchForSex() {
  var input, filter, table, tr, i;
  input = document.getElementById("txtSearch");
  filter = input.value.toUpperCase();
  table = document.getElementById("tblStudent");
  tr = table.getElementsByTagName("tr");

  for (i = 0; i < tr.length; i++) {
    let tds = tr[i].getElementsByTagName("td");
    let sextd = tds[2];
    if (sextd) {
      sextd.style.backgroundColor = ""; // Reset color when re-searching
      if (sextd.innerHTML.toUpperCase() === filter){
          sextd.style.backgroundColor = "green";
      }
    }
  }
}
Search:
<select id="txtSearch">

  <option value="Male">Male</option>
  <option value="Female">Female</option>
</select>

<button onclick="searchForSex()">Search</button>

 ID:

<input type="text" id="txtProdName">

 FULL Name:

<input type="text" id="txtProdName">

 SEX:

<select id="cboSex">
  <option value="Male">Male</option>
  <option value="Female">Female</option>
</select>

 COURSE:

<input type="text" id="txtCourse">

 SUBJECT:

<input type="text" id="txtSubject">

<button onclick="insertValueTable()">Save</button>
<button>Cancel</button>

  ID
  FULL NAME
  SEX
  COURSE
  SUBJECT

         1
         Pat Johnsson
         Male
         Subject 1

         2
         Molly McGill
         Female
         Subject 2

A: Here's a much simpler solution:

var input;
var tableTD = document.body.querySelectorAll("#tblStudent td");

function searchForSex() {
  input = document.body.querySelector("#txtSearch").value;
  for (var tableCell of tableTD){
    tableCell.style.backgroundColor = "transparent";
    if(tableCell.innerHTML == input){
      tableCell.style.backgroundColor = "red";
    }
  }
}


text:
Q: List of Items we cannot migrate with Data Loader I have to migrate whole Full Copy Sandbox org to my new Production that includes the following  majorly:

*

*All Standard/Custom object records.

*All Note & Attachments part.

*All Libraries & Content within them.

*Chatter Feeds for few selected objects. etc.

But as per my knowledge there are few things which we cannot migrate through API (Apex Data Loader) eg.
a. We cannot create Libraries from DL nor we load contents within Libraries with it.
b. We cannot migrate all the type of Chatter Feeds with DL.
I believe there are some more items also which cannot be migrated with DataLoader(DL) and there only way to migrate them manually ! Can anyone list those out other then the 2 I mentioned.

Thanks !
Chirag

A: If the libraries exist you can upload Content through dataloader and a local hard drive. I'm doing this myself currently for a migration of 12000 records so it can be done.
More info @ https://help.salesforce.com/HTViewHelpDoc?id=loader_content.htm&language=en_US
Edited:
I was incorrect about the ContentURL field it's for uploading links to websites:
Description
URL for links. This is only set for links. One of the fields that determines the FileType
From: http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_objects_contentversion.htm

A: As per my knowledge the history of the object we will not be able to migrate because history automatically create when any changes made by user on record and also  they don't have creatable and updatable attributes.

A: This popped in my news feed and I thought to add my update to it based on recent salesforce features.

*

*Custom  Metadata being a metadata record cannot be migrated via Data Loader ( But its fine as they can be deployed)

*Platform Events the next big things cant be migrated.


text:
Q: Display element by hovering without javascript I'd like to prevent jquery in some stuff I do and therefore stumbled upon this article here: Displaying submenus on hover without javascript
So, I tried to implement it with a very simple test like that:

Hover this

Supersecret content

and the css therefore like this:
.target-hover{
    display:none;
    background:red;
    padding:300px;
    text-align:center;
    vertical-align: middle;
}

.trigger-hover:hover div.target-hover{
display:block;
}

But this just doesn't do anything on my side. What is the trick with it? Does the target that shall get displayed be nested into the triggering element? Is it something in the syntax?
Thanks

A: .trigger-hover:hover div.target-hover {...} would show a .target-hover within .trigger-hover, whereas your divs are adjacent. You'll want to use:
.trigger-hover:hover + .target-hover {
   display:block;
}

To show the adjacent div

.target-hover {
  display: none;
  background: red;
  padding: 300px;
  text-align: center;
  vertical-align: middle;
}

.trigger-hover:hover + .target-hover {
  display: block;
}

Hover this

Supersecret content

A:

.target-hover {
    display: none;
}
.trigger-hover:hover ~.target-hover{
    display: block;
}

Hover this

Supersecret content

A: .trigger-hover:hover div.target-hover means that target-hover div is inside trigger-hover div, but in your html they are one after another.


text:
Q: How to build associations for multiple roles? I'm building a Rails application with multiple roles. I can't use inheritance against the user model because each role has very different properties and behavior (ie - different page access and abilities once logged in). So I've decided to build separate models for each role (ie - customer, service provider, customer representative, etc).
How would the associations for this work? I came up with the following but the Role class just looks bad to me. It wouldn't be so bad if the User could have multiple roles but since they only have one I'd have to write a custom validation in Role ensuring that only one role was selected. What do you guys think?
class User < ActiveRecord::Base
  has_one :role
end

class Role < ActiveRecord::Base
  has_one :customer
  has_one :service_provider
  has_one :customer_representative
end

class Customer < ActiveRecord::Base
end

class ServiceProvider < ActiveRecord::Base
end

class CustomerRepresentative < ActiveRecord::Base
end

A: I think the problem here is with your "Role" model.  The role isn't actually a physical thing, but an interface that other objects should adhere to.  Therefore, its a polymorphic relationship.
class User < ActiveRecord::Base
  belongs_to :role, polymorphic: true
end

class Customer < ActiveRecord::Base
  has_one :user, as: :role
end

class ServiceProvider < ActiveRecord::Base
  has_one :user, as: :role
end

class CustomerRepresentative < ActiveRecord::Base
  has_one :user, as: role
end

Then you need to add role_id and role_type to your user table.
This should get your what you want I believe.
Joe


text:
Q: MongoDB aggregation condition translated to JAVA driver I'm relatively new to MongoDB and I'm currently working with java towards a "find by most tags matching" solution to information within a collection.
I'm stuck now trying to translate a MongoDB shell operation to the JAVA driver version (this sintaxis is part of the definitions needed )
$cond:[{$eq: ["$tags", 200]}, 1, 0]
What would be a correct JAVA implementation for the sentence above?
Thank you in advance

A: Whatever the $cond object where in your aggregation operation, to build it to should do something like this:
BasicDBList eqList = new BasicDBList();
eqList.add("$tags");
eqList.add(200);

DBObject eqObject = BasicDBObjectBuilder.start()
    .add("$eq", eqList)
    .get();

BasicDBList condList = new BasicDBList();
condList.add(eqObject);
condList.add(1);
condList.add(0);

DBObject condObject = BasicDBObjectBuilder.start()
    .add("$cond", condList)
    .get();

I'm confusing about your aggregation operation, could you give more details?


text:
Q: how to fetch object array from node i am creating a simple todo app using React js and node ,how to fetch object array(task list) from node to react for display that list at the time of button click
  const lists =[
    {toDo:"learn react"}
  ]
  app.post('/Todo',function(req, res){
    lists.push({ "toDo":req.body.list})
    console.log(lists)
    res.status(200).send({ message: "Task added!!"})
  }
)

  axios.post('http://localhost:8080/Todo',request)
        .then(resp=>{
            alert(resp.data.message);
        })
        .catch( err=>{
            console.log(err);
        })
  }

  return (

ToDo List

        <form onSubmit={handleSubmit}>
        <input type="text" placeholder=" Add item..." name="list" value={toDos} onChange={(e)=>setToDos(e.target.value)}/>
        <button id="btn" type="submit">Add</button>
        </form>

  )
}

export default Todo;

How can I fetch the array to react page?

A: You need to store the data from the response in state. The empty array in the useState is initially empty. However, once the axios call has been made and returned some data, the useEffect function will be called and cause the task list array to be populated. The result of which can then be iterated over and displayed on the front end.
let taskList = axios.post('http://localhost:8080/Todo',request)
    .then(resp=>{
        alert(resp.data.message);
    })
    .catch( err=>{
        console.log(err);
    })

const [tasks, setTasks] = useState([]);

useEffect(() => {
    setTasks(taskList);
}, [taskList]);

    return (

ToDo List

        <form onSubmit={handleSubmit}>
            <input type="text" placeholder=" Add item..." name="list" value={toDos} onChange={(e)=>setToDos(e.target.value)}/>
            {tasks.map(() => {
                return (

{tasks}

                )
            })}
            <button id="btn" type="submit">Add</button>
        </form>

    );
}

export default Todo;


text:
Q: Changing the index format in Lucene I used lucene 4.2 to build the index and I am trying to query the index using 3.6. It throws some exception on index format. I dont want to spend time in rebuilding the index using 3.6.
Is there a workaround for this quickly?

A: Open the index with 4.2 in order to be able to read it. The index format has changed, that's why you cannot open a 4.x index with a 3.x lucene.


text:
Q: Error debugging SSIS (excel source, data conversion, OLE DB destination) I am having issues creating a good data flow from Excel Source to SQL DB in BIDS 2010. I'm using 32-bit runtime, i have windows authentication on the SQL Server. I'm trying to send the data to a table that has no relationships or constraints at all. My excel file is .xls and I've tried doing this to SS2012 and SS2008R2 databases, getting the same errors back.
Here's my Package Validation Error:
Error at Data Flow Component [SSIS.Pipeline]: "component "Source for Excel Connection Manager" (1)" failed validation and returned validation status "VS_ISBROKEN".

Error at Data Flow Component [SSIS.Pipeline]: One or more component failed validation.

Error at Data Flow Component: There were errors during task validation.

(Microsoft.DataTransformationServices.VsIntegration)

A: Please check at this URL, I have commented earlier today.
BIDS Package Error's on Truncate while EXPORTING to flat file
Some suggestion as well:
1) Check the Data type in excel source. If the Source data type is different Convert or cast them as it is in Database.
2) Map the column correctly. Check if there are not null field in the destination.
3) Make sure you change the Project properties to RUN64bits to FALSE

A: This may not relate, but I was getting a very similar error while trying to write data to Excel from global tables.  Turned out to be an issue with the Connection Manager for the database.  I had to set "RetainSameConnection" to True and it started working right away.  Again, this may be unrelated to your issue, and this is several months later, but it could be a solution for someone else that runs into the problem.

A: Again this may not be the case always but for me the excel was corrupted.
I followed these steps after wasting 3 hours:

*

*tried to open the source excel file, it didn't open and prompted the file is corrupted.

*recreated the excel file from the source, saved as excel (.xlsx) file

*recreated the connection manager and edited excel source

and everything works fine.


text:
Q: Handling invalid URL's when using @ParamValue in Spring MVC I am using @ParamValue annotation in my controller (Spring MVC).
Say My valid URL's are:
www.temp.com/test/a,

www.temp.com/test/b and
www.temp.com/test/c

So, my RequestMapping is:
@RequestMapping(value = "/test/{value}", method = RequestMethod.GET)

Now, my problem is that if anyone types a wrong URL like this :
www.temp.com/test/youarebroken

then I have to manually handle such a case in my controller to show 404 or not found.
Isn't there something inbuilt that sends a "not found or 404" notification to server that I can use directly ?

A: The simplest solution is to define a custom exception handler and to throw the custom exception when a validation fails within your controller. That would require that you manage the conditions manually as you stated you do not want to do.
A different solution is to use a global exception handler and define it to deal with the HTTP errors that are handled by Spring built-in.
In this link you can see both approaches: http://www.journaldev.com/2651/spring-mvc-exception-handling-exceptionhandler-controlleradvice-handlerexceptionresolver-json-response-example
However, from your question I understand you would like to return automatically an exception when certain condition in your param value does not meet, and you do not want to validate this manually within your controller. For this, you can add custom validation for an specific class and then set @Valid before the @ParamValue.
You can check this link for DataBinding http://docs.spring.io/spring/docs/current/spring-framework-reference/html/validation.html
And this link for specific validation on param attributes: Spring Web MVC - validate individual request params
So, in plain a solution would be to define a custom validator that throws a custom exception when fails. To set @Valid for the parameters (check link) and to adjust the custom exception to handle HTTP errors (e.g. HttpStatus.NOT_FOUND).

A: You can use a regex in your @RequestMapping URL. Example:
@RequestMapping(value = "/test/{value:[a-z]}", method = RequestMethod.GET)


text:
Q: java.time.temporal.ValueRange bug when constructing I am working with some time stuff in a project, and as I was implementing unit testing, I am not sure if I have found a bug, or if I have have just misunderstood the documentation.  The javadocs for ValueRange.of(long min, long maxSmallest, long maxLargest) state:
 * @return the ValueRange for min, smallest max, largest max, not null
 * @throws IllegalArgumentException if
 *     the minimum is greater than the smallest maximum,
 *  or the smallest maximum is greater than the largest maximum

The way I read that is if the value passed for min is larger than the value for maxSmallest, it should throw an exception.  However, the following code works:
ValueRange vr = ValueRange.of(5, 2, 10);
I think this should fail.  The value for min is larger than the value for smallest maximum, but no exception is thrown.  In addition, when printing the resulting ValueRange, it looks very strange:  5 - 2/10
Is this a bug?  Or am I just not understanding the javadocs?

A: It is a bug JDK-8239520 and it has been fixed in JDK 15 Build 12.
I have created unit tests based on ValueRange.of() API for different value ranges:
package org.mycompany.mavenproject1;

import java.time.temporal.ValueRange;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.function.Executable;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

public class ValueRangeTest {

    @ParameterizedTest
    @CsvSource({
        "5, 2" // the minimum is greater than the maximum
    })
    public void testFixedValueRange(long min, long max) {
        Executable when = () -> ValueRange.of(min, max);

        assertThrows(IllegalArgumentException.class, when,
                () -> "min: " + min + ", max: " + max);
    }

    @ParameterizedTest
    @CsvSource({
        "5, 2, 10", // the minimum is greater than the smallest maximum - THIS FAILS!
        "2, 10, 2" // the smallest maximum is greater than the largest maximum
    })
    public void testVariableValueRange(long min, long maxSmallest, long maxLargest) {
        Executable when = () -> ValueRange.of(min, maxSmallest, maxLargest);

        assertThrows(IllegalArgumentException.class, when,
                () -> "min: " + min + ", maxSmallest: " + maxSmallest + ", maxLargest: " + maxLargest);
    }

    @ParameterizedTest
    @CsvSource({
        "5, 1, 2, 10", // the smallest minimum is greater than the smallest maximum
        "1, 2, 10, 2", // the smallest maximum is greater than the largest maximum
        "1, 11, 2, 10" // the largest minimum is greater than the largest maximum
    })
    public void testFullyVariableValueRange(long minSmallest, long minLargest, long maxSmallest, long maxLargest) {
        Executable when = () -> ValueRange.of(minSmallest, minLargest, maxSmallest, maxLargest);

        assertThrows(IllegalArgumentException.class, when,
                () -> "minSmallest: " + minSmallest + ", minLargest: " + minLargest + ", maxSmallest: " + maxSmallest + ", maxLargest: " + maxLargest);
    }

}

All scenarios pass but one - if the minimum is greater than the smallest maximum
Tests run: 6, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.087 s <<< FAILURE! - in org.mycompany.mavenproject1.ValueRangeTest
testVariableValueRange{long, long, long}[1]  Time elapsed: 0.034 s  <<< FAILURE!
org.opentest4j.AssertionFailedError: min: 5, maxSmallest: 2, maxLargest: 10 ==> Expected java.lang.IllegalArgumentException to be thrown, but nothing was thrown.
    at org.mycompany.mavenproject1.ValueRangeTest.testVariableValueRange(ValueRangeTest.java:30)

This makes me believe that this is a bug in the ValueRange.


text:
Q: C Programming Error: too few arguments to function "whatever's inside" These Functions should work but why aren't they? The compiler says Error: too few arguments to function "whatever's inside". I am a beginner to C so forgive my stupidness. I would also like to know what can be in a function.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int x;
int y;

int multiply (int x, int y)
{
    printf("()");
    return x*y;
    getchar();
    scanf("%d", &x);
    scanf("%d", &y);
    printf(":\n", multiply(x, y));

}

int add (int x, int y)
{
    printf("()");
    return x+y;
    getchar();
    scanf("%d", &x);
    scanf("%d", &y);
    printf(":\n", add(x, y));
}

int divide (int x, int y)
{
    printf("()");
    return x/y;
    getchar();
    scanf("%d", &x);
    scanf("%d", &y);
    printf(":\n", divide(x, y));
}

int subtract(int x, int y)
{
    printf("()");
    return x-y;
    getchar();
    scanf("%d", &x);
    scanf("%d", &y);
    printf(":\n", divide(x, y));
}

int power(int x, int y)
{
    printf("()");
    pow(x, y);
    getchar();
    scanf("%d", &x);
    scanf("%d", &y);
    printf(":\n", power(x, y));
}

//main code

int main(void)
{
    int option;

    switch (option)
    {
    case 1:
    add();
    break;

    case 2:
    subtract();
    break;

    case 3:
    multiply();
    break;

    case 4:
    divide();
    break;

    case 5:
    power();
    break;

    }
    getchar();
}

A: You are probably looking for the following code:
#include <stdio.h>
#include <math.h>

int multiply (int x, int y)
{
    return x*y;
}

int add (int x, int y)
{
    return x+y;
}

int divide (int x, int y)
{
    return x/y;
}

int subtract(int x, int y)
{
    return x-y;
}

int power(int x, int y)
{
    return pow(x, y);
}

//main code

int main(void)
{
    int option, result, x, y;
    printf("Enter the numbers:\n");
    scanf("%d%d",&x,&y);
    printf("1. Add\n2. Subtract\n3. Multiplu\n4. Divide\n5. Power\nEnter your choice:\t");
    scanf("%d",&option);
    switch (option)
    {
    case 1:
    result = add(x,y);
    break;

    case 2:
    result = subtract(x,y);
    break;

    case 3:
    result = multiply(x,y);
    break;

    case 4:
    result = divide(x,y);
    break;

    case 5:
    result = power(x,y);
    break;

    }
    printf("\nRequired result = %d",result);
    getchar();
}

You might want to include some condition in your code like division by 0 shouldn't be allowed, et cetra.

A: You havent passed any parameters to the functions.
Also, if you are intending to use global variables, dont use global names for local variables like parameters to the functions
eg:
add(1,2);
subtract(1,2)

Also, the part after return doesnt get executed cuz you have returned immediately

A: Just pass some correct values to functions while calling them. eg, when you call add(); call it like : add(5, 4)
And, just remove void from main(void).
It will work. and do vote up if you like answer.