text:
Q: can i make this into 1 switch case instead of many if else statements const ticket = {
                   movie : document.getElementById("movie").value,
                   amount : document.getElementById("amount").value,
               };

This is my object and I want to validate input. But I'm not sure how to change if-else statements to one switch case, since it has different statements.
PS: for learning purpose I need to use javaScript and not jQuery.
if(ticket.movie ===""){
    document.getElementById("warningMovie").innerHTML = "need to choose a movie"
}else{
    document.getElementById("warningMovie").innerHTML = "";
}

if(ticket.amount === ""){
    document.getElementById("warningAmount").innerHTML = "need to choose amount"
}else{
     document.getElementById("warningAmount").innerHTML = "";
}

A: I would use ternary operator in this case. Eg.:
document.getElementById("warningMovie")
 .innerHTML = ticket.movie ? "" : "need to choose a movie"

A: Something like this?
I am using Object.entries and
a Conditional operator (ternary) twice :)
and add the key of the object to the ID of the span - I could use warningAmount but then I would have to capitalise the key
Note the object could have been created by looping over input elements
Also ignore ("aeiou".indexOf(item[0].toLowerCase())>=0?"n ":" ") if you do not like it

const ticket = {
  movie: "",
  amount: 0,
  snack: "Chips",
};

for (let [key, value] of Object.entries(ticket)) {
  document.getElementById("warning_" + key).innerHTML =
    value ? "" :
    "need to choose a"+ ("aeiou".indexOf(key[0].toLowerCase())>=0?"n ":" ") + key
}


