text:
Q: fast way to compare whether the number is in the list of ranges in python I need to compare a list of number to a list of range and see is the number is inside any of range.
Example:
list1 = [23,100,1,50,60,73]
list2 = [[0-10],[25-35],[100-110],[75-85]]

So i need to iterate list1 and compare this number with the list of range and see if this number fall in any of the range, if yes, i will increase the counter for that range.
both lists will be very big (100k to few millions or more) and the number is random.
So what is the best way to handle this problem?
Edit - the format of list could be list like [low,high,counter]. The example above is data sample and it is not really follow Python code syntax. both list will be huge.
Also the number is int.
Thanks.

A: An easy way is to have the second list in form of tuples (or two-element lists) and then use any:
list1 = [23,100,1,50,60,73]
list2 = [(0,10), (25,35), (100,110), (75,85)]

[any(y[0] <= x <= y[1] for y in list2) for x in list1]

timeit gives:
100000 loops, best of 3: 4.17 us per loop

Now, I assume your ranges are inclusive, that is such numbers as 85 and 25 are inside. If numbers in list1 are integers, and list2 is static (and also contains only ints, plus the ranges are non-overlapping), flatten it out, sort it and shift borders by 0.5 to get rid of border-cases, then you can use very efficient bisect O(log(N)) algorithm:
list2 = [(0,10),(25,35),(100,110),(75,85)]
list2 = [x for tup in list2 for x in tup]
list2.sort()
list2 = [l - 0.5 + i%2 for i,l in enumerate(list2)]
timeit [bisect_left(list2, x)%2 == 1 for x in list1]
100000 loops, best of 3: 1.64 us per loop

This is a less readable design because you have a bunch of numbers with no obvious indication where is left border where is right, but it is considerably quicker and more scalable. Here if the number from list1 gets into a place with even index, it is in between the ranges, otherwise, it is inside.

It is still slower than simply storing all the numbers in set and using in (which will only work if your numbers in list1 are all ints):
list3 = set(range(0,11) + range(25,36) + range(100,111) + range(75,86))
[x in list3 for x in list1]

which gives:
1000000 loops, best of 3: 376 ns per loop

This solution could be not viable for you because if your second list is indeed huge, it will likely not even fit in memory.


text:
Q: undefined method `length' for # What is wrong here? I'm getting this error:

undefined method `length' for #<Subproject:0x007faca1e4a318>

class UserMailer < ApplicationMailer
 default from: 'notifications@example.com'

  def changeDate_email(user, nameOfSubproject)
    @user = user
    @url  = 'http://example.com/login'
    mail(to: @user.email, subject: "Your Projects", body: nameOfSubproject)
  end
end

Thanks

A: As body you have to pass an string... You are passing a SubProject object and that is why rails is complaining.
I have to say that the way that you are using the mailer is not the best one.
I recommend you to read the action mailer rails guide to learn the way ActionMailer is meant to be used.
You can find more guides at http://guides.rubyonrails.org/

A: Class of nameOfSubProject, i am unsure of. Did you check that your nameOfSubProject parameter refers to sub_project.name or sub_project.get_email_html that returns a String?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there any function that avoids needing to print specific coefficient I'm trying to print a quadratic equation.
But if one of the coefficients is zero, then avoid print it and if one of them is 1, also print it without the number one.
I started to do it with if else but there are too much combinations.
double a, b, c;
printf("The quadratic equation is\n");

if (a == 0 && b != 0 && c != 0)
    printf("%.2lfX + %.2lf = 0\n", b, c);
else if (b == 0 && a != 0 && c != 0)
    printf("%.2lfX^2 + %.2lf = 0\n", a, c);
else if (c == 0 && a != 0 && b != 0)
    printf("%.2lfX^2 + %.2lfX = 0\n", a, b);
else if (a == 0 && b == 0 && c !=0)
    printf("%.2lf = 0\n", c);
else if (b == 0 && c == 0 && a != 0)
    printf("%.2lfX^2 = 0\n", a);
else if (a == 0 && c == 0 && b != 0)
    printf("%.2lfX = 0\n", b);
else if (a == 0 && b == 0 && c == 0)
    printf("");
else if (a == 1 && b != 1 && c != 1) {
    printf("X^2 + %.2lfX + %.2lf = 0\n", b, c);
}
else if (b == 1 && a != 1 && c != 1) {
    printf("%.2lfX^2 + X + %.2lf = 0\n", a, c);
}
else if (c == 1 && a != 1 && b != 1) {
    printf("%.2lfX^2 + %.2lfX + 1 = 0\n", a, b);
}
else if (a == 1 && b == 1 && c != 1) {
    printf("X^2 + X + %.2lf = 0\n", c);
}
else if (b == 1 && c == 1 && a != 1) {
    printf("%.2lfX^2 + X + 1 = 0\n", a);
}
else if (a == 1 && c == 1 && b != 1) {
    printf("X^2 + %.2lfX + 1 = 0\n", b);
}
else if (a == 1 && b == 1 && c == 1) {
    printf("X^2 + X + 1 = 0\n");
}
else {
    printf("%.2lfX^2 + %.2lfX + %.2lf = 0\n", a, b, c);
}

There must be a better way for doing it.
Now, I have to handle with cases like one of them is 0 and one of them is 1.
Please help me.
I'm trying to do it shorter.

A: You print each term in multiple parts with multiple printf() calls each. Make this into a function and you can easily extend it for larger equations.
#include <stdio.h>
#include <math.h>
#include <stdbool.h>

bool printTerm(double coeff, int degree, bool isFirst) {
    // If this coefficient is 0, print nothing
    if (coeff == 0 && degree != 0) {
        return true;
    }

    // Handle minus sign
    if (coeff < 0) {
        printf(" - ");
    }
    // Print "+" only if some previous terms were printed
    else if (!isFirst) {
        printf(" + ");
    }

    // Print the coefficient
    if (coeff != 1 || degree == 0) {
        // Minus sign was already printed, so fabs() is needed here
        printf("%.2lf", fabs(coeff));
    }

    // Print "X" and the degree
    if (degree >= 1) {
        printf("X");
        if (degree > 1) {
            printf("^%d", degree);
        }
    }

    // Return false if something was printed
    return false;
}

int main() {
    double a = 4.0, b = 1.0, c = 0.0;

    // Once printTerm returns false (something was printed), isFirst is set false
    bool isFirst = true;
    isFirst &= printTerm(a, 2, isFirst);
    isFirst &= printTerm(b, 1, isFirst);
    isFirst &= printTerm(c, 0, isFirst);
    printf(" = 0\n");
}

A: You can print the terms separately after each other.  Be careful when comparing floating point numbers.  As mentioned in the comments, some floating point numbers are represented exactly for example 0.0 and 1.0 but others are not (so the comparison a == 1.3 will not work as one might expect).
#include <stdio.h>
#include <string.h>
#include <stdbool.h>

double a = 1.0, b = 1.0, c = 1.0;

bool print_term(char *t, double coeff, bool needsign) {

    if (coeff != 0.0) {
        if (needsign && coeff > 0.0) {
            printf("+");
        }
        if (coeff != 1.0 || strcmp("", t) == 0) // also print c if it is 1.0
            printf("%.2lf%s", coeff, t);
        else
            printf("%s", t);
    }
    return coeff != 0.0;
}

int main() {
    bool need_operator = false;

    printf("The quadratic equation is\n");
    need_operator |= print_term("X^2", a, need_operator);
    need_operator |= print_term("X", b, need_operator);
    need_operator |= print_term("", c, need_operator);
    printf("\n");
    return 0;
}

Code tested with onlinegdb.com


text:
Q: HTML justify content and span

.d1 {
    background-color: red;
    display: flex;
    justify-content: center;
}
.s1 {
    color: blue;
}

    list:

item1

item2

item3

I am trying to make a div where its contents are aligned in the center. I use the above code to display the text list: item1 item2 item3 one below the other, list: underlined and the item3 to have blue color but this gives so strange results:

item1 and item2 but item3 is... on top and next to list:... What's the matter and how can I fix this? Ty

A: You can use
 along with  and add u li {list-style-type: none;} to disable list item circle.
Check this  :

.d1 {
    background-color: red;
    display: flex;
    justify-content: center;
}
.s1 {
    color: blue;
}
u li {list-style-type: none;}

    list:

item1

item2

item3

A: You can fix this by not using flex but inline-block and a wrapper
 instead.

.d1 {
    background-color: red;
    text-align: center;
}
.d2 {
    display: inline-block;
    text-align: left;
}
.s1 {
    color: blue;
}

        list:

item1

item2

item3

A:

.d1 {
    background-color: red;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
}
.s1 {
    color: blue;
}

    list:

item1

item2

item3

Result okay?

A: You could make you usage of an unsorted list like this one here:
If you need a more specific solution let me know that!

.d1 {
    background-color: red;
    justify-content: center;
    display: block;
    text-align: center
}
.s1 {
    color: blue;
}

Items:

<lu>

item1

item2

item3

 </lu>

A: why you used  tag and "display:flex". If you use display:flex then its child nodes will take the whole height and list:, item3 have done that and created 3 column. besides other content are not considered as the child nodes.
You can see the link to clear the idea of flex


text:
Q: I am trying to convert ARM Template to Bicep using Powershell When I am trying to convert json to bicep by using PowerShell It throws an error and dropped a link below

Is there any alternate method to convert json to bicep
I tried and got an error as mentioned above. And trying for an alternate method.

A: *

*I have converted the Json to Bicep using VS Code.

*Follow the below steps

*Create a folder and save your Json template in that folder. After that open VS Code and GOTO files on the left corner -> Click on Select Folder -> Select the folder Which you have created in the VS Code

*After that press Ctrl+P it will open a command palette then search for  >Bicep: decompile to Bicep as below

*

*It will convert json to bicep and create a.bicep file in the same directory.


text:
Q: "java.lang.VerifyError: Cannot inherit from final class" when running GWTTestCase I just wrote my very first GWTTestCase but running it always gives me a VerifyError. Here's my embryo of a great testsuite to be :
public void test() {
    Invoice invoice = new Invoice();
    invoice.setInvoiceDate(DateTimeFormat.getFormat(DomainResource.DATE_PATTERN).format(new Date()));
    InvoiceEditorDriver driver = GWT.create(InvoiceEditorDriver.class);
    InvoiceNumberEditor editor = new InvoiceNumberEditor();
    driver.initialize(editor);
    driver.edit(invoice);

    assertFalse(driver.isDirty());
    }

For completeness, I use Google AppEngine and GWT together, and I think this may relate to the security sandbox of AppEngine.
The class that is being loaded is "com.gargoylesoftware.htmlunit.SocksSocketFactory".
The full stacktrace here :
Exception in thread "htmlUnit client thread" java.lang.VerifyError: Cannot inherit from final class
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    at com.gargoylesoftware.htmlunit.HttpWebConnection.createHttpClient(HttpWebConnection.java:542)
    at com.gargoylesoftware.htmlunit.HttpWebConnection.getHttpClient(HttpWebConnection.java:506)
    at com.gargoylesoftware.htmlunit.HttpWebConnection.getResponse(HttpWebConnection.java:150)
    at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseFromWebConnection(WebClient.java:1281)
    at com.gargoylesoftware.htmlunit.WebClient.loadWebResponse(WebClient.java:1198)
    at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:307)
    at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:376)
    at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:361)
    at com.google.gwt.junit.RunStyleHtmlUnit$HtmlUnitThread.run(RunStyleHtmlUnit.java:136)

I tried excluding GAE validation for given class but without success. I'm not sure if excluding validation is sufficient and if it's possilble to setup validation exclude rules for files in a jar.

