text:
Q: Jquery display problem in IE I have a kind of "tab" solution built in jquery. When a user clicks a tab I get the id of that tab and shows the right content for that tab based on the id. It works perfect in Firefox, when the tab is clicked it hides all divs with class "Page" and then show the right Page.
In IE8 it also works in the same way BUT a strange thing happens, sometimes some content of another Page is shown over the content of the active Page. So if I click Tab1 it shows cotent of Page1 but the awesome-buttons from Page2 also show up. When dragging the mouse over the awesome-button that shouldn't be there it disappears, so it seems like a kind of "graphic/display" problem. It doesn't happen all the time, sometimes it works like it should.
Have anyone seen a problem like this and is there a solution?
This is the code in jquery, the html and css:
$(document).ready(function() {

$('.Pages').hide();

$('.Tab').click(function() {
    var isActive = $(this).hasClass('TabActive');
    var pages = $(this).closest('div').prev('div');
    var tabs = $(this).closest('div');
    $(".Page").hide();
    $(".Page").css({ 'z-index:': '0' });
    $(".Tab").removeClass('TabActive')

    //Toggle Open/Close
    if (isActive || pages.is(":hidden")) {
        pages.animate({ width: "toggle" }, 200);
    }

    //Show the content
    var id = this.id.substring(3, 4);
    $('#Page' + id).show();
    $("#Page" + id).css({ 'z-index:': '999'});

    //Mark the tab as active
    if (!isActive) {
        $(this).addClass('TabActive');
    }
});
});

HTML:

        Content 1
        Test

        Content 1
        Test

Tab1

Tab2

CSS:
div .Pages
{
    width: 300px;
    min-height: 350px;
    background: #fff;
    border: solid 1px #333;
    position: relative;
    float: left;
    overflow: hidden;
    padding: 20px;
}

div .Page
{
    width: 100%;
    z-index: 0;
}

div .Tabs
{
    float: left;
    margin: 10px 0px 0px 0px;
}

.Tabs ul
{
    list-style: none;
    padding: 0px;
    margin: 0px;
}

.Tabs li
{
    padding: 0px;
    margin: 0px 0px 10px 0px;
}

.Tab
{
    margin: 0px 0px 0px 0px;
}

.TabActive
{
    color: red;
}

//THESE BUTTONS ARE THE ONES THAT SHOWS UP WRONG:
//GOT THESE FROM: http://www.zurb.com/article/266/super-awesome-buttons-with-css3-and-rgba

.awesome, .awesome:visited {
background: #f9f9f9 url(/images/alert-overlay.png) repeat-x;
display: inline-block;
padding: 5px 10px 6px;
color: #fff;
text-decoration: none;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
-moz-box-shadow: 0 1px 3px rgba(0,0,0,0.1);
-webkit-box-shadow: 0 1px 3px rgba(0,0,0,0.1);
text-shadow: 0 -1px 1px rgba(100,100,100,0.1);
border-bottom: 1px solid rgba(0,0,0,0.1);
position: relative;
cursor: pointer;
}

.medium.awesome, .medium.awesome:visited        { font-size: 11px; font-weight: bold; line-height: 1;  }
.green.awesome, .green.awesome:visited      {     background: url(images/buttons/greenbuttonbg.png) repeat-x 0 0; }

A: It would help to know what your css looks like. try adding a z-index:10 to the currently displayed div.

A: I'd be tempted to do:
if(!$(this).hasClass('TabActive'))
{
  // Hide/show pages
  $('.Page').hide();
  $('#Page' + this.id.substring(3, 4)).show();

  // Show Pages
  pages.animate({ width: "toggle" }, 200);

  // Deal with active classes
  $(".TabActive").removeClass('TabActive');
  $(this).addClass('TabActive');
}
else
{
  if($(".Pages").is(":hidden"))
    pages.animate({ width: "toggle" }, 200);
}

That way you know all the pages are always being hidden.

A: Does your page have a valid doctype?  Sounds like there may possibly be some malformed HTML somewhere in your page?

A: This might be related to the IE z-index bug. I know that IE6 and 7 both have issues with displaying content wrong in regards to the z-index. A quick Google search might shed some light on this as there a some work arounds with jQuery

A: try display:none instead of display:hidden

A: I couldn't quite reproduce the problem you're having, but I did notice an issue in your JavaScript. When you set the z-index, you example code looks like this:
$(".Page").css({ 'z-index:': '0' });

You don't need the colon after 'z-index' - it should be like this:
$(".Page").css({ 'z-index': '0' });

I don't know if this will fix your problem or not.

A: Could be an IE8 bug, it's not the first time something in IE jumps to front when it shouldn't have.
Also please loot at this question: Z-index broken in IE8?


text:
Q: MongoDB update Item in Array I need to edit an item at a position(index) in an array without having to add an index to each item.
// The record in the collection
const data = {
    library: 'The book store',
    books: ['bookA', 'bookB', 'bookC']

}

I'm looking to only change the item at index 1 within the books array
I'm trying the following but it's not working...
return Record.updateOne(
    {
      video_id,
    },
    {
      $set: {
        "books[1]": 'Book H'
      },
    },
    (err, data) => {
      if (err) {
        console.log(err);
      }
      return data;
    }
  );

Any ideas?

A: as long as you need to always update the second element in the array, so you can use the dot notation
your query should be something like that
return Record.updateOne(
  { video_id }, // filter part
  {
    $set: { // update part
      "books.1": 'Book H'
    },
  },
  (err, data) => { // call back function
    if (err) {
      console.log(err);
    }
    return data;
  }
);

hope it helps

A: I am demonstrating in pure MongoDB query without unnecessary details so everyone can understand easily.
db.getCollection("libraries").update({/* your filter*/}, {
    $set: {
        "books.1": "Book H"
    }
})

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get the list of due assignments using Google Classroom API I am trying to get the list of assignments due/coursework for all the courses using the Google Classroom API. I am getting a list of courses using the below code :
results = service.courses().list(pageSize = 10).execute()
courses = results.get('courses',[])

Once I get the list of all the courses, I loop over each the course and try to supply the courseID in order to get the list of coursework using courses.courseWork.list method, but I'm getting an error.
I have written the following code :
for course in courses :
    print(course['name'])
    print "Assignments you have due in this course : "
    print course[u'id']
    course_work_results = service.courses().courseWork().list().execute()
    print course_work_results

Since I am not supplying the courseID anywhere (which I need to know how to do), I get the following error :
Traceback (most recent call last):
File "classroom.py", line 53, in <module>
  course_work_results = service.courses().courseWork().list().execute()
File "/usr/local/lib/python2.7/dist-packages/googleapiclient/discovery.py", line 727, in method
  raise TypeError('Missing required parameter "%s"' % name)
TypeError: Missing required parameter "courseId"

The error is caused due to the line
course_work_results = service.courses().courseWork().list().execute()

How to fix this ?


text:
Q: How can i insert element an element into BST? I've to build a binary search tree using two classes (1-BSTnode,2-BSTFCI), and i faced a problem with (insert) function.
when i did a test for this function , it gives me run time error
can anyone help me please?
This is the definition of the BSTnode:
template <class T>
class BSTnode
{
public:
    T data;
    BSTnode<T>* left;
    BSTnode<T>* right;
    BSTnode()
    {
        left = right = NULL;
    }
};

This is the definition of the BSTFCI:
template <class T>
class BSTFCI
{
public:
    BSTnode<T>* root;
};

and this is the insert function.
template <class T>
BSTnode<T>* BSTFCI<T>::Insert(BSTnode<T>*& node,T value)
    {
/// If the tree still empty.
    if(node == NULL)
    {
        node = create_new_node(value);
    }
    if(value < node->data)
    {
        node->left = Insert(node->left, value);
    }else if(value > node->data)
    {
        node->right = Insert(node->right,value);
    }

    return node;
}

main function
int main()
{
    BSTFCI<int> o;
    o.Insert(o.root,6);
    return 0;
}

A: I implemented and checked your code. The only problem I found is that you have not initialized the value of root as NULL in BSTFCI constructor. You need to write the constructor of BSTFCI and assign the initial value of root as NULL.
class BSTFCI
{
public:
    BSTnode<T>* root;
    BSTnode<T>* Insert(BSTnode<T>*& node,T value);
    BSTFCI()
    {
        root = NULL;
    }
};


text:
Q: jQuery card animation on hover When hovering on one of the cards, the rest of the cards should properly decrement the size one by one - hover on card 1 for example.
Currently my solution for this was to add and remove classes one by one, but I'd like to know if there's a better way to get it done using jQuery.

$(".card").mouseover(function() {
  $(".card").removeClass('active');
  $(this).addClass('active');
});

$(".card").mouseout(function() {
  $(".card").removeClass('active');
  $(".c").addClass('active');
});

$(".a").mouseover(function() {
  $(".b").addClass('size1');
  $(".c").addClass('size2');
  $(".d").addClass('size3');
  $(".e").addClass('size4');
});

$(".a").mouseout(function() {
  $(".b").removeClass('size1');
  $(".c").removeClass('size2');
  $(".d").removeClass('size3');
  $(".e").removeClass('size4');
});

$(".b").mouseover(function() {
  $(".c").addClass('size1');
  $(".d").addClass('size2');
  $(".e").addClass('size3');
});

$(".b").mouseout(function() {
  $(".c").removeClass('size1');
  $(".d").removeClass('size2');
  $(".e").removeClass('size3');
});
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 100px;
}

.container .card {
  background-color: red;
  color: #fff;
  width: 100px;
  height: 150px;
  text-align: center;
  display: inline-block;
  transition: 0.2s;
}

.container .card.active {
  transform: scale(1.4, 1.4);
  position: relative;
  z-index: 100;
}

.container .card.a {
  background-color: black;
}

.container .card.b {
  background-color: blue;
  width: 120px;
  height: 170px;
}

.container .card.c {
  background-color: red;
}

.container .card.d {
  background-color: orange;
  width: 120px;
  height: 170px;
}

.container .card.e {
  background-color: yellow;
}

.container .card.size1 {
  transform: scale(1.1, 1.1);
  z-index: 1;
}

.container .card.size2 {
  transform: scale(1.15, 1.15);
  z-index: -1;
}

.container .card.size3 {
  transform: scale(0.9);
  z-index: -2;
}

.container .card.size4 {
  transform: scale(0.8);
  z-index: -3;
}

Card 1

Card 2

Card 3

Card 4

Card 5

jsFiddle

A: You could use the switch statement combined with arrays that contain the different classes to be toggle for each case, something like so:

const arr1 = ['b', 'c', 'd', 'e'];
const arr2 = ['a', 'c', 'd', 'e'];
const arr3 = ['a', 'b', 'd', 'e'];
const arr4 = ['a', 'b', 'c', 'e'];
const arr5 = ['a', 'b', 'c', 'd'];
var l = arr1.length;

$(".card").mouseover(function() {
  $(".card").removeClass('active');

  switch($(this).attr('class')){
  case 'card a':
    for(var i=0;i<l;i++){$("." + arr1[i]).addClass('size' + i)}
    break;
  case 'card b':
    for(var i=0;i<l;i++){$("." + arr2[i]).addClass('size' + i)}
    break;
  case 'card c':
    for(var i=0;i<l;i++){$("." + arr3[i]).addClass('size' + i)}
    break;
  case 'card d':
    for(var i=0;i<l;i++){$("." + arr4[i]).addClass('size' + i)}
    break;
  case 'card e':
    for(var i=0;i<l;i++){$("." + arr5[i]).addClass('size' + i)}
    break;
  }
  $(this).addClass('active');
});