text:
Q: How much data is needed for transfer learning in convolutional neural networks? The issue with medical datasets are low count of observations. I would like to utilize Transfer Learning with CNN to correctly predict illnesses based on either writings (i.e. paper Refining Parkinson's neurological disorder identification through deep transfer learning), drawings (or possibly in future voice - with different NN than CNN).
I am looking for rule of thumb how many observations do we need to utilize TL over those datasets? What would be the optimal base dataset?
Should I use pretrained imagenet or try to utilize different datasets?

A: It generally depends on how similar your new task is with respect to the task the network was originally trained on. Also, it depends on the model architecture and if/how many of the layers you are going to update using the new dataset.
Assume you have a convolutional neural network that was trained for ImageNet classification. Now, you want to specialize this network in distinguishing cats from dogs. You would replace the last layer (if it is a fully connected layer, you change $\mathbb{R}^{d, o}$, where $o$ is the number of output classes, such that $o=2$ for your new binary classification task). Then, you can probably get away with training it with ~500-5000 cats vs dog images. It's hard to be more specific, though because there is no hard and fast rule.

redpajama_set_name: RedPajamaStackExchange


text:
Q: authentication on golang/MySQL doesn't work I wanted to create a registration/authorization on the site, registration is already working, but the authentication code for some reason is not. I expect to go to the home page if the data entered is correct(and the message is displayed in the opposite case), but it does not go. Maybe I'm doing the wrong thing in general, maybe the problem is in the code. Here is the code itself:
func log(w http.ResponseWriter, r *http.Request) {
FormEmail := r.FormValue("email")
FormPassword := r.FormValue("password")
var email string
var password string
// подключение
db, err := sql.Open("mysql", "root:root@tcp(127.0.0.1:8889)/service")
if err != nil {
    panic(err)
}

defer db.Close()

// авторизация
res, err := db.Query(fmt.Sprintf("SELECT * FROM `users` WHERE `email` = '%s'", email))
result, error := db.Query(fmt.Sprintf("SELECT * FROM `users` WHERE `password` = '%s'", password))
if err != nil || error != nil {
    panic(err)
}

posts = []User{}
for res.Next() {
    var post User
    err = res.Scan(&post.Id, &post.Name, &post.Surname, &post.Email, &post.Number, &post.Password)
    if err != nil {
        panic(err)
    }
    if post.Email != FormEmail {
        fmt.Fprintf(w, "incorrect mail")
    }
}
for result.Next() {
    var post User
    error = res.Scan(&post.Id, &post.Name, &post.Surname, &post.Email, &post.Number, &post.Password)
    if error != nil {
        panic(err)
    }
    if post.Password != FormPassword {
        fmt.Fprintf(w, "incorrect password")
    }
}
http.Redirect(w, r, "/", http.StatusSeeOther)

}
html:
    <form action="/log" method="post">
  <input type="email" name="email">
  <input type="password" name="password">
  <button>Login</button>
</form>

The idea is as follows: a person enters an email address and password into the form, and you need to check the data in the database. The user is created on top of the structure to which you assign data from the table field. formemail and formpassword are values from form fields, while email and password are initially empty variables of the with string type. No errors are displayed, the database is connected correctly. I think I'm doing something wrong, I'll be grateful for every hint. I apologize if the question is stupid, I'm just learning

A: I just solved this problem like this:
func log(w http.ResponseWriter, r *http.Request) {
    FormEmail := r.FormValue("email")
    FormPassword := r.FormValue("password")
    // connection
    db, err := sql.Open("mysql", "root:root@tcp(127.0.0.1:8889)/service")
    if err != nil {
        panic(err)
    }

    defer db.Close()

    // check if there is a user with the specified email + password
    res, err := db.Query(fmt.Sprintf("SELECT * FROM `users` WHERE `email` = '%s' and password = '%s'", FormEmail, FormPassword))
    if err != nil {
        fmt.Printf("%w", err)
        JSONError(500, "DB100 error code example", "DB error", w)
        return
    }

    // we check whether there are records in the database.
    if !res.Next() {
        JSONError(413, "trololo", "user not found", w)
        return
    }

    http.Redirect(w, r, "/", http.StatusSeeOther)
}

func JSONError(httpcode int, code, msg string, w http.ResponseWriter) {
    type Error struct {
        Code      *string `json:"code,omitempty"`
        Message   *string `json:"message,omitempty"`
    }

    w.Header().Set("Content-Type", "application/json; charset=utf-8")
    w.Header().Set("X-Content-Type-Options", "nosniff")
    w.WriteHeader(httpcode)
    json.NewEncoder(w).Encode(
        Error{
            Code:      &code,
            Message:   &msg,
        },
    )
}

please don't repeat my mistakes


text:
Q: How to use cert and key file with Python Requests on client side? I have a homework assignment, where I have to communicate with a server. I'm at the last task, but I can't get it to work. The task is the following:

*

*Connect to http://[Server IP] and download cert.php and key.php files.

*After that, use these files to GET https://[Server IP].

*If the HTTPS request is successful, the server will reply with the unique flag. (hw's solution)

I can download the files no problem, but when I try to use them, I get errors:
Traceback (most recent call last):
  File "C:\Users\user\PycharmProjects\pythonProject\venv\lib\site-packages\urllib3\connectionpool.py", line 699, in urlopen
    httplib_response = self._make_request(
  File "C:\Users\user\PycharmProjects\pythonProject\venv\lib\site-packages\urllib3\connectionpool.py", line 382, in _make_request
    self._validate_conn(conn)
  File "C:\Users\user\PycharmProjects\pythonProject\venv\lib\site-packages\urllib3\connectionpool.py", line 1010, in _validate_conn
    conn.connect()
  File "C:\Users\user\PycharmProjects\pythonProject\venv\lib\site-packages\urllib3\connection.py", line 411, in connect
    self.sock = ssl_wrap_socket(
  File "C:\Users\user\PycharmProjects\pythonProject\venv\lib\site-packages\urllib3\util\ssl_.py", line 432, in ssl_wrap_socket
    ssl_sock = _ssl_wrap_socket_impl(sock, context, tls_in_tls)
  File "C:\Users\user\PycharmProjects\pythonProject\venv\lib\site-packages\urllib3\util\ssl_.py", line 474, in _ssl_wrap_socket_impl
    return ssl_context.wrap_socket(sock)
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\ssl.py", line 500, in wrap_socket
    return self.sslsocket_class._create(
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\ssl.py", line 1040, in _create
    self.do_handshake()
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\ssl.py", line 1309, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate (_ssl.c:1122)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\user\PycharmProjects\pythonProject\venv\lib\site-packages\requests\adapters.py", line 439, in send
    resp = conn.urlopen(
  File "C:\Users\user\PycharmProjects\pythonProject\venv\lib\site-packages\urllib3\connectionpool.py", line 755, in urlopen
    retries = retries.increment(
  File "C:\Users\user\PycharmProjects\pythonProject\venv\lib\site-packages\urllib3\util\retry.py", line 574, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='152.66.249.144', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate (_ssl.c:1122)')))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\user\PycharmProjects\pythonProject\HF\hf_script.py", line 195, in <module>
    final_conn = requests.get(url_https,
  File "C:\Users\user\PycharmProjects\pythonProject\venv\lib\site-packages\requests\api.py", line 76, in get
    return request('get', url, params=params, **kwargs)
  File "C:\Users\user\PycharmProjects\pythonProject\venv\lib\site-packages\requests\api.py", line 61, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Users\user\PycharmProjects\pythonProject\venv\lib\site-packages\requests\sessions.py", line 542, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Users\user\PycharmProjects\pythonProject\venv\lib\site-packages\requests\sessions.py", line 655, in send
    r = adapter.send(request, **kwargs)
  File "C:\Users\user\PycharmProjects\pythonProject\venv\lib\site-packages\requests\adapters.py", line 514, in send
    raise SSLError(e, request=request)
requests.exceptions.SSLError: HTTPSConnectionPool(host='152.66.249.144', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate (_ssl.c:1122)')))

Process finished with exit code 1

I have also tried saving the files with .pem extension, I don't even know if that makes sense, but didn't work. Furthermore I have tried to use ssl and creating an unverified context, but it says Cannot find reference '_create_unverified_context' in 'ssl.pyi'
Here's the code I work with:
# Creating request with session cookie
s = requests.session()
r = s.post(url, data=data)

# Downloading the cert
cert = s.get(cert_url)
open('cert.php', 'wb').write(cert.content)

# Downloading the key
key = s.get(key_url)
open('key.php', 'wb').write(key.content)

final_conn = requests.get(url_https,
                          cert=('C:/Users/user/PycharmProjects/pythonProject/HF/cert.php',
                                'C:/Users/user/PycharmProjects/pythonProject/HF/key.php'))
print(final_conn.text)

A: Okay, I got it. I doubt anyone will use this, but the cert and key I used was fine, the pbroblem was, the server itself was using a self-signed certificate, and I had to establish the connection anyway. The solution that worked for me:
final_conn = requests.get(url_https,
                          cert=('C:/Users/user/PycharmProjects/pythonProject/HF/cert.php',
                                'C:/Users/user/PycharmProjects/pythonProject/HF/key.php'),
                          verify=False)


text:
Q: SVN (svnserve) virtual root --root= not recognized I'm running SubVersion 1.6.11 on RHEL6.
I added a new svn repo like so: svnadmin create /var/svn
I run svnserve as the svn user like: svnserve -d --root=/var/svn
The repository is setup like /var/svn/projectname/branch
I can check out files like this svn co svn+ssh://svnhost/var/svn/projectname localco
But this shouldn't work because svnserve is set with --root=/var/svn
I should be able to do svn co svn+ssh://svnhost/projectname localco
But get an error "svn: No repository found in 'svn+ssh://svnhost/projectname'"
Why is the virtual root not working?

A: svn+ssh handles the whole transaction including writing and reading the files so it ignores the --root parameter in svnserve.
Here is how to fix it over at serverfault --
Basically you just make svnserve into a script that calls svnserve with the proper variables.

A: --root, if used, defines common parent of all repositories, served by pure svnserve. You have repo in root location, it's wrong


text:
Q: Editing a specific cell based on any change to another specific cell in the same row In a Google Sheet, is it possible to automatically edit (i.e. toggle a checkbox or change color) a cell whenever another specific cell in that same row is changed in any way? For example, if I wanted to toggle a checkbox in cell A1 whenever the value in cell D1, K1, or M1 was changed, is that possible?

A: You could implement a script:
function onEdit(e) {
  ss = e.source
  sheet = ss.getActiveSheet();
  range = e.range //This is the edited range

  if(range.getA1Notation() == "D1") {
    sheet.getRange('A1').setValue('TRUE')
  }
}

A: *

*toggle a checkbox: yes, possible

*change color: also possible

whenever the value in cell D1, K1, or M1 was changed

depends if by manual change or not
example - if any of those 3 cells become "not empty" the checkbox gets checked:

then a color change can be done like:


text:
Q: Get value from .not result Below code returns the 'not' of two lists arrays :
var original = "test1,test2,test3"

var updated = "test1,test2,test4,test5"

var originalArray  = original.split(',');

var updatedArray  = updated.split(',');

console.log(originalArray.length)
console.log(updatedArray.length)

console.log($(originalArray).not(updatedArray))
console.log($(updatedArray).not(originalArray))

fiddle : http://jsfiddle.net/zhHfG/8/
The value of console.log($(updatedArray).not(originalArray)) is :
["test4", "test5", prevObject: jQuery.fn.jQuery.init[4], context: undefined, selector: ".not(test1,test2,test3)", constructor: function, init: function…]

How can the values "test4", "test5" be accessed ?
I could access them using array accessors [0],[1] but is there a cleaner way since the amount of returned values is variable ?


text:
Q: What is the %d value of char? Can someone explain the result of this? Please explain step by step clearly. Thanks a lot.
Why it's -16, -6, - 22? How compiler got these value?
Here's the code:
int main(void)
{
    char i=240, j=250, sum;
    sum = i+j;
    printf("Result is: %d + %d = %d\n",i,j,sum);

    return 0;
}

Here is the result: Result is: -16 + -6 = -22

A: Because Char is 8 bits and it's capacity is 255

When you add i+j you put 490 in sum

Then sum variable overflow and it generate negative number
Use int instead of char for sum variable it will solve your problem
Read https://www.cquestions.com/2011/02/char-overflow-in-c.html for more information

A: char i=240

Overflow. char = 8 bits. When signed, it ranges from -128 to 127.
So this converts it to negative.
Suggestion: read your compiler's warnings carefully.


text:
Q: Align vertically boxes with different height in Flexbox in a row I am using Flexbox and I am trying to create something like this:

I want the three "parent" boxes to be vertically aligned within the row. Each box have different height.
In the snippet (Codepen is better in this case as there was a character limit in Stack) I am trying to replicate the first box as a start, the boxes float to the top. They are not vertically aligned:

.box, .box-first, .box-large, .box-nested, .box-row {
    position: relative;
    box-sizing: border-box;
    min-height: 1rem;
    margin-bottom: 0;
    background: #007FFF;
    border: 1px solid #FFF;
    border-radius: 2px;
    overflow: hidden;
    text-align: center;
    color: #fff;
}

.box-nested {
    background: #036;
    border-color: #007FFF;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/flexboxgrid/6.3.1/flexboxgrid.css" rel="stylesheet"/>

111 222

105,306

111

222

105,306

When I tried adding the for the display: flex; align-items: center; in the CSS it messes up with the nested divs:

I am not that familiar with Flexbox and I have seen many different versions online that don't help.


text:
Q: Using xlswrite to export a large matrix from MATLAB to Excel I need to export a matrix which is much larger than the 1024 character limit.  Is there a way around this limitation?

A: You have way more control interacting with Excel through COM instead of MATLAB's built-in functions. Below is a small sample of what you can do. Perhaps it can help you write your array.
% Open a connection to Excel.
h = actxserver('Excel.Application');

% Make the Excel window visible.
set(h, 'Visible', 1);

% Create a new Excel workbook.
h.Workbooks.Add;

% Get the active Excel worksheet.
hSheet = h.ActiveSheet;

% Write to the cell at (A,1) on the active worksheet.
set(hSheet.Cells, 'Item', 1, 1, 123.456);

% Save and close the workbook.
h.ActiveWorkbook.Save;
h.ActiveWorkbook.Close;


text:
Q: subclassing file objects (to extend open and close operations) in python 3 Suppose I want to extend the built-in file abstraction with extra operations at open and close time.  In Python 2.7 this works:
class ExtFile(file):
    def __init__(self, *args):
        file.__init__(self, *args)
        # extra stuff here

    def close(self):
        file.close(self)
        # extra stuff here

Now I'm looking at updating the program to Python 3, in which open is a factory function that might return an instance of any of several different classes from the io module depending on how it's called.  I could in principle subclass all of them, but that's tedious, and I'd have to reimplement the dispatching that open does.  (In Python 3 the distinction between binary and text files matters rather more than it does in 2.x, and I need both.)  These objects are going to be passed to library code that might do just about anything with them, so the idiom of making a "file-like" duck-typed class that wraps the return value of open and forwards necessary methods will be most verbose.
Can anyone suggest a 3.x approach that involves as little additional boilerplate as possible beyond the 2.x code shown?

A: I had a similar problem, and a requirement of supporting both Python 2.x and 3.x. What I did was similar to the following (current full version):
class _file_obj(object):
    """Check if `f` is a file name and open the file in `mode`.
    A context manager."""
    def __init__(self, f, mode):
        if isinstance(f, str):
            self.file = open(f, mode)
        else:
            self.file = f
        self.close_file = (self.file is not f)
    def __enter__(self):
        return self
    def __exit__(self, *args, **kwargs):
        if (not self.close_file):
            return  # do nothing
        # clean up
        exit = getattr(self.file, '__exit__', None)
        if exit is not None:
            return exit(*args, **kwargs)
        else:
            exit = getattr(self.file, 'close', None)
            if exit is not None:
                exit()
    def __getattr__(self, attr):
        return getattr(self.file, attr)
    def __iter__(self):
        return iter(self.file)

It passes all calls to the underlying file objects and can be initialized from an open file or from a filename. Also works as a context manager. Inspired by this answer.

A: You could just use a context manager instead. For example this one:
class SpecialFileOpener:
    def __init__ (self, fileName, someOtherParameter):
        self.f = open(fileName)
        # do more stuff
        print(someOtherParameter)
    def __enter__ (self):
        return self.f
    def __exit__ (self, exc_type, exc_value, traceback):
        self.f.close()
        # do more stuff
        print('Everything is over.')

Then you can use it like this:
>>> with SpecialFileOpener('C:\\test.txt', 'Hello world!') as f:
        print(f.read())

Hello world!
foo bar
Everything is over.

Using a context block with with is preferred for file objects (and other resources) anyway.

A: tl;dr Use a context manager.  See the bottom of this answer for important cautions about them.

Files got more complicated in Python 3.  While there are some methods that can be used on normal user classes, those methods don't work with built-in classes.  One way is to mix-in a desired class before instanciating it, but this requires knowing what the mix-in class should be first:
class MyFileType(???):
    def __init__(...)
        # stuff here
    def close(self):
        # more stuff here

Because there are so many types, and more could possibly be added in the future (unlikely, but possible), and we don't know for sure which will be returned until after the call to open, this method doesn't work.
Another method is to change both our custom type to have the returned file's ___bases__, and modifying the returned instance's __class__ attribute to our custom type:
class MyFileType:
    def close(self):
        # stuff here

some_file = open(path_to_file, '...') # ... = desired options
MyFileType.__bases__ = (some_file.__class__,) + MyFile.__bases__

but this yields
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __bases__ assignment: '_io.TextIOWrapper' deallocator differs from 'object'

Yet another method that could work with pure user classes is to create the custom file type on the fly, directly from the returned instance's class, and then update the returned instance's class:
some_file = open(path_to_file, '...') # ... = desired options

class MyFile(some_file.__class__):
    def close(self):
        super().close()
        print("that's all, folks!")

some_file.__class__ = MyFile

but again:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __class__ assignment: only for heap types

So, it looks like the best method that will work at all in Python 3, and luckily will also work in Python 2 (useful if you want the same code base to work on both versions) is to have a custom context manager:
class Open(object):
    def __init__(self, *args, **kwds):
        # do custom stuff here
        self.args = args
        self.kwds = kwds
    def __enter__(self):
        # or do custom stuff here :)
        self.file_obj = open(*self.args, **self.kwds)
        # return actual file object so we don't have to worry
        # about proxying
        return self.file_obj
    def __exit__(self, *args):
        # and still more custom stuff here
        self.file_obj.close()
        # or here

and to use it:
with Open('some_file') as data:
    # custom stuff just happened
    for line in data:
        print(line)
# data is now closed, and more custom stuff
# just happened

An important point to keep in mind: any unhandled exception in __init__ or __enter__ will prevent __exit__ from running, so in those two locations you still need to use the try/except and/or try/finally idioms to make sure you don't leak resources.


text:
Q: Mountain like plot for data in Square matrix I have data as a square matrix. I want to plot it like meshgrid in Matlab (mountains with color gradients). Also, if there is a big cliff, I want to label it. Something like shown below

The data I have is
            _92765  _222156 _384259 _384249 _384247 _384250
_92765  -1  3.4 4.85106 8.12927 8.462   9.12643
_222156 3.4 -1  1.50877 3.66383 3.58554 3.69655
_384259 4.85106 1.50877 -1  4.48433 4.51367 4.14421
_384249 8.12927 3.66383 4.48433 -1  0.288   0.252
_384247 8.462   3.58554 4.51367 0.288   -1  0.196
_384250 9.12643 3.69655 4.14421 0.252   0.196   -1

How can I go about it?
Thanks

A: Have you looked at the wireframe() function in the lattice library?
Here is an example from the on-line help:
library(lattice)
wireframe(volcano, shade = TRUE,
    aspect = c(61/87, 0.4),
    light.source = c(10,0,10))


text:
Q: How to perform file upload monitoring with Play! framework Is it possible to monitor file uploads, somehow, with Play! framework? Also, if the file should be BIG (i.e. +500MB), would it be possible to save the received bytes into a temporary file instead of keeping it in memory? (see update below)
note : there is no code to show as I'm wondering these questions and cannot seem to find the answers with Google
Thanks!
** Update **
(I almost forgot about this question.) Well, apparantly, files uploaded are stored in temporary files, and the files are not passed as a byte array (or something), but as a Java File object to the action controller.
But even in a RESTful environment, file monitoring can be achieved.
** Update 2 **
Is there a way to get early event listeners on incoming HTTP requests? This could allow for monitoring request data transfer.

A: Large requests and temp files
Play! is already storing large HTTP requests in temp files named after UUIDs (thus reducing the memory footprint of the server). Once the request is done, this file gets deleted.
Monitoring uploads in Play!
Play! is using (the awesome) Netty project for its HTTP server stack (and also on the client stack, if you're considering Async HTTP client.
Netty is:

*

*asynchronous

*event-driven

*100% HTTP

Given Play!'s stack, you should be able to implement your "upload progress bar" or something. Actually, Async HTTP client already achieves progress listeners for file uplaods and resumable download (see the quick start guide).
But play.server package doesn't seem to provide such functionality/extension point.
Monitoring uploads anyway
I think Play! is meant to be behind a "real" HTTP server in reverse proxy mode (like nginx or lighthttpd).
So you'd better off using an upload progress module for one of those servers (like HttpUploadProgressModule for nginx) than messing with Play!'s HTTP stack.


text:
Q: How to find parent element from knowing child So i have this element:
element = self.driver.find_element_by_xpath('//android.widget.LinearLayout[@resource-id=\'blabla\'')

And i want to find its parent.
This is what i have try (until now not working):
parent = element.find_element_by_xpath(/..android.widget.LinearLayout[@resource-id=\'some_id\'')

A: you can try this line of code
parent = self.driver.find_element_by_xpath("//android.widget.LinearLayout[@resource-id='blabla']/..")

A: Try this and let me know
element = self.driver.find_element_by_android_uiautomator("new UiScrollable(new UiSelector()"
                + ".resourceId(\"android:id/list\")).scrollIntoView("
                + "new UiSelector().text(\"blabla\"));");


text:
Q: Lotus Notes 6.5 and 7, unwanted space on small td's I'm testing an email and it is laid out correctly in all the clients except for Lotus notes 6.5 and 7.
The problem occurs when td's become very small (less than 10px). Those td's then do not get any smaller and end up with extra unwanted padding on either the bottom or the right.
Below is a screenshot of it happening to 1px wide images in Lotus notes 6.5. I've made this as an example of the strange layout occurring. As you can see (in the top left) the td's is set to the correct width (1px) and so is the image, however the td has some extra padding, about 12px, on the right of it. The extra space is highlighted in pink.

This also happens with 1px height image too, there is unwanted padding on the bottom.
The sample email's html is here:
Demo Email
I would really appreciate some help with this, It's a bug I just can't seem to fix. If you find a solution I'll send you a muffin or something.

A: After loads of research, it turns out that lotus notes 6 and 7 can't display cells smaller than 12px. It's impossible.

A: The fact is that Lotus Notes' HTML rendering is far from standards-based.  There is little documentation on it so your only hope is a lot of trial and error.
You might try using basic CSS instead of tables, or not putting each row of images in separate cells.  But whatever you do, don't expect Lotus Notes email to behave like a real browser.


text:
Q: Open multiple directories in different tabs in the same window in CentOS How can I set my CentOS to be able to open multiple directories in different tabs in the same window?
I have already enabled the feature to open the folders in the same window, but this is different: I would like to be able to open as many tabs I want for different folders.
Unfortunately, I don't know my graphical environment, since:
[user@maxipub9 extractions]$ echo $DESKTOP_SESSION
default

A: Both CentOS and Fedora make use of GNOME for their desktop environments. To open multiple tabs you can use Ctrl+T to add additional tabs.

If you're attempting to have Nautilus open these tabs pre-populated with specific directories this, to my knowledge, is not possible. You'll have to resort to a scripted method such as this one from this AU Q&A titled: open nautilus as new tab in existing window. Specifically the answer that shows the technique using xdotool along with wmctrl.
However the tabs feature was only made available in version GNOME 2.24 or higher. Looking at CentOS 5.10 it comes with Nautilus 2.16.

This article from ArsTechnica titled: GNOME file manager gets tabbed file browsing discusses the addition of this feature. So you're out of luck in using tabs with this particular version of Nautilus.

This feature will likely be ready to roll for GNOME 2.24, which is scheduled for release in September. Another long-awaited Nautilus feature that is planned for GNOME 2.24 is the compact column view. A lot of other work has been done to iron out the remaining GVFS regressions.


text:
Q: How to stop displaying repeated JSON data in HTML? When I load JSON data in HTML using append() it will display data but when I click again it will repeat the data.
How can I display the data only once? I want to stop repeating data. Thank you in advance.
fetch('extracontent.json').then(function(response) {
  return response.json();
}).then(function(data) {
  appendData(data);
}).catch(function(err) {
  console.log('error: ' + err);
});

function appendData(data) {
  var mainContainer = document.getElementById("myData");
  document.getElementById("panel").style.display = "block";

  for (var i = 0; i < data.abc.length; i++) {
    var d = document.createElement("d");
    d.innerHTML = data.abc[i].sectionname + data.abc[i].unitname + data.abc[i].link;
    mainContainer.appendChild(d);
  }
}


text:
Q: Strange behaviour of php using wamp I have been using wamp server do build small websites with php for a long time.. but this morning something strange just happend :
here is my home.html file :

  <title>Test PHP</title>

 <?php echo '
Hello world
'; ?>

and here is what I get when I display the page :
Hello world
'; ?>

And when I display the source code, here is what I get :

  <title>Test PHP</title>

 <?php echo '
Hello world
'; ?>

It seems to be a very stupid problem where the php code is not interpreted by the server.. Any suggestion ?

A: You saved the filename as .html
Use .php instead of .html it will interrupt.


text:
Q: Android: How to check which Fragment/Activity called the method my case is as follows, I have a common toolbar between activities and fragments, I have a method attached to this toolbar (like a back button) which can be called by all, but however, i want this method to behave differently according to the activity/fragment which called it.So what should my code look like inside this method?
Here is my code
 public boolean onSupportNavigateUp(){
    Intent mainActivity=new Intent(this,main_activity.class);
    mainActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(mainActivity);
    this.finish();
    return true;
}

A: use putExtra and getExtra with intent and set different values for different activity in put extra to identify the exact calling activity/fragment.

A: You could add an extra in your intent, then check it to know who send it. Something like :
Activity 1
Intent intent = ...
intent.putExtra("SENDER","activity1");
startActivity(intent);

Activity receiving the intent
Intent intent = getIntent();
String sender = intent.getExtras().getString("SENDER");
if(sender=="activity1")
//do

Hope it helps!

A: Another way would be using reflection:
if (getClass() == Activity1.class){
  // Do something
}

A: WHy dont you make 1 common activity with a tool bar and a framelayout and switch fragments like that. It is less code to write. This also reduces code redundancy. Or I don't understand what you are asking?


text:
Q: Php frameworks 2010 i am looking for a new php(5) framework it must be lightweight(x<500kb), oop, have orm, active record built in, simple to learn, fast to use, active community and dev.
I need it for small, personal app development.
My php skills are quite low and i have .net background. I have previously used LightVc+cough and codeIgnitor php frameworks.
There are so-many frameworks there and it is quite hard to find the best.
I have checked the other threads here but they are to old to consider sustainable.
Thanks for your time.

A: I think you dig out the http://www.phpframeworks.com/. It has details about each and every accepted framework.

A: Code Igniter is very popular and also supports PHP4: http://codeigniter.com/

A: Unlike .NET and miscellaneous other programming languages, you really don't need a framework to write a PHP application. In fact, I'd advise against it. Learn the language, not a framework.

A: For someone with low PHP skills I'd say codeigniter although it doesn't have ORM built-in (it has a sort of lightweight active record class), but there are tutorials on how to use Doctrine (a good PHP ORM solution) with it.
However if you want a PHP5 only framework (as in written to take full advantage of PHP5) then I'd suggest looking at Kohana (a PHP5 only fork of codeigniter), Yii or Zend framework.


text:
Q: Non-Noetherian module which is not a ring I was thinking about the following question:

Find a non-Noetherian module which is not a ring.

All the examples I have in mind can be thought as rings. For instance, one can take the space of real sequences $(a_n)_{n \in \mathbb{N}} \subset \mathbb{R}$. It is indeed an $\mathbb{R}$-vector space which is infinite dimensional and hence not Noetherian. However it is also a ring, and it is not Noetherian also as a ring.
I was thinking of something similar to this: an infinite-dimensional vector space $V$ over a field $\mathbb{k}$, but where I cannot put the structure of a ring. I tried spaces of functions like $\mathbb{C}^{\infty}(\mathbb{R}^n)$ or Lebesgue spaces of functions $L^p(\mathbb{R}^n)$, but here too, since I can multiply functions, it still makes this a ring.

A: So as it turns out, every set $S$ can be thought as a ring. Just consider:
$$ \bigoplus_{s \in S} \mathbb{Z} $$
So the only possible answer to the question is to find a set which is only equipped with a module structure which is not a ring structure and such that it is not Noetherian. As already pointed out by myself, one can search within infinite dimensional vector spaces. For instance, as suggested by @Mark in the answers, if $\mathbb{k}$ is a field, $\mathbb{k}[x]$ is an infinite dimensional vector space, which is hence not Noetherian.


text:
Q: Count and Show Compile Error \documentclass{article}

\def\ad#1{$^{#1}$}
\def\aff#1{$^{#1}$}
\def\address#1{#1}
\def\dept#1{#1}
\def\inst#1{#1}
\def\cyname#1{#1}
\def\country#1{#1}
\def\pcode#1{#1}
\def\stname#1{#1}
\def\phone#1{#1}
\def\fax#1{#1}
\def\ad#1{$^{\rm #1}$}
\def\aff#1{$^{#1}$}
\def\fn#1{#1}
\def\sn#1{#1}
\def\corr#1{#1}
\def\statename#1{#1}

\begin{document}

\title{Sample}

\author{Sas Santhome\ad{a} Author\ad{b} and Susanna Waxxarin\ad{c} }

\maketitle

\address{\aff{a}\dept{Department of Sciences}, \inst{University}, \cyname{City}, \country{Italy}; \aff{b}\dept{Department of Economics}, \inst{University}, \cyname{Trieste}, \country{Italy}}

\end{document}

what i want to acheive is in \author i have \ad{} 'n' number of times,
the link text \ad{a} should also be there in \aff{a} or else, i need to show compile error,
for example in the above coding, we can see
\ad{a} - \aff{a}
\ad{b} - \aff{b}
\ad{c} - Missing \aff{c}

\aff{c} is missing but \ad{c} is present, so i should throw compile error
Please guide

A: For example you can save the \ad labels into the \afflist macro and you can use these labels from \afflist when \aff is used. This means that you needn't to repeat the labels again and the \aff macro is used without parameter.
\def\addto#1#2{\expandafter\def\expandafter#1\expandafter{#1#2}}
\def\ad#1{$^{\rm #1}$\global\addto\afflist{{#1}}}
\def\aff{%
   \ifx\afflist\empty \errmessage{There is more \noexpand\aff than \string\ad}%
   \else \expandafter\affA\afflist\end $^{\rm\tmp}$%
   \fi
}
\def\affA#1#2\end{\gdef\afflist{#2}\def\tmp{#1}}
\def\address#1{#1%
  \ifx\afflist\empty\else \errmessage{There is more \noexpand\ad than \string\aff}\fi
}
\def\afflist{}

\def\dept#1{#1}
\def\inst#1{#1}
\def\cyname#1{#1}
\def\country#1{#1}
\def\pcode#1{#1}
\def\stname#1{#1}
\def\phone#1{#1}
\def\fax#1{#1}
\def\fn#1{#1}
\def\sn#1{#1}
\def\corr#1{#1}
\def\statename#1{#1}

...

\address{\aff\dept{Department of Sciences}, \inst{University}, \cyname{City}, \country{Italy};
         \aff\dept{Department of Economics}, \inst{University}, \cyname{Trieste}, \country{Italy};
         \aff\dept{Somewhere}}

If you need to repeat the labels in the \aff macro again then you can check if the label is the same:
\def\aff#1{\def\tmpa{#1}%
   \ifx\afflist\empty \errmessage{There is more \noexpand\aff than \string\ad}%
   \else \expandafter\affA\afflist\end $^{\rm\tmp}$%
         \ifx\tmp\tmpa \else \errmessage{unmatched labels \tmpa--\tmp}\fi
   \fi
}


text:
Q: Oracle JDK 1.8 supported on AIX server? I am new to AIX environment want to check if we can install JDK 8 on AIX server by overriding the IBM JDK.
If yes, how?.

A: Oracle JDK 1.8 for AIX does not exist.
If you really want JDK 1.8, you can override your current (I suppose now you have an older version) downloading a new one from here.
Just to be clear, every version of Oracle JDK or JRE is machine dependent. And it is compiled to run only on a defined set of operating systems. You can see the complete list of Oracle's JDK supported OSs here.
Looking around I saw there is a OpenJDK (Open Java Development Kit) porting to PowerPC/AIX, they're are actively working to have a stable 1.8 version.

*

*OpenJDK - PowerPC/AIX Port Project

*OpenJDK Wiki - PowerPC/AIX Port Project

*OpenJDK PowerPC Port
Consider that OpenJDK is not only a free and open source implementation of the Java Platform, Standard Edition (Java SE). But it is also actively supported by Oracle (primarily) and by IBM.


text:
Q: Regular Expression: Letters, numbers, spaces, hyphens, periods, and underscores only and must begin with a letter After a few tutorials I thought I had this, but nope ---
I am trying to only match a string of letters, numbers, spaces, hyphens, periods, and underscores only and must begin with a letter in a jquery function
This is what I came up with after the tutorials but it only accepts letters:
/^[a-z][a-z0-9_ .-]*?/i

Please help!
++EDITED++
This is the code where I am trying to use this:
$('input[name=albumName]').keyfilter(/^[a-z][a-z0-9_ .-]*?/i);

The name that a user is entering will also be used in a URL so I want to limit their entry. I would want this to be allowed ( Texas AandM - 2012 ) but this not to be allowed ( 2012 -  Texas A&M )

A: Your regex looks ok to me. Perhaps there is a problem with the surrounding code rather than the regex? This is a Python example:
s_re = re.compile('^[a-z][a-z0-9_.-]*',re.I) # case insensitive match

In [12]: if s_re.match('A'): print 'match'
match

In [14]: if s_re.match('A.-'): print 'match'
match

In [15]: if s_re.match('1.-'): print 'match'

In [16]: if s_re.match('1_.-'): print 'match'

In [17]: if s_re.match('A_.-'): print 'match'
match

If you want to make sure you want at least one character after the first letter, you can replace the * with a +, or {2,} with at least 2 more characters, or {2,5} with between 2 and 5 characters.

A: ^[a-z][a-z0-9_ .-]* works.
Because of the Question Mark, the Regex matched only letters,
because the match is the smallest possible match.
Reference/RegExp


text:
Q: How do I select columns conditional to the value of another column? (dplyr) Name1    Col1    Col2    Col3    Name2    Col4    Col5    Col6    Col7
John     A       A       A       Alex       B       B       B      1
Alex     B       B       B       John       A       A       A      0

Looking at the data frame above, I would like to select the data based on the value of Col7. Specifically, if Col7 = 1 then I want to select Columns 1, 2, and 3. If Col7 = 0, then Cols 4,5,6 are selected. Cols 4,5,6 are the same variable as Cols 1,2,3 just associated to Alex instead of John (in row 1). Therefore, John's data is selected both times, and this will be the same for every pair.
I was thinking some form of select in "Dplyr" would work, but I am having trouble with the conditional selection aspect.
My final data frame would appear as follows:
Name1    Col1    Col2    Col3
John      A       A       A
John      A       A       A

A: Hi try something very basic (combining filter and select_at) :
df1 <- df %>%
  filter(Col7 == 1) %>%
  select_at(vars(Name = Name1, Col1, Col2, Col3))
df2 <- df %>%
  filter(Col7 == 0) %>%
  select_at(vars(Name = Name2, Col1 = Col4, Col2 = Col5, Col3 = Col6))
df <- bind_rows(df1, df2)

You get exactly the data frame you seek :
> df
  Name Col1 Col2 Col3
1 John    A    A    A
2 John    A    A    A

A: You can use melt from data.table or reshape2 and then left join on the condition:
library(data.table)
setDT(d)

d[, row := .I]
md = melt(d, id=c("row", "Col7"),
  meas = Map(c, 1:4, 5:8),
  variable.factor = FALSE,
  variable.name = "colset",
  value.name = names(d)[1:4])
#    row Col7 colset Name1 Col1 Col2 Col3
# 1:   1    1      1  John    A    A    A
# 2:   2    0      1  Alex    B    B    B
# 3:   1    1      2  Alex    B    B    B
# 4:   2    0      2  John    A    A    A

cond = data.table(Col7 = 0:1, colset = c("2", "1"))
#    Col7 colset
# 1:    0      2
# 2:    1      1

res = md[cond, on=names(cond), nomatch=0]
#    row Col7 colset Name1 Col1 Col2 Col3
# 1:   2    0      2  John    A    A    A
# 2:   1    1      1  John    A    A    A

This approach extends to more than two sets of columns, eg with meas=Map(c, 1:4, 5:8, 9:12).

A: In base R:
df <- read.table(text = "Name1    Col1    Col2    Col3    Name2    Col4    Col5    Col6    Col7
John     A       A       A       Alex       B       B       B      1
                  Alex     B       B       B       John       A       A       A      0'",
                 header = TRUE, stringsAsFactors = FALSE)

for(i in 1:nrow(df)){
  if(df$Col7[i] == 1){
    df1 <- df[i, c("Name1", "Col1", "Col2", "Col3")]
  }else if(df$Col7[i] == 0){
    df2 <- df[i, c("Name2", "Col4", "Col5", "Col6")]
  }
}

colnames(df2)[1] <- "Name1"
colnames(df2)[2] <- "Col1"
colnames(df2)[3] <- "Col2"
colnames(df2)[4] <- "Col3"

df <- rbind(df1, df2)

   Name1 Col1 Col2 Col3
1  John    A    A    A
2  John    A    A    A

A: Here's a tidyverse (more tidyr than dplyr) approach. It's fairly verbose, as your original data is not in a tidy form, so most of the code is just getting to a long form, cleaning, and spreading back to wide form.
library(tidyverse)

df <- data_frame(Name1 = c("John", "Alex"),
                 Col1 = c("A", "B"), Col2 = c("A", "B"), Col3 = c("A", "B"),
                 Name2 = c("Alex", "John"),
                 Col4 = c("B", "A"), Col5 = c("B", "A"), Col6 = c("B", "A"),
                 Col7 = c(1L, 0L))

df %>%
    # reshape to long form
    gather(col, col_val, num_range('Col', 1:6)) %>%
    gather(name_var, name, contains('Name')) %>%
    # clean, subset, clean for spreading
    mutate(col = parse_number(col),
           name_var = parse_number(name_var)) %>%
    filter(ifelse(Col7 == 1,
                  col %in% 1:3 & name_var == 1,
                  col %in% 4:6 & name_var == 2)) %>%
    mutate(col = paste0('Col', col %% 3 + 1),
           name_var = 'Name') %>%
    # reshape back to wide form
    spread(name_var, name) %>%
    spread(col, col_val) %>%
    # clean
    select(-Col7)
#> # A tibble: 2 x 4
#>   Name  Col1  Col2  Col3
#>   <chr> <chr> <chr> <chr>
#> 1 John  A     A     A
#> 2 John  A     A     A


text:
Q: using cookies in up/down voting system I want to build Up/down voting system for several articles retrieved from database, but i want to add cookie for each article to limit number of votes so cookie will expires in one day, but i don't know where to add the appropriate code.
more details:

the above code is a script calling ajax method to increase number of votes per one every time user click on the up arrow and decrease conversely.
    public string updateVotes(string id,int value)
{

    System.Threading.Thread.Sleep(500); // delay for 2.5 seconds Network latency

   post p = db.posts.Find(int.Parse(id));
    // assign new values
   p.totalVotes += value;
    db.Entry(p).State = System.Data.EntityState.Modified;
    db.SaveChanges();

    string dataBack =p.totalVotes.ToString();
    return dataBack;
}

This is the webmethod.
Now i tried to think loudly and i code the following function to ewxamine if the cookie is null or not.
 public bool enableVoting()
{

    HttpCookie cookie = Request.Cookies["enableVote"];

    if (Request.Cookies["enableVote"] != null)
    {
       return true;

    }

    else
    {

      return false;
    }

}

i know it's wrong but at least i tried.
also where to add a for each loop to add cookie whenever user vote for article.?
   foreach(post p in db.posts){
        HttpCookie cookie = new HttpCookie("enableVote"+p.ID);
        cookie.Value = "article:"+p.ID;
        cookie.Expires = DateTime.Now.AddDays(1);
        Response.Cookies.Add(cookie);
    }

A: A suggestion. Don't use cookies for this. They are easily manipulated. Clear browser history and you can vote again.. and again.. and again.
Instead, create a Vote table in your database and add a record with the ip of the voter and the id of the post they voted for along with a timestamp.
This way you can easily count the votes and when someone votes you do a quick check on how long ago that IP last voted for that article (or any article).
Also with a vote table in your database you can easily catch bots that are up or downvoting everything, and limit the number of votes a single ip can make on any article (no more than 1 or two votes every few minutes maybe).
If your worried about multiple people behind the same IP not being able to vote you can include the browser name and only count unique ip and browser version as a vote. This is fairly unique. It can also be manipulated but its a little bit harder for the normal user.
Update:
I use this code for the purpose of getting a somewhat unique key in one of my MVC projects. The user can switch browsers and vote again, but it takes a bit of effort and its more of a pain than just clearing browser history.
I combine the IP, browser, and Country into a string and use that as a vote key.
public class UserInfo
{
    public String ip { get; private set; }
    public String browser { get; private set; }
    public String country { get; private set; }

    public UserInfo(HttpRequestBase Request)
    {
        ip = Request.UserHostAddress;
        browser = Request.Browser.Platform + " " + Request.Browser.Type + "/" + Request.Browser.Id + " " + Request.Browser.Version;
        country = "";

        if (Request.UserLanguages.Length > 0)
            country += " - " + Request.UserLanguages.ElementAt(0);
    }
}

I'm using this system here: http://filepublicator.com/ to check if the user has any previously uploaded files (try to upload something and close browser and go there again, it will be in the list).


text:
Q: Conditional execution based on result of previous stage in declarative pipeline My pipeline setup is as follows.

I need to get it working with adherence to following conditions. Help me defining when blocks and other code to be used and in which stages?

*

*If A fails, no other stage is executed and job run is marked failed.

*If any of the B stage fails, then corresponding C stage should not be invoked.

*Stage D should get executed when either C1 or C2 have been executed regardless of failure in their execution.

*Also, if any of the stages have been failed, then the over all job run status should be fail.

What have I tried & observed?
From above conditions defined, 1 and 2 are working as expected but not 3 and 4 with my following attempt.
In C1 and C2, I added catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') referring to Continue Jenkins pipeline past failed stage.
But what I have observed is -

*

*D executes if C1 or C2 fails, but over all job run is marked Success. Expected is failure as one of the C steps have failed. But due to catch it gets success status.

*When any of the B stages fail, their corresponding C also doesn't execute (expected) but it doesn't trigger D either. As I need D to be triggered because some other C has been executed.

A: This is what you need:
stageResultMap = [:]

pipeline {
    agent any
    stages {
        stage('A') {
            steps {
                println("This is stage: ${STAGE_NAME}")
            }
        }
        stage('BC') {
            parallel {
                stage ('1'){
                    stages {
                        stage('B1') {
                            steps {
                                script {
                                    // Catch exceptions, set the stage result as unstable,
                                    // build result as failure, and the variable didB1Succeed to false
                                    try {
                                        sh "exit 1"
                                        stageResultMap.didB1Succeed = true
                                    }
                                    catch (Exception e) {
                                        unstable("${STAGE_NAME} failed!")
                                        currentBuild.result = 'FAILURE'
                                        stageResultMap.didB1Succeed = false
                                    }
                                }
                            }
                        }
                        stage('C1') {
                            // Execute only if B1 succeeded
                            when {
                                expression {
                                    return stageResultMap.find{ it.key == "didB1Succeed" }?.value
                                }
                            }
                            steps {
                                // Mark the stage and build results as failure on error but continue pipeline execution
                                catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
                                    sh "echo Hello"
                                }
                            }
                        }
                    }
                }
                stage ('2'){
                    stages {
                        stage('B2') {
                            steps {
                                script {
                                    // Catch exceptions, set the stage result as unstable,
                                    // build result as failure, and the variable didB2Succeed to false
                                    try {
                                        sh "echo Hello"
                                        stageResultMap.didB2Succeed = true
                                    }
                                    catch (Exception e) {
                                        unstable("${STAGE_NAME} failed!")
                                        currentBuild.result = 'FAILURE'
                                        stageResultMap.didB2Succeed = false
                                    }
                                }
                            }
                        }
                        stage('C2') {
                            // Execute only if B2 succeeded
                            when {
                                expression {
                                    return stageResultMap.find{ it.key == "didB2Succeed" }?.value
                                }
                            }
                            steps {
                                // Mark the stage and build results as failure on error but continue pipeline execution
                                catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
                                    sh "echo Hello"
                                }
                            }
                        }
                    }
                }
            }
        }
        stage('D') {
            // Execute only when C1 or C2 have executed, that is B1 or B2 have succeeded
            when {
                expression {
                    return stageResultMap.any {it.value}
                }
            }
            steps {
                println("This is stage: ${STAGE_NAME}")
            }
        }
    }
}

*

*For stages C1 & C2, use catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') to mark both the stage and build results as FAILURE but continue pipeline execution.

*For stages B1 & B2, first initialize an empty map stageResultMap = [:] at the top of your Jenkinsfile to capture the results of each stage. Now, for every Bn stage, use a try-catch block so that on success a unique key-value pair stageResultsMap.didBnSucceed = true is added to the map, and on exception the stage result is set to UNSTABLE, build result to FAILURE, and stageResultsMap.didBnSucceed = false. We use the method unstable here because none of the other two methods catchError or warnError let us add to the map. Then, in the corresponding Cn stage, evaluate the map and execute only if Bn did succeed. Also, if both B1 and B2 fail, i.e., both C1 and C2 do not execute, D wouldn't execute either because when {expression {return stageResultMap.any {it.value}}} will evaluate to false. But D will execute if either C1 or C2 executed regardless of failures.

In both the above scenarios, the overall build status will be marked as FAILURE if any of the stages fail.
Of course, a green build on no failures.


text:
Q: Power source redundancy for low voltage application I am trying to design a circuit that u would like to be as reliable as possible. One feature I would like to add to my circuit is an additional voltage regulator for redundancy purpose. The problem is that the voltage contains a 1.2 V rail that powers the MCU. I have considered using Schottky diodes and ideal diodes, but each of them have their own problems.
My biggest worry with the ideal diode is that the voltage-drop over the diode will vary depending on the MCUs current consumption. Those small voltage variations represent a large percentage of the whole, and MCU should have a very low ripple.
In the added picture, the circuit is using a ORing design.  But I've already decided to change it.
The Schottky diode has a much more stable voltage/current relationship, but the threshold voltage can very a lot depending on the temperature.
Are there any other options that I am overlooking?

A: Ideal diodes are the way to go in this case.
You need a controller whose power is independent from the current path to make the oring. For example LTC4352  "0V to 18V Supply ORing or Holdup"

Use 5V (You have 5V available before the DC/DC) to supply the Vcc input and then Vin will work reliably with 1.2 V
This IC needs external mosfet, so you are free to pick a mosfet with the best Rds ON that you can afford. The mosfet will be turned ON with a Vgs bigger than 5V, which is enough for most mosfets.

When one thinks about reliability, latent faults are to be avoided, so you need to find a way to diagnose whether or not the circuit is working properly, the outputs \status and \fault will give you valuable information.

A: EDIT: I just noticed the other linked article, which basically does what I explain here. I'll leave this here, though, maybe it's still useful.
An approach I've seen used to parallel DC-DC converters is by taking feedback not from the converter's own output, but rather from after the diode-steering arrangement:

simulate this circuit – Schematic created using CircuitLab
This causes the converter to compensate for the voltage drop across the steering diode, so you still get your 1.2V overall output.
However, we choose the fraction of feedback in each converter to be slightly different, so that one of the converters is presented with a slight "over-voltage", causing it to cease switching while the other converter functions normally.
In the above diagram, BUCK1 will operate normally, but BUCK2 will effectively be disabled, because its feedback signal exceeds its Vref. If BUCK1 fails, though, the output will drop slightly, enough to bring feedback for BUCK2 below its own Vref, at which point it starts up, taking over operations.
I have no idea if this is acceptable practice for any old switcher though, so I present this only as something to consider.


text:
Q: How can I merge these two JSON arrays? My php generates two JSON arrays like:
[{"category":183,"private_review_ids":[63,59,62]},
{"category":363,"private_review_ids":[331]},
{"category":371,"private_review_ids":[341]},
{"category":379,"private_review_ids":[350]}]
[{"category":363,"public_review_ids":[331]},
{"category":373,"public_review_ids":[343]},
{"category":384,"public_review_ids":[356]},
{"category":183,"public_review_ids":[347]}]

How could I merge these arrays so they are just one array of the form below. It is not simply merging the arrays - it is the possible tranferring of the value from one key (public_review_ids) to another key (private_review_ids) within the JSON Object. Here's the form I want the JSON Array:
[{"category":183,"private_review_ids":[63,59,62],"public_review_ids":[347] },
{"category":363,"private_review_ids":[331],"public_review_ids":[]},
{"category":371,"private_review_ids":[341],"public_review_ids":[]},
{"category":379,"private_review_ids":[350]},"public_review_ids":[]},
{"category":373,"private_review_ids":[],"public_review_ids":[343]},
{"category":384,"private_review_ids":[],"public_review_ids":[356]}]

As you can see, if the value is in both private_review_ids and public_review_ids, it should appear in just the private_review_ids key.
I tried using array_unique and array_merge but I was having no success, really.
Here's my code:
<?php
require('myfile.php');

    //here is the user_id, which is the corresponding user_id for username +5555555

$user_id = "21";
//Select all related info in the review_shared table
//where the contact_id column is equal to $user_id.

//a value in the contact_id column means a review is shared with a person, $user_name,
//who owns that number, $user_id
$sql = "SELECT * FROM review_shared WHERE contact_id = ?";
$stmt2 = $con->prepare($sql) or die(mysqli_error($con));
$stmt2->bind_param('i', $user_id) or die ("MySQLi-stmt binding failed ".$stmt2->error);
$stmt2->execute() or die ("MySQLi-stmt execute failed ".$stmt2->error);
$result2 = $stmt2->get_result();

//fetch all rows associated with the respective contact_id value
//in review_shared table
while ($row = $result2->fetch_assoc()) {

    //get the corresponding cat_id in the row
    $cat_id = $row["cat_id"];

    //get the corresponding review_id in the row
    $review_id = $row["review_id"];
    //make an array called $results
    $results[$row['cat_id']][] = $review_id;

}

$jsonData = array_map(function($catId) use ($results) {
    return [
        'category' => $catId,
        'private_review_ids' => $results[$catId],
        ];
}, array_keys($results));
echo json_encode($jsonData);

    //**********************

//select all rows where public_or_private column = 2
//in review table
$sql2 = "SELECT * FROM review WHERE public_or_private = 2";
$result2 = mysqli_query($con,$sql2);

    //fetch all associated rows where public_or_private column = 2
    while ($row = $result2->fetch_assoc()) {

    //get the corresponding review_id in the row
    $review2_id = $row["review_id"];

    //get the corresponding cat_id in the row
    $cat2_id = $row["cat_id"];

    //make an array called $results
    $results2[$row['cat_id']][] = $review2_id;

    }

    $jsonData2 = array_map(function($cat2Id) use ($results2) {
    return [
        'category' => $cat2Id,
        'public_review_ids' => $results2[$cat2Id],
        ];
}, array_keys($results2));
echo json_encode($jsonData2);

?>

A: If you refactor your code, you can remove the need for iterating over the data 4 times (twice each) by immediately appending the query results into your desired data structure.
If you execute your public and private review queries, such that their results are in variables $publicReviews and $privateReviews then:
<?php

// Public and private review query results
$publicReviews = $stmt1->get_result();
$privateReviews = $stmt2->get_result();

// Prepare combined reviews array
$reviews = [];

// Iterate through private review results and append to combined reviews
while (($row = $privateReviews->fetch_assoc())) {
    $category_id = $row['cat_id'];
    $review_id = $row['review_id'];

    $reviews[$category_id]['category'] = $category_id;
    $reviews[$category_id]['private_review_ids'][] = $review_id;
    $reviews[$category_id]['public_review_ids'] = [];
}

// Iterate through public review results and append to combined reviews
while (($row = $publicReviews->fetch_assoc())) {
    $category_id = $row['cat_id'];
    $review_id = $row['review_id'];

    $reviews[$category_id]['category'] = $category_id;

    // Create empty private reviews array, where it doesn't exist
    if (! isset($reviews[$category_id]['private_review_ids'])) {
        $reviews[$category_id]['private_review_ids'] = [];
    }

    // Add review id to public reviews where it doesn't exist in private reviews
    if (! in_array($review_id, $reviews[$category_id]['private_review_ids'])) {
        $reviews[$category_id]['public_review_ids'][] = $review_id;
    }
}

echo json_encode(array_values($reviews));


text:
Q: При подключении к AmneziaVPN пропадает интернет Суть вопроса такова:
Я установил на свой халявный сервер от AlibabaCloud AmneziaVPN с протоколом OpenVPN, пробросил порт 1194 для SSL
Попробовал подключиться через приложение AmneziaVPN для Windows подключение прошло успешно, но отвалился интернет (соединение с сервером при этом не пропало).
Попробовал подключиться через OpenVPN Client аналогичная ситуация -
на сервере интернет есть, а у меня нет.
вот выхлоп OpenVPN клиента
Mon Jun  6 00:16:45 2022 Windows version 10.0 (Windows 10 or greater) 64bit
Mon Jun  6 00:16:45 2022 library versions: OpenSSL 1.1.1n  15 Mar 2022, LZO 2.10
Mon Jun  6 00:16:45 2022 MANAGEMENT: TCP Socket listening on [AF_INET]127.0.0.1:25341
Mon Jun  6 00:16:45 2022 Need hold release from management interface, waiting...
Mon Jun  6 00:16:45 2022 MANAGEMENT: Client connected from [AF_INET]127.0.0.1:25341
Mon Jun  6 00:16:45 2022 MANAGEMENT: CMD 'state on'
Mon Jun  6 00:16:45 2022 MANAGEMENT: CMD 'log all on'
Mon Jun  6 00:16:45 2022 MANAGEMENT: CMD 'echo all on'
Mon Jun  6 00:16:45 2022 MANAGEMENT: CMD 'bytecount 5'
Mon Jun  6 00:16:45 2022 MANAGEMENT: CMD 'hold off'
Mon Jun  6 00:16:45 2022 MANAGEMENT: CMD 'hold release'
Mon Jun  6 00:16:45 2022 Outgoing Control Channel Authentication: Using 512 bit message hash 'SHA512' for HMAC authentication
Mon Jun  6 00:16:45 2022 Incoming Control Channel Authentication: Using 512 bit message hash 'SHA512' for HMAC authentication
Mon Jun  6 00:16:45 2022 TCP/UDP: Preserving recently used remote address: [AF_INET]8.209.74.136:1194
Mon Jun  6 00:16:45 2022 Socket Buffers: R=[65536->65536] S=[65536->65536]
Mon Jun  6 00:16:45 2022 UDP link local: (not bound)
Mon Jun  6 00:16:45 2022 UDP link remote: [AF_INET]8.209.74.136:1194
Mon Jun  6 00:16:45 2022 MANAGEMENT: >STATE:1654463805,WAIT,,,,,,
Mon Jun  6 00:16:45 2022 MANAGEMENT: >STATE:1654463805,AUTH,,,,,,
Mon Jun  6 00:16:45 2022 TLS: Initial packet from [AF_INET]8.209.74.136:1194, sid=4582bf91 366fc246
Mon Jun  6 00:16:45 2022 VERIFY OK: depth=1, CN=ChangeMe
Mon Jun  6 00:16:45 2022 VERIFY KU OK
Mon Jun  6 00:16:45 2022 Validating certificate extended key usage
Mon Jun  6 00:16:45 2022 ++ Certificate has EKU (str) TLS Web Server Authentication, expects TLS Web Server Authentication
Mon Jun  6 00:16:45 2022 VERIFY EKU OK
Mon Jun  6 00:16:45 2022 VERIFY OK: depth=0, CN=ChangeMe
Mon Jun  6 00:16:46 2022 Control Channel: TLSv1.3, cipher TLSv1.3 TLS_AES_256_GCM_SHA384, peer certificate: 2048 bit RSA, signature: RSA-SHA256
Mon Jun  6 00:16:46 2022 [ChangeMe] Peer Connection Initiated with [AF_INET]8.209.74.136:1194
Mon Jun  6 00:16:46 2022 PUSH: Received control message: 'PUSH_REPLY,route 10.8.0.1,topology net30,ping 10,ping-restart 120,ifconfig 10.8.0.6 10.8.0.5,peer-id 0,cipher AES-256-GCM'
Mon Jun  6 00:16:46 2022 OPTIONS IMPORT: timers and/or timeouts modified
Mon Jun  6 00:16:46 2022 OPTIONS IMPORT: --ifconfig/up options modified
Mon Jun  6 00:16:46 2022 OPTIONS IMPORT: route options modified
Mon Jun  6 00:16:46 2022 OPTIONS IMPORT: peer-id set
Mon Jun  6 00:16:46 2022 OPTIONS IMPORT: adjusting link_mtu to 1624
Mon Jun  6 00:16:46 2022 OPTIONS IMPORT: data channel crypto options modified
Mon Jun  6 00:16:46 2022 Outgoing Data Channel: Cipher 'AES-256-GCM' initialized with 256 bit key
Mon Jun  6 00:16:46 2022 Incoming Data Channel: Cipher 'AES-256-GCM' initialized with 256 bit key
Mon Jun  6 00:16:46 2022 interactive service msg_channel=728
Mon Jun  6 00:16:46 2022 open_tun
Mon Jun  6 00:16:46 2022 tap-windows6 device [OpenVPN TAP-Windows6] opened
Mon Jun  6 00:16:46 2022 TAP-Windows Driver Version 9.24
Mon Jun  6 00:16:46 2022 Notified TAP-Windows driver to set a DHCP IP/netmask of 10.8.0.6/255.255.255.252 on interface {6C31F4FC-F170-4512-A655-E812389CE8C0} [DHCP-serv: 10.8.0.5, lease-time: 31536000]
Mon Jun  6 00:16:46 2022 Successful ARP Flush on interface [16] {6C31F4FC-F170-4512-A655-E812389CE8C0}
Mon Jun  6 00:16:46 2022 MANAGEMENT: >STATE:1654463806,ASSIGN_IP,,10.8.0.6,,,,
Mon Jun  6 00:16:46 2022 IPv4 MTU set to 1500 on interface 16 using service
Mon Jun  6 00:16:46 2022 Blocking outside dns using service succeeded.
Mon Jun  6 00:16:51 2022 TEST ROUTES: 2/2 succeeded len=1 ret=1 a=0 u/d=up
Mon Jun  6 00:16:51 2022 C:\windows\system32\route.exe ADD 8.209.74.136 MASK 255.255.255.255 192.168.141.113
Mon Jun  6 00:16:51 2022 Route addition via service succeeded
Mon Jun  6 00:16:51 2022 C:\windows\system32\route.exe ADD 0.0.0.0 MASK 128.0.0.0 10.8.0.5
Mon Jun  6 00:16:51 2022 Route addition via service succeeded
Mon Jun  6 00:16:51 2022 C:\windows\system32\route.exe ADD 128.0.0.0 MASK 128.0.0.0 10.8.0.5
Mon Jun  6 00:16:51 2022 Route addition via service succeeded
Mon Jun  6 00:16:51 2022 MANAGEMENT: >STATE:1654463811,ADD_ROUTES,,,,,,
Mon Jun  6 00:16:51 2022 C:\windows\system32\route.exe ADD 10.8.0.1 MASK 255.255.255.255 10.8.0.5
Mon Jun  6 00:16:51 2022 Route addition via service succeeded
Mon Jun  6 00:16:51 2022 WARNING: this configuration may cache passwords in memory -- use the auth-nocache option to prevent this
Mon Jun  6 00:16:51 2022 Initialization Sequence Completed
Mon Jun  6 00:16:51 2022 MANAGEMENT: >STATE:1654463811,CONNECTED,SUCCESS,10.8.0.6,8.209.74.136,1194,,

помогите пожалуйста, тыкните носом в мою ошибку
UPD: С телефона подключился, та же фигня

A: Решил проблему тем что удалил Амнезию и установил впн с этого репозитория
https://github.com/emobortnik/easy-openvpn


text:
Q: SSIS Failed to retrieve long data for column varchar(max) I want build a package that imports excel rows to an SQL server table, the problem is that sometimes there is an error that fails the package process.

[Excel Source [1]] Error: SSIS Error Code DTS_E_OLEDBERROR.  An OLE DB
  error has occurred. Error code: 0x80040E21. [Excel Source [1]] Error:
  Failed to retrieve long data for column "RECOMENDACION". [Excel Source
  [1]] Error: There was an error with output "Excel Source Output" (9)
  on component "Excel Source" (1). The column status returned was:
  "DBSTATUS_UNAVAILABLE".

as you can see, there is something wrong with the column "RECOMENDACION".
Note: the error is in Excel Source task.

A: I had the same issue. Apparently the MS Jet Database Engine checks the first 8 rows of a column to try and guess what the data type of the column is (regardless of what type you specify).
Mine was fixed when I changed the value of the registry key TypeGuessRows from 8 to 0.
This key is going to be in either of these locations:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\4.0\Engines\Excel
HKEY_LOCAL_MACHINE -> SOFTWARE -> Wow6432Node -> Microsoft -> Jet -> 4.0 ->Engines -> Excel

A: Decreasing the DefaultBufferMaxRows helped in my case.
It might be luck, but it helped.

A: For me it was creating a new oledb source. I was reusing the existing oledb source for my new query. Changing it solved my issue

A: I know this is an old question, but I've just had the problem, and it turned out to be a missing"C:\SSISTempStoragePath" directory. Such a simple problem with a very cryptic error message. SSIS will create a file in this directory for each column and each row in the source. Beware of AntiVirus wanting to scan all these files.
The files are named "DTB{>a GUID here<}.tmp", and are all zero (0) bytes long.


text:
Q: Is there a way to group a series of events by date on SQL. ie Get the minimum and max event times that happen for every empid(employee) and day This code would group all the events between the selected times. Is there a way that the max and min events could be grouped by date automatically without having to specify the dates like I have. ie Get the max and min events for each day grouped by ID.
SELECT MIN(ev.EVENT_TIME_UTC) AS Time_In, MAX(ev.EVENT_TIME_UTC) AS Time_Out, EMPID
    FROM dbo.EVENTS ev
    WHERE (ev.EVENT_TIME_UTC
    BETWEEN '2019-04-09'
    AND '2019-04-09 23:59:59')
    GROUP BY EMPID

A: SELECT
  empid
, CAST(event_time_utc AS DATE) AS event_dt
, MIN(event_time_utc)          AS time_in
, MAX(event_time_utc)          AS time_out
FROM events
GROUP BY
  empid
, CAST(event_time_utc AS DATE)
;

A: One method uses window functions:
SELECT EMPID, MIN(ev.EVENT_TIME_UTC) AS Time_In,
       MAX(ev.EVENT_TIME_UTC) AS Time_Out,
       MIN(CASE WHEN seqnum_asc = 1 THEN EVENT END) as first_event,
       MIN(CASE WHEN seqnum_desc = 1 THEN EVENT END) as last_event
FROM (SELECT ev.*,
             ROW_NUMBER() OVER (PARTITION BY EMPID ORDER BY ev.EVENT_TIME_UTC) as seqnum_asc,
             ROW_NUMBER() OVER (PARTITION BY EMPID ORDER BY ev.EVENT_TIME_UTC DESC) as seqnum_desc
      FROM FROM dbo.EVENTS ev
      WHERE ev.EVENT_TIME_UTC >- '2019-04-09' AND ev.EVENT_TIME_UTC < '2019-04-10'
     ) e
GROUP BY EMPID;


text:
Q: Entity framework: one table, two entities - concurrency problem in our system we have one table, named Customer. And for some reason we have 2 entities referenced to this table, say Customer and AdditionalProperty.
I need to test something and I create entities, Customer and AdditionalProperty. But when I try to delete them I have the following exception: "Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries."
Could someone explain me what to do?
Thanks!


text:
Q: Help with complex number phasor notation I am having trouble understanding how $10jy$ is converted to $10 e^{j\pi/2}$. Here $x$ and $y$ are unit vectors:
(original image)
$$\large=\operatorname{Re}\left[(10\hat{x}-10j\hat{y})e^{-j10\pi z}e^{jwt}\right]$$
$$\large=\operatorname{Re}\left[(10\hat{x}-10e^{j\pi/2}\hat{y})e^{-j10\pi z}e^{jwt}\right]$$
$$\large=\underbrace{10\hat{x}\cdot\cos(\omega t-10\pi z)}_{Ex}+\underbrace{10\hat{y}\cos(\omega t-10\pi z-\tfrac{\pi}{2})}_{Ey}$$
Thank you.

A: Euler's formula says that for any $\theta$,
$$e^{j\theta}=\cos(\theta)+j\sin(\theta).$$
Therefore,
$$e^{j\pi/2}=\cos(\tfrac{\pi}{2})+j\sin(\tfrac{\pi}{2})=0+j\cdot 1=j$$
and thus $10j=10e^{j\pi/2}$ (or, if you want to talk about vectors, $10j\hat{y}=10e^{j\pi/2}\hat{y}$; but note that it is incorrect to say that $10j\hat{y}=10e^{j\pi/2}$, because the left side is a vector, and the right side is a scalar).


text:
Q: External 8MHz Oscillator not working for STM32F405RGT6 custom Hardware I am using custom-designed hardware for STM32F405RGT6. I need to put the chip in DFU mode to perform a DFU firmware upgrade. I am able to flash the chip via the STLINK, which indicates that the chip is functional. I have connected the Boot0 pin to Vdd. I am connecting the board to the PC via a USB cable whose DM, DP, and GND are connected to PA11 (DM), PA12(DP), and GND of chip respectively. The board is not detected on PC and doesn't show up on the device manager irrespective of BOOT0 status. As per my understanding, the USB needs HSE to function correctly as per AN2606.

I checked the waveform with an oscilloscope on both the terminals of the crystal and all I get is DC 1.8~1.75V on both pins (which means the oscillator isn't working). I also checked the waveform on the oscillator on the discovery kit from STM where I can clearly see an 8MHz 1.8V Vpp waveform. I am using the same oscillator as on the STM discovery kit and the resistor values are also the same.
Crystal Oscillator Troubleshooting Guide https://www.nxp.com/docs/en/application-note/AN3208.pdf
USB DFU Protocol (Pg 6) https://www.st.com/resource/en/application_note/cd00264379-usb-dfu-protocol-used-in-the-stm32-bootloader-stmicroelectronics.pdf
STM32 microcontroller system memory boot mode (Pg 110) https://www.st.com/resource/en/application_note/cd00167594-stm32-microcontroller-system-memory-boot-mode-stmicroelectronics.pdf
I need your help to get the external crystal working as I believe it is the reason why my board isn't detecting on a PC.
Thank you.
Edit 1: Adding oscillator schematic for reference. Component Y1 is the crystal oscillator.


text:
Q: Ubuntu: Flash Videos in Fullscreen Freeze I am using Ubuntu 10.10 on my IBM X200t. Installed is the standard flash player plugin for Firefox: (flashplugin-nonfree, 10.1.102.65). Everytime I switch a flash video to fullscreen, the video freezes. However, the video continues to play and I hear sound. How can I fix this?

A: the answer by mervin might work too, but i know for a fact that this thread worked: http://ubuntuforums.org/showthread.php?p=10513659#post10513659

A: Try the following in a terminal:
sudo mkdir /etc/adobe
sudo su
sudo echo \"OverrideGPUValidation = 1\" >> /etc/adobe/mms.cfg


text:
Q: Getting error in viewbag list I am trying to pass queried data from controller to view and I am using ViewBag for this. But getting error while writing View code.
Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace club.Models
{
    public class DetailMember
     {
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Gender { get; set; }
}

}
Controller:
 public ActionResult ViewDetail(string id)
    {
         var db= new clubDataContext();
        int id1 = Convert.ToInt32(id);
        var list = (from m in db.M_Registarions where m.M_id == id1 select new DetailMember() { FirstName = m.M_Fname, LastName = m.M_Lname, Gender = m.M_Gender }).ToList();
        ViewBag.memberDetail = list;

View:
@model club.Models.DetailMember
@{
  ViewBag.Title = "ViewDetail";
 }

ViewDetail

@foreach (var item in (List<**DetailMember**>)ViewBag.memberDetail)
{

}

Here I am getting error in DetailMember List. I don't know what is wrong in this. Please help me to solve this error.
Error: The type or namespace name 'DetailMember' could not be found

A: Try using simple foreach:
@foreach (var item in ViewBag.memberDetail)
{
@item.FirstName
}


text:
Q: Let $\|\cdot\|$ be a norm on $\mathbb R^2$. Show that the perimeter of the closed unit ball is between $4$ and $12$. Let $\|\cdot\|$ be a norm on $\mathbb R^2$. The length of a polygon line is given by this norm. Let $A$ be a non-empty bounded convex part of  $\mathbb R^2$. The perimeter of $A$ is defined as the upper bound of the perimeters of the convex polygons included in $A$. Show that the perimeter of the closed unit ball is between $4$ and $12$.
Not very familiar with geometry, I do not not see how to deal with this problem from an oral exam (if not to frame the unit ball with polygons). If you have an idea ...
Note that the norm is not necessarily euclidean (i.e. issue from a scalar product).

A: Let $u$ be a point on the boundary $\partial B$ of the unit ball $B$ of a norm on $\mathbb R^2$. Then $\partial B$ and the boundary $u+\partial B$ of the unit ball with center $u$ intersects (for instance by the Intermediate Value Theorem). Let $v$ be a point in the intersection. Then $u$, $v$, $v-u$, $-u$, $-v$, $u-v$ are 6 points in this order on the boundary, with successive points at distance $1$ apart. They subdivide $\partial B$ into 6 arcs, each of length (in the norm) of at least $1$. This shows that the length of $\partial B$ is at least $6$.
Next, among all $u,v\in\partial B$, choose two for which the area $\det(u,v)$ of the parallelogram with vertex set $\{o, u, v, u+v\}$ is maximized.
Then the line through $u$ parallel to $v$ supports $B$ at $u$ (otherwise $\det(u,v)$ could be increased) and the line through $v$ parallel to $u$ supports $B$ at $v$. It follows that the parallelogram $P$ with vertices $\pm u\pm v$ contains $B$ and subdivides $B$ into $4$ parts. One of the parts is the arc of $\partial B$ from $u$ to $v$, which is contained in the convex hull of $o, u, u+v, v$. It can be shown (using the triangle inequality) that the length of the arc of $\partial B$ from $u$ to $v$ is at most the length of the corresponding arc of $\partial P$, which consists of the two segments $[u,u+v]$ and $[u+v,v]$, and thus has length $2$. It follows that the length of $\partial B$ is at most $8$.
Remarks

*

*The above two bounds were first proved by Stanislaw Golab in 1932. It can also be found in Chapter 4 of Thompson's book Minkowski Geometry.

*The result can also be shown by choosing $P$ to be a parallelogram of minimum area containing $B$.

*There is, up to isometry, only one norm where the length of the unit ball is $6$, namely when $B$ is an affine regular hexagon.

*There is, up to isometry, only one norm where the length of the unit ball is $8$, namely when $B$ is a parallelogram.

*See my survey with Martini and Weiß for an elementary proof from the triangle inequality that if a convex arc $\gamma$ from $a$ to $b$ is contained in the triangle $\triangle abc$, then the length of $\gamma$ is at most $\|a-c\|+\|b-c\|$. Thompson proves it indirectly using an area argument.

References
S. Golab, Some metric problems in the geometry of Minkowski (Polish. French summary), Prace Akademii Górniczej w Krakowie 6 (1932), 1-79.
H. Martini, K. J. Swanepoel, and G. Weiß, The geometry of Minkowski spaces — a survey. Part I, Expositiones Mathematicae 19 (2001), 97-142.
A. C. Thompson, Minkowski Geometry, Cambridge University Press, Cambridge, 1996.

A: w.l.g. normalize the norm such that $||(1,0)|| = 1$, and take $a,b>0$ such that $||(1/2,a)|| = 1$ and $||(0,b)||=1$, then we can consider the following paralelograms (with sides paralels to the axes):
Polygon $P_1$: such that its corners are $\{(1/2,a), (-1/2,a), (-1/2,-a), (1/2,-a)\}$.
Polygon $P_2$: such that its corners are $\{(1,b), (-1,b), (-1,-b), (1,-b)\}$.

Then notice that the ball of radius one $\mathbb{B} \subset \mathbb{R}^2$ satisfies
$$ P_1 \subset \mathbb{B} \subset P_2$$
To prove this, just use the convexity of the sets.
Notice that since $||(1/2,a)|| = 1$ and $||(1/2,0)|| = 1/2$, employing the triangular inequality we can show that $1/2 \leq ||(0,a)||$. Therefore the perimeter of $P_1$, that is composed of 4 strokes, can be estimated as:
$$\text{Perim} (P_1) = 4 ||(1/2,0)|| + 4||(0,a)|| \geq 4\cdot 1/2 + 4\cdot 1/2 = 4$$
Similarly with $P_2$, its perimeter can be computed as
$$\text{Perim}(P_2) = 4||(1,0)|| + 4||(0,b)|| = 8$$.
So we proved that
$$ 4 \leq \text{Perim}(\mathbb{B}) \leq 8 \leq 12 $$


text:
Q: JSON result in Tableview in Swift showing list of results instead of each result in each cell (picture attached) So I am making an app with Swift 2 (not 3.0) and I've come across a problem in which I've gotten the JSON to show up on my Tableview but it's showing all the results in each cell instead of one result in each cell. Here's a picture showing the problem
My MasterViewController:
import UIKit
import Alamofire
import SwiftyJSON

class MasterViewController: UITableViewController {

var tableTitle = [String]()
var tableBody = [String]()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    getJSON()

}

func getJSON() {

    Alamofire.request(.GET, "http://www.graydoncs.club/api/posts").responseJSON { (Response) in

        if let value = Response.result.value {

            let json = JSON(value)

            for anItem in json.array! {

                let title: String? = anItem["title"].stringValue
                self.tableTitle.append(title!)
                print(anItem["title"].stringValue)

            }

            dispatch_async(dispatch_get_main_queue()) {

                self.tableView.reloadData()

            }

        }

    }

}

override func viewWillAppear(animated: Bool) {
    self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed
    super.viewWillAppear(animated)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Segues

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "showDetail" {
        if let indexPath = self.tableView.indexPathForSelectedRow {
            let object = tableTitle[indexPath.row] as! String
            let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
            controller.detailItem = object
            controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
            controller.navigationItem.leftItemsSupplementBackButton = true
        }
    }
}

// MARK: - Table View

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return tableTitle.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)

    let object = tableTitle[indexPath.row] as! String
    cell.textLabel!.text = tableTitle.description
    return cell
}

override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    // Return false if you do not want the specified item to be editable.
    return false
}

}

Any help regarding this problem would be greatly appreciated. Thanks!

A: override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)

let object = tableTitle[indexPath.row] as! String
cell.textLabel!.text = object
return cell

}


text:
Q: How can I create repeated fields in Form Builder with Orbeon Forms 3.9? Alex, I don't think I explained myself well enough (Although the information you provided was useful.) Lets say that I have an employment application that was created to collect information about a persons previous employers. Lets say that the grid for one employer was 15 fields deep. If i were going to allow the user to enter up to 10 past employers, I am going to have to manually create 150 individual fields...then....to make matters more complicated, if i were using validation rules for my form, I will have to modify the properties on each control one at a time. So my question is two fold: First, is there a way to quickly replicate whole grids within the form builder? Second, is there a way to modify visibility rules for a whole grid rather than right clicking on each control one at a time to add visibility rules (or change control names for that matter.)

A: Orbeon is working on adding support for Form Builder to build a UI for what XForms refers to as "repeats". With repeat support built in Form Builder, you'll be able to create just one "line", i.e. the fields for one sibling, and say that this line can be repeated. But since this is not available yet, you can work around this by editing the source generated by Form Builder to use repeats. Let me expand on that idea:
Form Runner, the runtime, already supports repeats. It's just that Form Builder doesn't let you edit them. You can use a repeat by editing the code generated by Form Builder from Advanced / Edit Source. You can see what a repeat looks like in the Bookshelf example, and see what the code looks like in the source of the Bookshelf example (look for the <fr:repeat> on the <fr:grid>).
In your case, since you'd like to limit the number of possible siblings to 14, also add an attribute maxOccurs="14" on the <fr:repeat>.


text:
Q: Incrustar combobox con datos de la base en ajax Hola buenos dias tengo un ajax que lo que hace es cargar preguntas en un accordion tengo un campo el cual es un input text que yo escribo algun dato de la base de datos y me manda la info segun si esta incrustrado pero ahora lo que quiero es cambiarlo por un combobox para que las personas puedan ver quienes estan hay y no tener que poner a escribir siempre en el input text me podrian ayudar como hacer para que me los muestre en un combobox

A: Cuando finalize el recorrido de los datos recogidos,yo crearía otra función pasándole los datos y apuntaría al elemento txt_tec_ins_inc.No se si con este ejemplo te sirve.Si llegas a tener mas select en la creación,yo lo haría recorriendo el DOM seleccionando todos los select dentro de ese contenedor.Espero que te sirva de ayuda

$(document).ready(function(){
var datos = ["peter","antonio","juan","Andrés","Javi"];

function rellenaCampos(datos){
    $.each(datos,function(i,e){
     $("#txt_tec_ins_inc").append('<option value="'+ e +'">'+ e +'</option>');

    })

   };

  function rellenarSelects(){

      $("#caja").append('<select class="form-control" id="txt_tec_ins_inc"></select>');

    rellenaCampos(datos);
  };
  rellenarSelects();
});
div{
margin-left:200px;
}

#txt_tec_ins_inc{
width:200px;
}

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


text:
Q: custom fittype with two expressions in matlab I would like to make a custom fittype using two related expressions:
(f1/(1+ksv1*Q))+(f2/(1+ksv2*Q)) == I/I0 and f1 + f2 == 1.
I made a fittype using the first expression and for now have f1 and f1 set to be defined manually with the 'problem' argument. Obviously, fitting with them as plain coefficients doesn't result in f1 + f2 = 1.
Is there a way to add this second condition to the fittype?
Q = [ 0; 1; 10; 21;];
I = [ 2376.4; 2148.6; 1000.8; 736.52;];
% (f1/(1+ksv1*Q))+(f2/(1+ksv2*Q))== I/I0
g = fittype('2376.4*((f1/(1+ksv1*Q))+(f2/(1+ksv2*Q)))','dependent',{'I'},'independent',{'Q'},'problem',{'f1','f2'}','coefficients',{'ksv1','ksv2'});
myfit = fit(Q,I,g,'problem',{.23,.77})
plot(myfit,Q,I)

A: I ended up plugging the second expression into the first and setting upper and lower bounds for the coefficients.
Q = [ 0; 1; 10; 21;];
I = [ 2376.4; 2148.6; 1000.8; 736.52;];
% (f1/(1+ksv1*Q))+(1-f1/(1+ksv2*Q))== I/I0 ; f1+f2=1, f2=1-f1 ; I0 = 2376.4
g = fittype('2376.4*((f1/(1+ksv1*Q))+((1-f1)/(1+ksv2*Q)))',...
        'independent',{'Q'},'dependent','I')

myfit = fit(Q,I,g,'lower',[0 0 0],'upper',[1 inf inf]) % bounds for [f1 ksv1 ksv2]
figure
plot(myfit,Q,I)


text:
Q: Redirecting stdin with FIFO (names pipe) I'm creating a C program with a server-client bases.
I've been trying to redirect the stdin to a named pipe I created and I've managed to put a client writing to the pipe. On the server side I opened the same pipe, closed stdin and redirected the stdin, using dup (tried with dup2 as well), to the pipe.
I have to read the input with the function getline. The problem is it reads the first input correctly, but recieves only nulls after it. I'll add a sample to the question.
server:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

main () {
    char* str;
    size_t size=0;
    int pshell_in;

    unlink("/tmp/par-shell-in");
    if(mkfifo("/tmp/par-shell-in", 0777) < 0){
        fprintf(stderr, "Error: Could not create pipe\n");
        exit(-1);
    }

    if((pshell_in = open("/tmp/par-shell-in", O_CREAT | O_RDONLY, S_IRUSR)) < 0){
        fprintf(stderr, "Error: Failed to open file\n");
        exit(-1);
    }

    dup2(pshell_in, 0);
    close(pshell_in);

    while(1) {
        if (getline(&str, &size, stdin)<0) {
            printf("Oh dear, something went wrong with getline()! %s\n", strerror(errno));
            return -1;
        }

        printf("%s", str);
    }
}

* I know its null cause I've printed it with read (instead of redirecting) and it prints (null).
client:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>

#define VECTORSIZE 7

int main() {

    char* buf;
    int pshell_in;
    size_t size=0;

    if((pshell_in = open("/tmp/par-shell-in", O_WRONLY, S_IWUSR)) < 0){
        fprintf(stderr, "Error: Failed to open file\n");
        exit(-1);
    }

    printf("%d\n", pshell_in);

    while(1) {
        if (getline(&buf, &size, stdin) < 0) {
            return -1;
        }

        write(pshell_in, buf, 256);
    }
}

*

*I suspect its right because if I use read on the client side (replacing O_WRONLY with O_RDWR) it prints the string as I typed it.

Can anyone help me with this one?

A: FIFOs are funny things.  If a process tries to open one for reading, it will block until there's a process that opens it for writing.  Conversely, if a process tries to open one for writingt, it will block until there's a process that opens it for reading.  However, multiple processes can open it for reading or writing.  When there are no more processes with it open for reading, writes will fail; when there are no more processes with it open for writing, reads will fail.  And when the operations fail, you have to close and reopen the FIFO to continue processing data afresh.
I strongly suspect you're running into problems because of these behaviours.
Additionally, your client write code is dubious; you aren't paying any attention to how much data was read.  You have:
while(1) {
    if (getline(&buf, &size, stdin) < 0) {
        return -1;
    }
    write(pshell_in, buf, 256);
}

If, as is probable, you read less than 256 characters of input in the line, then it's quite possible that you go writing beyond the bounds of the array that was allocated by getline().  It's also distinctly possible that some or even most of that data is null bytes.  However, the (null) you're seeing in the server typically indicates that you're trying to print a string but passed printf() a null pointer.  Whatever's going on, most of it is undefined behaviour which is a Bad Thing™ and should be avoided at all costs.
You should have something more like:
ssize_t nbytes;

while ((nbytes = getline(&buf, &size, stdin)) > 0)
{
    if (write(pshell_in, buf, nbytes) != nbytes)
    {
        fprintf(stderr, "Short write to FIFO\n");
        break;
    }
}
free(buf);

Note how this only writes as much data as was read and doesn't assume that 256 bytes were available to be written.


text:
Q: Least square circle via fixed point iteration You have a collection of 2d points that you want to fit to a circle. Form the sum of the squares of the distances from the points to a generic circle. The variables are the $x,y$ coordinates of the center, and the radius. Set the gradient to 0, then one equation gives the radius as the average distance from the center to the points. For a given point $C$, let $r(C)$ denote the average distance from $C$ to the points. Using the other two equations, we find the center is a fixed point of the mapping $T(C)$, defined in the following way:
From each point, travel towards $C$ a distance $r(C)$, and then average all of these shifted points to get $T(C)$.
The mapping is not well defined at the points. It is possible in some arrangements of points and some starting point $C_0$ for the fixed point iteration $C_{n+1}=T(C_n)$ to land on one of the points to be fit. With this in mind, I'm trying to find a set on which $T$ is a contraction. Intuitively, we could take disks centered at each point to be fit, and grow them uniformly until they all intersect in a nonempty set, maybe let the disks grow a little more, and assuming the intersection doesn't contain any of the points to be fit, this should serve as a good candidate set to prove $T$ is a contraction. Indeed, it is easy to see that the shifted points will remain in their respective disks about each point to be fit, but it is not at all clear that $T(C)$, the average of the shifted points, will lie in every disk, but it has to be close! Note that the intersection of disks is a compact and convex set, and $T$ is continuous, so I have Brouwer fixed point theorem in mind.
Any ideas how to choose the Set? Is the intersection I described good? I just can't figure out a proof. I have tested the problem fairly thoroughly on a computer and the convergence of the fixed point iteration seems is quite reliable choosing $C_0$ as the average of the points.
In general, I do not expect uniqueness, for suppose there are only 1 or 2 distinct points, then there are infinitely many circles fitting the points exactly. Also note that if the points are distributed on a small arc of the circle, the average of the points is quite far from the center, yet convergence is observed, albeit quite slowly.
Edit
I was asked for formulas, so I give
$T(C) = \frac{1}{n}\sum_{i=1}^n (P_i + r(C)\frac{C-P_i}{|C-P_i|})$ where $r(C) = \frac{1}{n}\sum_{i=1}^n |C-P_i|$. And we want to find $C$ such that $T(C)=C$. I just need a set that $T$ maps into itself.

A: There's a pretty extensive body of literature on this problem. Apart from the theoretical interest, there is an important practical problem. When manufactured parts are inspected for quality, you get a bunch of points from a coordinate measuring machine. You often want to fit circles to these points, to estimate sizes of holes, diameters of shafts, etc.
For numerous papers and a book on the subject, look here.

A: Probably not an answer to the question but too long for a comment.
Supposing that you have $n$ data points $(x_i,y_i)$ and you want the "best" circle of radius $r$ centered at $(a,b)$, you need to minimize
$$SSQ(a,b,r)=\sum_{i=1}^n \left(r-\sqrt{(x_i-a)^2+(y_i-b)^2} \right)^2$$ which is an highly nonlinear problem. Any minimization method would do it provided goo estimates.
To get such estimates, in a preliminary step, you could write $$f_i=(x_i-a)^2+(y_i-b)^2-r^2$$ and now consider all the $\frac {n(n-1)}2$ equations
$$g_{ij}=f_j-f_i=2a(x_i-x_j)+2b(y_i-y_j)+\left((x_j^2-x_i^2)+(y_j^2-y_i^2)\right)$$ A linear regression (or matrix calculation) based on these $\frac {n(n-1)}2$ data points will provide $a$ and $b$. Using them would give as an estimate $$r=\frac 1n \sum_{i=1}^n \sqrt{(x_i-a)^2+(y_i-b)^2}\tag 1$$ Now, you have all elements for starting the optimization. You could even use Newton-Raphson method to solve
$$\frac{\partial SSQ}{\partial a}=\frac{\partial SSQ}{\partial b}=\frac{\partial SSQ}{\partial r}=0$$  which reduce to
$$\frac{\partial SSQ}{\partial a}=\sum_{i=1}^n \frac{(x_i-a) \left(r-\sqrt{(x_i-a)^2+(y_i-b)^2}\right)}{\sqrt{(x_i-a)^2+(y_i-b)^2}}=0\tag 2$$
$$\frac{\partial SSQ}{\partial b}=\sum_{i=1}^n \frac{(y_i-b) \left(r-\sqrt{(x_i-a)^2+(y_i-b)^2}\right)}{\sqrt{(x_i-a)^2+(y_i-b)^2}}=0\tag 3$$
$$\frac{\partial SSQ}{\partial r}=\sum_{i=1}^n \left(r-\sqrt{(x_i-a)^2+(y_i-b)^2}\right)=0\tag 4$$ The solution of $(4)$ is already given by $(1)$; so, you are left with two nonlinear equations in $(a,b)$.
If you are as lazy as I am, use numerical derivatives.


text:
Q: Manage user restrictions to different apps within a single B2C Tenant Within a single Azure AD B2C Tenant I have a directory of Users. Also, I have 2 Applications registered. Call them App1 and App2.
Assume that a User has registered his/her Account coming from (and being redirected back to) App1, now that the user is in the common User directory, he/she could also sign in to App2 and I can't do anything about it.
It doesn't make much sense to me, and I need to restrict it. How can I control which Apps the Users can access? A User could have access to any amount of registered Applications. I can't seem to find that in the Azure Portal...
Of course I can apply any solution also on App side, e.g. by checking some claim or something, but still, I need to know how to manage such restrictions. (this could be a fully custom way)

A: You would have to implement in B2C exactly what you said you'd implement in the app

by checking some claim or something

Apart of your B2C user journey you would introduce a precondition to check whether a claim exists or equals a certain value. This would require custom policies. There isn't an easy way to "error" out, but you could create a self asserted page that just shows an error message with a dummy input claim.
You're much better off building this logic in your application.
 <OrchestrationStep Order="3" Type="ClaimsExchange">
      <Preconditions>
        <Precondition Type="ClaimEquals" ExecuteActionsIf="false">
          <Value>app_permission</Value>
          <Value>portalapp</Value>
          <Action>SkipThisOrchestrationStep</Action>
        </Precondition>
      </Preconditions>
      <ClaimsExchanges>
        <ClaimsExchange Id="AppRestrictionExchange" TechnicalProfileReferenceId="TechnicalProfileHere" />
      </ClaimsExchanges>
    </OrchestrationStep>