A: Might be a classpath problem.
There was a similar problem on the mailing list, solved by removing a second instance of the PlainSocketFactory from the classpath.


text:
Q: Why does an async TypeScript function not return a Promise In an Angular/TypeScript based web app there I have a component with a method to register a user. It uses an authentication service to register a user
async registerNewUser() {

  try {
    let value = await this.authService.registerRegular(this.user.email, this.user.password);
    console.log(value); // #2: value is undefined (I expect that it also prints the same result as in #1)
  }
  catch (err) {
    this.registerError = err;
    console.log(err);
  }
}

The service method registerRegular looks as follows
async registerRegular(email, password): Promise<any> {
  var credentials = await this.firebaseAuth.auth.createUserWithEmailAndPassword(email, password);
  var promise = this.db.database.ref('users').child(credentials.user.uid).set({hello:"world"});
  console.log(promise); // #1: works. Promise is printed to console
  return promise;
}

Problem: I'm awaiting the result from registerRegular but it always returns undefined in #2. When I print the promise before returning it (#1) then I can see the printed promise object.
So it seems like that the promise of that async method is not returned. At least in the calling method it's never there.
What am I doing wrong here?

A: Using value = await f() is the synchronous version of f().then((v) => value = v). i.e. you don't get a Promise when you await, you get the value that the Promise resolves to.


text:
Q: cancelling a suspend function in kotlin if the same function is called again I want to cancel the function i created which simply increments a counter value. For example, if the specific function is triggered by click, I only want to display the log for the last uninterrupted click within 2 seconds. Basically, i want the function to cancel itself if called again if its ongoing (delay is ongoing). Is there such thing in kotlin?
val counter = mutableStateOf(0)
suspend fun addCounter(){
    counter.value++

    delay(2000)
    Log.e("click cat","click $counter")
}`

A: This kind of event processing is usually handled using reactive streams and is often named the debounce operator. It exists in both ReactiveX (Debounce) and in Kotlin flows (debounce()).
As you already use coroutines, I suggest going with Kotlin flows. Please see the example below:
private val flow = MutableStateFlow(0)

suspend fun main() = coroutineScope {
    launch {
        // consumer of events
        flow
            .debounce(2.seconds)
            .collect { println(it) }
    }

    // producer
    delay(100)
    addCounter() // 1
    delay(500)
    addCounter() // 2, ignore 1
    delay(500)
    addCounter() // 3, ignore 2
    delay(2500) // show 3
    addCounter() // 4
    delay(500)
    addCounter() // 5, ignore 4
    delay(3000) // show 5
}

fun addCounter() {
    flow.value++
}

It shows only 3 and 5, because all other events were "cancelled" by subsequent events that came too fast.

A: Suspend function is a function that could be started, paused, and resume. Suspend functions are only allowed to be called from a coroutine or another suspend function and you can not cancel it in this way.
Coroutine structured concurrency is the thing that you're looking for. You can use a Job to perform your task above. Now you can cancel the job anytime you need.


text:
Q: Docker making source code available to multiple containers in Production and mounting for development I've read mutliple resources about how to make source code available to docker containers in dev and in prod.
For me, it still is not really clear, when and how to use what. As I've read differing opinions on how to do this.
What my goal is:
In development I want to use bind mounts to directly see the source code changes reflected in the container. For production, I want the source code to be immutable.
I read that I can use docker volumes for that. (I read I should not COPY or ADD the source into the container to keep the image small) But to me it looks as if volumes and bind mounts are almost equal.
The source code directory has to be accessible by two different containers. One of them does write into a cache directory from time to time.
Questions:
Is this the correct way to go? (bind-mounts when developing and volumes when in PROD?)
How can I have one docker-compose which depending on the environment either makes a bind-mount or a volume?
How can i have a staged build which builds the code, puts it into a volume which then can be used by two containers?

A: It depends on the Programming Language you use.
For really interpreted languages the code is evaluated every time. In that case you could use Volume-mapping.
But there are not that many really interpreted languages around.
A language like Python is compiling into *.pyc files so volume mapping is not advisable.
If you want to try volume-mapping *.pyc files, go ahead, and have fun with a whole lot of weird effects :-)
My advice would be to build the container with the code. And if you want the fast watch-functions on development, try to run the application outside a container on development and only use containers for Stage and Production. (If that is even possible with your application)

A: You should keep the application code in the image (assuming it's an interpreted language).
In particular, Docker named volumes are especially hard to manage.  You will wind up with a deployment sequence that involves starting a temporary container to get access to the volume, then copying data into it, then restarting your containers, and you'll lose a lot of Docker's capabilities around for example rolling back containers if a deployment fails.  You're not even saving any space here, since the code still exists on the target system in the volume.
Conversely, it's very easy to run two containers off the same image, and you don't have to do anything special for that.
# docker-compose.yml
version: '3.8'
services:
  first:
    image: registry.example.com/application:${APPLICATION_TAG:-latest}
    ports:
      - '8080:8080'
  second:
    image: registry.example.com/application:${APPLICATION_TAG:-latest}
    environment:
      FIRST_URL: 'http://first:8080/'
    # no volumes: on either container

Especially for production use I've added the image tag as an environment variable reference, so you can run
APPLICATION_TAG=20220502 docker-compose up -d
curl http://localhost:8080
...
# nope, it's not working, roll back
APPLICATION_TAG=20220429 docker-compose up -d

If you want to replace the application code with something totally different, maybe what a developer has on their system, you can add a docker-compose.override.yml file and Compose will merge their settings.
# docker-compose.override.yml
version: '3.8'
services:
  first:
    build: .
    volumes:
      - .:/app
  second:
    build: .
    volumes:
      - .:/app
    # no ports:, environment:, etc. on either container

You may also find it easier to ignore Docker during development and use ordinary host tools.  There are a number of potential problems with the bind-mount approach: if the Dockerfile does any processing at all this won't be present in the bind-mounted content, and particularly in Node the bind mount also hides the application's library tree (there is a popular hack to store the node_modules directory in an anonymous volume).  The bind mount can reintroduce the "works on my system" problem and I've seen a couple of examples of that go by on SO.


text:
Q: Duplicate identifier 'test' function test(){
    return 1;
}

Why do such test cases report duplicate definitions when using tsc conversion, as follows
**
node_modules/@types/mocha/index.d.ts:2620:13 - error TS2300: Duplicate identifier 'test'.
2620 declare var test: Mocha.TestFunction;
~~~~
test2.ts:1:10
1 function test(){
~~~~
'test' was also declared here.
test2.ts:1:10 - error TS2300: Duplicate identifier 'test'.
1 function test(){
~~~~
node_modules/@types/mocha/index.d.ts:2620:13
2620 declare var test: Mocha.TestFunction;
~~~~
'test' was also declared here.
Found 2 errors.
**


text: Q: F-test with "inverse" restricted model Say I have a full model $y = \beta_0 +  \beta_1 x_1 + \beta_2 x_2 + \beta_3x_3 + \beta_4 x_4$. I have regression output giving an overall F-test, standard errors, coefficients, t-test for each coefficient. I would like to preform an F-test on $H_0: \beta_1 = \beta_2 = 0$ against $H_a: \beta_1 \neq 0$ or $\beta_2 \neq 0$. However, my restricted model is $y = \beta_0 +  \beta_1 x_1 + \beta_2 x_2$, instead of  $y = \beta_0 + \beta_3x_3 + \beta_4 x_4$, which would usually be used to test $H_0: \beta_3 = \beta_4 = 0$.  I have the same regression output for the restricted model. Am I still able to test my hypothesis even though my restricted model is the opposite of what is usually used?


text:
Q: Webcam stopped working but appears in lsusb, works fine in windows This has been bugging me for some time now...
Laptop: Thinkpad T420
Ubuntu 12.04 Precise
When I installed Precise, I could use my webcam without any issue (Cheese, Skype...)
However, all of a sudden (I suppose after an update) it stopped working, Cheese showing me "no device found", but stll shows up in lsusb
lsusb
Bus 001 Device 004: ID 04f2:b221 Chicony Electronics Co., Ltd integrated camera

However /dev/video0 does not exist...
I don't see how to debug this, I assume it must be easy since it used to work perfectly on this same machine and installation.
It is worth mentioning that the webcam is not damaged or disconnected as it is working flawlessly in my dual-boot windows partition. The only reason I boot on Windows now is to use Skype, since Ubuntu doesn't allow me thus luxury...Any help would be greatly appreciated. Please let me know if you need more details.
Thank you!


text:
Q: Add horizontal scroll indicator to DIV I want to show an horizontal scroll indicator for a scrollable DIV container.
After some testing I'm pretty sure that it's not possible wit pure CSS.
I found a snippet in an answer for a similar question.
Unfortunately I couldn't figure out how to change the script to my needs.
I'm using a simple DIV container with some elements in it.
Here's my code:

1

2

                [....]

        <button>Prev</button>
        <button>Next</button>

And the CSS:
.scroll-wrapper {
    width: 100%;
    overflow-x: scroll;
    overflow-y: hidden;
    position: relative;
    white-space: nowrap;
}

.scroll-indicator {height: 4px; width: 100%; background-color: #ddd; margin-bottom: 2rem;}

.scroll-indicator-bar {height: 4px; width: 20%; background-color: #000;}

Working example
Is there any way to animate the scrollbar indicator with CSS and/or jQuery?
EDIT: I found another good example here: https://codepen.io/mahish/pen/RajmQw
I tried to use the code in my example but the prev/next buttons doesn't work. And I also don't know how to use the scroll position to show and move a scroll indicator.
Here's the JS code from the example (change to my class names):
// duration of scroll animation
var scrollDuration = 300;
// paddles
var leftPaddle = document.getElementsByClassName('left-paddle');
var rightPaddle = document.getElementsByClassName('right-paddle');
// get items dimensions
var itemsLength = $('.item').length;
var itemSize = $('.item').outerWidth(true);
// get some relevant size for the paddle triggering point
var paddleMargin = 20;

// get wrapper width
var getMenuWrapperSize = function() {
    return $('.scroll-wrapper').outerWidth();
}
var menuWrapperSize = getMenuWrapperSize();
// the wrapper is responsive
$(window).on('resize', function() {
    menuWrapperSize = getMenuWrapperSize();
});
// size of the visible part of the menu is equal as the wrapper size
var menuVisibleSize = menuWrapperSize;

// get total width of all menu items
var getMenuSize = function() {
    return itemsLength * itemSize;
};
var menuSize = getMenuSize();
// get how much of menu is invisible
var menuInvisibleSize = menuSize - menuWrapperSize;

// get how much have we scrolled to the left
var getMenuPosition = function() {
    return $('.scroll-container').scrollLeft();
};

// finally, what happens when we are actually scrolling the menu
$('.scroll-container').on('scroll', function() {

    // get how much of menu is invisible
    menuInvisibleSize = menuSize - menuWrapperSize;
    // get how much have we scrolled so far
    var menuPosition = getMenuPosition();

    var menuEndOffset = menuInvisibleSize - paddleMargin;

    // show & hide the paddles
    // depending on scroll position
    if (menuPosition <= paddleMargin) {
        $(leftPaddle).addClass('hidden');
        $(rightPaddle).removeClass('hidden');
    } else if (menuPosition < menuEndOffset) {
        // show both paddles in the middle
        $(leftPaddle).removeClass('hidden');
        $(rightPaddle).removeClass('hidden');
    } else if (menuPosition >= menuEndOffset) {
        $(leftPaddle).removeClass('hidden');
        $(rightPaddle).addClass('hidden');
}

    // print important values
    $('#print-wrapper-size span').text(menuWrapperSize);
    $('#print-menu-size span').text(menuSize);
    $('#print-menu-invisible-size span').text(menuInvisibleSize);
    $('#print-menu-position span').text(menuPosition);

});

// scroll to left
$(rightPaddle).on('click', function() {
    $('.scroll-container').animate( { scrollLeft: menuInvisibleSize}, scrollDuration);
});

// scroll to right
$(leftPaddle).on('click', function() {
    $('.scroll-container').animate( { scrollLeft: '0' }, scrollDuration);
});

A: You can have your own custom horizontal scroll behavior with vanilla js, you just need to handle mousedown, mouseup and mousemove events, calculate the needed scroll value and move your elements using transform: translateX() style, and to keep track with these values,
I did some changes and added some js code, check the snippet bellow:

const scrollBar = document.getElementById('myBar');
const scrollBarWrapper = document.getElementById('barWrapper');
const scrollContent = document.getElementById('scroll-container');

scrollBar.style.width =  ((scrollContent.offsetWidth * scrollBarWrapper.offsetWidth) / scrollContent.scrollWidth) + 'px';

let isScrolling = false;
let cursorX = 0;
let translateXValue = 0;

scrollBar.addEventListener('mousedown', function(e) {
    e.preventDefault();
    isScrolling = true;
    cursorX = e.clientX;
});

document.addEventListener('mouseup', function(e) {
    if (isScrolling) {
        e.preventDefault();
        isScrolling = false;
        translateXValue += (e.clientX - cursorX);
    }
});

document.addEventListener('mousemove', function(e) {
    if (isScrolling && cursorX !== e.clientX) {
        e.preventDefault();
        const translateAmount = (translateXValue + (e.clientX - cursorX));
        const scrollLength = (barWrapper.offsetWidth - scrollBar.offsetWidth);
        const barScroll = Math.min(Math.max(0, translateAmount), scrollLength);
        const contentTranslateRatio = (barScroll * scrollContent.scrollWidth) / scrollContent.offsetWidth;

        scrollBar.style.transform = 'translateX(' + barScroll + 'px)';
        scrollContent.style.transform = 'translateX(' + -contentTranslateRatio + 'px)';
    }
});
.scroll-wrapper {
    width: 100%;
    overflow: hidden;
    position: relative;
    white-space: nowrap;
}

.scroll-indicator {height: 6px; width: 100%; background-color: #ddd; margin-bottom: 2rem;}

.scroll-indicator-bar {height: 6px; width: 20%; background-color: #000;}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>

1

2

3

4

5

6

7

8

9

        <button>Prev</button>
        <button>Next</button>

by this code you have a dynamic scrollbar width dynamic width based on the content, and you can manage your own scroll behavior,
then, you can add custom next() and previous() functions to add translate for both scrollbar and content, as implemented in mousemove handler

A: I found a solution by using SimpleBar: https://github.com/Grsmto/simplebar/tree/master/packages/simplebar


text:
Q: ASP.NET MVC Beta 1 - URI Routing Syntax I have scoured the web for a decent explanation of the routing syntax in ASP.NET MVC Beta 1 but I still can't get it to work.
Please could someone explain what I need to put in my Global.asax.cs file to have two supported URIs for my site:
www.mysite.com/map.aspx (i.e the site without any explicit parameters/actions for performing the default action), and,
www.mysite.com/map.aspx/search/searchParam1/searchParam2/searchParam3/ (for performing a search)
PS: In the meantime, I'll continue working on this and I'll post the answer myself if I find it.

A: routes.MapRoute("Default", "map.aspx", new { controller = "DefaultController", action = "DefaultAction" });

routes.MapRoute("Search", "map.aspx/search/{*params}", new { controller = "SearchController", action = "Search" } );

Example URL : http://www.mysite.com/map.aspx/search/dogs/cats/
Parameters passed to SearchController.Search() :  params="/dogs/cats"
You can then parse the params in order to process your search results.
However, in my opinion, putting map.aspx in the URL looks wrong if you are building an MVC application.
Your url should look like http://www.mysite.com/search/


text:
Q: how to assign values for a vector datatype OK guys, i have the x ,y and z coordinates for a set of points of an image and I want to transfer it to a vector<Point3f>. I do not know how to use vector.push_back() to pushback individual elements, so is there some other way as simple as the push_back for me to use ?

A: Yes, you can:
    vector<Point3f> points;
    points.push_back(Point3f(0.44,0.30,0.46));
                                x    y    z

A: Here's a way to fill a vector without using `pushback(), with C++11
void push_points(int N, float* x float* y, float* z, std::vector<cv::Point3f>& points)
{
    points.resize(N);
    for(cv::Point3f & point : points)
        point = cv::Point3f(x, y, z);
}