$(".card").mouseout(function() {
  $(".card").removeClass('active');

  switch($(this).attr('class')) {
  case 'card a':
    for(var i=0;i<l;i++){$("." + arr1[i]).removeClass('size' + i)}
    break;
  case 'card b':
    for(var i=0;i<l;i++){$("." + arr2[i]).removeClass('size' + i)}
    break;
  case 'card c':
    for(var i=0;i<l;i++){$("." + arr3[i]).removeClass('size' + i)}
    break;
  case 'card d':
    for(var i=0;i<l;i++){$("." + arr4[i]).removeClass('size' + i)}
    break;
  case 'card e':
    for(var i=0;i<l;i++){$("." + arr5[i]).removeClass('size' + i)}
    break;
  }
   $(".c").addClass('active');
});
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 100px;
}

.container .card {
  background-color: red;
  color: #fff;
  width: 100px;
  height: 150px;
  text-align: center;
  display: inline-block;
  transition: 0.2s;
}

.container .card.active {
  transform: scale(1.4, 1.4);
  position: relative;
  z-index: 100;
}

.container .card.a {
  background-color: black;
}

.container .card.b {
  background-color: blue;
  width: 120px;
  height: 170px;
}

.container .card.c {
  background-color: red;
}

.container .card.d {
  background-color: orange;
  width: 120px;
  height: 170px;
}

.container .card.e {
  background-color: yellow;
}

.container .card.size0 {
  transform: scale(1.1, 1.1);
  z-index: 1;
}

.container .card.size1 {
  transform: scale(1.15, 1.15);
  z-index: -1;
}

.container .card.size2 {
  transform: scale(0.9);
  z-index: -2;
}

.container .card.size3 {
  transform: scale(0.8);
  z-index: -3;
}

Card 0

Card 1

Card 2

Card 3

Card 4


text:
Q: Killing threads from completion service? Problem
I am using a completion service and spawning child threads to perform some ETL.
As I debug in my IDE and then stop all processes, I notice I still have a bunch of zombie threads killing my CPU. This is due to the fact that I'm not terminating the child threads properly.
Minimum Example

  Future<Boolean> future = completionService.submit(conversionProcessor);
  boolean isCompleted = false;
  while (!isCompleted && !closed.get()) {
    try {
      isCompleted = future.get(CONSUMER_HEARTBEAT_INTERVAL,
          TimeUnit.SECONDS); // Wait until heartbeat interval exceeds
      if (isCompleted) {
        // do some things here
        future.cancel(true);
        break;
      }
    } catch (TimeoutException e) {
      // Used to keep consumer alive in the cluster
      consumer.poll(Duration.ofSeconds(CONSUMER_HEARTBEAT_INTERVAL)); // does heart-beat
    } catch (CancellationException e) {
      future.cancel(true);
      break;
    } catch (InterruptedException e) {
      future.cancel(true);
      break;
    } catch (WakeupException we) {
      future.cancel(true);
      break;
    } catch (Exception e) {
      future.cancel(true);
      break;
    }

Thoughts
Essentially, I submit my Callable<Boolean> to my completion service.
    ExecutorCompletionService<Boolean> completionService = new ExecutorCompletionService<>(
        Executors.newSingleThreadExecutor());

If I stop the debugger, this thread is presumably still running. I just added this future.cancel(true) piece, which seems to have stopped continuously uploaded files from my child thread, but I still see these java processes running on my activity monitor.
I'm wondering how I should be thinking about this? I want the callable as it tells me when the underlying ETL has completed or not (true/false)
edit:
future.cancel actually seems to be helping quite a bit.. Is this what I want to be using?

A: Once you are done with your CompletionService you need to shutdown underlying executor so you need to do the following
ExecutorService es = Executors.newSingleThreadExecutor();
ExecutorCompletionService<Boolean> completionService = new ExecutorCompletionService<>(es);

And a the end call
es.shutdown();
es.awaitTermination(1, TimeUnit.SECONDS);


text:
Q: CakePHP 2.1 loggedIn user in views I am using cakephp 2.1. So I am looking for getting loggedIn user in views. How to get the logged user in views.

A: You can take a look here:
http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#accessing-the-logged-in-user
or here:
http://api20.cakephp.org/class/auth-component#method-AuthComponentuser

A: Try this in $this->Auth->loggedIn() in your view. If it doesn't work then you have to use
$this->Auth->user('id').
For example;
if($this->Auth->loggedIn()) {
  // then do something
}

or:
if($this->Auth->user('id')) {
  // then do something
}

A: If you want to show the current logged in user details to all views. it will be better to put the logic in the layout file rather than putting the code in all view files.
to get the current logged in user details you can use $this->Auth->user
Lets say if you want to display the current loged in user name you can use echo $this->Auth->user('user_name');

A: If you are using the Auth Component the user data is also stored in the Session's "Auth.User" key.
So in a view it can be accessed with the SessionHelper::read() method:
$user = $this->Session->read("Auth.User");

Auth.User contains the user record from the database.
Don't forget to include the Session Helper in the $helpers array in your controller.


text:
Q: Is this the right way to store passwords in database and activate user accounts? I'm building a website with HTML5, CSS, JavaScript, PHP and MySQL DB. I've created a login page and a 'create new user page' and would like to have an email send to active the user account. What I've built now is working but I would like to verify that I'm doing it safe enough.
When creating the user account I use this code:
$Allowed_Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789./';
$Chars_Len = 63;
$Blowfish_Pre = 'xxxxxxxxxxx';   <- not sure if that is something I can share with anyone
$Blowfish_End = 'xxxxxxxxxxx';   <- not sure if that is something I can share with anyone

$Salt_Length = 21;
$mysql_date = date( 'Y-m-d' );
$salt = "";
for($i=0; $i<$Salt_Length; $i++)
{
    $salt .= $Allowed_Chars[mt_rand(0,$Chars_Len)];
}
$bcrypt_salt = $Blowfish_Pre . $salt . $Blowfish_End;
$hashed_password = crypt($password, $bcrypt_salt);
$activationkey = crypt( $hashed_password . $uname);

(I use the hash_pass + uname to create a new hash for $activationKey, without salt.)
In the database I then store:
uname, hashed_password, salt, activationkey and I set a flag that shows the account is NOT activated.
Then I send an e-mail to the user with the activationkey included.
When they user clicks the link I search for the e-mail addres and activationkey. If found I clear the activationkey field in the database and set the flag to show the user is activated and then redirect the user to the activation page.
Would love to hear your thoughts on this.
Gabrie

A: No that's not what you should do, the parameters for crypt() require a certain format, otherwise you will not get a BCrypt value and the salt will not be secure. In PHP 5.5 there is a function called password_hash() which solves exactly your problem, for earlier versions there exists a compatibilty pack from the same author, using this function is "future proof".
Activation keys should better not be derrived from other parameters, just generate a random token and send this token to the user. In the database you store only a hash of this token. This system can be used to generate password reset links too. An example implementation of a such tokens you can find here.


text:
Q: Does anybody know a way to make a video game in turbo c where you have an A moving around on the screen? I am trying to make a game with ms-dos called find the key.
What i am struggling with is using graphics.h to move an ASCII character move over a red screen using keyboard input.
Here is a snippet of my source code:
if (cn == 1) {
initgraph(&gd, &gm,"C:\\TC\\BGI");
settextstyle(DEFAULT_FONT,HORIZ_DIR,3);
setbkcolor(RED);
setcolor(BLACK);
outtextxy(100+i,100,"a");
while (getch() != '\033') { // if the first value is esc
    getch(); // skip the [
    switch(getch()) { // the real value
    case 'D':
        moveleft();
    case 'A':
        // code for arrow down
        break;
    case 'W':
        // code for arrow right
        break;
    case 'S':
        // code for arrow left
        break;
    }
}

Here is the moveleft() Function:
void moveleft() {
int i;

int j;
for( i = 0 ; i <= 420 ; i = i + 10, j++ ){
outtextxy(100+i,100,"a");
setcolor(j);
delay(100);
if( i == 420 )
break;
if ( j == 15 )
j = 2;
cleardevice(); // clear screen
}
}


text:
Q: $T$-invariant subspaces, where the characteristic polynomial of $T$ is $x^4-3x^3$ Let $T:V\to V$ be a linear transformation of a four-dimensional real vector spaces $V$. Assume that the characteristic polynomial of $T$ is $x^4-3x^3$.

*

*Show that $V$ hash $T$-invariant subspaces of dimension 1,2,and 3.

*What can you say about the rank of $T$?

A: The characteristic polynomial of $T$ splits as $p_T(x) = x^3(x - 3)$ and so the real eigenvalues of $T$ are $\lambda_1 = 0$ and $\lambda_2 = 3$. Consider the minimal polynomial of $T$:

*

*If $m_T(x) = x(x-3)$ then $T$ is diagonalizable and in particular $\dim V_{\lambda_1} = \dim \ker(T - \lambda_1 I) = \dim \ker(T) = 3$. Any subspace of $V_{\lambda_1}$ is $T$-invariant and so $T$ has invariant subspaces of any dimension. Also, $T$ has rank $1$.

*If $m_T(x) = x^2(x-3)$ then $V = \ker(T^2) \oplus \ker(T - \lambda_2 I)$. In this case, we have a basis of the form $(v, Tv, w)$ for $\ker(T^2)$ with $T^2v = Tw = 0$. The subspace $\ker(T^2)$ is a three-dimensional invariant subspace, the subspace $\operatorname{span} \{ v, Tv \}$ is a two-dimensional invariant subspace and the subspace $\operatorname{span} \{ w \}$ is a one-dimensional invariant subspace. In this case $\ker(T) = \operatorname{span} \{ v, w \}$ and so $T$ has rank $2$.

*If $m_T(x) = x^3(x-3)$ then $V = \ker(T^3) \oplus \ker(T - \lambda_2 I)$. In this case, we have a basis of the form $(v, Tv, T^2v)$ for $\ker(T^3)$ with $T^3 v = 0$. The subspace $\ker(T^3)$ is a three-dimensional invariant subspace, the subspace $\operatorname{span} \{ Tv, T^2v \}$ is a two-dimensional invariant subspace and $\operatorname{span} \{ T^2 v \}$ is one-dimensional invariant subspace. In this case, $\ker(T) = \operatorname{span} \{ v \}$ and so $T$ has rank $3$.

A: The characteristic equation implies $T$ has eigenvalue $3$ of multiplicity $1$ and eigenvalue $0$ of multiplicity $3$ i.e. nullity of $T$ is $3$. So rank is $1$.
Construct an orthonormal basis as follows (Do you know how to construct such a basis from a given basis? like by the Grahm Schimdt procedure or other procedures)
Take the vector which has eigenvalue $3$ as $1$ basis element. Then with the help of the canonical basis (you know what it is right?) construct the other $3$ basis elements (say $b_2,b_3\ \&\ b_4$).
Clearly these $3$ vectors ($b_2,b_3\ \&\ b_4$) belong to Nullspace of $T$. So take any one of these $3$ vectors and its span will be $T$ invariant and have dimension $1$.
Similarly take any $2$ of these vectors and their span will be both $T$ invariant and have dimension $2$. Similar is the case for $3$.

A: Write the characteristic polynomial as $x^3(x-3)$. Recall that $V\cong \mathbb{R}^4$ can be considered as a finitely generated torsion $\mathbb{R}[x]$-module via the multiplication $f(x)\cdot v:=f(T)(v)$. Since the invariant factors of $T$ multiply to give the characteristic polynomial, and the invariant factor of largest degree is the minimal polynomial, the only possibilities for the minimal polynomial are
(1) $x^3(x-3)$, or
(2) $x^2(x-3)$.
Using the Fundamental Theorem for finitely generated modules over PIDs, we get
$$
(1)\implies V\cong \frac{\mathbb{R}[x]}{(x^3)}\oplus\frac{\mathbb{R}[x]}{(x-3)},
$$
and
$$
(2)\implies V\cong \frac{\mathbb{R}[x]}{(x)}\oplus\frac{\mathbb{R}[x]}{(x^2)}\oplus\frac{\mathbb{R}[x]}{(x-3)}.
$$
In the first case, the first summand has $\mathbb{R}$-basis $\{1,\bar{x},\bar{x}^2\}$, therefore dimension 3, and the second summand has dimension $1$. Note that the subspace $\langle \bar{x},\bar{x}^2\rangle$ of the first summand has dimension 2. In the second case, there are clearly subspaces of dimensions 1,2, and 3. Regarding the rank of $T$, recall that $T$ acts on the right hand side of the above isomorphisms by multiplication by $\bar x$, and so we need to determine the dimension of the image each summand under this multiplication. In the first case, the new bases  (after applying the transformation) for the first and second summands become $\{\bar{x},\bar{x}^2\}$ (since $\bar x^3=0$) and $\{\bar x\}$, respectively, so the rank of $T$ in this case is 3. In the second case, the first summand vanishes and the $\mathbb{R}$-bases for the second two are both $\{\bar x\}$, so the rank of $T$ in this case is 2.


text:
Q: Edit text parsing integer android I am making android app and I have edit text surrounded by two buttons for increase and decrease

and when I click the button increase or decrease for the first time it did not work but it start working from the second time
e.g if the number in edit text field is 50 when I press increase it still 50 when I press increase again it change to 51 and again it change to 52 and so on
here is my java code for the two buttons
 add.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            if (quantityEdit.getText().toString().equals("") || quantityEdit.getText().toString() == null) {
                quantityEdit.setText("0");
            } else {
                int a = Integer.parseInt(quantityEdit.getText().toString());
                int b = a + 1;

                quantityEdit.setText(String.valueOf(b));
            }

        }
    });

    sub.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            int a = Integer.parseInt(quantityEdit.getText().toString());

            if (a >= 1) {
                int b = a - 1;

                quantityEdit.setText(String.valueOf(b));
            } else {

                quantityEdit.setText("0");
            }
        }
    });