And with old C++
void push_points(int N, float* x float* y, float* z, std::vector<cv::Point3f>& points)
{
    points.resize(N);
    for(int i = 0; i < N; ++i)
        points[i] = cv::Point3f(x, y, z);
}


text:
Q: Connecting mean points of a line plot in ggplot2 I have a sample dataset with the columns: PATIENTID (IDs of patients), VISITNUMBER (their number of visits to the hospital), TIME (time in years since first visit), HEALTH (their health status). I am trying to plot HEALTH over time.
This is my code in R:
# data structure
PATIENTID <- c(126, 126, 126, 255, 255, 389, 389, 389, 389, 389, 470, 470, 470)
VISITNUMBER <- c(1, 2, 3, 1, 2, 1, 2, 3, 4, 5, 1, 2, 3)
TIME<- c(0, 4, 6, 0, 3, 0, 1, 2, 3, 4, 0, 1, 2)
HEALTH <- c(0.333, 0.452, 0.468, 0.571, 0.522, 0.444, 0.452, 0.431, 0.510, 0.532, 0.214, 0.333, 0.400)

mydata <- data.frame(PATIENTID, VISITNUMBER, TIME, HEALTH)

# converting patient ID and visit number to factor

mydata$PATIENTID   <- factor(mydata$PATIENTID)
mydata$VISITNUMBER <- factor(mydata$VISITNUMBER)

# creating a spagetti plot of health over time

sp_HEALTH <- ggplot(data = mydata, aes(TIME, HEALTH, group=PATIENTID))
sp_HEALTH +
  geom_line() +
  stat_smooth(aes(group=1), method = "lm", se = FALSE) +
  stat_summary(aes(group=1), geom = "point", fun.y = mean,
               shape = 17, size = 3, col = "red")

This is my plot that's generated as a result of this code:

My issue is that I am trying to figure out a way to connect the mean points (shown in red in the above link) using a blue line that goes from point to point but I get this straight regression type of line. I want it to be like how a regular line plot connects points using lines (please click link below). How do I insert a line that connects the mean points?

Thank you!

A: Perhaps easier to use dplyr::mutate to calculate the mean, then add separate geoms for patient and mean values?
library(dplyr)
library(ggplot2)

mydata %>%
  mutate(PATIENTID = factor(PATIENTID)) %>%
  group_by(TIME) %>%
  mutate(MEAN = mean(HEALTH)) %>%
  ungroup() %>%
  ggplot() +
  geom_line(aes(TIME, HEALTH, group = PATIENTID)) +
  geom_line(aes(TIME, MEAN), color = "blue") +
  geom_point(aes(TIME, MEAN), color = "red", size = 3, shape = 17)

Or you could just add a second stat_summary with geom = "line". Note in both cases how aes() is used in the geom, not the ggplot().
mydata %>%
  ggplot() +
  geom_line(aes(TIME, HEALTH, group=PATIENTID)) +
  stat_summary(aes(TIME, HEALTH), geom = "point", fun = mean, shape = 17, size = 3, col = "red") +
  stat_summary(aes(TIME, HEALTH), geom = "line",  fun = mean, col = "blue")


text:
Q: Use Semantic UI's Visibility for infinite scrolling within an overflowing div I want to make use of Infinite Scrolling using the Semantic UI Visibility Behavior but within an overflow-y: auto div rather than in relation to the whole page. Here is a simplified version of my code:
HTML

Alert should appear when this is visible

CSS
#myDiv {
  height: 200px;
  overflow-y: auto;
}

JQuery
$('.myElementWithinTheDiv')
    .visibility({
        once: false,
        observeChanges: true,
        onTopVisible: function() {
            console.log('top visible');
        }
});

JSFiddle of the above working without the CSS restricting the DIV height: https://jsfiddle.net/jtge3s2o/
JSFiddle of the above not working with the CSS restricting the DIV height: https://jsfiddle.net/wznxkef2/2/
Is there a way to make this work with the div set to a fixed height?

A: As per the Behavior's Settings the context can be set as follows:
$('.myElementWithinTheDiv')
    .visibility({
        once: false,
        context: document.getElementById('myDiv'),
        observeChanges: true,
        onTopVisible: function() {
            console.log('top visible');
        }
});


text:
Q: Firefox crashes ONLY if connected to internet - Fresh Lubuntu 17.10 (other versions too) If firefox is connected to the internet and a page starts to load it crashes.
Prefer Firefox (my fav browser) over others. Firefox is the default browser for Lubuntu.
Firefox crashes with Lubuntu 16.04. 17.04 or 17.10 installed or live CD. Other programs like lubuntu updates can use the internet just fine.
What I tried: Clean install. Safe mode, refresh, delete cache and cookies, different theme, different Ubuntu theme, command line firefox, new profile and sudo firefox. Turned off drivers, only one listed was micro codes - likely IBM. No change, still crashes.
Chromium crashes too. I have not reinstalled or downgraded Firefox.
The computer is an older ThinkPad A20p notebook - I set bios to factory defaults. Edimax usb wifi - works on many ubuntu systems out of the box easy including ubuntu 16.04.
Summery: If I disconnect from the internet Firefox runs and I can change preferences and such within Firefox. Seconds into loading a page after reconnecting it crashes. Disconnecting allows me to try different settings which is nice.
Details: Command line firefox  (from installed version of Firefox)
firefox
ExceptionHandler::GenerateDump cloned child 1170
ExceptionHandler::SendContinueSignalToChild sent continue signal to child
ExceptionHandler::WaitForContinueSignal waiting for continue signal...

firefox -safe-mode
    ExceptionHandler::GenerateDump cloned child 3893
    ExceptionHandler::SendContinueSignalToChild sent continue signal to child
    ExceptionHandler::WaitForContinueSignal waiting for continue signal...

The crash reporter gives a lot of technical info, anything in all that I should be looking for?
Does NOT work from liveDVD. In other words, it is the same, Firefox works. Connect to the net and immediate crash.
Running from the liveDVD:
Examples leafpad and gnumeric and Disks alias gnome-disks all work - no crashes.
Terminal: firefox
Broken pipe errors and FileDecriptorSet destroyed.
Firefox Crash report info: (from installed version of Firefox)
Add-ons: shield-recipe-client%40mozilla.org:65,activity-stream%40mozilla.org:0.0.0,e10srollout%40mozilla.org:3.00,followonsearch%40mozilla.com:0.9.3,screenshots%40mozilla.org:10.12.0,onboarding%40mozilla.org:0.1,aushelper%40mozilla.org:2.0,firefox%40getpocket.com:1.0.5,webcompat%40mozilla.org:1.1,formautofill%40mozilla.org:1.0,clicktoplay-rollout%40mozilla.org:1.4,%7B972ce4c6-7e08-4474-a285-3208198ce6fd%7D:56.0,langpack-en-ZA%40firefox.mozilla.org:56.0,langpack-en-GB%40firefox.mozilla.org:56.0,ubufox%40ubuntu.com:3.3
AddonsShouldHaveBlockedE10s: 0
BuildID: 20171003222115
CTPCohort: user-changed-from-test
ContentSandboxCapabilities: 119
ContentSandboxCapable: 1
ContentSandboxLevel: 2
CrashTime: 1510859794
DOMIPCEnabled: 1
E10SCohort: addons-set50allmpc-test
EMCheckCompatibility: true
Email: ########@#######.###
FramePoisonBase: 0000004041121792
FramePoisonSize: 4096
InstallTime: 1508703061
Notes: Ubuntu 17.10FP(D00-L1000-W00000000-T000) OpenGL: VMware, Inc. -- llvmpipe (LLVM 5.0, 128 bits) -- 3.0 Mesa 17.2.2 -- texture_from_pixmap
WR? WR-
ProductID: {ec8030f7-c20a-464f-9b0e-13a3a9e97384}
ProductName: Firefox
ReleaseChannel: release
SafeMode: 0
SecondsSinceLastCrash: 53886
StackTraces:
StartupCrash: 0
StartupTime: 1510859765
TelemetryEnvironment: {"build":{"applicationId":"{ec8030f7-c20a-464f-9b0e-13a3a9e97384}","applicationName":"Firefox","architecture":"x86","buildId":"20171003222115","version":"56.0","vendor":"Mozilla","platformVersion":"56.0","xpcomAbi":"x86-gcc3","hotfixVersion":null},"partner":{"distributionId":null,"distributionVersion":null,"partnerId":null,"distributor":null,"distributorChannel":null,"partnerNames":[]},"system":{"memoryMB":492,"virtualMaxMB":null,"cpu":{"count":1,"cores":1,"vendor":"GenuineIntel","family":6,"model":8,"stepping":3,"l2cacheKB":null,"l3cacheKB":256,"speedMHz":null,"extensions":["hasMMX","hasSSE"]},"os":{"name":"Linux","version":"4.13.0-16-generic","locale":"en-US"},"hdd":{"profile":{"model":null,"revision":null},"binary":{"model":null,"revision":null},"system":{"model":null,"revision":null}},"gfx":{"D2DEnabled":null,"DWriteEnabled":null,"ContentBackend":"Skia","adapters":[{"description":"VMware, Inc. -- llvmpipe (LLVM 5.0, 128 bits)","vendorID":"VMware, Inc.","deviceID":"llvmpipe (LLVM 5.0, 128 bits)","subsysID":null,"RAM":null,"driver":null,"driverVersion":"3.0 Mesa 17.2.2","driverDate":null,"GPUActive":true}],"monitors":[],"features":{"compositor":"none","gpuProcess":{"status":"unused"}}}},"settings":{"blocklistEnabled":true,"e10sEnabled":true,"e10sMultiProcesses":1,"e10sCohort":"addons-set50allmpc-test","telemetryEnabled":false,"locale":"en-US","update":{"channel":"release","enabled":true,"autoDownload":true},"userPrefs":{"browser.cache.disk.capacity":358400,"browser.newtabpage.enhanced":true},"sandbox":{"effectiveContentProcessLevel":2},"addonCompatibilityCheckEnabled":true,"isDefaultBrowser":null},"profile":{},"experiments":{"clicktoplay-rollout":{"branch":"user-changed-from-test"},"e10sCohort":{"branch":"addons-set50allmpc-test"}}}
Theme: classic/1.0
ThreadIdNameMapping: 1090:"Gecko_IOThread",1091:"Timer",1092:"Link Monitor",1093:"Socket Thread",1094:"JS Watchdog",1100:"Hang Monitor",1106:"Cache2 I/O",1107:"GMPThread",1108:"StreamTrans #1",1109:"SoftwareVsyncThread",1110:"Compositor",1111:"ImgDecoder #1",1112:"ImageIO",1117:"SysProxySetting",1119:"ProxyResolution",1120:"DataStorage",1121:"URL Classifier",1123:"DataStorage",1122:"DNS Resolver #1",1124:"DataStorage",1125:"HTML5 Parser",1126:"IPDL Background",1127:"Classifier Update",1128:"DOM Worker",1132:"ImageBridgeChild",1156:"SaveScripts",1157:"Cache I/O",1158:"mozStorage #1",1159:"mozStorage #2",1161:"mozStorage #4",1162:"mozStorage #5",1163:"mozStorage #6",1165:"DNS Resolver #2",1164:"DNS Resolver #3",1166:"DOM Worker",1168:"SSL Cert #1",1171:"ProcessHangMon",
Throttleable: 1
URL: about:startpage
UptimeTS: 30.910163
Vendor: Mozilla
Version: 56.0
useragent_locale: en-US

This report also contains technical information about the state of the application when it crashed.

If I connect a network cable nothing happens - the computer does not connect to the internet and I do not know how to connect it. The network icon offers no options to connect that I can tell.
Computer had no errors on Memtest86+.
Booting live to liveDVD (try Lubuntu) on a different computer: Firefox does NOT crash when connected to the internet.
I added error code from a single crash from both the command line and the Firefox crash report.
I found another USB WiFi adapter to try and had the same errors and crash.
If I go to the GUI Additional Drivers - no drivers are offered even though I am online.
I am not intentionally running a virtual machine. This was a vanilla default install. How do I check if that virtual machine is running?
Computer had no errors on Memtest86+.
Is there a simple command one uses to initiate connecting to the internet once the cable is plugged in or is it automatic?
What to try:
Any thoughts? Is it hardware like the wifi adapter or usb itself - two different adapters gives the same crash but USB in the bios settings an issue?
Software? Firefox runs just not when connected - it crashes the instant it uses the internet.
Firmware? A setting in the bios?
Sorry for any typos and thank your help.


text:
Q: Is there a list of which browser supports which TLS cipher suite? I'm trying to increase the security of my application by having a higher version of TLS. However, I do not want to exclude too many users.
Does anyone know if there is a list which lists all main browsers, and which versions supported which cipher suites for TLS?
e.g
Chrome version Y supports TLS_RSA ...., TLS_ECDHE...., ...
Chrome version Y+1 supports....
Safari version X ...
IE version Z ....
Microsoft Edge ...
Opera ....
Firefox ...

I've been googling my behind off and I cant seem to find it anywhere.
Anyone seen a website like this?
Thanks a million!

A: The PyTLS project is a very low-level SSL/TLS implementation in pure python and comes with a basic server implementation that handles this job well, right out of the box.

*

*clone https://github.com/WestpointLtd/pytls

*run python server.py -p 4433

*point your browser at https://localhost:4433/
The running python script will print out the cipher suites requested by the browser to the console. They are listed in order of preference, with the browser's most preferred cipher suite at the top of the list.
e.g.
Google Chrome 56, Windows 10, April 2017
Binding...
Connection from ('127.0.0.1', 64858)
Record Version: TLS1_0
Handshake Version: TLS1_2
Session ID Length: 0
Cipher Suites Length (bytes): 32
Cipher Suites:
0x8a8a GREASE_i
0xc02b TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
0xc02f TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
0xc02c TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
0xc030 TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
0xcca9 TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
0xcca8 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
0xcc14 TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_non_iana
0xcc13 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_non_iana
0xc013 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
0xc014 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
0x009c TLS_RSA_WITH_AES_128_GCM_SHA256
0x009d TLS_RSA_WITH_AES_256_GCM_SHA384
0x002f TLS_RSA_WITH_AES_128_CBC_SHA
0x0035 TLS_RSA_WITH_AES_256_CBC_SHA
0x000a TLS_RSA_WITH_3DES_EDE_CBC_SHA

Mozilla Firefox 52, Windows 10, April 2017
Binding...
Connection from ('127.0.0.1', 64814)
Record Version: TLS1_0
Handshake Version: TLS1_2
Session ID Length: 0
Cipher Suites Length (bytes): 26
Cipher Suites:
0xc02b TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
0xc02f TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
0xcca9 TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
0xcca8 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
0xc02c TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
0xc030 TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
0xc00a TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
0xc009 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
0xc013 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
0xc014 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
0x002f TLS_RSA_WITH_AES_128_CBC_SHA
0x0035 TLS_RSA_WITH_AES_256_CBC_SHA
0x000a TLS_RSA_WITH_3DES_EDE_CBC_SHA

curl 7.42.1 (x86_64-suse-linux-gnu) libcurl/7.42.1 OpenSSL/1.0.1k zlib/1.2.8 libidn/1.31 libssh2/1.5.0, April 2017
Binding...
Connection from ('127.0.0.1', 47096)
Record Version: TLS1_0
Handshake Version: TLS1_2
Session ID Length: 0
Cipher Suites Length (bytes): 118
Cipher Suites:
0xc030 TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
0xc02c TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
0xc028 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
0xc024 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384
0xc014 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
0xc00a TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
0x00a3 TLS_DHE_DSS_WITH_AES_256_GCM_SHA384
0x009f TLS_DHE_RSA_WITH_AES_256_GCM_SHA384
0x006b TLS_DHE_RSA_WITH_AES_256_CBC_SHA256
0x006a TLS_DHE_DSS_WITH_AES_256_CBC_SHA256
0x0039 TLS_DHE_RSA_WITH_AES_256_CBC_SHA
0x0038 TLS_DHE_DSS_WITH_AES_256_CBC_SHA
0x0088 TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA
0x0087 TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA
0xc032 TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384
0xc02e TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384
0xc02a TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384
0xc026 TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384
0xc00f TLS_ECDH_RSA_WITH_AES_256_CBC_SHA
0xc005 TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA
0x009d TLS_RSA_WITH_AES_256_GCM_SHA384
0x003d TLS_RSA_WITH_AES_256_CBC_SHA256
0x0035 TLS_RSA_WITH_AES_256_CBC_SHA
0x0084 TLS_RSA_WITH_CAMELLIA_256_CBC_SHA
0xc02f TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
0xc02b TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
0xc027 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
0xc023 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
0xc013 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
0xc009 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
0x00a2 TLS_DHE_DSS_WITH_AES_128_GCM_SHA256
0x009e TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
0x0067 TLS_DHE_RSA_WITH_AES_128_CBC_SHA256
0x0040 TLS_DHE_DSS_WITH_AES_128_CBC_SHA256
0x0033 TLS_DHE_RSA_WITH_AES_128_CBC_SHA
0x0032 TLS_DHE_DSS_WITH_AES_128_CBC_SHA
0x009a TLS_DHE_RSA_WITH_SEED_CBC_SHA
0x0099 TLS_DHE_DSS_WITH_SEED_CBC_SHA
0x0045 TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA
0x0044 TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA
0xc031 TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256
0xc02d TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256
0xc029 TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256
0xc025 TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256
0xc00e TLS_ECDH_RSA_WITH_AES_128_CBC_SHA
0xc004 TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA
0x009c TLS_RSA_WITH_AES_128_GCM_SHA256
0x003c TLS_RSA_WITH_AES_128_CBC_SHA256
0x002f TLS_RSA_WITH_AES_128_CBC_SHA
0x0096 TLS_RSA_WITH_SEED_CBC_SHA
0x0041 TLS_RSA_WITH_CAMELLIA_128_CBC_SHA
0xc012 TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
0xc008 TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA
0x0016 TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA
0x0013 TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA
0xc00d TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA
0xc003 TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA
0x000a TLS_RSA_WITH_3DES_EDE_CBC_SHA
0x00ff TLS_EMPTY_RENEGOTIATION_INFO_SCSV