A: It looks like you are checking for empty string or null in "add", but not in "sub". As Michael Krause said, you should use TextUtils.isEmpty(), and set a default value before performing add or sub operations.
If you are setting a default value elsewhere, please show your code.

A: Consider refactoring your code like so
add.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        quantityEdit.setText(String.valueOf(getIntVal(quantityEdit) + 1));
    }
});

sub.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        int value = getIntVal(quantityEdit);
        if (value > 0) {
            value--;
        }
        quantityEdit.setText(String.valueOf(value));
    }
});

// helper method to get the integer value of a TextView
private int getIntVal(TextView textView) {
    CharSequence rawValue = textView.getText();
    int value;
    if (!TextUtils.isEmpty(rawValue)) {
        try {
            value = Integer.parseInt(rawValue.toString());
        } catch (NumberFormatException e) {
            value = 0;
            // TODO log / notify user
        }
    } else {
        value = 0;
    }
}

This way your initialization is handled in one place and it's more clear.
In any event, your first condition is wrong. You do a null check after trying to access the object (it's backwards). Have you checked your logs? This could throw an exception for a null value and "lose" the first click.


text:
Q: unsubscribe channel not working in socketcluster with swift (iOS) Unsubscribe channel not working on socketcluster.
I have to subscribe 20 channel. Now I want unsubscribe 10 channel. So We are use below code for subscribe.
//  For subscribe
SoketManager.client.subscribeAck(channelName:"random") { (str, obj1, obj2) in
        print ("Got data for channel", str)
 }

//  Listening to channel
SoketManager.client.onChannel(channelName:"random", ack: {
         (channelName : String , data : AnyObject?) in
      print ("Got data for channel", channelName, " object data is ", data ?? "")
 })

We are use below code for unsubscribe.
//  For unsubscribe
 SoketManager.client.unsubscribeAck(channelName:"random", ack : {
       (channelName : String, error : AnyObject?, data : AnyObject?) in
          if (error is NSNull) {
                        print("Successfully unsubscribed to channel ", channelName)
           } else {
                        print("Got error while unsubscribing ", error ?? "")
          }
 })

When I am call "unsubscribeAck" method always get error. Here is error.
{
    message = "Failed to unsubscribe socket from the [object Object] channel - Socket YFaGYE5Tbu1_8we2AAAG tried to unsubscribe from an invalid channel name";
    name = BrokerError;
}

Also I am trying with socketcluster demo as well but It not working for me.
Github link: https://github.com/sacOO7/socketcluster-client-swift
Appreciate your help.
Thanks


text:
Q: Using Amazon S3 Java Api, can you use --query within ListObject? Currently, I'm transferring files from one bucket to another that are little over a year old. In order to do that, I'm using to ListObjects method, and then filter accordingly. However, it's pulling all files, including those that over 2 years old. Is there a way filter out those older files without prefix?
Thank you,


text:
Q: Is this a valid way to take a list of digit characters and use them to create a long integer? Is this a valid way to take a list of digit characters and use them to create a long integer?
LongInt operator+(const LongInt& x, const LongInt& y)
{
    int xCount = 1;
    long int xValue = 0;
    list<char>::iterator it;

    //x.val is a list<char> that contains the digits needed to create the long int
    for(it = x.val.begin(); it != x.val.end(); it++)
    {
        xValue = xValue + (*it - '0');
        xCount++;
    }
}

The purpose of xCount is to keep track of the type of number it is (1's, 10's, 100's, 1000's, etc).
LongInt is a custom class which has a list called val.  This method is supposed to take the two LongInt objects, convert their list to Long Ints, then add them together.  I know I'm missing the code for the y object but I wanted to make sure I have the x down before I try for y.
Thanks in advance!

A: No, and I explained how to do it in your previous thread, except that I was wrong with the reverse iterator. You have to start from the beginning not the end. Sorry about that confusion.. This should be enough:
   list<char> digits;
   digits.push_back('1');
   digits.push_back('2');
   digits.push_back('3');

   long int xValue = 0;
   list<char>::iterator it;

   for(it = digits.begin(); it != digits.end(); it++)
   {
      xValue = xValue * 10 + (*it - '0');
   }

Let's say the list is {'1','2', '3'}. Initially xvalue is 0, then it becomes 0*10+1, which is 1. Then it 1*10 + 2 = 12. Last 12 * 10 + 3 = 123.

A: You need to be taking 10^ to the xCount power, anyway (but you don't increment it anywhere). xCount should probably be the length of your number. The if statement should have == and be if(xCount == 1), but you don't need to distinguish that, because you can consider the first digit multiplier as 10^0.
"123" = 1*10^2+2*10^1+2*10^0

A: If LongInt is a class that can have arbitrary precision, it can't be converted to primitive data type like long int xValue.
If you want to add two LongInts, then you've to do it manually. Character by characer. For example, if x = "174", y = "43", then you're program will do the following:
carry = 0;

174
 43
  ^---- 4 + 3 + carry = 7, carry = 0

174
 43
 ^----- 7 + 4 + carry = 1, carry = 1

174
 43
^------ 1 + 0 + carry = 2, carry = 0

From the algorithm above, the result is "217", which you should store in another LongInt and return that.

A: Am I missing something about operator overloading (sp? :-) ? Why not just forget about xCount and just:
long xValue = 0;
for(it = x.val.rbegin(); it != x.val.rend(); it++)
{
  xValue = xValue * 10 + ( *it - '0');
}

What does xCount have to do with it?


text:
Q: Plotting Data generated in C++ program using Python's Matplotlib I am currently developing a C++ application using Qt and I have to plot some data which is generated by C++ (vectorfields, time-signals correlation matrices etc...). I found the Matplotlib from Python quite nice which is why I want to pass the data from the C++ program to a Python function which will do the plotting. The problem is that the call to the Python function is blocking e.g. it stops the Qt GUI. I currently solve this issue by forking a new process and calling the Python function from the child process.
My question is whether there is a more efficient way of opening a Python Plot from C++ or if forking a new process is pretty much all I can do?
C-Testprogram that calls Python-Plotting-Function:
#include <python3.6/Python.h>
#include <python3.6/listobject.h>
#include <stdlib.h>
#include <fstream>
#include <unistd.h>
#include <math.h>

#define N_LIST 100

using namespace std;

//define some constants for plotting sin(2*pi*50*t)
double f=50;
double ang_frequency=2*M_PI*f;
double dt=1/(f*N_LIST);

int main(int argc,char** argv){
    //set the PYTHONPATH variable to that python can find the Python script containing the plotting function
    char currentdir[200];
    getcwd(currentdir,200);
    printf("%s\n",currentdir);
    if(setenv("PYTHONPATH",currentdir,0)!=0){
        printf("Could not set PYTHONPATH\n");
    };
    //start the python interpreter
    Py_Initialize();
    //load the python module
    PyObject* modulename=PyUnicode_FromString("Module");
    PyObject* module=PyImport_Import(modulename);
    Py_DECREF(modulename);
    if(module!=NULL){
        //load the python function which should do the plotting
        PyObject* py_function=PyObject_GetAttrString(module,"plotFunction");
        //create two python lists for holding the time points and signal points
        PyObject* py_listy=PyList_New(N_LIST);
        PyObject* py_listx=PyList_New(N_LIST);
        //fill the lists with values
        for(int i=0; i<N_LIST; i++){
            double c_currentdouble=sin(i*dt*ang_frequency);
            double c_currenttime=dt*i;
            PyObject* py_currentdoubley=Py_BuildValue("d",c_currentdouble);
            PyObject* py_currenttime=Py_BuildValue("d",c_currenttime);
            PyList_SetItem(py_listy,i,py_currentdoubley);
            PyList_SetItem(py_listx,i,py_currenttime);
        }
        //call the python and pass the data generated in C
        //------------------------------------------------------------------------------------------------------
        if(py_function&&PyCallable_Check(py_function)){
            pid_t pid=fork();
            if(pid==0){
                PyObject* res=PyObject_CallFunctionObjArgs(py_function,py_listx,py_listy,NULL);
                return EXIT_SUCCESS;
            }
        }
        //------------------------------------------------------------------------------------------------------
        else{
            printf("Could not create function object.");
            printf("\n%d",py_function);
            return EXIT_FAILURE;
        }
    }
    else{
        printf("Cannot find module.");
        return EXIT_FAILURE;
    }
    printf("Exiting program\n");
    return EXIT_SUCCESS;
}

Python Script containing plotFunction(argx,argy):
import matplotlib.pyplot as plt
import numpy as np

def plotFunction(argx,argy):
    if type(argx)==list or type(argx)==np.ndarray and type(argy)==list or type(argy)==np.ndarray:
        plt.plot(argx,argy)
        plt.grid()
        plt.show()
    else:
        print("Not all arguments passed are lists. Call failed.")

A: If you want to stick to python you can call the function in a new thread instead of a whole new process. This is quite easy if you have C++11 std::thread but you can also use QtThread.
An easier way would be to use QtCharts though and plot directly in C++.
A third way would be to save the plot from python to an image and display that image in Qt.


text:
Q: Building the protobuf library as a static library Is there a elegant way to build the protobuf library as a static library with  bazel?
If not then not is there a way to build in bazel and get the absolute path of the so for linking?

A: You can build a library as static using the linkstatic option. See: https://docs.bazel.build/versions/master/be/c-cpp.html#cc_library.linkstatic
As for linking, you should let Bazel generate the linker flags for you by adding the Protobuf library to the deps list. See: https://docs.bazel.build/versions/master/be/c-cpp.html#cc_library.deps


text:
Q: How to load image from Firebase into users avatar I have a problem with loading images from firebase. I have two functions. One of them collect info about user, second one load users avatar image. Unfortunately images load after function creates new user. I know it will be problem with asynchronous of Firebase but I don't know how to set up DispatchQueue to work properly. Can you help me with that?
// function that load user image in user manager class
func loadUserImage(contactUserID: String, completion: @escaping (UIImage) -> Void) {
        let userID = Auth.auth().currentUser!.uid
        var userImageRef = self.storage.child("\(userID)/userImage.jpg")
        var image = UIImage()

        if contactUserID != "" {
            userImageRef = self.storage.child("\(contactUserID)/userImage.jpg")
        }
        userImageRef.getData(maxSize: 5 * 1024 * 1024) { (data, error) in
            if let error = error {
                print("Error with retrieving data: \(error.localizedDescription)")
            } else {
                if data?.count != 0 {
                    image = UIImage(data: data!)!
                } else {
                    image = UIImage(systemName: "person.circle.fill")!
                }
                completion(image)
            }
        }
    }

// function that load user in contact manager class
func loadContactList(completion: @escaping ([User]) -> Void) {
    let currentUserID = Auth.auth().currentUser!.uid
    db.collection("contacts")
        .document(currentUserID)
        .collection("userContacts")
        .addSnapshotListener { (querySnapshot, error) in
            var contactList = [User]()
            if let error = error {
                print("Error with retrieving data from DB: \(error.localizedDescription)")
            } else {
                if let snapshotDocuments = querySnapshot?.documents {
                    for document in snapshotDocuments {
                        let data = document.data()
                        let uid = data["uid"] as! String
                        let name = data["name"] as! String
                        let email = data["email"] as! String
                        var contact = User(email: email, name: name, userID: uid)

                        DispatchQueue.global().sync {
                            self.userService.loadUserImage(contactUserID: uid) { (image) in
                                contact.photoURL = image
                            }
                        }
                        contactList.append(contact)

                        contactList.sort {
                            $0.name < $1.name
                        }
                        completion(contactList)
                    }
                }
            }
        }
}

// Function implementation in viewController
func loadContactList() {
    self.contactService.loadContactList { (contactArray) in
        self.contactList = contactArray
        self.tableView.reloadData()
    }
}

A: What you can do is to store the image url in the firebase database and after that create this extension:
import UIKit

let imageCache: NSCache = NSCache<AnyObject, AnyObject>()

extension UIImageView {

    func loadImageUsingCacheWithUrlString(urlString: String) {

        self.image = nil

        if let cachedImage = imageCache.object(forKey: urlString as AnyObject) as? UIImage {
            self.image = cachedImage
            return
        }

        let url = URL(string: urlString)
        if let data = try? Data(contentsOf: url!) {

            DispatchQueue.main.async(execute: {

                if let downloadedImage = UIImage(data: data) {
                    imageCache.setObject(downloadedImage, forKey: urlString as AnyObject)

                    self.image = downloadedImage
                }
            })
        }
    }
}

And call:
if let url = data["imgUrl"] as? String {
    self.myImageView.loadImageUsingCacheWithUrlString(urlString: url)
}

For that what you need to do is to create and initialize an UIImage object. If you are working with cell classes you need to create this object in the cell.


text:
Q: How to detect if a variable lies in range for more than 2 seconds continuously in JavaScript I'm writing this JavaScript code to detect if a live recording is silent for more than 2 seconds. I used a library to get mic level values and update it to a variable every 100 ms. (the function outputs values between 0-1 if it is silent and value larger than 1 if speech is present). I want to show an alert "You became silent" if the variable levels is in range 0-1 for 2 consecutive seconds.
var levels;
setInterval(function(){
  levels=meter.volume*1000;
},100);

How do I proceed with this?

A: Instead of reassigning a variable corresponding to the volume, when the volume is less than 1 and no timeout is currently set, set a timeout which runs after 2 seconds which alerts the user. Clear the timeout whenever the volume is greater than 1:
let timeout;
setInterval(function(){
  const vol = meter.volume * 1000;
  if (vol > 1) {
    clearTimeout(timeout);
    timeout = null;
  } else if (!timeout) {
    timeout = setTimeout(() => {
      console.log("You became silent");
    }, 2000);
  }
},100);

Live demo:

let timeout;
setInterval(function() {
  const vol = Math.random() + 0.05;
  console.log(vol);
  if (vol > 1) {
    clearTimeout(timeout);
    timeout = null;
  } else if (!timeout) {
    timeout = setTimeout(() => {
      alert("You became silent");
    }, 2000);
  }
}, 100);

A: Remember the last time volume was loud. React if that was 2 seconds ago.
let lastLoud = new Date();
setInterval(() => {
  let now = new Date();
  if (now - lastLoud >= 2000) {
    console.log("You became silent");
  }
  let levels = meter.volume * 1000;
  if (levels > 1) {
    lastLoud = now;
  }
}, 100);


text:
Q: why when I change the device type in the inspect window the whole structure of my website changes [this is the viewport the device type is mobileand this is when the device is desktop](https://i.stack.imgur.com/kRGJE.png)
when I change the device type in the inspect window from desktop to mobile the fixed elements on the right get out of the viewport and I have to zoom out to see them, just the whole structure start looking messed up, and when I hover on the empty space there is no element placed in that area it's just an empty spot.
I tried some of the parent's attributes, and checking the right and left values, but none of them worked, frankly I suspect that maybe there is problem in the structure of the website, I would be glad if you could clarify the reason for this error


text:
Q: Is K-2 cross-validation essentially equal to train-test split of 50:50? I am working on an data project assignment where I am asked to use 50% of data for training and remaining 50% of data for testing. I would like to use the magic of cross-validation and still meet the aforementioned criteria.
Currently, my code is following:
clf = LogisticRegression(penalty='l2', class_weight='balanced'

tprs = []
aucs = []
mean_fpr = np.linspace(0, 1, 100)

#cross validation
cv = StratifiedKFold(n_splits=2)
i = 0
for train, test in cv.split(X, y):
    probas_ = clf.fit(X[train], y[train]).predict_proba(X[test])
    # Compute ROC curve and area the curve
    fpr, tpr, thresholds = roc_curve(y[test], probas_[:, 1])
    tprs.append(interp(mean_fpr, fpr, tpr))
    tprs[-1][0] = 0.0
    roc_auc = auc(fpr, tpr)
    aucs.append(roc_auc)
    i += 1

print("Average AUC: ", sum(aucs)/len(aucs),"AUC: ", aucs[-1],)

Since I am using just 2 splits, is it considered as if I was using train-test split of 50:50? Or should I first split data into 50:50 and then use cross validation on the training part, and finally use that model to test the remaining 50% on test data?

A: You should implement your second suggestion.
Cross-validation should be used to tune the parameters of your approach. Among others, such parameters in your example are the value of the C parameter and the class_weight='balanced'  of Logistic Regression. So you should:

*

*split in 50% training, 50% test

*use the training data to select the optimal values of the parameters of your model with cross-validation

*Refit the model with the optimal parameters on the training data

*Predict for the test data and report the score of the evaluation measure you selected

Notice, you should use the test data only for reporting the final score and not for tuning the model, otherwise you are cheating. Imagine, that in reality you may not have access to them until the last moment, so you can not use them.


text:
Q: PostgreSQL query times out when selecting a smaller amount of data (different query plan) PostgreSQL 15.2. We have a table like this (simplified):
create table behavior.event_59 (
    event_id integer not null primary key,
    second_offset integer not null,
    -- ... more columns
)

create index event_59_ix_second_offset on behavior.event_59 using brin (second_offset);

It has over 1.1 billion rows.
Our application uses Npgsql to read all or some of the data from it like this:
set enable_seqscan = off; -- Doesn't seem to make a difference here - see note below

select *
from behavior.event_59
where second_offset >= OPTIONAL_FROM_TIME
    and second_offset <= OPTIONAL_TO_TIME
order by event_id;

*

*When we read the entire table (don't filter by second_offset) it works fine.

*When we filter by <= or >= it works fine.

*When we filter by both of those ~~but the range is large enough it~~ it sometimes works fine.

But.. sometimes with both >= and <= filters on second_offset are used we get a timeout after all the data is read. That is, Npgsql reads all the data requested (which I can tell by looking at the last row returned), then waits for a long time before NpgsqlDataReader.Read() finally returns false. This is shown if I add some logging with timestamps:
2023-02-20 13:55:15 Loaded 146,000,000 events
2023-02-20 13:55:16 Loaded 147,000,000 events
2023-02-20 13:55:17 Loaded 148,000,000 events
2023-02-20 14:01:14 Loaded a total of 148,081,519 events (finished)

So it's normally reading ~1M rows/second, but then waits for 6 minutes at the end. With a CommandTimeout value of less than 6 minutes it throws a TimeoutException. I don't want to have such a long timeout, however, and even if it "works", I'd like to avoid this extra delay at the end.
So it seems like the server is taking too long looking for more rows that may match the filter (there aren't any). This is 100% reproducible for specific values of second_offset, but which values trigger it seems a bit erratic.
Running this query manually with explain analyze I can see that different query plans are chosen depending on the second_offset filter values. Sometimes an Index Scan and sometimes a Bitmap Heap Scan.
Index Scan using event_59_pkey on event_59  (cost=0.58..48284497.83 rows=143418782 width=59) (actual time=321.235..455714.741 rows=145158667 loops=1)
  Filter: ((second_offset >= 380394000) AND (second_offset <= 382297015))
  Rows Removed by Filter: 977953763
Planning Time: 0.342 ms
JIT:
  Functions: 2
  Options: Inlining true, Optimization true, Expressions true, Deforming true
  Timing: Generation 0.552 ms, Inlining 1.817 ms, Optimization 9.505 ms, Emission 3.714 ms, Total 15.588 ms
Execution Time: 459737.126 ms

or
Sort  (cost=20663255.83..20678499.99 rows=6097663 width=59) (actual time=134301.366..135077.460 rows=6732766 loops=1)
  Sort Key: event_id
  Sort Method: external merge  Disk: 429696kB
  ->  Bitmap Heap Scan on event_59  (cost=2261.61..19746794.05 rows=6097663 width=59) (actual time=356.105..132458.869 rows=6732766 loops=1)
        Recheck Cond: ((second_offset >= 382208400) AND (second_offset <= 382297015))
        Rows Removed by Index Recheck: 295436882
        Heap Blocks: lossy=3142644
        ->  Bitmap Index Scan on event_59_ix_second_offset  (cost=0.00..737.19 rows=6104341 width=0) (actual time=259.724..259.724 rows=33212620 loops=1)
              Index Cond: ((second_offset >= 382208400) AND (second_offset <= 382297015))
Planning Time: 0.386 ms
JIT:
  Functions: 2
  Options: Inlining true, Optimization true, Expressions true, Deforming true
  Timing: Generation 0.529 ms, Inlining 32.950 ms, Optimization 5.892 ms, Emission 4.476 ms, Total 43.848 ms
Execution Time: 135253.975 ms

I previously thought that this delay at the end only happens with the Bitmap Heap Scan, but no, auto_explain showed that the original case I started investigating actually does an Index Scan.
The set enable_seqscan = off in the query is because we have already had a similar problem with PG sometimes choosing a sequential scan plan, which is never better in my experience, but removing that doesn't make a different to this case.
How do I avoid this delay at the end, that requires an extra-long timeout to work around?


text:
Q: Create Kafka Topics using node-rdkafka AdminClient I am trying to create the Kafka Topic using the node-rdkafka AdminClient. But I am getting the below error. I am running this in Mac OS
Error: Local: Timed out

AdminClient:
const adminClient = Kafka.AdminClient.create({
        'security.protocol':'sasl_ssl',
        'bootstrap.servers': '*****:9092',
      'sasl.username': 'API Key',
      'sasl.password': 'API secret',
'sasl.mechanisms':'PLAIN'

adminClient.createTopic({
            topic: 'testTopic',
            num_partitions: 1,
            replication_factor: 1
          }, function(err) {
            // Done!
            console.log(`response::`+err);
          });

reference project: https://github.com/Blizzard/node-rdkafka

A: I have faced the same issue with my mac!
Solution:
Open a terminal and execute ls /etc/ssl and check whether cert.pem file exists.
If it exists, just add the following value next to 'sasl.mechanisms':'PLAIN'
'ssl.ca.location': '/etc/ssl/cert.pem'
You have to pass in the cert.pem file's location
Your modified code should look like this
const adminClient = Kafka.AdminClient.create({
    'security.protocol':'sasl_ssl',
    'bootstrap.servers': '*****:9092',
    'sasl.username': 'API Key',
    'sasl.password': 'API secret',
    'sasl.mechanisms':'PLAIN',
    'ssl.ca.location': '/etc/ssl/cert.pem'
 })

Hope this works for you!


text:
Q: NoSuchElementException after closing system.in [ Interrupt a thread waiting for user input and then exit the app ]
I wanted to do the same exercise as mentioned in the above link. But, I ran into NoSuchElementException when I tried to use inConsole.nextLine(), after successfully closing BufferedReader object, in spite of reassigning inConsole like inConsole = new Scanner(System.in) to read from Standard input.
After closing BufferedReader object, can't I reassign to Scanner object like above and use it?

A: Never close neither System.in nor System.out. This will work and cause some strange effects. Actually you will never be able to read or write to SYSIN of SYSOUT respectively. Find other solution.
If you need advise how to solve your problem without closing System.in please provide more information about lifecycle of your application and probably send relevant code snippets.


text:
Q: How to edit lists from user input in an HTML page I made a code in HTML with help from other that will evaluate a list from user input with several functions. The code now will track the sum of all the numbers in the list, the average, the max, min, and frequency of the numbers. The last thing that I want the code to be able to do is to be able to remove items from the list. For example, if the user types in 1,2,3,4,5 and they want to get rid of 3, they could hit a button and 3 would be removed from the list. I'm not exactly sure how to do this, so it would be helpful to receive some help with figuring it out.

.title { font-weight:bold; margin-top:1em; }
<!DOCTYPE html>

  <link rel="stylesheet" type="text/css" href="style.css">

  <link rel="stylesheet" type="text/css" href="style.css">

  <input type='number' id='input'>

  <input type='button' value='add to list' id='add' disabled="disabled">

Topics

  <button id="sum"> Sum </button>
  <button id="max"> Max </button>
  <button id="min"> Min </button>
  <button id="avg"> Avg </button>
  <button id="frequency"> Frequency </button>

<button onclick="lowHigh()">Sort</button>

    <button value="Refresh Page" onclick="window.location.reload()"> Reset! </button>

A: First I modified the addClick() function. I appended a new button to every list element together with an onclick event attached to the button which simply removes the parent element (
). Additionally I wrapped the list value in a . This should now serve your purpose well. Every line I modified got a comment in the code below so you get an overview what I have done / changed and why.
function addClick() {
  var li = document.createElement("li");
  var button = document.createElement("button"); //create new button
  var span = document.createElement("span"); //create span which is wrapped around value
  button.onclick = function() { //add onclick event to button
     this.parentNode.remove(this.parentNode); //remove
 node
     update(this.parentNode.firstChild.innerHTML, true); //update values e.g. frequency, sum, avg
  };
  button.innerHTML = "remove"; //give button a text
  list.appendChild(li);
  span.textContent = input.value; //the value is now added to span
  li.appendChild(span); //add span to li
  li.appendChild(button); //add button to li
  update(input.value);
  input.value = "";
  add.disabled = "disabled";
}

I also modified the update() function and changed the function parameters (signature) to distinguish between deleting and adding of elements. Moreover, I appended some code to adjust the frequency count in case of a delete. It was also necessary to delete the element from frequency if the count = 0. Finally, the line which retrieves the value of a single list element for the arithmetical operations was corrected because the DOM changed as there is a new  and <button> element within every
.
function update(enteredValue, remove) { //add parameter to know when a frequency should be removed
  if(remove){ // remove frequency
    frequency[enteredValue] = frequency[enteredValue] - 1; //substract by one
    if(frequency[enteredValue] == 0) //if frequency = 0
      delete frequency[enteredValue]; //delete the element
  }else{
    frequency[enteredValue] = (frequency[enteredValue] || 0) + 1;
  }

  sum = 0;
  min = Infinity;
  max = -Infinity;
  var count = 0;
  for (var i of list.children) {
    let val = +i.firstChild.innerHTML; //now retrieve the value from the first child ()
    sum += val;
    if (val > max) max = val;
    if (val < min) min = val;
    count++;
  }
  avg = sum / count;
}

Your list item now after creation looks like this:

VALUE<button>Remove</button>

Update: Initially I overlooked something, my code didn't respect the frequency variable which is modified every time an element is added. I corrected the issue now and changed / extended my explanation. Now the frequency is also correct when elements are removed.

Full Code here:

.title { font-weight:bold; margin-top:1em; }
<!DOCTYPE html>

  <link rel="stylesheet" type="text/css" href="style.css">

  <link rel="stylesheet" type="text/css" href="style.css">

  <input type='number' id='input'>

  <input type='button' value='add to list' id='add' disabled="disabled">

Topics

  <button id="sum"> Sum </button>
  <button id="max"> Max </button>
  <button id="min"> Min </button>
  <button id="avg"> Avg </button>
  <button id="frequency"> Frequency </button>

<button onclick="lowHigh()">Sort</button>

    <button value="Refresh Page" onclick="window.location.reload()"> Reset! </button>


text:
Q: nsurlsession for multiple request in loop I have been trying to download image/txt but i need to do it until that url exists & download that image/txt file,so i keep calling same method again & when i set debug point i see  this .
If url is right than i do not see any queue in debug navigator because it is not calling method again. i referred AFNetworking library to the same but i guess it`s working in same way as i am doing in NSURLSession,right?
Case:- I check for url if exists or not, so if it`s exists than load both urls(time.txt & image.png), otherwise call WebService(XmlParser) & keep check for urls for following files.

time.txt+image.png

or

tryagain.txt

show whichever exists.
Also checked this AFNetworking Question but it didnt helped because i do not want to add number of operations. i want to load file whichever exists.
Because Operations will be completed whether it is success or fail in AFNetworking/NSURLSession.

-(void)downloading
{
 NSString *imageUrl = [NSString stringWithFormat:@"%@",txtNumber.text];

 NSURLSessionConfiguration *sessionConfig =[NSURLSessionConfiguration defaultSessionConfiguration];

 NSURLSession *session =[NSURLSession sessionWithConfiguration:sessionConfig
                                               delegate:self
                                          delegateQueue:nil];

 NSURLSessionDownloadTask *getImageTask = [session downloadTaskWithURL:[NSURL URLWithString:imageUrl]

                                  completionHandler:^(NSURL *location,
                                                      NSURLResponse *response,
                                                      NSError *error)
                        {
                           UIImage *downloadedImage =[UIImage imageWithData:[NSData dataWithContentsOfURL:location]];

                                      dispatch_async(dispatch_get_main_queue(), ^{
                                          // do stuff with image
                                          if (downloadedImage)
                                          {
                                              carImgView.image = downloadedImage;
                                              result = TRUE;
                                          }
                                          else
                                          {
                                              result = FALSE;
                                              [self tryagain];
                                          }
                                      });
                                  }];

        [getImageTask resume];
}

-(void)tryagain
{
    NSString *strImg = [[NSString stringWithFormat:@"%@",gblPolicyNo] stringByAppendingString:FilePolStatus];

    NSString *apiImage = [NSString stringWithFormat:@"http://moviepoint.info/%@/%@",FolderPolStatus,strImg];

    NSURL *aImgUrl = [NSURL URLWithString:apiImage];
    // 2
    NSURLSessionConfiguration *sessionConfig =
    [NSURLSessionConfiguration defaultSessionConfiguration];

    // 3
    tryAgainSession =[NSURLSession sessionWithConfiguration:sessionConfig
                                           delegate:self
                                      delegateQueue:nil];

    // 1
    getTryAgainTask = [tryAgainSession downloadTaskWithURL:aImgUrl

                              completionHandler:^(NSURL *location,
                                                  NSURLResponse *response,
                                                  NSError *error)
                    {

                        // 2
                        UIImage *downloadedImage =[UIImage imageWithData:[NSData dataWithContentsOfURL:location]];
                        //3
                        dispatch_async(dispatch_get_main_queue(), ^{
                            // do stuff with image
                            if (downloadedImage)
                            {
                                [policyImgWebView loadData:[NSData dataWithContentsOfURL:location] MIMEType:nil textEncodingName:nil baseURL:nil];
                                NSLog(@"YES");
                            }
                            else
                            {
                                NSLog(@"NO");
                                [self performInBackground];
                            }
                        });
                    }];

    // 4
    [getTryAgainTask resume];

}

Please Correct me if i am doing wrong & Help me to solve this problem.

A: Solved by taking One Global NSURLSession


text:
Q: Generating series for binomial coefficients Is there a simple expression for the generating series $$f_n(z)=\sum_{k\geq 1}\binom{kn}{n}z^k$$
for $n=1$, I know it's $\frac{z}{(1-z)^2}$, but what happens for other $n$? Thanks for any help.

A: Let
$$ g_n(x) = \sum_{k \ge 0} \binom{k}{n}x^k = \frac{x^{n}}{(1 - x)^{n + 1}}. $$
Let $\zeta_n = \exp\left(2 \pi i/n \right)$. Then
$$ \frac{g_n(x) + g_n(\zeta_n x) + \cdots + g_n(\zeta_n^{n - 1} x)}{n} = \sum_{k \ge 0} \binom{kn}{n} x^{kn}. $$
So
$$ f_n(x) = \frac{g_n(x^{1/n}) + g_n(\zeta_n x^{1/n}) + \cdots + g_n(\zeta_n^{n - 1} x^{1/n})}{n}. $$

A: I think the general solution will be of the form $f_n(z)=\frac{P_n(z)}{(1-z)^{n+1}}$, where $P_n(z)$ is a polynomial. This is because $\binom{nk}{k}=\frac{nk(nk-1)..(nk-n)}{n!}$, so that you need to know how to evaluate $\sum_{k=0}^\infty nk(nk-1)...(nk-n)z^k$, which can be done by computing $n$ derivatives of $\frac{1}{(1-z^{n})}$. This is not fun.

A: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$

$\ds{\left.\vphantom{\Large A}\mrm{f}_{n}\pars{z}
\right\vert_{\ \verts{z}\ <\ 1} \equiv
\sum_{k \geq 1}{kn \choose n}z^{k}.\quad
\mbox{Note that}\quad \mrm{f}_{0}\pars{z} = {z \over 1 - z}}$.

Then,
\begin{align}
\left.\vphantom{\Large A}\mrm{f}_{n}\pars{z}
\right\vert_{\ n\ \in\ \mathbb{N}_{\large\ \geq\ 1}} & \equiv \sum_{k \geq 1}
{kn \choose n}z^{k} =
\sum_{k = 0}^{\infty}{kn \choose n}z^{kn/n} =
\sum_{k = n}^{\infty}{k \choose n}z^{k/n}
\,{\sum_{\ell = 0}^{n - 1}r_{\ell}^{k} \over n}
\end{align}

where $\ds{r_{\ell} = \exp\pars{{2\ell\pi \over n}\,\ic}.\ \ell = 0,1,2,\ldots,n - 1}$.

Then,
\begin{align}
\left.\vphantom{\Large A}\mrm{f}_{n}\pars{z}
\right\vert_{\ n\ \in\ \mathbb{N}_{\large\ \geq\ 1}} & =
{1 \over n}\sum_{\ell = 0}^{n - 1}\sum_{k = n}^{\infty}
{k \choose k - n}\pars{z^{1/n}r_{\ell}}^{k} =
{1 \over n}\sum_{\ell = 0}^{n - 1}\sum_{k = n}^{\infty}
{-n - 1 \choose k - n}\pars{-1}^{k - n}\pars{z^{1/n}r_{\ell}}^{k}
\\[5mm] & =
{1 \over n}\sum_{\ell = 0}^{n - 1}\sum_{k = 0}^{\infty}
{-n - 1 \choose k}\pars{-1}^{k}\pars{z^{1/n}r_{\ell}}^{k + n}
\\[5mm] & =
{1 \over n}\sum_{\ell = 0}^{n - 1}\pars{z^{1/n}r_{\ell}}^{n}
\sum_{k = 0}^{\infty}{-n - 1 \choose k}\pars{-z^{1/n}r_{\ell}}^{k} =
{z \over n}\sum_{\ell = 0}^{n - 1}\pars{1 - z^{1/n}r_{\ell}}^{-n - 1}
\end{align}

$$
\\
\bbox[15px,#ffe,border:1px dotted navy]{\ds{%
\mrm{f}_{n}\pars{z} =
\left\{\begin{array}{lcl}
\ds{z \over 1 - z} & \mbox{if} & \ds{n = 0}
\\[2mm]
\ds{{z \over n}\sum_{\ell = 0}^{n - 1}
\bracks{1 - z^{1/n}\exp\pars{-\,{2\pi\ell \over n}\,\ic}}^{-n - 1}} & \mbox{if} & \ds{n \geq 1}
\end{array}\right.}}\\
$$


text:
Q: How to migrate data from local on-premises HDFS to Azure storage I want to move the data from my local on-premises HDFS server to my Azure HDinsight cluster.
I tried distcp command but it does not understand the data lake storage path.

A: Steps for Connecting on-premise Hadoop to ADLS:
Step1: Create the Azure Data Lake Store account.
Step2: Create the identity to access Azure Data Lake Store.
Step3: Modify the core-site.xml in your on-premise Hadoop cluster.
Step4: Test connectivity to Azure Data Lake Store from on-premise Hadoop.
Step5: Use DistCp to transfer the data from on-premise Hadoop to Azure Data Lake Store.
Syntax: hadoop distcp <HDFS_Path> <ADLS_PATH>
Example: hadoop distcp README.txt adl://mydatalakename.azuredatakestore.net/
For more details, refer "Connecting On-premise Hadoop to Azure Data Lake Store" and Migrate on-premise Apache Hadoop cluster to Azure HDInsight - data migration best practices.
Hope this helps.


text:
Q: How to return IQueryable from an oData V4 api action Following the tutorial here I'm trying to return IQueryable but I get error The operation cannot be completed because the DbContext has been disposed
public class ProductsController : ODataController
{
    [EnableQuery]
    public IQueryable<Product> Get()
    {
        return GetRepository<Product>().GetQueryable();
    }
}

GetRepository() is part of a larger generic DI and Unit of work pattern class that basically
public Repository(DbContext context)
{
    Context = context;
    DbSet = Context.Set<T>();
}

public virtual IQueryable<T> GetQueryable()
{
    IQueryable<T> query = DbSet;

    return query;
}

A: If you look carefully on the examples, given in the link you provided, you can see that they have the context outside of the response methods and it is not disposed until Dispose method is called on the controller.
    public class ProductsController : ODataController
        {
            ProductsContext db = new ProductsContext();

            [EnableQuery]
            public IQueryable<Product> Get()
            {
               return db.Products;
            }

            protected override void Dispose(bool disposing)
            {
                db.Dispose();
                base.Dispose(disposing);
            }
        }

Most likely, you dispose the created context in your GetRepository() or GetQueryable() methods. For example, by applying using.

A: When you return an IQueryable from a controller, you don't have control over when that IQueryable is run.  What is happening is that your DbContext is being disposed before the Web API plumbing is getting around to running the IQueryable and returning the results.
What you are doing with GetRepository is referred to as the Service Locator Pattern. However Web API has a mechanism for doing Dependency Injection, which will give you more deterministic control of the lifetime of your resources.
https://www.asp.net/web-api/overview/advanced/dependency-injection
Using this approach, you constructor inject your services (the return type of GetRepository), and then override Dispose on your controller so you can clean up your constructor injected services.  Web API will call Dispose on your controller once it has finished running and returning the results from your IQueryable, and thus your lifetime issues will be fixed.
There are wrappers on NuGet for many of the common IOC containers to allow them to work automatically with Web API.


text:
Q: Reading DICOM 1.2.840.10008.1.2.4.70 I have a problem when reading DICOM file. This is the format 1.2.840.10008.1.2.4.70(Process 14 with a first-order prediction (Selection Value 1). I write my own software.
Here is result of my work.

I also give you a .dcm file.
What can be wrong with it? Only RadiAnt Dicom Viewer open it corectly ( i didn't find any working software with source code ).
Have someone any tutorial about it? Any working code?
I'll be very grateful!
Thanks for help.

I show you how I it do:
//I have:
numCOL= imageWidth;
numROW= imageHeight;

dwCurrentBufferLength;//-> where I in file

//and other stuff...

//First i decode first row:
//[0][0]

DecodeFirstRow(curRowBuf,dwCurrentBufferLength);

//I calculate difrences
HuffDecode ( table , &val, dwCurrentBufferLength);

//and extend
HuffExtend(extend, val);

curRowBuf[0][curComp]=extend+(1<<(Pr-Pt-1));

//[1-n][0]
//... huff stuff
curRowBuf[col][curComp]=extend+curRowBuf[col-1][curComp];

//Then i put row to the vector:
for (col = 0; col < numCol; col++)
{
v=RowBuf[col][0]<<point_transform_parameter;
m_vOutputBuf.push_back(v);
}

//Rest of columns
//[0][m]
curRowBuf[0][curComp]=extend+prevRowBuf[0][curComp];

predictor = left =curRowBuf[leftcol][curComp];
//[1-n][m]
curRowBuf[col][curComp]=extend+predictor;
//and also put it to vector ^^

Where i must sub this 1000??

A: Most likely you have not accounted for the Rescale Intercept, tag (0028,1052) when calculating your HU values. According to the DICOM file, the intercept is -1000.
To get the appropriate HU values of your image, use this formula:
HU = rescale_slope * pixel_value + rescale_intercept

where Rescale Intercept is thus obtained from tag (0028,1052) and Rescale Slope from tag (0028,1053).

A: Here is what I see using gdcmviewer:
$ gdcmviewer 3DSlice1.dcm

GDCM is open source you could study it.


text:
Q: Getting TypeError: path.split is not a function in Mongoose Error:
node_modules\mongoose\lib\schema.js:1160
const subpaths = path.split(/./g);
^
TypeError: path.split is not a function
at Schema.hasMixedParent (C:\Users\Travis\Desktop\Cop_Botv1\Cop_Site_Discord\node_modules\mongoose\lib\schema.js:1160:25)
at Schema.path (C:\Users\Travis\Desktop\Cop_Botv1\Cop_Site_Discord\node_modules\mongoose\lib\schema.js:636:23)
at C:\Users\Travis\Desktop\Cop_Botv1\Cop_Site_Discord\node_modules\mongoose\lib\document.js:2410:39
The error happens with this post.
    router.post('/', function(req, res, next) {
    let id = 'sdflksjdflksd';
    let activated = false;
    let end_date = '10/2';
    let email = 'random@gmail.com'
    let key = {key_id: id, end_date: end_date, activated: false, email: email }
    Keys.create(key, (err, result) => {
        if(err) console.log(err);
        else {
            console.log(result);
        }
    })
})

Schema File
const mongoose = require('mongoose');

let keySchema = new mongoose.Schema({
    key_id: String,
    end_date: String,
    activated: Boolean,
    email: String
});

module.exports = mongoose.model("Keys", keySchema);

The error is in the lib, not really sure what path is referring to.

A: Make sure to check model hooks e.g 'pre', 'save' etc., I had the same issue,
I was using this keyword in the wrong place as shortcut [lazyness] for all properties
Mistake
objectSchema.pre('save', async function(){

     if(this.isModified(this)) do something()

});

Solution
objectSchema.pre('save', async function(){

    if(this.isModified('property')) do something()

});

I hope this example may help you find your own solution to your issue.


text:
Q: Как переписать код, чтобы три функции превратить в одну универсальную? У меня повторяется 3 участка кода. Как можно переписать код, чтобы заменить три функции read_file превратить в одну универсальную?
import json
import threading

f1, f2, f3 = (None for i in range(3))

def read_file1():
    global f1

    name = '1'
    with open(name, 'r', encoding='utf-8') as read_file:
        f1 = json.load(read_file)

def read_file2():
    global f2

    name = '1'
    with open(name, 'r', encoding='utf-8') as read_file:
        f2 = json.load(read_file)

def read_file3():
    global f3

    name = '1'
    with open(name, 'r', encoding='utf-8') as read_file:
        f3 = json.load(read_file)

def f():
    global f1, f2, f3
    t1 = threading.Thread(target=read_file1)
    t1.start()
    t2 = threading.Thread(target=read_file2)
    t2.start()
    t3 = threading.Thread(target=read_file3)
    t3.start()

    t1.join()
    t2.join()
    t3.join()

A: Ваша проблема в том, что вы не можете передать ссылку на глобальную переменную, чтобы записать туда чтобы то ни было. Значит, надо использовать для хранения что-то другое, ссылку на что вы передать можете.
Базовый вариант - объект:
class ThreadResult:
    def __init__(self):
        self.data = None

f1, f2, f3 = (ThreadResult() for i in range(3))

def read_file(store):
    name = '1'
    with open(name, 'r', encoding='utf-8') as read_file:
        store.data = json.load(read_file)

threading.Thread(target=read_file, args=(f1, )).start()
threading.Thread(target=read_file, args=(f2, )).start()
threading.Thread(target=read_file, args=(f3, )).start()

Если лень вводить свой класс - всегда можно воспользоваться чем-то стандартным, главное чтобы оно позволяло хранить данные и было изменяемым. Например, можно использовать список из одного элемента:
f1, f2, f3 = ([None] for i in range(3))

def read_file(store):
    name = '1'
    with open(name, 'r', encoding='utf-8') as read_file:
        store[0] = json.load(read_file)

Наконец, есть устаревший способ, который всё ещё имеет право на жизнь - наследование от Thread:
class ReaderThread(threading.Thread):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.result = None

    def run(self):
        self.result = read_file()

def read_file():
    name = '1'
    with open(name, 'r', encoding='utf-8') as read_file:
        return json.load(read_file)

A: import json
import threading

f1, f2, f3 = (None for i in range(3))

def read_file(f):
    name = '1'
    with open(name, 'r', encoding='utf-8') as read_file:
        globals()[f] = json.load(read_file)

def f():
    threading.Thread(target=read_file, args=('f1', )).start()
    threading.Thread(target=read_file, args=('f2', )).start()
    threading.Thread(target=read_file, args=('f3', )).start()
    ...


text:
Q: Lose Attendence Numbers When some sport is "losing attendance numbers", what does "numbers" refer to?  I can't find a good definition in dictionaries that would fit this usage.

A: It's a form of metonymy. The "numbers" refers directly to the number recorded of attendees, and hence indirectly to those attendees themselves.
They are not losing numbers, they are loosing attendees, but this is spoken of metonymically as "losing numbers".


text:
Q: jQuery v1.11.1 .each() use on multi level child elements I need a way with jQuery or javascript (pref. jQuery) to truncate some slider descriptions.
My issues is when I run my function, it returns the first value into every . I've seen some things about using jQuery Index similar to how one would in php, but the jQuery API page doesn't explain it very well.
HTML to be trunked...

    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

    consectetur adipiscing elit, Lorem ipsum dolor sit amet, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua..

    sed do eiusmod tempor incididunt Lorem ipsum sit amet, consectetur adipiscing elit, ut labore et dolore magna aliqua.

below is my javascript..
pretened i'm using proper document ready functions and such...

Thanks for your advice in advance!

A: You should not append(), but replace the text.
$(this).text(cuttext + '...');
Also there is more clean solution for this particular task, using method $.text() with the callback as an argument (See documentation).
In this way you don't need the overhead of $.each() and its body.

$('div.slideshow_panel > div.description > div.hidden > a').text(function(index, text) {
  return text.substr(0, 20) + '...';
});

            Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

            consectetur adipiscing elit, Lorem ipsum dolor sit amet, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua..

            sed do eiusmod tempor incididunt Lorem ipsum sit amet, consectetur adipiscing elit, ut labore et dolore magna aliqua.

A: Use this keyword to reference the current element and use .text() to replace the contents.
jQuery('div.slideshow_panel > div.description > div.hidden > a').each(function(){

    var desctext = jQuery(this).text(); //use 'this' keyword to get current element
    var cuttext = desctext.substr(0,20);

    jQuery(this).text(cuttext +'...'); //use .text instead to replace

});

A: Use this to refer to the current element:
jQuery('div.slideshow_panel > div.description > div.hidden > a').each(function(){
var desctext = jQuery(this).text();
var cuttext = desctext.substr(0,20);

jQuery( this ).append(cuttext +'...');

});


text:
Q: bottom navigation пропадают буквы Хочу сделать вот такую навигацию

Но получается вот так:

Куда спрятались буквы? Исчезают буквы при добавлении элементов

A: Нужно добавить в разметку менюшки app:labelVisibilityMode="labeled"


text:
Q: Python PIL save location Trying to save an output GIF, but despite changing the path for the save multiple times and the code running fine, no GIF files show up in my documents folder.
frames[0].save('Users\\alexdhesi\\Documents\\output.gif', format='GIF', append_images=frames[1:], save_all=True, duration=100, loop=0)

Help please!!!

A: I will suppose that you are on Windows. If you're not, please specify it.
Right now, you are saving somewhere that is relative to the place you are running the Python interpreter. You should be using an absolute path to be sure where you file is going to be saved. So I'm going to guess that something like that is going to work:
frames[0].save(r'C:\Users\alexdhesi\Documents\output.gif', format='GIF', append_images=frames[1:], save_all=True, duration=100, loop=0)


text:
Q: Using TypeScript Generics with Feature Checks I am working with new and legacy pieces of UI and for a new feature that is rolling out, am using a feature toggle to decide which piece of the UI to show. The back-end, for the new feature now returns a different model so, throughout my code base, I have to account for this by creating V2 versions of existing methods/properties.
Throughout my code, there is a lot of this:
let someCollection: ModelV1 | ModelV2;

this.featureEnabled
    ? someCollection = someCollection as ModelV2
    : someCollection = someCollection as ModelV1;

With the usage of TypeScript, I would like to create a generic function that would return to me whichever type I ask for and would abstract the feature check.
Another example is when I use the feature check to set a specific version of a property to a specific version of an array:
if (this.featureEnabled) {
    this.someCollectionV2 = this.usersV2.filter(user => user.selected);
} else {
    this.someCollection = this.users.filter(user => user.selected);
}

It's cumbersome to have this spread out over my code and it feels like a code-smell. How can I optimize this and make it more functional?

A: The OOP way to handle this would be to define an interface which has all of the functionality that depends on whether the feature is enabled.  Then your main class stores an instance of a feature class which is either enabled or disabled.  The main class only needs to check in one place -- where it creates and stores the feature instance -- and after that it never needs to check again because both classes have the same interface.
In my opinion this is the way to go as it resolves all of the typescript issues and also removes lots of if statements and unnecessary branching. We don't even need to store the featureEnabled boolean because we don't need it.  Here's a dummy setup:
interface DependentFunctions {
    doSomething(): number;
}

class MyClass {

    private _handler: DependentFunctions;

    constructor(featureEnabled: boolean) {
        if ( featureEnabled ) {
            this._handler = new V2Class();
        } else {
            this._handler = new V1Class();
        }
    }

    exampleMethod() {
        const num = this._handler.doSomething();
    }

}

class V2Class implements DependentFunctions {
    doSomething() {
        return 2;
    }
}

class V1Class implements DependentFunctions {
    doSomething() {
        return 1;
    }
}

Playground Link
If you want to instead tackles typescript issues directly, then you can make use of type guards and assertion functions.
Some Examples


text:
Q: Python cStringIO take more time than StringIO in writing (performance of string methods) In my way to profile string methods in python so that I can use the fastest one.
I have this code to test string concatenation in files, StringIO, StringIO and normal string.
#!/usr/bin/env python
#title           : pythonTiming.py
#description     : Will be used to test timing function in python
#author          : myusuf
#date            : 19-11-2014
#version         : 0
#usage           :python pythonTiming.py
#notes           :
#python_version  :2.6.6
#==============================================================================

import time
import cStringIO
import StringIO

class Timer(object):

    def __enter__(self):
        self.start = time.time()
        return self

    def __exit__(self, *args):
        self.end = time.time()
        self.interval = self.end - self.start

testbuf = """ Hello This is a General String that will be repreated
This string will be written to a file , StringIO and a sregualr strin then see the best to handle string according to time

""" * 1000

MyFile = open("./testfile.txt" ,"wb+")
MyStr  = ''
MyStrIo = StringIO.StringIO()
MycStrIo = cStringIO.StringIO()

def strWithFiles():
    global MyFile
    print "writing string to file "
    for index in range(1000):
        MyFile.write(testbuf)
    pass

def strWithStringIO():
    global MyStrIo
    print "writing string to StrinIO "
    for index in range(1000):
        MyStrIo.write(testbuf)

def strWithStr():
    global MyStr
    print "Writing String to STR "
    for index in range(500):
        MyStr =  MyStr +  testbuf

def strWithCstr():
    global MycStrIo
    print "writing String to Cstring"
    for index in range(1000):
        MycStrIo.write(testbuf)

with Timer() as t:
    strWithFiles()
print('##Request took %.03f sec.' % t.interval)

with Timer() as t:
    strWithStringIO()
print('###Request took %.03f sec.' % t.interval)

with Timer() as t:
    strWithCstr()
print('####Request took %.03f sec.' % t.interval)

with Timer() as t:
    read1 = 'x' + MyFile.read(-1)
print('file read ##Request took %.03f sec.' % t.interval)

with Timer() as t:
    read2 = 'x' + MyStrIo.read(-1)
print('stringIo read ###Request took %.03f sec.' % t.interval)

with Timer() as t:
    read3 = 'x' + MycStrIo.read(-1)
print('CString read ####Request took %.03f sec.' % t.interval)

MyFile.close()

*

*While the Python documentation site says that cStringIO is faster than StringIO but the results says that StringIO has better performance in concatenation, why?

*The other hand is that, reading from cStringIO is faster than StringIO (its behavior similar to file), as I read the implementation of file and cStringIO are in C, so why string concatenation is slow?

*Is there any other way to deal with string more faster than these methods?

A: The reason that StringIO performs better is behind the scenes it just keeps a list of all the strings that have been written to it, and only combines them when necessary. So a write operation is as simple as appending an object to a list. However, the cStringIO module does not have this luxury and must copy over the data of each string into its buffer, resizing its buffer as and when necessary (which creates much redundant copying of data when writing large amounts of data).
Since you are writing lots of larger strings, this means there is less work for StringIO to do in comparison to cStringIO. When reading from a StringIO object you have written to, it can optmise the amount of copying needed by computing the sum of the lengths of the strings written to it preallocating a buffer of that size.
However, StringIO is not the fastest way of joining a series of strings. This is because it provides additional functionality (seeking to different parts of the buffer and writing data there).  If this functionality is not needed all you want to do is join a list strings together, then str.join is the fastest way to do this.
joined_string = "".join(testbuf for index in range(1000))
# or building the list of strings to join separately
strings = []
for i in range(1000):
    strings.append(testbuf)
joined_string = "".join(strings)


text:
Q: Let $f: \mathbb{R} \rightarrow \mathbb{R}$. Is it true that $f \circ f = f \iff f \upharpoonright rng(f) = id_{rng(f)}$? I think the answer is no, because we can take $f(x) = -x$. Then $f \circ f = f$, but $f \upharpoonright rng(f) = - id_{rng(f)} \neq id_{rng(f)}$.

A: Your example satisfies a similar equation: $f\circ f={\rm id}$.
In fact, $f\circ f=f\iff\forall x:f(f(x))=f(x) \iff\forall y\in{\rm range}(f):f(y)=y$.


text:
Q: I am working on a website with bootstrap4 FORM
I am creating a form like this but i dont know how to place all radio buttons serially in a row. Could someone help me with this.

                    No. Of Guests

                          1
                       <input type="radio" name="opt2" class="form-control" id="opt2">
                      2

                      <input type="radio" name="opt3" class="form-control" id="opt3">
                      3
                      <input type="radio" name="opt4" class="form-control" id="opt4">
                      4
                      <input type="radio" name="opt5" class="form-control" id="opt5">
                      5

            </form>

This is my code for the radio buttons.When i run this code all buttons are placed vertically.
please don't report this question. I am a noob on this platform so, i dont know exactly how it works.
Thank you in advance.

A: Use this code :

      <input name="gruppo2" type="radio" id="radio4" checked>
      Opzione 1

      <input name="gruppo2" type="radio" id="radio5">
      Opzione 2

What change? if you use form-check-inline class input radio will display in one row.


text:
Q: haproxy not logging I have configured rsyslog (CentOS 6.3) adding the -c 0 -r options and the line
local2.* /var/log/haproxy.log

and restarted rsyslog but all that happens is an haproxy.log gets created.  It is never written to.
Not quite sure how to troubleshoot this.
Below is my haproxy.cfg file.  Nothing else is configured to use local2 according to grepping for it in rsyslog.conf.  My haproxy config is basically the default, just trying to get logging working first.

A: I believe haproxy only have syslog logging via UDP.  What is your log config line in haproxy.cfg?
Is it?
log 127.0.0.1 local2

If so, you'll need to enable the UDP server modules in the rsyslog configuration by uncommenting:
$ModLoad imudp.so
$UDPServerRun 514

Tip:  I run the following command on all my haproxy servers:
sudo sed -i 's/#$ModLoad imudp.so/$ModLoad imudp.so/' /etc/rsyslog.conf; sudo sed -i 's/#$UDPServerRun 514/$UDPServerRun 514/' /etc/rsyslog.conf; sudo service rsyslog restart


text:
Q: Why does a propeller suck in air from the front? A rotating but fixed propeller sucks in air from the front. What is the cause for this acceleration of air particles? Since propeller blades act like rotating wings, my best guess is that the blades create a lower pressure zone in front of them which causes higher atmospheric pressure air to flow into this lower pressure zone. This creates the effect if the propeller would "suck in" air from the front.

A: A propeller imparts momentum on the air - when the blades hit the air molecules, it gives them momentum towards the back (high pressure) side; this creates a net velocity towards the rear of the propeller. Normally air molecules in the plane of the propeller have equal probability of moving forward or backwards; the propeller's action makes the situation asymmetrical. Since more air molecules move backwards, a low pressure area is created in front - and air will be pushed towards this region be the atmospheric pressure "far away".

A: when you look at an airplane propeller, you will se that parts of the propeller blades are slanted. These slants, when rotating, push the air back, creating a low pressure zone, sucking more pressure in, while at the same time pushing more air back.


text:
Q: RESTful Web Serice on the Server-Side I'm a C++/Java guy trying to get started with developing a web service.  I've read a LOT about RESTful services and I understand the architecture and how URIs should be formed, and I think I understand the client-side stuff since that is what of what I've found addresses.  My question is probably a lot more basic - if I have a URI like this:
http://www.mysite.com/products/gadgets/spypen

what do I do on the server side to set this up?  In my (obviously minimal) web programming experience, I would have a directory under HTTP root called "products" and then a subdir under that called "gadgets", and then a subdir "spypen" with an index.html in it.  Obviously, this is NOT the way to do it in this type of situation.
It seems to me that I'd like to tell my (Linux-based Apache) web server to interpret the URI that it received and then call a specific PHP script (or whatever) with parameters of "gadgets" and "spypen".  I may just be looking in the wrong places, but I can't find any resources that tell me what to do on the server side to get the PHP script called with those params when the URI is received by Apache.  Any help would be appreciated and I hope I'm not asking a completely stupid question, but I'm pretty sure I am.. :-)  Thanks!

A: Recess is a PHP framework for working with HTTP requests directly. In the java world, you should look at the comments and answer to this SO question for options. Looking at those frameworks will at least give you an idea of what's involved before you try to manually roll your own implementation.


text:
Q: Best practice - when to overload? When designing a class is it best to force the implementer to pass in all required parameters by making it part of the method signature or to create an overload and allow the user to set properties, then check that they are set properly?
For example, let's say we have a class Emailer with a method Send.  Send requires
public bool Send(string ToAddress, string FromAddress, string subject, string body, string Attachment = null)

I also have public properties
public string To { get; set; }
public string From { get; set; }
/// <summary>
/// Full filepath to attachment
/// </summary>
public string Attachment { get; set; }
public string Subject {get;set;}
public string Body {get;set;}

Now, should I create an overload for Send?
public void Send()
And then write checks for unpopulated properties.  Or, leave out the overload and possibly remove the properties?

A: I feel that your Emailer has too much resposibility by holding those properties. Perhaps you should look into separating that into a Message class, then you can pass that.
Have a look at the way the .NET mail classes do it.

A: I'd require anything needed as a parameter to make it harder to mess up... it's too easy to miss a required field if you leave it as a property.  Plus, requiring certain fields as parameters makes it very explicit that you need those fields.
@Daniel A. White has already suggested using a Message class to separate your concerns (mailer vs message).  I'd take in a Message object, which in turn requires the required data in the constructor (minimum of To and From).
This, of course, is assuming that you only used email as an example.  In real life you'd use the built in classes :)


text: Q: Ultra-Low Temperature semiconductors What benefits does cooling semiconductors have for technology or any other innovations? I understand semiconductors can become good conductors at high temperatures which are ideal for everyday things we use like laptops or phones. What I do not see is what is the benefit of low temperature semiconductors ? Is it like how superconductive material is great for the efficiency of flow of current or something completely different ? Maybe I am not asking the right questions but any help will be appreciated or even sources as well.


text:
Q: How to get PROJ C++ to recognize grid directory? I've not been able to actually get EGM96 to WGS84 transformations to work in PROJ C++. I have however, gotten what I want to work in python, via pyproj, like this:
from pyproj import Transformer, CRS
from pyproj.transformer import TransformerGroup, TransformDirection
from pyproj.datadir import append_data_dir, get_data_dir

def main():
    lat = 43.70012234
    lng = -79.41629234
    z = 100

    append_data_dir("/absolute_directory_to/proj/")

    transformer = Transformer.from_crs("epsg:4326", "epsg:5773",)

    results = transformer.transform(lat, lng, z,  None, False, True, TransformDirection.INVERSE)

    print(results)

if __name__ == "__main__":
    main()

This provides the result:
(43.70012234, -79.41629234, 62.71016021909354)

And the file us_nga_egm96_15.tif located in the ./proj/ directory
However, my replication of the same in C++ doesn't appear to work.
#include <proj.h>
#include <filesystem>
#include <array>
void main(){
    auto proj_context = proj_context_create();
    const char * path =  "/absolute_directory_to/proj";
    const char * db_path = proj_context_get_database_path(proj_context);

    std::filesystem::path db_path_path = std::filesystem::path(db_path);
    std::string db_path_str = db_path_path.parent_path().string();
    std::array paths = {path, db_path_str.c_str()};
    proj_context_set_search_paths(proj_context, paths.size(), paths.data());

    std::cout << proj_errno_string(proj_context_errno(proj_context)) << std::endl;
    auto temp = proj_create_crs_to_crs (proj_context,
                                        "EPSG:4326",
                                        "EPSG:5773",
                                        NULL);
    std::cout << proj_errno_string(proj_errno(temp)) << std::endl;
    std::cout << proj_errno_string(proj_context_errno(proj_context)) << std::endl;
    auto b = proj_trans(temp, PJ_INV, {43.70012234,-79.41629234,100,0});
    std::cout << proj_errno_string(proj_errno(temp)) << std::endl;
    std::cout << proj_errno_string(proj_context_errno(proj_context)) << std::endl;

    std::cout << b.v[0] << "," << b.v[1] << "," << b.v[2] << "," << b.v[3] << std::endl;
    std::cout << proj_errno_string(proj_errno(temp)) << std::endl;
    std::cout << proj_errno_string(proj_context_errno(proj_context)) << std::endl;

    proj_destroy(temp);

    proj_context_destroy(proj_context);
    return 0;
}

It actually prints out nothing (some strange character seems to be eating all the other characters), and in debug mode, I can see that b = {inf,inf,inf,inf}.  Same thing happens if I don't manually specify the proj locaiton (but make sure the actual .tiff is located there).
What am I doing wrong here?

A: Something I didn't mention here, is that I was using VCPKG, due to https://github.com/microsoft/vcpkg/pull/16169, it is actually impossible to use GEO TIFF's on linux for PROJ through VCPKG  I would recommend simply not using PROJ through VCPKG at all. The issues that are blocking this from being fixed have been blocked for years at this point, and don't seem to be something that is going to be fixed anytime soon.
seen how data is manually set here: https://raw.githubusercontent.com/Microsoft/vcpkg/master/ports/proj4/portfile.cmake
Stepping through the code, the issue was apparently that I set the correct file location, but that the code silently fails when TIFF_ENABLED is not defined.
 //grids.cpp

    if (IsTIFF(header_size, header)) {
#ifdef TIFF_ENABLED
        auto set = std::unique_ptr<VerticalShiftGridSet>(
            GTiffVGridShiftSet::open(ctx, std::move(fp), actualName));
        if (!set)
            pj_ctx_set_errno(ctx, PJD_ERR_FAILED_TO_LOAD_GRID);
        return set;
#else
        pj_log(ctx, PJ_LOG_ERROR,
               "TIFF grid, but TIFF support disabled in this build");
        return nullptr;
#endif

Because I was using VCPKG, this was not possible to amend.


text:
Q: Why is docstrip putting extra macro calls in a hyperlink inside a footnote that has a tilde? Here's a minimal example of Docstrip putting extra macro bits into a \href call inside a footnote when the URL has a tilde:

% \iffalse
\documentclass[a4paper]{ltxdoc}
\usepackage{hyperref}
\begin{document}
\DocInput{foo.dtx}
\end{document}
% \fi

% \title{The foo package\thanks{This document corresponds to
%     foo version, dated date.}}
%
% \author{The Author\thanks{Author's website with bad link:
%     \href{http://example.com/~user/} {foo}. Working link:
%     \href{http://example.com/user}{foo}} }
%
% \maketitle
%
% \section{Introduction}
%
% a link that works: \href{http://example.com/~user}
%     {foo}.

In the resulting PDF, the tilde in the URL in the footnote has some TeX macros in it you get:
http://example.com/\protect \unhbox \voidb@x \penalty \@M \ {}user/

so something is wrong with the tilde. How can I fix this?

A: I have to admit that I have no idea why this is happening.  However, replacing the literal tilde with \textasciitilde will fix your problem.
% \author{The Author\thanks{Author's website with bad link:
%     \href{http://example.com/\textasciitilde user/}{foo}. Working link:
%     \href{http://example.com/user}{foo}} }

A: \href and friends have to do some magic to make special characters like # or ~ work. This magic works only if the commands are used outside of any other commands. But the hyperref package accepts "escaped" versions as well: \#, \~ and so on. They work in any case and are a bit easier to remember than commands like \textasciitilde.
This is actually independent of docstrip, the following example exhibits the same behavior:
\documentclass{article}
\usepackage{hyperref}
\title{Test}
\author{Me\footnote{\url{http://example.com/~}}}
\begin{document}
\maketitle
\url{http://example.com/~}
\end{document}