Repeat connections from the same browser will often show different sets of cipher suites, as the browser may randomly throw in different GREASE ciphers at various locations in the requested cipher list.
Note that this project only handles the transport of TLS Records and Messages and does not deal with any crypto. It is primarily aimed at security researchers that want to investigate or replicate the behaviour of different SSL/TLS implementations at the protocol level, and requires some knowledge of the required protocol behaviour to extend its use effectively as a library.
Disclaimer: I have worked closely with the author and contributed to some aspects of this project.

A: I don't know if there is somewhere you can find this information.
I see 2 ways to ensure compatibility with most browsers:

*

*Use Qualys SSLLabs to check handshakes after each change you make to your configuration,

*Keep using TLSv1.0 is you need support for Android v4.3 and earlier and support at least cipher suites defined in corresponding TLS RFC.

The mandatory cipher suites to be compliant to the RFCs are:

*

*TLS_RSA_WITH_3DES_EDE_CBC_SHA for TLSv1.1 (let's say for TLSv1.0 too)

*TLS_RSA_WITH_AES_128_CBC_SHA for TLSv1.2

If you use these settings, you will support all browsers, except IE6 on Windows XP.
Then once you support these protocols and cipher suites, you can add and prefer stronger ones:

*

*TLS_(EC)DHE_RSA_WITH_AES_256_GCM_SHA384 (not widely supported yet)

*TLS_(EC)DHE_RSA_WITH_AES_128_GCM_SHA256

*TLS_(EC)DHE_RSA_WITH_AES_256_CBC_SHA

*TLS_(EC)DHE_RSA_WITH_AES_128_CBC_SHA

With these settings, you should support almost all browsers and have a good security level with the modern ones.
If you want to know for a specific browser version, install it and go to this website (Still Qualys SSLLabs, but for client).


text:
Q: What's the number of arrangements of all 7 letters of the word "MINIMUM" in which the letters M are separated? I came across a question in a exerise booklet for Mathematical Olympiad for year 6 primary school students in Australia. The questions is as follows:
Find the number of arrangements of all 7 letters of the word "MINIMUM" in which the letters M are separated.
I calculated the number of arrangements as 360, but the provided keys says it's 720 instead. I'm not sure whether the key is right because the totoal number of arrangements when there are no restrictions is 420. I don't know why the key is 720. Thank you for your help.

A: The correct answer should be 96 (of course, without duplicate arrangements). There are many ways to solve this problem.
Method 1. Start with arrangements of _ I _ N _ I _ U _ and place 3 Ms in 3 of 5 places. Then subtract arrangements where 2 I's are together
$$= \frac{4!}{2!} . \binom{5}{3} - 3!.\binom{4}{3}$$
Method 2. Start with arrangements of _ N _ U _ and place 2 I's in 2 of 3 places. This results in 4 letters and 5 adjacent places. Then place 3 M's in 3 of 5 places. Then add arrangements where I's are together. Place one M between two I's and 2 M's in 2 of  resulting 4 places.
$$= 2!.\binom{3}{2}.\binom{5}{3} + 2!.\binom{3}{1}.\binom{4}{2}$$
Method 3. Start with arrangements of _ N _ U _ and place 3 M's in 3 places. This results in 5 letters and 6 adjacent places. Then place 2 I's in 2 of 6 places. Then add arrangements where 2 M's are together. Place the other M in 1 of 2 remaining places. Then place one I between two M's and other I in resulting 5 places. The last step will be to add arrangement where all M's are together. Place 2 I's between 3 M's to separate them.
$$= 2!.\binom{3}{3}.\binom{6}{2} + 2!.\binom{3}{1}.\binom{2}{1}.\binom{5}{1} + 2!.\binom{3}{1}$$


text:
Q: Why the data did not appear when I put bracket () after THEN? There are condition in my code: if the age of employee 50 and above, he will receive 'ESP1' medical benefit. If the age of employee 35-50 years old, he will receive 'ESP' medical benefit.
For the employee who 50 and above, their screen shouldn't view 'ESP'.
This is my code:
Select sh_benefitclaimtype.description,
        'entitlement'= case when sh_medicalentitlement.amount = 9999 then 'N/A'
                            when  sh_medicalentitlement.benefitclaimid = 'BG' then 'RM300 per baby(Female)'
                            when  sh_medicalentitlement.benefitclaimid = 'CC' then 'RM200 per deceased'
                    else convert(nvarchar,sh_medicalentitlement.amount)
       end,
        convert(decimal(15,2),isnull(#appr.appramt,0.00))as 'appramt',
        convert(decimal(15,2),isnull(#pend.pendamt,0.00)) as 'pendamt',
        'balance' = case when sh_medicalentitlement.amount = 9999 then 'N/A'
                         when sh_medicalentitlement.benefitclaimid in ('BG','CC') then 'N/A'
                    else convert(nvarchar,sh_medicalentitlement.amount - isnull(#appr.appramt,0))
       end,
       'benefitclaimid' = sh_medicalentitlement.benefitclaimid
   From sh_medicalentitlement
   LEFT OUTER JOIN #appr
   ON sh_medicalentitlement.benefitclaimid = #appr.benfid
   LEFT OUTER JOIN #pend
   ON sh_medicalentitlement.benefitclaimid = #pend.benfid
   LEFT OUTER JOIN is_empstatus
   ON is_empstatus.jobgradeid = sh_medicalentitlement.jobgradeid
   LEFT OUTER JOIN sh_benefitclaimtype
   ON sh_medicalentitlement.regisno = sh_benefitclaimtype.regisno
   and sh_medicalentitlement.benefitclaimid = sh_benefitclaimtype.benefitclaimid
   Where sh_medicalentitlement.regisno = @RegNo
   And is_empstatus.empid = @EmpID
   And dateadd(year,sh_benefitclaimtype.minage,@BirthDate) <= @date
   AND sh_benefitclaimtype.benefitclaimid = CASE WHEN (datediff(year,@BirthDate,@date) >=50) then (select benefitclaimid from sh_benefitclaimtype WHERE benefitclaimid <>'ESP') else  sh_medicalentitlement.benefitclaimid end
   Order by sh_benefitclaimtype.description + space(180) + sh_medicalentitlement.benefitclaimid
   end

A: Are you getting a specific error message?  I see one potential problem:
SELECT benefitclaimid FROM sh_benefitclaimtype WHERE benefitclaimid <>'ESP')

Your THEN condition for > 50 years old must return a scalar result.  If the sub-query above returns more than one row, this will error out.

A: AND sh_benefitclaimtype.benefitclaimid = CASE WHEN (datediff(year,@BirthDate,@date) >=50) then (select benefitclaimid from sh_benefitclaimtype WHERE benefitclaimid <>'ESP')
If the query "select benefitclaimid from sh_benefitclaimtype WHERE benefitclaimid <>'ESP'" is returning more than one record then use "IN" instead of "=" as below
AND sh_benefitclaimtype.benefitclaimid IN CASE WHEN (datediff(year,@BirthDate,@date) >=50) then (select benefitclaimid from sh_benefitclaimtype WHERE benefitclaimid <>'ESP')

A: Use the below condition in select statement and check what is the output. My guess is, it is returning either null or unexpected value.
CASE WHEN (datediff(year,@BirthDate,@date) >=50) then (select benefitclaimid from sh_benefitclaimtype WHERE benefitclaimid <>'ESP') else  sh_medicalentitlement.benefitclaimid end

A:     Select sh_benefitclaimtype.description,
            'entitlement'= case when sh_medicalentitlement.amount = 9999 then N'N/A'
                                when  sh_medicalentitlement.benefitclaimid = 'BG' then N'RM300 per baby(Female)'
                                when  sh_medicalentitlement.benefitclaimid = 'CC' then 'RM200 per deceased'
                        else convert(nvarchar(20),sh_medicalentitlement.amount)
           end,
            convert(decimal(15,2),isnull(#appr.appramt,0.00))as 'appramt',
            convert(decimal(15,2),isnull(#pend.pendamt,0.00)) as 'pendamt',
            'balance' = case when sh_medicalentitlement.amount = 9999 then N'N/A'
                             when sh_medicalentitlement.benefitclaimid in ('BG','CC') then N'N/A'
                        else convert(nvarchar,sh_medicalentitlement.amount - isnull(#appr.appramt,0))
           end,
           'benefitclaimid' = sh_medicalentitlement.benefitclaimid
       From sh_medicalentitlement
       LEFT OUTER JOIN #appr
       ON sh_medicalentitlement.benefitclaimid = #appr.benfid
       LEFT OUTER JOIN #pend
       ON sh_medicalentitlement.benefitclaimid = #pend.benfid
       LEFT OUTER JOIN is_empstatus
       ON is_empstatus.jobgradeid = sh_medicalentitlement.jobgradeid
       LEFT OUTER JOIN sh_benefitclaimtype
       ON sh_medicalentitlement.regisno = sh_benefitclaimtype.regisno
       and sh_medicalentitlement.benefitclaimid = sh_benefitclaimtype.benefitclaimid
       Where sh_medicalentitlement.regisno = @RegNo
       And is_empstatus.empid = @EmpID
       And dateadd(year,sh_benefitclaimtype.minage,@BirthDate) <= @date
       AND sh_benefitclaimtype.benefitclaimid = (CASE
                 WHEN (datediff(year,@BirthDate,@date) >=50) then (select TOP(1) benefitclaimid from sh_benefitclaimtype WHERE benefitclaimid ='ESP1')
                 WHEN datediff(year,@BirthDate,@date) between 35 and 50 then (select TOP(1) benefitclaimid from sh_benefitclaimtype WHERE benefitclaimid ='ESP')
          else  sh_medicalentitlement.benefitclaimid end )
       Order by sh_benefitclaimtype.description + space(180) + sh_medicalentitlement.benefitclaimid


text:
Q: I do not know the key I use:
\documentclass[hyperref={unicode,bookmarks=true}, clock,fragile]{beamer}
\usepackage{amsmath,amssymb,amsfonts, mathrsfs}
\usepackage[utf8]{vietnam}
\usepackage{tikz,tkz-tab,pgf}
\usepackage{pgfplots}
\usetikzlibrary{arrows,decorations,decorations.pathmorphing,
shapes}
\usetikzlibrary{arrows,decorations,decorations.pathmorphing,
shapes,decorations.text,trees,positioning,datavisualization}
\usepackage{pgfcore}
\usepgflibrary{datavisualization.formats.functions}
\usetheme{Darmstadt}
\usetheme{CambridgeUS}
\begin{document}
\begin{frame}
\begin{tikzpicture}[baseline]
\datavisualization [ scientific axes=clean,
y axis=grid,
visualize as smooth line/.list={sin,cos,tan},
style sheet=strong colors,
style sheet=vary dashing,
sin={label in legend={text=$\sin x$}},
cos={label in legend={text=$\cos x$}},
tan={label in legend={text=$\tan x$}},
data/format=function ]
data [set=sin] {
var x : interval [-0.5*pi:4];
func y = sin(\value x r);
}
data [set=cos] {
var x : interval [-0.5*pi:4];
func y = cos(\value x r);
}
data [set=tan] {
var x : interval [-0.3*pi:.3*pi];
func y = tan(\value x r);
};
\end{tikzpicture}
\end{frame}
\end{document}

But when run pdfLatex I get"! Package pgfkeys Error: I do not know the key '/tikz/data visualization/style
sheet'" How to fix it? Thanks.


text:
Q: Magento 2: Allow Arabic string in "letters-only" validation I'am working on the Magento store that have Arabic language store and English language store.
I have added the "letters-only" validation on firstName input field on registration page and when I check this validation on English version its working fine, but in Arabic version validation not working.
"Letters only" validation not accept Arabic string.
I'm trying below rules one by one but no luck:-
//return this.optional(element) || !/^[0-9_]+$/i.test(value);
return this.optional(element) || /^[\p{Arabic}a-zA-Z\- .ـ]+$/i.test(value);
return this.optional(element) || /^[a-zA-Z\-+,()/'\s\p{Arabic}]+$/i.test(value);
return this.optional(element) || /^[\s\p{Arabic}]+$/i.test(value);

Please suggest any solution to get rid this issue So in Arabic version user can add their information.
Thanks!!!

A: To validate the Arabic language characters you have to use the Unicode.
var unicode=e.charCode? e.charCode : e.keyCode

You can check the Example on GIT from here.

A: After spent more time on this, I get the solution to fix this issue.
Copy the validation.js file from below path:
lib\web\mage\validation.js

put in below directory:
**app\design\frontend\venorName\themename\web\mage\validation.js**

'letters-only': [
            function (value, element) {
                return this.optional(element) || /^[a-zA-Z \u0600-\u06ff]+$/i.test(value);
            },
            $.mage.__('Letters only please')
        ],

After above changes 'letters-only' validation working well in Arabic version.


text:
Q: My background image is not showing up in emulator but in browser it is coming I am using phonegap to develop android app
but in emulator my background image is not showing up but in browser it is coming
plz help me out what mistake i had done in css
in css3:-
background: url('images/pw.png') top left no-repeat !important;

in image folder my image is present

A: Check the location of image folder. As of your code, images folder should be inside CSS folder. And the syntax is wrong in your css.
background: url('images/pw.png') no-repeat top left !important;

|-- CSS/
     |-- images/
          |-- pw.png

If images folder is beside CSS, then use
background: url('../images/pw.png') no-repeat top left !important;

|-- CSS/
|-- images/
       |-- pw.png

A: Try this..
background: url('images/pw.png') no-repeat top left !important;


text:
Q: Is it possible to fetch AWS RDS MySQL transaction logs? I have AWS RDS MySQL instance, without general query logs.
Is it possible to get all transaction logs? I understand that MySQL binlog retention time is very short, but obviously, AWS RDS keeps all transactions for providing point-in-time recovery. So - is/how it possible to fetch this log?

A: The point-in-time recovery also uses the binary log. To use them for PITR, you must have non-expired binary logs back to the most recent full backup.
You can use SHOW BINARY LOGS in a query client to view the currently non-expired binary logs. You can use the command-line tool mysqlbinlog to dump logs from a remote instance (i.e. you could run this on an EC2 instance or another server that was set up to be a client for your RDS instance).
The term "transaction log" in MySQL usually refers to the InnoDB redo log. This is a different log. There's no way to fetch this from a remote client, and there's no tool to use it for PITR anyway.
Fetching the binary logs yourself might not be the solution intended by AWS for PITR of RDS instances. You should review the information they have about backup solutions: https://aws.amazon.com/blogs/storage/point-in-time-recovery-and-continuous-backup-for-amazon-rds-with-aws-backup/

A: Run this
SHOW VARIABLES LIKE '%expire_logs%';

Then see if AWS lets you change any of them.
That will keep the binlogs around for longer.
Also, see if AWS has a different setting to allow for a longer "PITR" (Point In Time Recovery).
Since you have configured to keep 30 days' worth of binlogs (and assuming you can access them), the commandline mysqlbinlog with let you read those files and grep for the data you desire.  Good luck.


text:
Q: Android Hardware Echo Cancellation Detection Some of the new Android phones are having Hardware Echo Cancellation capability.
Is there a way to detect if a device has hardware echo cancellation capability? We have software echo cancellation in one of our app and like to disable it at run-time if hardware echo cancellation is present.
Thanks

A: I think that you can use the "isAvailable()" method of the AccousticEchoCanceler class. This is the docs description.


text:
Q: MPI.exe вызвал срабатывание точки останова Вот пример программы:
Ошибка: MPI.exe вызвал срабатывание точки останова.
#include <stdio.h>
#include "mpi.h"
#include "conio.h"
int main(int argc, char* argv[]) {
    int Size, Rank, nNext;
    int dResult = 1;
    MPI_Status cStatus;
    MPI_Init(&argc, &argv);

    MPI_Comm_size(MPI_COMM_WORLD, &Size);
    MPI_Comm_rank(MPI_COMM_WORLD, &Rank);

    // Приём и обработка данных от предыдущего процесса
    if (0 < Rank) {
        MPI_Recv(&dResult, 1, MPI_DOUBLE, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD,&cStatus);
        dResult += 1.;
        printf("Rank: %d, result: %lf\n", Rank,dResult);
    }

    nNext = (Rank + 1) % Size;
    MPI_Send(&dResult, 1, MPI_DOUBLE,nNext, 99, MPI_COMM_WORLD);

    if (Rank == 0) {
        MPI_Recv(&dResult, 1, MPI_DOUBLE, Size-1, MPI_ANY_TAG, MPI_COMM_WORLD, &cStatus);
        dResult += 1;
        printf("Rank: %d, final result: %d\n", Rank, dResult);
    } // if (0 == nRank)

    MPI_Finalize();
    getch();
}

При запуске через MPI через консоль ничего не выводит тоже.


text:
Q: Oracle How to Chained Method Invocation PL/SQL Using PL/SQL, how does one chain two method calls in the same statement without assigning an output to some variable in the calling scope?
I first saw this technique in utPLSQL framework.
begin
  ut.expect(6/2).to_equal(3);
end;
/

This db<>fiddle shows my various failed attempts, but the primary statements are copied below.
create or replace type obj as object
  ( var number
  , member function fn(self in out obj, val number) return obj
  , member procedure proc(val number)
  )
;
/

create or replace type body obj
as
  member function fn(self in out obj, val number)
    return obj
    as
    begin
      self.var := val;
      return self;
    end
  ;

  member procedure proc(self in out obj, val number)
    as
    begin
      self.var := self.var * val;
    end
  ;
end;
/

declare
  o obj;
begin
  o := obj(4);
  o.fn(5).proc(2); --PLS-00363: expression 'FIDDLE_ZCGFGJIACZWGMWNQLREX.OBJ.FN(O, 5)' cannot be used as an assignment target
  dbms_output.put_line(o.var);
end;
/

I am expecting 10 to display (the result of 5 * 2) instead of the PLS-00363.
Using Oracle 19c Enterprise Edition (though the db<>fiddle is 21c).
Thank you in advance.


text:
Q: Problems positioning element based on browser width I have a fixed position div that I want to have position left: 0 when the browser window is smaller than 1200px, but no left positioning when larger than 1200px.  I'm using this code
var $window = $(window);
function checkWidth() {
    var windowsize = $window.width();
    document.write(windowsize);
    if (windowsize < 1200) {
        document.getElementById("DBCIbox").style.left = "0";
    } else {50
        document.getElementById("DBCIbox").style.left = "500px";
    }
}
checkWidth();
$(window).resize(checkWidth);

but it doesnt seem to be doing anything.  I'm setting the left=500px as simply a test to get the javascript working, then I'll worry about where I want to position it.
I've done some googleing and from what I can tell this should work, what am I missing?
If theres a way to clear the left positioning I'd like to know that as well.

A: var $window = $(window);

That line is cacheing that instance of window. You need to re-evaluate $(window) everytime you call this code to get updated width and height values
Updated code below
function checkWidth() {
    var $window = $(window);
    var windowsize = $window.width();
    document.write(windowsize);
    if (windowsize < 1200) {
        document.getElementById("DBCIbox").style.left = "0";
    } else {50
        document.getElementById("DBCIbox").style.left = "500px";
    }
}

checkWidth();

$(window).resize(checkWidth);

A: @Jnatalzia had it right, I needed to make a few tweaks, and the comments wouldn't let me post the code, but credit goes to @Jnatalzia for the answer.
   function checkWidth() {
        var $window = $(window);
        var windowsize = $window.width();
        var position;
        if (windowsize < 1390) {
            document.getElementById("DBCIbox").style.marginLeft = 0 + "px";
        } else if (windowsize >= 1390) {
            position = windowsize - 1060;
        position = position / 2;
        position = position - 175;
            document.getElementById("DBCIbox").style.marginLeft = position + "px";
        }
    }

    $("document").ready(function(){

       $(window).load(function(){
          checkWidth();
       });

       $(window).resize(function(){
          checkWidth();
       });

    });


text:
Q: Android-Studio won't start, NoClassDefFoundError com/intellij/openapi/diagnostic/Logger I'm trying to run Android-Studio on a Debian Jessie machine, but it won't.
Just unpacked it, marked bin/studio.sh as executable and executed it.
All I get is the following stacktrace:
    Exception in thread "main" java.lang.NoClassDefFoundError: com/intellij/openapi/diagnostic/Logger
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Class.java:2615)
    at java.lang.Class.getMethod0(Class.java:2856)
    at java.lang.Class.getMethod(Class.java:1668)
    at sun.launcher.LauncherHelper.getMainMethod(LauncherHelper.java:494)
    at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:486)
    Caused by: java.lang.ClassNotFoundException: com.intellij.openapi.diagnostic.Logger
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    ... 6 more

No log is written or anything else. Already searched and tried various things (e.g. adding lib/openapi.jar manually to the classpath, etc) for more than an hour, but it is still not working

A: Please ensure that there are no spaces in the path where Android Studio is installed.


text:
Q: What is breaking my Process.StartInfo.OutputDataReceived callbacks prematurely? The following problem occurs on .NET Framework v3.5. Don't know if it applies to v4*.
To capture stdout for some processes I've successfully used p.StartInfo.UseShellExecute = false; and p.StartInfo.RedirectStandardOutput = true; and an event handler hooked to p.StartInfo.OutputDataReceived+=...;. Then I call p.Start(); then p.BeginOutputReadLine(); and then p.WaitForExit();
All is well so far. I get all stdout on the event handler, line by line, as expected.
I had to introduce a timeout instead of WaitForExit() because some processes unpredictably trigger requests for input at stdin (e.g. are you sure? [y/n]) leading to a deadlock where I wait forever and so do they.
The first thing I tried is changing to while (!p.HasExited && DateTime.Now < timeoutmom) p.WaitForExit(200); where timeoutmoment is 2 minutes after proc.Start(). This is when I ran into problems. Very consistently, the code works for calls that produce up to a few hundred lines of stdout but it breaks for one call that produces about 7500 lines. What happens is the proc.WaitForExit(200); thread exits the while when my OutputDataReceived event handler was called for only ~ 7300 lines (this number is again very consistent it varies by only +/- 1 between tests) and the handler is not called anymore for the rest of the stdout lines so I lose them.
Strangely, the problem doesn't appear if I avoid WaitForExit(200) and instead use while (!p.HasExited && DateTime.Now < timeoutmom) System.Threading.Thread.Sleep(1000); (not shown in the code below). When I posted the question I was pretty sure the problem was avoided using Sleep(1000) but I was wrong. It worked a few dozen times like that and then it didn't, it started behaving just like when I checked WaitForExit(200).
I now speculate that the reasons for this problem are (1) I take too long to process each OutputDataReceived callback. I noticed the problem was aggravated when I added a conditional breakpoint in the event handler which lengthened the method execution by a lot. I can now reproduce the problem by simply adding 3x Debug.WriteLines without the conditional breakpoint; PLUS (2) my context is somehow corrupted by me accessing HasExited / WaitForExit(200) before the system had a chance to perform all the callbacks on my event handler. I now do a blind System.Threading.Thread.Sleep(30000) just after p.Start() and before accessing any p.* method and I get all the callbacks. When I used WaitForExit() it seemed I can take however much time I want to process every callback and I would still get them all.
Can someone make more sense of this?
Code:
    private int _execOsProc(
        ProcessStartInfo Psi
        , string SecInsensArgs
        , TextWriter ExtraStdOutAndErrTgt
        , bool OutputToExtraStdOutOnly
        )
    {
        var pr = new Process();
        pr.StartInfo = Psi;
        pr.StartInfo.UseShellExecute = false;
        pr.StartInfo.RedirectStandardOutput = pr.StartInfo.RedirectStandardError = true;
        pr.StartInfo.CreateNoWindow = true;
        var ol = new DataReceivedEventHandler(this._stdOutDataReceived);
        var el = new DataReceivedEventHandler(this._stdErrDataReceived);
        pr.OutputDataReceived += ol;
        pr.ErrorDataReceived += el;
        try
        {
            __logger.Debug("Executing: \"" + pr.StartInfo.FileName + "\" " + SecInsensArgs);
            if (ExtraStdOutAndErrTgt == null)
            {
                this.__outputToExtraStdOutOnly = false;
            }
            else
            {
                this.__extraStdOutAndErrTgt = ExtraStdOutAndErrTgt;
                this.__outputToExtraStdOutOnly = OutputToExtraStdOutOnly;
            }
            pr.Start();
            pr.BeginOutputReadLine();
            pr.BeginErrorReadLine();
            var startmom = DateTime.Now;
            var timeoutmom = startmom.AddMinutes(2);
            while (!pr.HasExited && DateTime.Now < timeoutmom) pr.WaitForExit(200);
            pr.CancelOutputRead();
            pr.CancelErrorRead();
            if (pr.HasExited)
            {
                __logger.Debug("Execution finished with exit status code: " + pr.ExitCode);
                return pr.ExitCode;
            }
            else
            {
                __logger.Debug("Timeout while waiting for execution to finish");
                pr.Kill();
                return -100;
            }
        }
        finally
        {
            pr.OutputDataReceived -= ol;
            pr.ErrorDataReceived -= el;
            if (this.__extraStdOutAndErrTgt != null)
            {
                this.__extraStdOutAndErrTgt = null;
                this.__outputToExtraStdOutOnly = false;
            }
        }
    }

    private void _stdOutDataReceived(
        object sender
        , DataReceivedEventArgs e
        )
    {
        string rdata = string.IsNullOrEmpty(e.Data) ? "" : e.Data.Trim();
        if (!this.__outputToExtraStdOutOnly) __logger.Debug("SO: " + rdata);
        if (this.__extraStdOutAndErrTgt != null)
        {
            lock (this.__extraStdOutAndErrTgt)
            {
                try
                {
                    this.__extraStdOutAndErrTgt.WriteLine(rdata);
                    this.__extraStdOutAndErrTgt.Flush();
                }
                catch (Exception exc)
                {
                    __logger.Warn(
                                "WARNING: Error detected but ignored during extra stream write"
                                    + " on SODR. Details: " + exc.Message
                                , exc
                                );
                }
            }
        }
    }

    private void _stdErrDataReceived(
        object sender
        , DataReceivedEventArgs e
        )
    {
        string rdata = string.IsNullOrEmpty(e.Data) ? "" : e.Data.Trim();
        if (!__outputToExtraStdOutOnly) __logger.Debug("SE: " + rdata);
        if (this.__extraStdOutAndErrTgt != null)
        {
            lock (this.__extraStdOutAndErrTgt)
            {
                try
                {
                    this.__extraStdOutAndErrTgt.WriteLine(rdata);
                    this.__extraStdOutAndErrTgt.Flush();
                }
                catch (Exception exc)
                {
                    __logger.Warn(
                                "WARNING: Error detected but ignored during extra stream write"
                                    + " on SEDR. Details: " + exc.Message
                                , exc
                                );
                }
            }
        }
    }

A: I'm not sure if it will solve the problem, but it is too long to post it in the comment.
MSDN says about Process.HasExited:

When standard output has been redirected to asynchronous event
  handlers, it is possible that output processing will not have
  completed when this property returns true. To ensure that asynchronous
  event handling has been completed, call the WaitForExit() overload
  that takes no parameter before checking HasExited.

and about WaitForExit():

This overload ensures that all processing has been completed,
  including the handling of asynchronous events for redirected standard
  output. You should use this overload after a call to the
  WaitForExit(Int32) overload when standard output has been redirected
  to asynchronous event handlers.

It indicates, that call to WaitForExit() with no parameters should solve the problem. Something like:
var startmom = DateTime.Now;
var timeoutmom = startmom.AddMinutes(2);
while (!pr.HasExited && DateTime.Now < timeoutmom)
    pr.WaitForExit(200);

if (pr.HasExited)
{
    WaitForExit();//Ensure that redirected output buffers are flushed

    pr.CancelOutputRead();
    pr.CancelErrorRead();

    __logger.Debug("Execution finished with exit status code: " + pr.ExitCode);
    return pr.ExitCode;
}
else
{
    pr.CancelOutputRead();
    pr.CancelErrorRead();

    __logger.Debug("Timeout while waiting for execution to finish");

    pr.Kill();
    return -100;
}


text:
Q: How to make white space hoverable? When the mouse is hovered over the white space in-between the X hover is not working.
How is that fixed so that hovering over the white space causes the svg to change to green?
https://jsfiddle.net/Lu1bm5pf/

.exit {
  margin: auto;
  right: 0;
  left: 0;
  width: 47.63px;
  height: 47.63px;
  cursor: pointer;
  border: none;
  background: none;
  padding: 0;
  border-radius: 50%;
}

.exitHover:hover  {
  fill: green;
}
<button class="exit" type="button" aria-label="Close">
    <svg class="exitsvg" width="100%" height="100%" viewBox="-144 -144 288 288">
        <g id="exit">
            <title>exit</title>
            <path class="exitHover" d="m-143 0a143 143 0 1 1 286 0 143 143 0 0 1 -286 0m128-112a113 113 0 0 0 -97 97h97zm-97 127a113 113 0 0 0 97 97v-97zm127 97a113 113 0 0 0 97 -97h-97zm97-127a113 113 0 0 0 -97 -97v97z" transform="rotate(45)" fill="red" />
        </g>
    </svg>
</button>

A: Before:
.exitHover:hover {
      fill: green;
}

After:
button:hover .exitHover {
  fill: green;
}


text:
Q: Por que o pattern Open Session In View é considerado um anti-pattern? Gostaria de saber por que muitos desenvolvedores e arquitetos consideram o padrão Open Session In View um anti-pattern?

A: O que é Open Session In View?
É um padrão usado com frameworks de Mapeamento Objeto-Relacional como o Hibernate e outras implementações de JPA.
Um objeto gerenciado por um framework JPA é conhecido como Entidade. Uma entidade pode ter relacionamentos com outras entidades e esses relacionamentos são resolvidos automaticamente pelo framework.
O problema é que os dados de entidades relacionadas por padrão são recuperados apenas quando efetivamente o código executa o método que recupera o valor. Se a chamada for feita após a conexão com o banco ter sido encerrada ocorre o famoso erro LazyInitializationException ou equivalente.
No padrão Open Session In View, a "sessão" (conexão´) fica aberta até o final da requisição, possibilitando que os dados de relacionamentos sejam recuperados a qualquer momento, incluindo durante a renderização da View, pois é um momento em que muitos dados são acessados.
Quando este padrão é usado?
Por exemplo, se existem duas views que usam o mesmo serviço para recuperar uma entidade, mas somente uma delas acessa uma outra entidade relacionada, as soluções poderiam ser:

*

*Carregar sempre os dados desse relacionamento, porém é um desperdício pois se sabe que em algumas situações os dados serão desnecessários.

*Criar outro serviço que já retorne os dados do relacionamento, porém isso pode levar a código duplicado.

*Permitir que os dados sejam recuperados fora do serviço. Este é o padrão! Isso significa que quando uma View acessar, por exemplo, cliente.getEndereco() o framework irá buscar o endereço do cliente no banco de dados.

Por que ele é um anti-pattern?
Ele "quebra" o encapsulamento das camadas da arquitetura.
Será necessário código implementado na camada de controle ou da View para gerenciar conexão e transação com o banco de dados.
Além de ferir o princípio do "menor conhecimento possível", temos um forte acoplamento entre o código da View e os serviços disponíveis no core do sistema.
Isso pode dificultar a realização de testes unitários e a reutilização dos serviços em outros locais.
O desempenho e a escalabilidade pode ser afetados
O padrão exige que a transação e, consequentemente, a conexão com o banco de dados fique aberta até o final da requisição. Mas segurar um recurso tão essencial pode causa impactos enormes no desempenho do sistema, principalmente se houver vários acessos simultâneos.
Fazendo um chute bem grosseiro, poderíamos dizer que se as transações demorarem o dobro para serem finalizadas por causa do tempo de geração da view, o sistema poderá atender a metade dos usuários comparando com uma versão que encerre a transação na camada de serviços.
Só que geralmente isso é bem pior. Se a transação continua aberta durante a view, ela pode estar bloqueando recursos importantes de vários outros usuários. As transações devem ser fechadas o mais rapidamente possível.
Trabalhei em um sistema que tinha um processamento "pesado" de mais ou menos 1 minuto. Em teoria ele funcionaria em paralelo, mas notamos que todas as requisições de diferentes usuários estavam sendo enfileiradas. O motivo? Um lock em uma tabela causada pelo incremento do ID no início do serviço. A resolução foi simples: realizar o processamento pesado fora da transação.
Falta de transparência
Quando a sessão fica "solta" durante a requisição, é mais fácil que problemas passem despercebidos. O desenvolvedor se acomoda em saber que suas entidades podem fazer de "tudo" depois que são retornadas pela camada de serviços.
A tendência é que o número de queries executadas durante a renderização das views aumente sem controle. Até o sistema começar a ser usado em produção por vários usuários, este problema irá passar totalmente despercebido.
A não ser que o desenvolvedor esteja sempre com o log ligado e analise todas as queries geradas. E isso deverá ser feito sempre que a view mudar, pois novas chamadas a novos atributos podem fazer com que novas queries sejam executadas a qualquer momento!
Um JSP com uma EL aparentemente inocente pode na verdade ocupar 99% do tempo de resposta.
Ele é usado por preguiça
Pode ser preguiça de refatorar os serviços, de argumentar com outros desenvolvedores para criar uma arquitetura melhor, de estudar um padrão melhor e assim por diante.
A questão é que a camada de serviços deveria retornar os dados prontos para a view de forma a não necessitar de processamento adicional. Só que para isso o desenvolvedor precisaria analisar os dados e ver o que vai ser necessário.
Então, da mesma forma que é mais fácil criar uma variável global para usar em todo lugar, deixa-se a sessão aberta para ser usada "quando for necessário".
Lidando com erros
Se a transação for finalizada após a renderização da View, isso tratá uma complexidade maior para o tratamento de possíveis erros.
Imagine que enquanto uma tela é gerada ocorre um erro numa das queries, talvez porque a coluna de uma tabela foi excluída. Como isso será tratado?
Numa aplicação web, por exemplo, isso vai exigir um filtro que faça tratamento desse tipo de erro.
Casos excepcionais são um grande problema
Imagine que um determinado serviço precisa ler dados de um banco de dados para outro. Isso vai exigir duas conexões e, talvez, uma transação distribuída.
O problema é que sua arquitetura já está acoplada, então teria que ser feita alguma gambiarra para abrir outra conexão, com outra transação desvinculada da primeira, ou coisa do tipo.
Conclusões
Particularmente, não vejo vantagens e situações onde seria necessário o uso do padrão Open Session In View.
Por outro lado, em aplicações Desktop ele poderia ser usado sem maiores problemas porque não há a questão de concorrência e escalabilidade citadas, embora a separação das camadas continue a ser quebrada.
Do meu ponto de vista, o desenvolvedor deve se preocupar com quais dados serão usados após a chamada de cada serviço e forçar isso, por exemplo usando fetch joins.
E padrões como Transfer Object são nossos amigos nesses momentos em que precisamos trazer dados a mais do banco sem alterar nossas entidades ou abusar do uso de relacionamentos.


text:
Q: Upgrade to 18.04 from 16.04 still not available? It's my understanding that upgrades from Ubuntu 16 to Ubuntu 18 should be enabled after the 18.04.1 release. According to the release schedule, this release came out on July 26.
I am running Ubuntu 16.04.5. I've run
sudo apt update
sudo apt upgrade
sudo apt dist-upgrade

Then, I try to run
sudo do-release-upgrade

However, this fails. The output is:
Checking for a new Ubuntu release
No new release found.

Can anyone explain next steps? I've been browsing recent questions, and it seems that others have managed the upgrade. I'll be happy to post other relevant system info if needed.
This is not a duplicate of the suggested thread, because the upgrade is actually available now. Anyway, I have written my own answer to the question already.

A: I went to Software and Updates > Updates, then set it to notify me of a new Ubuntu version for any new version.
Then I restarted. After that, the commands above worked for me.


text:
Q: How can I determine the circuitry in this module? Previously I asked about the purpose of this module.  Now I'd like to figure out how module accomplishes that by diagramming the circuitry. What is the best way?  The backside of the PCB is obscured by a metal disc.
Is it sufficient to check for continuity between all the exposed terminals using a basic multimeter? What cautions do I need to take to avoid damaging the module?  For example, does the  capacitor need to be discharged before, and if so, how?
Or, is the white layer removable in a non-harmful way with a solvent? and if so, with what solvent? and would this reveal enough information to draw the schematic?

A: There aren't a lot of parts.  The brute force method is to de-solder all the parts, then use a continuity tester to make a map of the connections.
A simpler way that will probably work is to use a ohmmeter in low voltage mode.  This is intended to not turn on silicon semiconductor junction.  In other words, a diode looks open regardless of polarity.  Not all ohmmeters have such a mode, but it's out there.
This won't help with resistors, but if all the resistors are large enough compared to a copper trace, then you can still distinguish a direct connection.
If you can't find a ohmmeter with a low voltage mode, you can rig up something yourself.  You're not actually trying to measure resistance, but determine whether the resistance is below a threshold.
One way you can do this is to start with a fixed current source, like 1 mA.  Clamp that with a diode so that the voltage doesn't exceed 700 mV or so.  Then look for the voltage dropping to maybe 100 mV or lower.  At that voltage, no semiconductor junction will conduct.  The effective resistance needs to be 100 mΩ or lower to trigger your continuity tester.

A: Simply "track" the tracks on the PCB via your own eyes and use the multimeter continuity tester. And ZD1 is a Zener diode.
See the example how I did it A 1USD 11W led bulb circuit and parts analysis
But I suspect the circuit may look something like this

A: You could reverse engineer the circuit with a multimeter and also by holding the circuit board at various angles to see the traces under the white masking...
Or...
You can do it the easy way and just click on this link for the datasheet:
****EDIT: Sorry. I thought that link would take you right to the part. Try this revised link. It may work.
http://www.datasheetspdf.com/pdf/774462/ETC/AMC7136/1
If not, use the following homepage link and then search for AMC7136. Scroll down a little until you see your part number and then click the PDF symbol to the right of it. Don't click on the big blue words at the top that say "Download Datasheet". That will point you towards a part that they are advertising.
http://www.datasheetspdf.com/
The second schematic on the datasheet resembles what you have. I would start with that one. The datasheet also explains the operation of the device and circuit.
Here's a tip for new techs: If you're ever working on something, have no schematic for it and believe the problem involves an IC or the circuit around it, check the datasheet. The example schematics are provided as a starting point for engineers. Unless modifications need to be made, more often than not, the circuit in the datasheet will be very close, and sometimes exact, to the device you are working on. A lot of engineers will just copy the circuit and use it in their product. Why reinvent the wheel, right?
Good luck!


text:
Q: Increasing the efficiency of a Differential Pulley The efficiency of a Weston differential pulley block can be determined using the following equation.
$$E=\frac{FR \ (100)}{MR}$$
As this is the case, in order to increase the efficiency the biggest possible force ratio value is needed and the smallest possible movement ratio is needed.
\begin{align}
FR & = \frac{Ouput \ Force}{Input \ Force} \\
 & = \frac{2}{1-\frac{r_{output}}{r_{input}}}
\end{align}
$$MR = \frac{Input \ Movement}{Output \ Movement}$$
To work out the radius of a cog the equation is $r = chain \ pitch \ (\frac{1}{2sin(\frac{\pi}{teeth})})$ but as the chain pitch is constant in a Weston differentail pulley block, we can just use the number of teeth on each cog as the values for $r_{output}$ and $r_{input}$.
With this is mind the I decided to try it out in this simple set of factors.

Input Cog: 25 teeth
  Output Cog: 20 teeth
  Chain Pitch: 20mm
  Input Cog Pulled: 1m

\begin{align}
Revolutions & = \frac{1000}{20(25)} \\
& = 2
\end{align}
\begin{align}
Output \ Movement & = 2(20)(20) \\
& = 0.8m
\end{align}
$$MR = 1.25$$
\begin{align}
FR & = \frac{2}{1-\frac{20}{25}} \\
& = 10
\end{align}
So the efficiency would be $\frac{10(100)}{1.25}$ which is $800\%$.
Am I correct in assuming I went wrong somewhere as the efficiency is so high? And where did I go wrong?

A: Yes your force ratio and movement ratio are both wrong.
Firstly the equation for force ratio is actually the equation for movement ratio.  And the little r's are NOT the number of teeth on the cogs, they are the RADII of those cogs.  The equation is derived from effort movement / force movement which is 2R / (R-r) after the pi's are cancelled out, and can be rearranged into the form you give it in above, but I repeat it is the movement ratio not the force ratio.
Force ratio is Load Force divided by Effort Force.
So quite a lot to think about!


text:
Q: Django rest framework versioning I'm new to the DRF. I tried to write an example by description on links:
http://james.lin.net.nz/2014/02/18/django-rest-framework-api-versioning/
django-rest-framework: api versioning
and share it: https://github.com/van2048/DRF_versioning
, but I get the error "NoReverseMatch at / app_drf/v1 /".
Please tell me, that was not written correctly?

A: Try replacing your pattern with this in /app_drf/v1/urls.py:
router.register(r'^$', ver_views.AppDrfModelViewSet)
The $ is a regex operator that matches to the end of the string. https://docs.python.org/2/library/re.html


text:
Q: Editing Passthrough SQL Query with Replace in Microsoft Access VBA In Access I have a SQL passthrough query that returns an entire table filtered by first name.
Example
SELECT * FROM dbo.Original_Data
WHERE first_name = 'Mike';

I am trying to write some VBA that on click of a button takes the passthrough query and replaces 'Mike' with any name I put in (this will later be done by a combo box but that's another step).
I have this where TempPT is the name of the passthrough query.
Private Sub Command12_Click()

TempPT = Replace(TempPT, "Mike", "Sam")
DoCmd.OpenQuery "TempPT"

End Sub

This doesn't work.
Is there a way that whatever I type in where I have 'Sam' is what the passthrough query will filter by?
I am using passthrough because the DB is huge and clogs up Access.

A: You need to edit the SQL property of the query. Probably something like this:
With CurrentDb().QueryDefs("TempPT")
    .SQL = Replace(.SQL, "Mike", "Sam")
End With

DoCmd.OpenQuery "TempPT"


text:
Q: Split String and Store in Array using Java I have a string that would always output in the following format, but with different lengths.
String s1= "['Aaaa', 'Eeee', 'Ffff', 'Cccc', 'Dddd']";

How to split this string and store the values in a n array of strings, I tried String.Split(), but I failed to catch the inner values.
Do you think regular expressions could help???

A: Have you tried running it through Split with  the regex parameter as"[\\[\\]\\', ]"
Basically any of  [,],,,', - more information here

A: This is my code , Hope it will help
    String s1 = "['Aaaa', 'Eeee', 'Ffff', 'Cccc', 'Dddd']";
    String s2 = "['Aaaa', 'Eeee']";
    String[] xx = s1.substring(2, s1.length() - 2).split("', '");

A:    String s1= "['Aaaa', 'Eeee', 'Ffff', 'Cccc', 'Dddd']";

       String[]  array = s1.split(",");
       for(int i=0;i<array.length;i++)
       {
           System.out.println(array[i]);
       }


text:
Q: "Time elapsed" or "elapsed time" In a document I have a plot where one of the labels represents the total time taken for the process to complete. Should I label it as "Elapsed Time" or "Time Elapsed"? Which one is correct?

A: "Elapsed" is a participle a.k.a. verbal adjective.
As an attributive adjective, it can come either before or after the noun, as long as it is next to it.
And since you're only using it in a label (not in a sentence), both "elapsed time" and "time elapsed" are correct and possible.

A: It may be just a matter of style, but I'd prefer "Elapsed Time".  "Elapsed" is an adjective, which normally preceeds the noun.  For a plot label, either is fine.


text:
Q: Thunderbird Debian 7.4 - Can't get the command symbolic link working I'm installing thunderbird 24.4.0 on Debian 7.4. A very easy install with which I had never any issue .. but on Debian I can't launch the application
The installation is as simple as downloading the correct binaries and making a symbolink link to the main executable in /usr/bin
so I downloaded and extract the tarball
sudo tar -xjf thunderbird-24.4.0.tar.bz2 -C /opt

Application stuff is located in [b]/opt/thunderbird[/b]
jeby6372@mercure:/opt/thunderbird$ ls
application.ini     libmozalloc.so    mozilla-xremote-client
blocklist.xml       libmozsqlite3.so  omni.ja
chrome              libnspr4.so       platform.ini
chrome.manifest     libnss3.so        plugin-container
components          libnssckbi.so     precomplete
crashreporter       libnssdbm3.chk    removed-files
crashreporter.ini   libnssdbm3.so     run-mozilla.sh
defaults            libnssutil3.so    searchplugins
dependentlibs.list  libplc4.so        Throbber-small.gif
extensions          libplds4.so       ***thunderbird***
icons               libprldap60.so    thunderbird-bin
isp                 libsmime3.so      updater
libfreebl3.chk      libsoftokn3.chk   updater.ini
libfreebl3.so       libsoftokn3.so    update-settings.ini
libldap60.so        libssl3.so
libldif60.so        libxul.so

And as required in the documentation I create the symbolic link
sudo ln -s /opt/thunderbird/thunderbird /usr/bin/thunderbird

my PATH variable is:
jeby6372@mercure:/opt/thunderbird$ echo $PATH
/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/usr/sbin:/sbin

When I issue the startup command, it fails
jeby6372@mercure:~$ thunderbird
bash: /usr/bin/thunderbird: No such file or directory
jeby6372@mercure:~$

I don't understand what's wrong. The link seems correct too :
jeby6372@mercure:~$ file /usr/bin/thunderbird
/usr/bin/thunderbird: symbolic link to `/opt/thunderbird/thunderbird

Thanks for your help in advance

A: IceDove mail client
Icedove is an opensource clone of Thunderbird. It provides the same features and installs fine on debian 7.4 with
sudo apt-get install icedove

This workaround solved the problem.