text:
Q: Perform an action when a number of checkboxes are checked My app have 10 checkboxes, when 5 checkboxes is checked i want display a picture in a ImageView below. But i dont know how to code it. if someone here can help me with this code i will be really greatful.

A: You can add checkedListener to all checkboxes, and initialize a counter for checkboxes.
Check update the counter on checking of every checkbox and when counter reaches the count 5 do your operation which you need
checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // TODO Auto-generated method stub
            if(isChecked) {
               checkBoxCounter = checkboxCounter + 1;
               if(checkBoxCounter == 5)
                 //do your imageview task here;
                 imageView.setImageResource(R.drawable.ic_image);
            } else {
               //if checkbox is unchecked
               checkBoxCounter = checkBoxCounter - 1;
            }
        }
    });

Place this code in all your checkbox onCheckedListener

A:     public class babyconquistas extends AppCompatActivity {

EditText conqtext1, conqtext2,
Button button;
ImageView img, img1;
CheckBox conq1, conq2, conq3, conq4, conq5, conq6, conq7, conq8, conq9, conq10;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_babyconquistas);

    img = (ImageView) findViewById(R.id.imgconq2);
    img1 = (ImageView) findViewById(R.id.imgconq4);

    conq1 = (CheckBox) findViewById(R.id.conq1);
    conq2 = (CheckBox) findViewById(R.id.conq2);
    conq3 = (CheckBox) findViewById(R.id.conq3);
    conq4 = (CheckBox) findViewById(R.id.conq4);
    conq5 = (CheckBox) findViewById(R.id.conq5);

    conq6 = (CheckBox) findViewById(R.id.conq6);
    conq7 = (CheckBox) findViewById(R.id.conq7);
    conq8 = (CheckBox) findViewById(R.id.conq8);
    conq9 = (CheckBox) findViewById(R.id.conq9);
    conq10 = (CheckBox) findViewById(R.id.conq10);

    conqtext1 = (EditText) findViewById(R.id.conq1text);
    conqtext2 = (EditText) findViewById(R.id.conq2text);
    button = (Button) findViewById(R.id.salvar);
    loadSavedPreferences();

}

//checkboxes
private void loadSavedPreferences() {
    SharedPreferences sp = PreferenceManager
            .getDefaultSharedPreferences(this);
    boolean cbValue1 = sp.getBoolean("CHECKBO1", false);
    boolean cbValue2 = sp.getBoolean("CHECKBO2", false);
    boolean cbValue3 = sp.getBoolean("CHECKBO3", false);
    boolean cbValue4 = sp.getBoolean("CHECKBO4", false);
    boolean cbValue5 = sp.getBoolean("CHECKBO5", false);
    boolean cbValue6 = sp.getBoolean("CHECKBO6", false);
    boolean cbValue7 = sp.getBoolean("CHECKBO7", false);
    boolean cbValue8 = sp.getBoolean("CHECKBO8", false);
    boolean cbValue9 = sp.getBoolean("CHECKBO9", false);
    boolean cbValue10 = sp.getBoolean("CHECKBO10", false);

    if (cbValue1) {
        conq1.setChecked(true);

    } else {
        conq1.setChecked(false);
    }
    if (cbValue2) {
        conq2.setChecked(true);
    } else {
        conq2.setChecked(false);
    }
    if (cbValue3) {
        conq3.setChecked(true);
    } else {
        conq3.setChecked(false);
    }
    if (cbValue4) {
        conq4.setChecked(true);
    } else {
        conq4.setChecked(false);
    }
    if (cbValue5) {
        conq5.setChecked(true);
    } else {
        conq5.setChecked(false);
    }
    if (cbValue6) {
        conq6.setChecked(true);
    } else {
        conq6.setChecked(false);
    }
    if (cbValue7) {
        conq7.setChecked(true);
    } else {
        conq7.setChecked(false);
    }
    if (cbValue8) {
        conq8.setChecked(true);
    } else {
        conq8.setChecked(false);
    }
    if (cbValue9) {
        conq9.setChecked(true);
    } else {
        conq9.setChecked(false);
    }
    if (cbValue10) {
        conq10.setChecked(true);
    } else {
        conq10.setChecked(false);
    }

}

private void savePreferences(String key, boolean value) {
    SharedPreferences sp = PreferenceManager
            .getDefaultSharedPreferences(this);
    SharedPreferences.Editor edit = sp.edit();
    edit.putBoolean(key, value);
    edit.commit();
}

private void savePreferences(String key, String value) {
    SharedPreferences sp = PreferenceManager
            .getDefaultSharedPreferences(this);
    SharedPreferences.Editor edit = sp.edit();
    edit.putString(key, value);
    edit.commit();
}

public void Salvar(View v) {
    // TODO Auto-generated method stub

    savePreferences("N1", conqtext1.getText().toString());
    savePreferences("N2", conqtext2.getText().toString());

    savePreferences("CHECKBO1", conq1.isChecked());
    savePreferences("CHECKBO2", conq2.isChecked());
    savePreferences("CHECKBO3", conq3.isChecked());
    savePreferences("CHECKBO4", conq4.isChecked());
    savePreferences("CHECKBO5", conq5.isChecked());
    savePreferences("CHECKBO6", conq6.isChecked());
    savePreferences("CHECKBO7", conq7.isChecked());
    savePreferences("CHECKBO8", conq8.isChecked());
    savePreferences("CHECKBO9", conq9.isChecked());
    savePreferences("CHECKBO10", conq10.isChecked());

}

there are 10 checkboxes.
if this first group of 5 checkboxes is ALL CHECKED, DISPLAY THE ImageView img
and the second group of 5 checkboxes, if this 5 checkboxes is all checked, display the ImageViw img1
i hope you understand and i am really thankfull for take your time for help me, thank you sou much really, and if is more easy and if you want of course, i have teamViewer.

A: public class babyconquistas extends AppCompatActivity {

EditText conqtext1, conqtext2,
Button button;
ImageView img, img1;
CheckBox conq1, conq2, conq3, conq4, conq5, conq6, conq7, conq8, conq9, conq10;
int cbCounter1=0, cbCounter2=0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_babyconquistas);

    img = (ImageView) findViewById(R.id.imgconq2);
    img1 = (ImageView) findViewById(R.id.imgconq4);

    conq1 = (CheckBox) findViewById(R.id.conq1);
    conq2 = (CheckBox) findViewById(R.id.conq2);
    conq3 = (CheckBox) findViewById(R.id.conq3);
    conq4 = (CheckBox) findViewById(R.id.conq4);
    conq5 = (CheckBox) findViewById(R.id.conq5);

    conq6 = (CheckBox) findViewById(R.id.conq6);
    conq7 = (CheckBox) findViewById(R.id.conq7);
    conq8 = (CheckBox) findViewById(R.id.conq8);
    conq9 = (CheckBox) findViewById(R.id.conq9);
    conq10 = (CheckBox) findViewById(R.id.conq10);

    conqtext1 = (EditText) findViewById(R.id.conq1text);
    conqtext2 = (EditText) findViewById(R.id.conq2text);
    button = (Button) findViewById(R.id.salvar);

    conq1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
             if(isChecked){
                 cbCounter1 = cbCounter1 + 1;
             } else {
                 cbCounter1 = cbCounter1 - 1;
             }
             if(cbCounter1 == 5) {
                  img.setImageResource(R.drawable.img);
                  //or if you want to handle it with visibility
                  img.setVisibility(View.VISIBLE);
             }
        }
    });

    conq2.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
             if(isChecked){
                 cbCounter1 = cbCounter1 + 1;
             } else {
                 cbCounter1 = cbCounter1 - 1;
             }
             if(cbCounter1 == 5) {
                  img.setImageResource(R.drawable.img);
                  //or if you want to handle it with visibility
                  img.setVisibility(View.VISIBLE);
             }
        }
    });

    conq3.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
             if(isChecked){
                 cbCounter1 = cbCounter1 + 1;
             } else {
                 cbCounter1 = cbCounter1 - 1;
             }
             if(cbCounter1 == 5) {
                  img.setImageResource(R.drawable.img);
                  //or if you want to handle it with visibility
                  img.setVisibility(View.VISIBLE);
             }
        }
    });

    conq4.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
             if(isChecked){
                 cbCounter1 = cbCounter1 + 1;
             } else {
                 cbCounter1 = cbCounter1 - 1;
             }
             if(cbCounter1 == 5) {
                  img.setImageResource(R.drawable.img);
                  //or if you want to handle it with visibility
                  img.setVisibility(View.VISIBLE);
             }
        }
    });

    conq5.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
             if(isChecked){
                 cbCounter1 = cbCounter1 + 1;
             } else {
                 cbCounter1 = cbCounter1 - 1;
             }
             if(cbCounter1 == 5) {
                  img.setImageResource(R.drawable.img);
                  //or if you want to handle it with visibility
                  img.setVisibility(View.VISIBLE);
             }
        }
    });

    conq6.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
             if(isChecked){
                 cbCounter2 = cbCounter2 + 1;
             } else {
                 cbCounter2 = cbCounter2 - 1;
             }
             if(cbCounter2 == 5) {
                  img1.setImageResource(R.drawable.img);
                  //or if you want to handle it with visibility
                  img1.setVisibility(View.VISIBLE);
             }
        }
    });

            conq7.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
             if(isChecked){
                 cbCounter2 = cbCounter2 + 1;
             } else {
                 cbCounter2 = cbCounter2 - 1;
             }
             if(cbCounter2 == 5) {
                  img1.setImageResource(R.drawable.img);
                  //or if you want to handle it with visibility
                  img1.setVisibility(View.VISIBLE);
             }
        }
    });

    conq8.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
             if(isChecked){
                 cbCounter2 = cbCounter2 + 1;
             } else {
                 cbCounter2 = cbCounter2 - 1;
             }
             if(cbCounter2 == 5) {
                  img1.setImageResource(R.drawable.img);
                  //or if you want to handle it with visibility
                  img1.setVisibility(View.VISIBLE);
             }
        }
    });

    conq9.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
             if(isChecked){
                 cbCounter2 = cbCounter2 + 1;
             } else {
                 cbCounter2 = cbCounter2 - 1;
             }
             if(cbCounter2 == 5) {
                  img1.setImageResource(R.drawable.img);
                  //or if you want to handle it with visibility
                  img1.setVisibility(View.VISIBLE);
             }
        }
    });

    conq10.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
             if(isChecked){
                 cbCounter2 = cbCounter2 + 1;
             } else {
                 cbCounter2 = cbCounter2 - 1;
             }
             if(cbCounter2 == 5) {
                  img1.setImageResource(R.drawable.img);
                  //or if you want to handle it with visibility
                  img1.setVisibility(View.VISIBLE);
             }
        }
    });

}

This code will do the task. And if you need to store the information in sharedPref, then you can store the counter value and checked, checkboxes info, then on page load you need to populate all the data of checked checkboxes and the counter


text:
Q: Stable portable wifi web server This is a somewhat strange issue, but here it goes:
A team (about 15 users) in our organization uses a self-contained Ruby-on-Rails web app to search and view data for competitions. There wouldn't be a problem except the competition rules prohibit connecting to the internet, so any cloud or office servers are off-limits. However, they do allow us to bring our own devices in to the venue so long as the data is offline. Therefore the only solution I can think of short of rewriting the web application on each device (which we don't have the resources for) is to bring in a battery powered wireless server and have all the devices (iOS, Android, OS X, Windows, Linux) connect to it.
The issue is IT personnel cannot be there to support it all the time. That means it needs to be crazy easy to setup and stable even in less than optimal conditions (e.g. possible power failure or improper shutdown).
I have set up plenty of web app servers, but I'm always monitoring the boot and reboot processes so I can fix problems that are encountered, something I can't do in this case.
I was wondering if this can be achieved with a decent laptop, simple server configuration (on some kind of linux distro preferably Ubuntu or Centos), and an off the shelf wireless access point or requires something closer to an embedded server with custom assembled hardware and major software modifications(e.g. writing custom redundant software)? Are there any packages to help with this kind of stability?

A: Does your app need to write? Booting a linux laptop from a cdrom with preconfigured hostap and your application on a hard disk mounted read-only should be pretty stable and reliable. If storage must be read-write, most modern journaling filesystems are resilient to crashes. Either way, you should be able to set up a cheap PC to do what you need.
There are tools available to help with making a custom linux live CDs for example [1] [2]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Passport Local.js with email instead of username I am using passport-local to authenticate users. However, I am using email and password to login instead of the default username.
How do I change my configuration to change username to email in passport.authenticate?
Here is my LocalStrategy code:
const strategy = new LocalStrategy(userSchema.authenticate() )
passport.use(strategy);

Here is my signup code:
app.post('/signup', async function (req, res) {

  const email = req.body.email;
  const password = req.body.password;
  const passwordretype = req.body.passwordretype
  const name = req.body.name
  if (password.length < 5) {

    return res.render('signup', { error: "Your Password must be at least 5 characters in length" })

  }
  if (password !== passwordretype) {
    return res.render('signup', { error: "Your Passwords must match" })

  }
  if (password.length > 40) {
    return res.render('signup', { error: "Your Password must be under 40 characters in length" })

  }

  if (name.length > 50) {
    return res.render('signup', { error: "Your Name must be under 50 characters in length" })

  }
  const doc = await userSchema.findOne({ email: email })
  if (doc) {
    return res.render('signup', { error: "This email is already in use with the sign up method: " + doc.method })
  }

  const randomnum = String(Math.floor(Math.random() * 10000))
  const username1 = name.split(' ').join('')
  const username = username1.concat(randomnum)

    userSchema.register(
      new userSchema({
        email: email,
        method: 'email',
        credits: 0,
        totalearned: 0,
        totalspent: 0,
        purchases: [],
        currentlysolving: null,
        solved: [],
        posted: [],
        currentposted: [],
        level: 0,
        username: username,
        feescollected:0,
        }), req.body.password, function (err, user) {

        if (err) {
          return res.render('signup', { error: err })
        } else {
          req.login(user, (er) =>  {
            if (er) {
              return res.render('signup', { error: err })
            }
            else {
              res.redirect('/')
            }
        });
    }
      }
    )

});

And finally, here is the login code that is not allowing email
app.post('/login', function (req, res) {
  //

  const state = req.query.state
  const email = req.body.email;
  const password = req.body.password;
//
passport.authenticate("local", function (err, user, info) {
  if (err) {
    return res.render('login', { error: err, state: state })  }
  else {
      if (!user) {
        return res.render('login', { error: `The email or password entered is incorrect`, state: state })
      }
      else {
          const token = jwt.sign({ userId: user._id, email: user.email }, secretkey, { expiresIn: "24h" });
          res.json({ success: true, message: "Authentication successful", token: token });
      }
  }
})(req, res);

})

How do I fix this?
Thank you

A: I changed the strategy configuration
passport.use(new LocalStrategy({
  usernameField: 'email'
}, userSchema.authenticate()));

I also changed the plugin in the schema to
userSchema.plugin(passportLocalMongoose,
  {
      usernameField: 'email'
  });


text:
Q: jQuery slideUp problem So i keep getting the error "Object doesn't support this property or method". I can get the menu to slide down but I can't get it to slide up when my mouse leaves the menu. (#suggestions)
Here is my code: (jQuery 1.6)
<script type="text/javascript">
function lookup(inputString) {
    if(inputString.length == 0) {
        // Hide the suggestion box.
        $('#suggestions').hide();
    } else {
        $.post("rpc.php", {queryString: ""+inputString+""}, function(data){
            if(data.length >0) {

                $('#suggestions').slideDown('slow');
                $('#autoSuggestionsList').html(data);

       // slideUp on mouseleave
        $('#suggestions').mouseleave(function() {
        $('#suggestions').slideUp('slow');
        });

            }

        });

    }

} // lookup

function fill(thisValue) {
    $('#inputString').val(thisValue);
    setTimeout("$('#suggestions').hide();", 200);
}

A: Are you wrapping this code in a ready handler?
$(function(){
  // all your stuff in here so all the elements you select exist before you assign handlers to them
});

If not, you can get inconsistent results depending on where you put your script.
edit actually, this won't matter in your case because you're only defining functions here.


text:
Q: OpenCV Python: How to warpPerspective a large image based on transform inferred from small region I am using cv2.getPerspectiveTransform() and cv2.warpPerspective() to warp an image according to Adrian Rosenbrock blog : https://www.pyimagesearch.com/2014/08...
However in my case I have an image where I can only select the region B to be warped but need to warp (top-down view) the whole larger image A.
Can the parameters of the perspective transform inferred from the smaller region B be applied to the full image A? Is that possible?enter image description here

A: Here is one way to demonstrate that the matrix from the red square applies to the whole image in Python OpenCV.
Here I rectify the quadrilateral into a rectangle on the basis of its top and left dimensions.
Input:

import numpy as np
import cv2
import math

# read input
img = cv2.imread("red_quadrilateral.png")
hh, ww = img.shape[:2]

# specify input coordinates for corners of red quadrilateral in order TL, TR, BR, BL as x,
input = np.float32([[136,113], [206,130], [173,207], [132,196]])

# get top and left dimensions and set to output dimensions of red rectangle
width = round(math.hypot(input[0,0]-input[1,0], input[0,1]-input[1,1]))
height = round(math.hypot(input[0,0]-input[3,0], input[0,1]-input[3,1]))
print("width:",width, "height:",height)

# set upper left coordinates for output rectangle
x = input[0,0]
y = input[0,1]

# specify output coordinates for corners of red quadrilateral in order TL, TR, BR, BL as x,
output = np.float32([[x,y], [x+width-1,y], [x+width-1,y+height-1], [x,y+height-1]])

# compute perspective matrix
matrix = cv2.getPerspectiveTransform(input,output)
print(matrix)

# do perspective transformation setting area outside input to black
# Note that output size is the same as the input image size
imgOutput = cv2.warpPerspective(img, matrix, (ww,hh), cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT, borderValue=(0,0,0))

# save the warped output
cv2.imwrite("red_quadrilateral_warped.jpg", imgOutput)

# show the result
cv2.imshow("result", imgOutput)
cv2.waitKey(0)
cv2.destroyAllWindows()


text:
Q: Pandas data frame change structure I have a dataframe for movie ratings like this:

I want to have a new data frame to have data as a sequence for each user and each item in the sequence contains a vector of movieid and its rating, that looks something like this:
userId    moviesandratings
1        [[296,5],[306,3.5],[307,5],etc]

for each user.

A: You can create new column filled by lsits and then aggregate lists in GroupBy.agg:
df['new'] = df[['movieId','rating']].to_numpy().tolist()

df1 = df.groupby('userId')['new'].agg(list).reset_index(name='moviesandratings')

Or use GroupBy.apply:
df1 = (df.groupby('userId')[['movieId','rating']]
         .apply(lambda x: x.to_numpy().tolist())
         .reset_index(name='moviesandratings'))


text:
Q: When do you use a new method? The simple way to print your name, age, and gender is to code it in one main method. Why do we have to make multiple methods to do this?
public static void main(String[] args) {
    sayMaster();
    Age();
    Gender();
}

static void sayMaster() {
    System.out.println("Hello Master Austin");
}

static void Age() {
    System.out.println(7);
}

static void Gender() {
    System.out.println("Robot");
}

A:
Why do we have to make multiple methods to do this?

actually you dont have to at all, but modularity is the key(remember the divide et impera rule), you can / need to change one of those methods latter with out a problem that your code will be broken...
then when you have those 3 methods you can always do an elegant solution like
public static void main(String[] args) {
    invokeThemAll();
}

public static void invokeThemAll() {
    sayMaster();
    printAge();
    printGender();
}

A: First of all no one forced you to make methods to just print 3 strings.
Making methods is preferable. Consider the scenario when you have to do this task 1000 times. Instead of writing print statement 1000 times you cab just call the method and send a parameter and rest will be done just by 3 lines of code.

A: Consider this:
In which of the examples can you immediately tell what the code is supposed to do?
Example 1
public static void main(String... args) {
    A a = new A();
    // CODE
    // CODE
    // CODE
    // CODE
    // ... 100 lines of setting up A
    B b = new B(a);
    // CODE
    // CODE
    // CODE
    // CODE
    // ... 100 lines of setting up B
    // CODE
    // CODE
    // CODE
    // CODE
    // ... 500 other lines of code using a and b
}

Example 2
public static A setupA() {
    A a = new A();
    // CODE
    // CODE
    // CODE
    // CODE
    // ... 100 lines of setting up A
    return a;
}

public static B setupB() {
    B b = new B();
    // CODE
    // CODE
    // CODE
    // CODE
    // ... 100 lines of setting up B
    return b;
}

public static void doFancyAlgorithm(A a, B b) {
    // CODE
    // CODE
    // CODE
    // CODE
    // 500 other lines of code using a and b
}

public static void main(String... args) {
    A a = setupA();
    B b = setupB();
    doFancyAlgorithm(a, b);
}

Clearly, example 2 would be easier to read and understand, because it's comprised of only 3 lines and because different responsibilities are encapsulated into different methods. You'd be able to understand what the main does just by looking at the sequence of methods, without knowing the actual implementation of said methods. Whereas in example 1 you'd need to wade through every line of code in order to understand.
Additionally, consider adding some new functionality to your code:
public static void main(String... args) {
    A a = setupA();
    B b = setupB();
    doFancyAlgorithm(a, b);

    A a2 = setupA(); // new instance of a because we absolutely need that
    C c = setupC();
    doAnotherAlgorithm(a2, c);
}

Now in the case of setting up a new instance of A, we can simply reuse the method setupA() which makes everything easier. Otherwise we would need to rewrite the whole 100 lines of setting up A again.
This has another huge benefit. If you ever need to change some lines in your code, you'd only need to change it in one place (that is once inside the method instead of everywhere the code occurs), which prevents oversights, copy-paste errors, and so on.


text:
Q: Make JQuery UI tabs look like buttons I would like to have a tab-like interface like the one in this page:
http://jqueryui.com/tabs/#default
Except that I would like the tabs to look more like buttons like:
http://jqueryui.com/button/#radio
Where the group of tabs would look like the group of radio buttons above. Is there a way I can change the way the tabs look so they look more like the "radio" buttons on the second link? Or is there another approach you'd recommend to make the tabs look like buttons? Thanks!

A: Here is your wished html + css.classes

    <input type="radio" name="radio" id="radio1" class="ui-helper-hidden-accessible">Choice 1
    <input type="radio" checked="checked" name="radio" id="radio2" class="ui-helper-hidden-accessible">Choice 2
    <input type="radio" name="radio" id="radio3" class="ui-helper-hidden-accessible">Choice 3

and here is a jQuery-ui TAB

Nunc tincidunt

Proin dolor

Aenean lacinia

Now, you want to display TABS has the ui-buttonset .. just re-use the classes by redesigning your html.

but this might be a harsh one to just 'recycle' jQuery-ui classes.
I suggest you to rewrite your own .css to overwrite with the styling associated. I mean, rewrite jQuery-ui TABS styling instead of attempting to recycle .css classes.


text:
Q: Validation that excludes itself on update action if fields have not changed I have a table called rents that hold a start and end date. I have then created a validation so that no new rents cant overlap existing rents start and end dates.
The thing is, when i click on a rent to update it and if i don't change any fields and click update. It trys to validate on itself and say that its overlapping an existing record. ( The existing record its referring to is it itself.)
The thing im trying to do is, how can i have my validation exclude itself. This is how my validation looks like.
def should_not_overlap_rental_periods
  errors.add(:start_date, "can't overlap other rental periods") if self.rents.where("end_date <= ? and start_date >= ?", self.end_date.strftime("%Y-%m-%d"), self.start_date.strftime("%Y-%m-%d")).count > 0 unless self.rents.blank?
end

A: You need to check up on ActiveModel's Dirty Checking module. You can check on attributes if they have changed and branch your logic accordingly.
http://railsapi.com/doc/rails-v3.0.1/classes/ActiveModel/Dirty.html


text:
Q: Null Check operator used on null value in Dart Flutter Null check operator on null value error in Dart flutter which is caused by User user instance variable. Please help how to run this code to get value from firebase. Dummy user variables working fine till now.
Code:
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../models/user.dart';
import '../services/database/users_database_services.dart';

class UserController extends GetxController {
  String userID = '';
  bool previouslyLoggedIn = false;
  UserDBService userDBService = UserDBService();

  User? user;
  setUser(String userID, String name, String phone, String email, int usercnic,
      String profilePictureLink) {
    this.userID = userID;
    user = User(
      email: email,
      name: name,
      phone: phone,
      userID: userID,
      usercnic: usercnic,
      profilePictureLink: profilePictureLink,
    );
  }

  updateDbUser() async {
    bool isSuccess = await userDBService.addUser(userID, user!.name,
        user!.phone, user!.email, user!.usercnic, user!.profilePictureLink);

    if (isSuccess) {
      Get.snackbar(
        "success",
        "User details updated successfully",
        snackPosition: SnackPosition.BOTTOM,
      );
    } else {
      Get.snackbar(
        "error",
        "User details not updated successfully",
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.red,
        colorText: Colors.white,
        duration: const Duration(seconds: 2),
      );
    }
  }
}

A: The null check operator ! will treat the nullable value in front of it, a variable that may or may not be null, as non-nullable. In your case, this is user inside updateDbUser.
As mentioned in the comments, it is likely caused by calling updateDbUser before the user field is set. Since you already have a way to display failed updates, I would suggest simply setting isSuccess to false if there is no user:
updateDbUser() async {
  bool isSuccess = user != null && await userDBService.addUser(...);

  ...
}

This should ensure that user is not null, and if it is, it will simply set isSuccess to false and show you the red banner. Where possible, it is advisable to avoid the null check operator !, as it leads you to runtime exceptions/errors.

A: Add null value condition in adding user like below  or you can check if user is not empty
bool isSuccess = await userDBService.addUser(userID, user?.name ?? "",
    user?.phone ?? "", user?.email ?? "", user?.usercnic ?? 0, user?.profilePictureLink ?? "");

or
bool isSuccess = false;

if(user!= null)
{
   isSucess = await userDBService.addUser(userID, user!.name,
               user!.phone, user!.email, user!.usercnic, user!.profilePictureLink);
}

A: your user data is null, check user data before update as below:
updateDbUser() async {
 bool isSuccess=false;
 if(user!=null){
isSuccess = await userDBService.addUser(userID, user!.name,
    user!.phone, user!.email, user!.usercnic, user!.profilePictureLink);
 }
if (isSuccess) {
  Get.snackbar(
    "success",
    "User details updated successfully",
    snackPosition: SnackPosition.BOTTOM,
  );
} else {
  Get.snackbar(
    "error",
    "User details not updated successfully",
    snackPosition: SnackPosition.BOTTOM,
    backgroundColor: Colors.red,
    colorText: Colors.white,
    duration: const Duration(seconds: 2),
  );
}
}


text:
Q: Error Actually, there were zero interactions with this mock, unittest public class ABCService implements XYZ
{

   private final ARepository aRepository;
   private final BRepository bRepository;

   private final SomeService someService;

   public ABCService (ARepository aRepository, BRepository bRepository)
   {
      this.aRepository= aRepository;
      this.bRepository= bRepository;
      this.someService= new SomeService (aRepository, bRepository);
   }

   @Transactional
   public void someMethod(Parameters parameter)
   {
    aRepository.findById(something)
     ...
     someService.doSomething(someParameters);

The test class:
@ExtendWith(MockitoExtension.class)
public class ABCServiceTest
{
   @Mock
   private ARepository aRepository;

   @Mock
   private BRepository bRepository;

   @Mock
   private SomeService someService ;

   private ABCService abcService;

 @BeforeEach
   public void setup()
   {

      abcService = new ABCService(aRepository, bRepository);

   @Test
   void someMethodTest()
   {
      when(aRepository.findById("12345")).thenReturn(null);

      abcService.someMethod(parameter);

      verify(someService, times(1)).doSomething(any());
   }

My error:
Wanted but not invoked:
someService.doSomething(
    <any>
);
-> at de.sick.agency.sapmirrorservice.domain.services.SapMirrorServiceTest.onLoiproReceivedTest(SapMirrorServiceTest.java:122)
Actually, there were zero interactions with this mock.

Wanted but not invoked:
someService.doSomething(
    <any>
);
-> at packages.ABCServiceTest.someMethodTest(ABCServiceTest.java:122)
Actually, there were zero interactions with this mock.


text:
Q: Get all tickets ID for a Group - Zendesk API I am in python trying to GET all the tickets (all the status for all the time) for an specific group called 'Sales'.
I have two problems.

*

*I dont know hot to add the filter by group name in the URL that I am using in the for. I want all the tickets assigned to 'Sales'.

*I am having a limit in the results. It is only showing me 1.000 records and the count of the total is more than 11.000
start_time ='1640995200'
df = pd.DataFrame()
for page_iter in range(4):
    url = "https://latchel.zendesk.com/api/v2/incremental/tickets/cursor.json?start_time="+start_time
    response = requests.get(url, auth=(user,pw))
    data = response.json()
    url = data['after_url']
    new_url = url```


text:
Q: react native : Best navigator/router component to use with redux i'm starting a new react native app, with redux and drawer based navigation, i'm looking for the best navigator/router component to choose , i would appreciate recommendation based on experience please.

A: Update 3.15.2017
based on the comment from Thomas you can use https://github.com/react-community/react-navigation
Based on the comments from here you should use NavigationExpermiental:
https://github.com/facebook/react-native/issues/6184
Here's a nice example to get you started:
https://github.com/thebakeryio/react-native-complex-nav


text:
Q: Change Oracle IP If I change Oracle database server IP , what problems may be caused and how to solve them?

*

*modify hosts file

*modify tnsnames.ora file

*modify listener.ora file

*modify clients' tnsnames.ora files

As I know it is not necessary to have listener.ora and tnsnames.ora files on the database server; it is necessary if you need to connect to another database. Am I right?
I have single-instance database, version 11.2.0.1.0

A: None of what you have listed as required is necessary if you use fully qualified domain names in the TNSNAMES and client TNSNAMES files, and you are using a Windows domain.
This is the reason why hard coding IP addresses is a maintenance headache.  Instead of:

MY_DB=   (DESCRIPTION=
    (ADDRESS=
      (PROTOCOL=TCP)
      (HOST=192.168.0.2)
      (PORT=1521)
    )
    (CONNECT_DATA=
      (SERVICE_NAME=MY_DB.HOME.LOCAL)
    )   )

Use:

MY_DB=   (DESCRIPTION=
    (ADDRESS=
      (PROTOCOL=TCP)
      (HOST=DB_MACHINE_NAME.HOME.LOCAL)
      (PORT=1521)
    )
    (CONNECT_DATA=
      (SERVICE_NAME=MY_DB.HOME.LOCAL)
    )   )


text:
Q: Mocha test. Import class from not exported namespace I need to write unit test for my Typescript app. I use Mocha test framework.
I have got internal module(A) in my web app and class B there.
namespace A {
    export class B {
       constructor() {

       }
    }
}

I need to write some unit test for class B.
/// <reference path="path/A.ts" />
import { expect } from 'chai';
    describe('B test', function () {

        describe('#constructor()', () => {
            it('Should create B with default data', () => {
                let b = new A.B();
                expect(b.age).to.equal(90);
            });

        });
    });

I'm starting my tests with command:
mocha --watch  --recursive  path/Tests

But every time in terminal I receive error message:
ReferenceError: A is not defined

A - is my internal module and I can't to export it. Is it some way, how is it possible to test internal module's class B?

A: There is no way to reach variables from local scopes in JavaScript. Basically this is same problem as:
(() => {
  let bar = 1;
})();
// bar cannot be reached from this scope

The class needs to be refactored to be reachable:
export namespace A {
    export class B {
       constructor() {

       }
    }
}

At this point namespace is of no use here, it can be omitted in favour of ES modules only.
It is a good practice to export everything for testability reasons. If a class is considered internal, it's exported from .ts file where it was defined but not from index.ts.
/** @internal */ JSDoc annotation and stripInternal compilation option can be used to exclude these exports from .d.ts declarations. They won't be available as regular imports but will still be reachable with require.


text:
Q: Win32 API to QT commands - Getting window properties I am trying to followings to an application (running outside my application) written in QT.  How should I approach it?
HWND hMainWnd = FindWindow(NULL, "QT Window App");
HWND hMenu = GetMenu(hMainWnd);
char strMenuText[128];
GetMenuString(hMenu,0, strMenuText, 127, MF_BYPOSITION);
HWND hChildWnd = FindWindoEx(hMainWnd, NULL, NULL, NULL);

Thanks a lot in advance!!
Kay


text:
Q: Dealing with JSON result I'm having trouble reading the JSON data from a venues search. Here is my code:
xmlhttpRC = new XMLHttpRequest();
url = "https://api.foursquare.com/v2/venues/explore?ll="+pointStrr+"&oauth_token=V5PI2GJ0KDOVH2GAHNHJ5DVLMRKNF440FR1N1HPG0XHX2OBQ&v=2015643&
callback=JSONP";
xmlhttpRC.open("GET", url, true);
xmlhttpRC.onreadystatechange = recCb;
xmlhttpRC.send(null);
//return recommendedArr;
}

function recCb(data){
//console.log(data);
if(xmlhttpRC.readyState == 4){
    if(xmlhttpRC.status == 200){
        var recRes = xmlhttpRC.response;

        console.log(recRes);

        //console.log(recRes);
        console.log(recRes.meta.code);
    }
}

}
I get the reponse I expect from the server, and firebug shows me that a JSON object is returned, but I am not sure how to access the data inside from here.
console.log(recRes.meta.code) returns the error:
"recRes.meta is undefined"
Where am I going wrong?
I want to access the venues information but I am just using meta.code as a simple test.
This is probably really simple but I'm stumped!
Thanks in advance,
Ross.

A: You need to parse JSON. Modern browsers have JSON.parse built in, older versions of IE etc. do not - you can theoretically use eval(response) but it creates a security hole.
There is a library to parse it if you cannot depend on users having modern browsers.

A: var decodedResp = JSON.parse(recRes);
if (decodedResp.meta.code === ...)

JSON-object is just a representation of an JS-object, see; it should be parsed first.


text:
Q: Is $\int^{\pi/4}_{0} \frac{1}{x\sin 2x}dx$ convergent?
Is the following integral divergent?
  $$\int^{\pi/4}_{0} \frac{1}{x\sin 2x}dx$$

I've tried to substitute $\alpha>0$ for $0$, as it is a second type of determinant integral. But then I am left with a tough integral. The comparison test gives me no solution since I get $1/x$ which is divergent and so nothing can be said about my function.
Please. while writing Your answer, try to tell me what principles are You using and how.
Thank You

A: Recall from elementary geometry that the sine function satisfies the inequalities
$$x\cos(x)\le \sin(x)\le x$$
for $0\le |x|\le \pi/2$.  Then, we see that
$$\left|\frac{1}{x\sin(2x)}\right|\ge \frac{1}{2x^2}$$
for  $x\in (0,\pi/4]$.
Then, we see that for all $\epsilon>0$
$$\begin{align}
\int_{\epsilon}^{\pi/4}\frac{1}{x\sin(2x)}\,dx &\ge \int_{\epsilon}^{\pi/4} \frac{1}{2x^2}\,dx\\\\
&=\frac{1}{2\epsilon}-\frac{2}{\pi}\\\\
&\to \infty \,\,\text{as}\,\,\epsilon\to 0^+
\end{align}$$

A: Hint. The integrand is a continuous function over $(0,\pi/4]$, a potential problem is at $x \to 0$.
By Taylor series expansion, as $x \to 0$, one has
$$
\frac1{x\sin(2x)} \sim \frac1{2x^2}
$$ then the inital integral is divergent by the comparison test.


text:
Q: XNA and Lidgren Error: Trying to read past buffer size? I am trying to create an online game using XNA and the Lidgren Networking Library. However, right now I am having trouble sending and receiving any messages without getting the error: "Trying to read past the buffer size - likely caused by mismatching Write/Reads, different size or order."
I send the messages to the client like this:
if (btnStart.isClicked && p1Ready == "Ready")
{
    btnStart.isClicked = false;
    NetOutgoingMessage om = server.CreateMessage();
    CurrentGameState = GameState.City;
    om.Write((byte)PacketTypes.Start);
    server.SendMessage(om, server.Connections, NetDeliveryMethod.Unreliable, 0);
    numPlayers = 2;
    Console.WriteLine("Game started.");
}

Where PacketTypes.Start is part of an enum set up to distinguish between different messages.
The client receives this message like so:
    if (joining)
{
    NetIncomingMessage incMsg;
    while ((incMsg = client.ReadMessage()) != null)
    {
    switch (incMsg.MessageType)
    {

    case NetIncomingMessageType.Data:
    if (incMsg.ReadByte() == (byte)PacketTypes.Ready)
    {
        p1Ready = "Ready";
    }
    else if (incMsg.ReadByte() == (byte)PacketTypes.Start)
    {
        CurrentGameState = GameState.City;
        Console.WriteLine("Game started");
        numPlayers = 2;
    }

    break;

    default:
        Console.WriteLine("Server not found, Retrying...");
    break;

        }
    }
}

But no matter what I've tried, I still get that error. Please, any help will be appreciated.

A: You only write one byte to your packets when you send them:
om.Write((byte)PacketTypes.Start);

But read two when you receive them:
// One read here
if (incMsg.ReadByte() == (byte)PacketTypes.Ready)
{
    p1Ready = "Ready";
}
// Second read here
else if (incMsg.ReadByte() == (byte)PacketTypes.Start)

Edit
To resolve the issue change your code to this:
case NetIncomingMessageType.Data:
    byte type = incMsg.ReadByte(); // Read one byte only

    if (type == (byte)PacketTypes.Ready)
    {
        p1Ready = "Ready";
    }
    else if (type == (byte)PacketTypes.Start)
    {
        CurrentGameState = GameState.City;
        Console.WriteLine("Game started");
        numPlayers = 2;
    }

break;


text:
Q: Как сделать random на Kivy, для Label, при нажатии на кнопку Делаю программу, "Правда или действие", и столкнулся с такой проблемой. У меня не работает random, выбивает NameError: name 'random' is not defined, (извините если не правильно написал ошибку). Если что, Пишу на Kivy, в python вместе с Builder.
Вот код:
from kivy.app import App

from kivy.config import Config

from kivy.lang import Builder

from kivy.uix.screenmanager import ScreenManager, Screen

from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.anchorlayout import AnchorLayout

import random

Config.set("graphics", "resizable", "0")
Config.set("graphics", "width", "500")
Config.set("graphics", "height", "850")

category6 = [("Пригни 10 раз"), ("Закрой глаза")]
ListCategory6 = len(category6)

Builder.load_string("""
<MenuScreen>:
    BoxLayout:
        orientation:
            "vertical"
        spacing: 10
        padding: [30]
        Button:
            text: "Начать игру'
            background_color: [5, 1.7, 1, 5]
            size_hint: [1, 0.1]
            font_size: 50
            on_press: root.manager.current = 'settings'

<SettingsScreen>:
    BoxLayout:
        orientation:
            "vertical"
        spacing: 10
        padding: [30]
        Button:
            text: 'Назад'
            size_hint: [1, 0.6]
            background_color: [5, 1, 1, 5]
            on_press: root.manager.current = "menu"
        Label:
            text: "Выбери возрастную категорию"
            size_hint: [1, 0.5]
            font_size: 35
        Button:
            text: "6+"
            background_color: [2.3, 0.1, 4, 1]
            font_size: 40
            on_press: root.manager.current = "Six"

<SixScreen>:
    AnchorLayout:
        anchor_x: "center"
        anchor_y: "top"
        padding: [25]
        Button:
            text: "Назад"
            background_color: [5, 1, 1, 5]
            size_hint: [1, 0.07]
            on_press: root.manager.current = 'settings'
    AnchorLayout:
        anchor_x: "center"
        anchor_y: "bottom"
        padding: [25]
        Button:
            text: "Получить Задание"
            background_color: [0, 1.7, 0, 1]
            size_hint: [1, 0.07]
            on_press: root.manager.current = 'SixLabel'
        Label:
            text: "Задания 6+"
            font_size: 50

<SixLabel>:
    AnchorLayout:
        anchor_x:
            "center"
        anchor_y:
            "top"
        padding: [25]
        Button:
            text: "Назад"
            size_hint: [1, 0.07]
            background_color: [5, 1, 1, 5]
            on_press: root.manager.current = "Six"
        Label:
            text: random.randrange(0, ListCategory6)
""")

class MenuScreen(Screen):
    pass

class SettingsScreen(Screen):
    pass

class SixScreen(Screen):
    pass

class SixLabel(Screen):
    pass

class randsix(Screen):
    pass

game = ScreenManager()
game.add_widget(MenuScreen(name = 'menu'))
game.add_widget(SettingsScreen(name = 'settings'))

game.add_widget(SixScreen(name = "Six"))

game.add_widget(SixLabel(name = "SixLabel"))

class PlayPutannyApp(App):
    def build(self):

        return game

if __name__ == "__main__":
    PlayPutannyApp().run()

A: .py
import random
category6 = [("Пригни 10 раз"), ("Закрой глаза")]
....
class SixLabel(Screen):
    def random_task(self):
        return str(random.choice(category6))

.kv
<SixLabel>:
    ....
    Label:
        text: root.random_task()


text:
Q: WCF security problems with named pipes I have a slightly complicated setup that, of course, works fine in XP, but chokes on Windows 7. It may seem like madness, but it made sense at the time!
I have a WPF application that launches and then launches another application that communicates with an external device. After launching it establishes communications with the new process using WCF (hosted by the new process) via a named pipe (net.pipe). This seems to work fine on either OS.
I wanted to make some of the functionality of the WPF application externally available to a command line program, so I set up another WCF service, this time hosted by the WPF application and again exposed it via named pipes. Again, this seems to work.
Next, I wanted to make the functionality of the WPF application available via the web. Now, it's important that the WPF application be runnable from a regular user account, so I thought the best way to make this work on Windows 7 would be to create a windows service that would provide the web service part and have it communicate back to the WPF application via the same named pipe that works fine for the command line. I implemented this and it runs fine on XP, but it chokes on Windows 7. The problem seems to be with trying to establish the named pipe connection between the windows service and the WPF application.
If I run the WPF app as an administrator, it works fine. So it seems to be a problem with the account that the windows service is running in can't communicate with a regular user account that is hosting the WCF service via named pipes. Is there a way to make this work? It seems a WCF service running in a regular user account can communicate using named pipes to another app running in the same account, but it seems it can't do the same thing with a different account.
Oddly, the reverse seems to work. The windows service does, in fact, also expose a service with a named pipe binding (it's used as an activation function since the service is running all the time). I can connect from the WPF app to this service without any problems.
My knowledge of security is somewhat limited. Can anybody shine a light on what's going on?

A: This question has been asked several times previously on SO. For example, see Connecting via named pipe from windows service to desktop app
The problem is that your user session applications don't possess the SeCreateGlobalPrivilege security privilege necessary to allow them to create objects in the global kernel namespace visible to other sessions, but only in the local namespace which is only visible within the session. Services, on the other hand, which run with this privilege by default, can do so.
It is not the named pipe object itself which is constrained to the local namespace in this way, but another named kernel object, a shared memory section, on which the WCF named pipe binding relies in order to publish to its clients the actual name of the pipe, which is a GUID which changes each time the service is started.
You can get round this constraint by reversing the roles - make the windows service application the WCF Service, to which your user session apps connect. The windows service has no problem publishing its service to your session. And connecting things up this way round makes more sense because the windows service is always running, whereas your session and its apps comes and goes as you log in and out. You'll want to define the service with a duplex contract, so that once the connection is established, the essential flow of communication over the WCF service can still happen in the same direction you originally intended.

A: The applications (WPF/Console) are creating locally scoped named pipes (this happens by default when they are unable to create globally scoped pipes). My guess is that they can communicate with each other because they can see each others named pipes because they are running under the same account.
The windows service has higher privileges and can therefore create a globally scoped named pipe for the client applications to see.
You can check out a discussion on Christian Weyer's Blog.


text:
Q: Failed to start MariaDB 10.3.25 database server I have just migrated from mysql to mariadb on Ubuntu 20.04 server with apt install mariadb-server.
The installation ended fine, but mariadb-server didn't start.
This is the output of the command:
service mariadb start; journalctl -xe

Job for mariadb.service failed because the control process exited with error code.
See "systemctl status mariadb.service" and "journalctl -xe" for details.
-- Defined-By: systemd
-- Support: http://www.ubuntu.com/support
--
-- A start job for unit mariadb.service has begun execution.
--
-- The job identifier is 22456.
Nov 04 13:46:18 Socrates mysqld[18047]: 2020-11-04 13:46:18 0 [Note] /usr/sbin/mysqld (mysqld 10.3.>
Nov 04 13:46:18 Socrates mysqld[18047]: 2020-11-04 13:46:18 0 [Warning] Could not increase number o>
Nov 04 13:46:19 Socrates audit[18047]: AVC apparmor="DENIED" operation="sendmsg" info="Failed name >
Nov 04 13:46:19 Socrates kernel: audit: type=1400 audit(1604493979.310:19): apparmor="DENIED" opera>
Nov 04 13:46:19 Socrates audit[18047]: AVC apparmor="DENIED" operation="sendmsg" info="Failed name >
Nov 04 13:46:19 Socrates kernel: audit: type=1400 audit(1604493979.530:20): apparmor="DENIED" opera>
Nov 04 13:46:19 Socrates systemd[1]: mariadb.service: Main process exited, code=exited, status=1/FA>
-- Subject: Unit process exited
-- Defined-By: systemd
-- Support: http://www.ubuntu.com/support
--
-- An ExecStart= process belonging to unit mariadb.service has exited.
--
-- The process' exit code is 'exited' and its exit status is 1.
Nov 04 13:46:19 Socrates systemd[1]: mariadb.service: Failed with result 'exit-code'.
-- Subject: Unit failed
-- Defined-By: systemd
-- Support: http://www.ubuntu.com/support
--
-- The unit mariadb.service has entered the 'failed' state with result 'exit-code'.
Nov 04 13:46:19 Socrates systemd[1]: Failed to start MariaDB 10.3.25 database server.
-- Subject: A start job for unit mariadb.service has failed
-- Defined-By: systemd
-- Support: http://www.ubuntu.com/support
--
-- A start job for unit mariadb.service has finished with a failure.
--
-- The job identifier is 22456 and the job result is failed.

This is what I found in /var/log/mysql/error.log:
2020-11-04 14:17:50 0 [ERROR] InnoDB: Invalid flags 0x4000 in ./ibdata1
2020-11-04 14:17:50 0 [ERROR] InnoDB: Plugin initialization aborted with error Data structure corruption
2020-11-04 14:17:50 0 [Note] InnoDB: Starting shutdown...
2020-11-04 14:17:51 0 [ERROR] Plugin 'InnoDB' init function returned error.
2020-11-04 14:17:51 0 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
2020-11-04 14:17:51 0 [Note] Plugin 'FEEDBACK' is disabled.
2020-11-04 14:17:51 0 [ERROR] Could not open mysql.plugin table. Some plugins may be not loaded
2020-11-04 14:17:51 0 [ERROR] Unknown/unsupported storage engine: InnoDB
2020-11-04 14:17:51 0 [ERROR] Aborting


text:
Q: Bellman-Ford Algorithm- what value to use when there is no market? https://algs4.cs.princeton.edu/44sp/, section 4.4, Arbitrage Detection
If two currencies do not have a market, i.e. do not trade with each other, what value should be used for the currency trading matrix? zero/0?

A: Dylan answered:
You want it to be 0 before taking the logarithms like they suggest. After taking the logarithm and negating, you should use ∞.


text:
Q: Passing Same In Function but output are different Facing issue with @Detail when passing value in function through string 'ABC' the getting correct output but when passing via variable then getting incorrect output. What i am doing wrong.
 DECLARE @Detail varchar(4000)

 SELECT @Detail = detail FROM table1
 select @Detail

select * from dbo.SDF_SplitString(@Detail,' ',88)

INCORRECT OUTPUT

select * from dbo.SDF_SplitString(' 11/13/2019 12:15:0 11/13/2019 12:15:0 11/13/2019 14:30:0 BOM GOP SG  438   24A MR Kamleshwar  Prasad  4',' ',88)

CORRECT OUTPUT

A: OK, so that query I had you run is showing that the character between 12:15:0 11/13/2019 is a TAB (ascii character 9), not a space (ascii character 32)
This is why you get the output you do; you should perhaps consider to replace tabs with spaces before you split, or upgrade your split function so you can pass multiple chars to it for splitting (I assume that's what the ' ' parameter is for)
When you copied your value out of SSMS results grid it swapped the tabs for spaces already (SSMS converted the tabs to spaces), so when you ran it, it "looked the right output" when using the hardcoded value that contained only spaces..
..but the data in the DB table definitely has tabs! Always be careful copying stuff out of SSMS results grid; it drops characters, changes characters and cuts longer data off at the end, so it cannot be guaranteed to be an accurate reflection of what is in the table.
select * from dbo.SDF_SplitString(REPLACE(@Detail, CHAR(9), ' '),' ',88)

should give the output you expect..
If you have the option of changing this field so it doesn't have delimited data in it would be safer; splitting can sometimes give unusable results if the positions change


text:
Q: Shortening redundant calculation Is there a faster or shorter way of writing the following code to aviod calculating f(x) twice without defining another variable?
# could be any function or condition
if f(x) == 0:
    print(f(x))

# with additional variable
y = f(x)
if y == 0:
    print(y)

A: The walrus operator would save you an extra line (but not the assignment of y).
if (y := f(x)) == 0:
    print(y)

A: Define a print_if_0() function, and use that where you need it.
def print_if_0(n):
    if n == 0:
        print(n)

print_if_0(f(x))

You can generalize it to any test:
def print_if(f, val):
    if f(val):
        print(val)

print_if(lambda x: x == 0, f(x))

A: Use lru_cache to cache the results of f(x).
from functools import lru_cache

@lru_cache
def f(x):
    ...


text:
Q: C# WPF TextBlock cannot show chinese character which is created using eudcedit I have some Chinese Characters created using windows 10 eudcedit.Those characters can be shown in WPF MessageBox, but cannot be shown in WPF TextBlock.Can anyone provide any solution to solve the problems.
the created character can be shown in WPF MessageBox
However, WPF TextBlock cannot show it

A: I think that you want to specify that TextBlock using the font that you modified.

You want to include that font to your application too. Maybe you want to read this.
How to include external font in WPF application without installing it


text:
Q: Is there a way to partially tint bitmaps in Allegro? I'm programming a game in Allegro 5 and I'm currently working on my drawing algorithm. After calculation I end up with two ALLEGRO_BITMAP*-objects where one of them is my "scene" with the terrain drawn on it and the other one is a shadow-map.
The scene are simply textures of game-elements drawn on the bitmap.
The shadow-map is a bitmap using black colors for light and white colors for shadows rendered previously.
For drawing those bitmaps on the screen I use al_draw_scaled_bitmap(...) and al_set_blender(ALLEGRO_DEST_MINUS_SRC, ALLEGRO_ONE, ALLEGRO_ONE) to substract the white elements of the shadow-map from the scene to make those visible.
The problem I have is that I want to have all pixels that are white on the shadows-map to be tinted in a world-color, which has been calculated in every frame before, and all black elements simply not modified (gray means partially tinted).
The final color could be calculated like p.r * c.r + 1 - p.r with p = the pixel-color on the scene and c = the world-color for red, green and blue channels in rgb.
Is there any way to achieve a partial tinting effect in Allegro 5 (possibly without massive overdraw)?
I thought of using shaders, but I haven't found a solution to implement these with my ALLEGRO_BITMAP*-objects.

A: Allegro's blenders are fairly simple, so you would need a shader for this. Simply write a shader, and when you're drawing your shadow map al_use_shader the shader and then al_use_shader(NULL) when you're done. The shader can use the default vertex source which you can get with al_get_default_shader_source. So you only have to write the fragment shader. Your fragment shader should have a uniform vec4 which is the tint colour. You would also have x, y floats which respresent the x and y values of the destination. It would also have a sampler which is the scene bitmap (which should be the target, since you're drawing to it). You'd sample from the sampler at x, y (x and y should be from 0 to 1, you can get these by using xpixel / width (same with y)) and then do your calculation with the input colour, and then store the result in gl_FragColor (this text assume you're using GLSL (OpenGL). The same principle applies to Direct3D.) Check out the default shaders in src/shader_source.inc in the Allegro source code for more info on writing shaders.


text:
Q: Resolve HttpClient depends on URL (with/without Proxy) The task is to configure proxy of HttpClient depends on an URL. For example, if an URL contains "hostname.com", must be set.
What is the best practice?
Is the following a solution?
egister different HttpClients in DI as:
-- Configured typed HttpClients with different proxies for each service
services.AddHttpClient<Service1>().ConfigurePrimaryHttpMessageHandler(GetHttpHandlerSetter(s => s.Service1));
services.AddHttpClient<Service2>().ConfigurePrimaryHttpMessageHandler(GetHttpHandlerSetter(s => s.Service2));

-- Configured named HttpClient without proxy
services.AddHttpClient("NoProxy");

And Service1 and Service2 will resolve IHttpClientFactory:
    public class Service1
{
    readonly IHttpClientFactory _httpClientFactory;

    public IdgwConnectorManager(IHttpClientFactory httpClientFactory)
    {
        _httpClientFactory = httpClientFactory;
    }

    public void Get(string url)
    {
        if (url...)
        {
            _httpClientFactory.CreateClient(nameof(Service1));
        }
        else
        {
            _httpClientFactory.CreateClient("NoProxy");
        }
    }
}

A: You want to create a client that could be configured in a single location. So you should create a service that would take as ctor parameter the http client and in this place you could configure it for your needs.
Note: Typed clients are good candidates for a single backend endpoint. In case of proxied clients i would use named clients instead. And i would use a dictionary to store the client's name with proxy value.
In regards to how you can use the typed client you've created then a more robust solution would be this one:
public class Service1
{
    private readonly HttpClient _httpClient;

    public Service1(HttpClient client)
    {
        _httpClient = httpClient;
        // here you can setup headers, base address
    }

    //encapsulate all logic dealing with the endpoint.
}

Now working with DI you could inject this typed client in a consumer class
and from there you can decide whether proxy or non-proxy client is required.
public class ConsumerClass
{
    //The typed client can be injected and consumed directly
    private readonly Service1 _service;

    public ConsumerClass(Service1 service)
    {
        _service= service;
    }

    //Consume Service1
}


text:
Q: SQL Server CE timestamp handing What is the formatting difference between:
DateTime datetimenow = DateTime.Now.ToLocalTime();

and
long ticks = 634687637580000000;
DateTime createdTimestamp = new DateTime(ticks).ToLocalTime();

Which causes SQL Server CE to throw error

There was an error in a part of the date format. [ Expression (if
  known) =  ]

I am attempting to insert two timestamps into a SQL Server CE database. The current date time and a date time from the past. The current date and time (now) can be inserted into both target fields in the table, however when I use the createdTimestamp the error above is thrown.
The format when I review the locals in debug are exactly the same between the two.
The target fields are both of datetime data type.
Why might this error be thrown?
Edit:
I've just found it appears to only affect timestamps in the past. Now and future timestamps work fine.
Edit: adding code for SQL insertion.
Query is built dynamically by my own SQL Server CE class.
{INSERT timeline (TweetID,Author,TimestampOfTweet,TimestampOfCollected,TweetText) VALUES ('185941815562739713','twitterapi','15/12/2011 13:52:39','01/04/2012 15:58:58','TweetDeck access - Update : This issue has been resolved. http://t.co/2yub0tYL')}

Execution Code:
//Take built statement and apply to command text
cmd.CommandText = buildSqlStatement.ToString();

//execute insert
try
{
   cmd.Connection = sqlConn;
   sqlConn.Open();
   int rows = cmd.ExecuteNonQuery();
   string results = Convert.ToString(rows);
   return results;
}
catch(Exception ex)
{
   return ex.Message;
}
finally
{
   sqlConn.Close();
}

A: Never include values directly in your SQL - always use parameterized SQL instead.
Benefits:

*

*Clean separation of "code" (the SQL) from data (the values)

*Protection against SQL injection attacks

*Avoids error-prone conversions such as in this question.


text:
Q: Invalid object name dbo.Categories I am working on MVC 3. I am trying to create Simliar application as MVC Music Store         but I am getting an error. My code is below:
 using EFCodeFirst
 BookDBContext _db = new BookDBContext();
 [ChildActionOnly]
 public ActionResult GenreMenu()
 {
    var categories = _db.Category.ToList();//**Giving error at this pointInvalid object name dbo.Categories**
        return PartialView(categories);
 }

A: Verify that your BookDBContext contains a property called Category and that your database contains table dbo.Categories.


text:
Q: Bind object to ConverterParameter fails with XamlParseException in WP8.1 Silverlight Initial situation
I have a Windows Phone 8.1 Silverlight app where I have a model that contains several properties as shown below (just an excerpt of 3 properties, it has a lot more).
public class WorkUnit : INotifyPropertyChanged
{
    public DateTime? To
    {
        get { return Get<DateTime?>(); }
        set
        {
            Set(value);
            OnPropertyChanged("To");
            OnPropertyChanged("ToAsShortTimeString");
        }
    }
    public string ToAsShortTimeString
    {
        get
        {
            if (To.HasValue)
            {
                if (Type == WorkUnitType.StartEnd)
                    return To.Value.ToString(CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern);

                var duration = To.Value - From;
                return DateHelper.FormatTime(duration, false);
            }

            return null;
        }
    }
    public short? Type
    {
        get { return Get<short?>(); }
        set
        {
            Set(value);
            OnPropertyChanged("Type");
        }
    }
}

I'm using MVVMLight. There are several work units in an ObservableCollection that is bound to a list box on a Windows Phone page. The collection itself is part of a (WorkDay) view model which in turn is bound to the page itself.
What I want to do
I have a lot of properties in my model that are just used to format some properties for the UI. One such is ToAsShortTimeString which returns the time given by the To property, depending on the Type and the From properties, formatted as string.
In order to clean up my model I want to remove such formatter-properties as much as possible and use converters (IValueConverter) as much as possible. One further reason to move away from such properties is that the database that I use (iBoxDB) doesn't have member attributes like [Ignore] that is available for SQLite. So all properties with supported types are stored in the database. However, such formatter properties shouldn't be stored if possible.
What I did - 1st try
I now transformed all properties to converters and most of the time this was no problem. However, ToAsShortTimeString not just uses one property but 3 to format the input. Therefore, in XAML I need to provide either those 3 properties to the value converter or the work unit itself which is bound to the page.
public class WorkUnitToEndTimeStringConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var workUnit = (WorkUnit) value;
        if (workUnit.To.HasValue)
        {
            if (workUnit.Type == WorkUnitType.StartEnd)
                return workUnit.To.Value.ToString(CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern);

            var duration = workUnit.To.Value - workUnit.From;
            return DateHelper.FormatTime(duration, false);
        }

        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

So I changed the binding of the Text property in the TextBlock that shows the formatted To property to the WorkUnit that is bound to the page.
<TextBlock
    Grid.Column="2" Grid.Row="0"
    Grid.ColumnSpan="2"
    Text="{Binding WorkUnit,Converter={StaticResource WorkUnitToEndTimeStringConverter}}"
    FontSize="28"
    FontFamily="Segoe WP Light"
    Foreground="{StaticResource TsColorWhite}"/>

Unfortunately, when the To property changes in the model, even though OnPropertyChanged is called (see model code above), the text block doesn't get updated. I assume the reason is that only those controls are updated where some property is directly bound to the changed model property.
What I did - 2nd try
So as I need 3 properties from WorkUnit in order to correctly format To I changed the binding as follows. I bound Text to WorkUnit.To and set the ConverterParameter to the WorkUnit itself. With this change I hoped that whenever To is changed in the model and the value converter is called, I can format the time because I have all the info provided from the converter parameter (WorkUnit). (I'm not printing the updated converter here but I changed it to accomodate the change on the value and parameter input parameters)
<TextBlock
    Grid.Column="2" Grid.Row="0"
    Grid.ColumnSpan="2"
    Text="{Binding WorkUnit.To,Converter={StaticResource WorkUnitToEndTimeStringConverter},ConverterParameter={Binding WorkUnit}}"
    FontSize="28"
    FontFamily="Segoe WP Light"
    Foreground="{StaticResource TsColorWhite}"/>

Unfortunately, in this case a XamlParseException exception is thrown.
{System.Windows.Markup.XamlParseException: Failed to assign to property 'System.Windows.Data.Binding.ConverterParameter'. [Line: 61 Position: 18] ---> System.InvalidOperationException: Operation is not valid due to the current state of the object.
   at MS.Internal.XamlManagedRuntimeRPInvokes.TryApplyMarkupExtensionValue(Object target, XamlPropertyToken propertyToken, Object value)
   at MS.Internal.XamlManagedRuntimeRPInvokes.SetValue(XamlTypeToken inType, XamlQualifiedObject& inObj, XamlPropertyToken inProperty, XamlQualifiedObject& inValue)
   --- End of inner exception stack trace ---
   at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)}

Question
So is there a way to remove the formatter-property from my model so that I can keep my model as clean as possible? Is there sth. wrong with my converter? Is there any other way that I currently don't know of?

A: You could have a property in your WorkUnit called EndTimeString
public string EndTimeString
{
    get
    {
        string endTime = null;

        if (this.To.HasValue)
        {
            if (this.Type == WorkUnitType.StartEnd)
            {
                endTime = this.To.Value.ToString(CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern);
            }
            else
            {
                var duration = this.To.Value - this.From;
                endTime = DateHelper.FormatTime(duration, false);
            }
        }

        return endTime
    }
}

Of course, if To value changes, you want to notify the UI that the EndTimeString has also changed so that it picks up the new value:
public DateTime? To
{
    get { return Get<DateTime?>(); }
    set
    {
        Set(value);
        OnPropertyChanged("To");
        OnPropertyChanged("EndTimeString");
    }
}

And then just bind straight to that string:
...Text="{Binding WorkUnit.EndTimeString}" />

A: Unfortunately you can't bind to parameters.
This would be easy with MultiBinding but that's not available for Windows Phone (as you stated in your comment).
You could implement it yourself but if you are not really into it :), there are implementations trying to mimic this behaviour. One of them can be found from the joy of code.
There is a NuGet package called Krempel's WP7 Library which has above implemented for WP7 but it works on WP8.x as well.
Downside is that it can only bind to elements in visual tree, so you have to use (for lack of a better word) relaying UI elements to get the job done. I have used similar technique myself when I can't bind directly to a property I need to. One case is AppBar, you can't bind directly to enabled property, so instead I use something like
<CheckBox Grid.Row="0" IsEnabled="{Binding AppBarEnabled}"
          IsEnabledChanged="ToggleAppBar" Visibility="Collapsed" />

Anyway, below is full example, without any groovy patterns, on how you can achieve multibinding using above library. Try it out and see if it's worth the trouble. Options are that you have "extra" properties in your model or some extra elements and complexity in your view.
I used your WorkUnit model and Converter to make it more useful and easier to understand.
Outcome should be something like this.

MainWindow.xaml
<phone:PhoneApplicationPage
    x:Class="WP8MultiBinding.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:controls="clr-namespace:Krempel.WP7.Core.Controls;assembly=Krempel.WP7.Core"
    xmlns:conv="clr-namespace:WP8MultiBinding"
    mc:Ignorable="d"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    DataContext="{Binding RelativeSource={RelativeSource Self}}"
    shell:SystemTray.IsVisible="True">

    <phone:PhoneApplicationPage.Resources>
        <conv:WorkUnitToEndTimeStringConverter
              x:Key="WorkUnitToEndTimeStringConverter" />
    </phone:PhoneApplicationPage.Resources>

    <Grid x:Name="LayoutRoot">
        <Grid.RowDefinitions>
            <RowDefinition Height="80" />
            <RowDefinition Height="80" />
            <RowDefinition />
        </Grid.RowDefinitions>

        <!-- Multibinding & converter -->
        <controls:MultiBinding
            x:Name="MultiBinding"
            Converter="{StaticResource WorkUnitToEndTimeStringConverter}"
            NumberOfInputs="3"
            Input1="{Binding ElementName=Type, Path=Text, Mode=TwoWay}"
            Input2="{Binding ElementName=From, Path=Text, Mode=TwoWay}"
            Input3="{Binding ElementName=To, Path=Text, Mode=TwoWay}" />

        <!-- Output from multibinded conversion -->
        <TextBox Text="{Binding ElementName=MultiBinding, Path=Output}" Grid.Row="0" />
        <!-- Update WorkUnit properties -->
        <Button Click="UpdateButtonClick" Grid.Row="1">Test MultiBinding</Button>

        <!-- Helper elements, might want to set visibility to collapsed -->
        <StackPanel HorizontalAlignment="Center" Grid.Row="2">
            <TextBlock x:Name="Type" Text="{Binding WorkUnit.Type, Mode=TwoWay}" />
            <TextBlock x:Name="From" Text="{Binding WorkUnit.From, Mode=TwoWay}" />
            <TextBlock x:Name="To" Text="{Binding WorkUnit.To, Mode=TwoWay}" />
        </StackPanel>
    </Grid>
</phone:PhoneApplicationPage>

MainWindow.xaml.cs
using System;
using System.ComponentModel;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Windows;
using Microsoft.Phone.Controls;

namespace WP8MultiBinding
{
    public partial class MainPage : PhoneApplicationPage
    {
        public MainPage()
        {
            InitializeComponent();
            WorkUnit = new WorkUnit()
                {
                    To = DateTime.Now.AddHours(5),
                    From = DateTime.Now,
                    Type = WorkUnitType.StartEnd
                };
        }

        public WorkUnit WorkUnit { get; set; }

        // Ensure bindings do update
        private void UpdateButtonClick(object sender, RoutedEventArgs e)
        {
            WorkUnit.Type = WorkUnit.Type == WorkUnitType.StartEnd ?
                            WorkUnit.Type = WorkUnitType.Other :
                            WorkUnit.Type = WorkUnitType.StartEnd;

            WorkUnit.From = WorkUnit.From.AddMinutes(60);
            if (WorkUnit.To.HasValue)
                WorkUnit.To = WorkUnit.To.Value.AddMinutes(30);
        }
    }

    public enum WorkUnitType
    {
        StartEnd,
        Other
    }

    public class WorkUnit : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private WorkUnitType _type;
        private DateTime _from;
        private DateTime? _to;

        public WorkUnitType Type
        {
            get { return _type; }
            set { _type = value; OnPropertyChanged(); }
        }

        public DateTime From
        {
            get { return _from; }
            set { _from = value; OnPropertyChanged(); }
        }

        public DateTime? To
        {
            get { return _to; }
            set { _to = value; OnPropertyChanged(); }
        }

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            var handler = PropertyChanged;
            if (handler != null)
                handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    // Multivalue Converter
    public class WorkUnitToEndTimeStringConverter : Krempel.WP7.Core.Controls.IMultiValueConverter
    {
        private const string DateFormat = "M/d/yyyy h:mm:ss tt";

        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            // Index: 0 = Type, 1 = From, 2 = To
            if (values[2] != null)
            {
                var type = (WorkUnitType) Enum.Parse(typeof (WorkUnitType), values[0].ToString());
                var from = DateTime.ParseExact(values[1].ToString(), DateFormat, CultureInfo.InvariantCulture);
                var to = DateTime.ParseExact(values[2].ToString(), DateFormat, CultureInfo.InvariantCulture);

                if (type == WorkUnitType.StartEnd)
                    return to.ToString(CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern);

                var duration = to - from;
                return duration; // DateHelper.FormatTime(duration, false);
            }

            return null;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

}


text:
Q: How to find estimator for $\lambda$ for $X\sim \operatorname{Poisson}(\lambda)$ using the 2nd method of moment? So an estimator for for $\lambda$ using the first method of moment is simply the sample mean:
$$\mu_1 = E(X) = \lambda = \bar{X} = \hat{\mu_2}$$
For the second moment,
$$\operatorname{Var}(X) = E(X^2) - E(X)^2$$
$$\lambda = E(X^2) - \lambda^2$$
$$\mu_2 = E(X^2) = \lambda + \lambda^2$$
$$s^2 = \frac{1}{n}\sum_{i=1}^n (X_i - \bar{X})^2$$
$$s^2 = \frac{1}{n}\sum_{i=1}^n X_i^2 - \bar{X}^2$$
$$\frac{1}{n}\sum_{i=1}^n X_i^2 = s^2 + \bar{X}^2$$
$$\hat{\mu_2} = s^2 + \bar{X}^2$$
Making $\mu_2 = \hat{\mu_2}$, we get:
$$\mu_2 = \lambda + \lambda^2 = s^2 + \bar{X}^2 = \hat{\mu_2}$$
$$ \lambda + \lambda^2 = s^2 + \bar{X}^2$$
From here I've no idea how to factorise it so I have $\lambda$ all on one side.

A: So you have three potential estimators:

*

*The first, $\bar X$ is unbiased and has the smallest
variance among unbiased estimators.

*The second, $S^2$
is also unbiased, but has much larger variance than $\bar X.$

*The third is given in @JimB's comment. It is unbiased
and its variance is not much larger than the variance of $\bar X.$
in the R simulation below, SDs of estimators are given instead of their variances. With $m = 100\,000$ iterations we can expect about two significant digits
of accuracy.
set.seed(2020)
m = 10^5;  n = 10;  lam = 3
x = rpois(m*n, lam)
MAT = matrix(x, nrow=m)
a = rowMeans(MAT)
v = apply(MAT, 1, var)
est.1 = a
mean(est.1);  sd(est.1)
[1] 3.0008      # aprx 3 (unbiased)
[1] 0.5484283   # smallest variability
est.2 = v
mean(est.2);  sd(est.2)
[1] 2.99409     # aprx 3 (unbiased)
[1] 1.518167    # largest variability of the 3
est.3 = .5*(sqrt(4*v+4*a^2+1)-1)
mean(est.3);  sd(est.3)
[1] 2.994443    # aprx 3 (unbiased)
[1] 0.581836    # slightly more variable than mean

par(mfrow=c(3,1))
mn = min(est.1, est.2, est.3)
mx = max(est.1, est.2, est.3)
 hist(est.1, prob=T, xlim=c(mn,mx), col="skyblue2")
 hist(est.2, prob=T, br=60, xlim=c(mn,mx), col="skyblue2")
 hist(est.3, prob=T, xlim=c(mn,mx), col="skyblue2")
par(mfrow=c(1,1))


text:
Q: How can I get JBehave to either override or skip the "@BeforeStories" for only a few specific stories? We have a @BeforeStories in a common file for our JBehave / Java / Selenium automation project that does some set up steps that we need for most story files in our automation project.  But, there are a few new story files in which we do not want to run everything in the @BeforeStories.  Ideally, I could just remove some of these items from the @BeforeStories if they do not apply to every .story file.  This actually is our end goal, but is not something we want to do at this moment as it would affect a lot of existing tests.  Anyways, for the time being, if I could override the @BeforeStories for only a few story files, that would work.  Then, I could take the parts of the @BeforeStories that I want to run for the new .story files and then leave out the other parts that I do not want to run for the new .story files I am creating.  Skipping the @BeforeStories would also work for these new .story files as I could find other ways to handle the necessary set up steps for the new .story files ( i.e. add a "@BeforeStory" to the new .story files to handle the necessary set up steps in the new .story file for example ).  Is an override or skip of the @BeforeStories possible?  Thanks in advance for any advice.

A: Your best solution, in my opinion, and what I do with my stories, is to have a base steps class that contains @BeforeStories and has only the common steps necessary for all stories.  Then I place a @BeforeStory in each steps class to address the requirements specific for that story.
As an example, in my Appium test suite, I place the code to start the Appium Server and the code to initialize my Extent Reports object in the @BeforeStories in the base class.
However, as each story has its own application, I don't establish the connection there but do it in the @BeforeStory of each steps class, along with further defining the Extent Reports object, and launching the emulator, if applicable.
I originally had those @BeforeStory steps in my base class @BeforeStories until I had multiple stories to run.


text:
Q: Check my hash contains all parameters rails Hi want to check that my hash contains all parameters or not e.g
product => {name: 'Test Product', sku: 'test_123', price: '' }

This is my hash, in this hash price parameter contains empty value so how i gonna check it wither price is empty or not using rails function in one line.
Thanks

A: I hope this will work for you.
product.all? {|k,v| !v.empty?}

If there are any value is missing then it will return false.

A: you can try this by ruby way
product.values.all? {|x| !x.blank? }

for rails use model validation for that attribute
validates :price, presence: true, allow_blank: false

A: Here I found another simple solution may be this will also help in case if nil is present.
product.values.include? "" and product.values.include? nil

Thanks


text:
Q: HTTPServletRequest getServerPort returning -1 Today I found the little surprise that getServerPort() can return a -1. I use the port to build the hostname like this:
String hostName = request.getServerName().toString();
Integer urlPort = request.getServerPort();

if((urlPort != null) && (urlPort.intValue() != 80) && (urlPort.intValue() != 443) && (urlPort.intValue() != -1)) {
    hostName += ":" + urlPort;
}

*

*Why is returning a -1? I expected it would always be 80/443

*Is there a prettier way to build the hostname?

A: See: http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getServerPort()
It will return -1 if the port was not specified in the URL.
Typically in a browser, it is common to access http without the port, which the browser will default to 80.
Likewise, https defaults to 443;
You can't depend or expect the port to be specified in all cases and should code to check that. You are checking for port == -1, checking for null is unnecessary as the method returns a primitive int and will never be null.
If you want to detect http or https, then use the
getScheme() method no the request: http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getScheme


text:
Q: Массив байт в изображение Мне нужно создать двумерный массив и конвертировать его в изображение, заполнив при этом каким-то любым символом. Как это можно сделать?

A: Вот простой пример, отрисовывающий прямоугольники согласно данным из массива.
Аналогично можно и работать с пикселами, только размер массива должен быть побольше, чтобы что-то увидеть.
 private void button1_Click(object sender, EventArgs e)
        {
            int[,] array2D = new int[,] { { 0, 1, 0 }, { 1, 0, 1 }};
            Graphics dc = this.CreateGraphics();
            Brush[] brushes = {new System.Drawing.SolidBrush(System.Drawing.Color.Black),
                               new System.Drawing.SolidBrush(System.Drawing.Color.White) };
            for (int i = 0; i < 2; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    dc.FillRectangle(brushes[array2D[i, j]], j * 20, i * 20, 20, 20);
                }

            }
        }


text:
Q: Unzip script password Ok here is my script
    #!/bin/bash
cd /var/backups/System/
unzip Themes.zip
exit 0

I need the script to put in the password automatically when unzipping the protected zip file which is the Themes.zip. Since the user don't know the password I need it to be enter through the script when extracting the zip archive. Hope this makes since?

A:
unzip -P password Themes.zip

exit 0

A: Use the -P flag for password. From man unzip:
-P password
              use  password to decrypt encrypted zipfile entries (if any).  THIS IS INSECURE!  Many multi-user operating systems provide ways for any user to see the current command line of any other user; even on stand-alone systems there is always the threat of over-the-shoulder peeking.  Storing the plaintext password as
              part of a command line in an automated script is even worse.  Whenever possible, use the non-echoing, interactive prompt to enter passwords.  (And where security is truly important, use strong encryption such as Pretty Good Privacy instead of the relatively weak encryption provided by standard  zipfile  utili-
              ties.)


text:
Q: Where does the parameter go in a callback? So a basic example of what I am wondering:
First I create an object with a callback, initiated like this.
lblogin.loginlightbox ("AddCallback", function(){ // this function is the callback

    // print true on success from callback in second snippet
    // or
    // print false on fail from callback in second snippet

});

Then from within the lightbox object the callback is set at self.options.curHandler, where self is a reference to the lightbox.
if(success) //arbitrary condition
  self.options.curHandler(true);
else
  self.options.curHandler(false);

The callback does work properly and everything, I am just wondering if it is possible to access these true/false values from the first code snippet. I am unable to find out where they go.
Thank you.

A: From what I understand, you just have to add a variable to access the arguments passed to your callback method.
lblogin.loginlightbox ("AddCallback", function(value){ // this function is the callback
    //You can use the value passed to callback here (boolean in your case)
});

A: Anonymous functions take parameters in exactly the same way named ones do, but you've declared a function with no parameters as your callback.
The following are all equivalent (as far as this behaviour is concerned):
function myCallback(someArg) { console.log(someArg); }
myCallback('hello');

function myCallback(someArg) { console.log(someArg); }
something.test.callback = myCallback;
something.test.callback('hello');

something.test.callback = function(someArg) { console.log(someArg); }
something.test.callback('hello');

A: Given this syntax:
var a = 1;
// or this could be an Ajax response handler, or some other asynchronous function
setTimeout(function(){
   a = 2;
   var b = 7;
   alert('something');
},1000);
alert(a);

*

*You will always receive an alert of "1". This is because that inner function is called after the alert is called. This means the value of a has not yet changed. You may want to look into asynchronisity.

*You would not be able to access b, because b only exists in the inside function. This is something called "variable scoping".

*You cannot access the value of 'something' because that isn't assigned to a variable at all.


text:
Q: updateLastConsumedMessageIndex freezes causing no update in messages When component is mounted the channel is either grabbed from existing or created a new. This channel is later saved in the state for persist-ency in component. When the component is clicked all the channel messages are updated to consumed.
The Code belongs to the 'Today's Shift Channel' column. The Right side code is separate.
Senario : When I click a User onTaskSelect is called which triggers the whole user chat in right side after setting all the messages consumed. here problem 1 and 2 occurs. Now I click another user and click back to previously clicked user problem 3 occurs
Problems :
1) It does not update the consumed messages and always return zero.
2) It stops receiving the new messages from the .on listener called in joinOrCreate function.
3) on recurrent click response with error
    SyncError: Access forbidden for identity (status: 403, code: 54007)
    at mapTransportError (http://localhost:3000/static/js/0.chunk.js:162153:12)
    at http://localhost:3000/static/js/0.chunk.js:162210:20
NOTE : Channels are set once and never left unless page refreshes
NOTE : The whole chat on right side is working fine and is in separate module.
NOTE : The Client was initialized at the start of application as context which persists for the whole lifecycle of application from opening to closing.
const TaskCard = props => {

    const [lastMessage, setLastMessage] = useState({})
    const [open, setOpen] = useState(false)
    const [unread, setUnread] = useState(0)
    const [channel, setChannel] = useState({})

    const joinOrCreate = useCallback(async() => {
        try{
            const fetchedChannel = await props.client.getChannelByUniqueName(props.task.id.toString())
            let joined = fetchedChannel
            if(fetchedChannel.state.status !== "joined") {
                joined = await fetchedChannel.join()
            }
            console.log()
            joined.getMessages()
            .then(messages => {
                if(messages.items.length > 0) {
                    if(joined.lastConsumedMessageIndex < messages.items.length - 1) {
                        setUnread(true)
                    }
                    const recent_message = messages.items[messages.items.length - 1]
                    const limit_message = recent_message.body.slice(0,14)
                    setLastMessage({
                        body: limit_message.length === 14? (limit_message + '...') : limit_message,
                        time: recent_message.timestamp,
                        index: recent_message.index,
                    })
                }
            })
            joined.on('messageAdded', messageUpdated)
            setChannel(joined)
        }
        catch(ch) {
            console.log(ch)
            try{
                const newChannel = await props.client.createChannel({
                    uniqueName: props.task.id.toString(),
                    friendlyName: 'General Chat Channel'
                })

                let joined = newChannel
                if(newChannel.state.status !== "joined") {
                    joined = await newChannel.join()
                }
                joined.getMessages()
                .then(messages => {
                    if(messages.items.length > 0) {
                        const recent_message = messages.items[messages.items.length - 1]
                        setLastMessage({
                            body: recent_message.body,
                            time: recent_message.timestamp,
                        })
                    }
                })
                joined.on('messageAdded', messageUpdated)
                setChannel(joined)
            }

            catch(e) {
                console.log(e)
            }
        }
    }, [props.client, props.task.id])

    const messageUpdated = message => {
        const limit_message = message.body.slice(0,14)
        setLastMessage({
            body: limit_message.length === 14? (limit_message + '...') : limit_message,
            time: message.timestamp,
            index: message.index
        })
    }

    const onTaskSelect = () => {
        // console.log(lastMessage.index)
        console.log(channel.uniqueName)
        if(lastMessage.body) {
            channel.updateLastConsumedMessageIndex(+lastMessage.index)
            .then(res => {
                console.log(res)
            })
            .catch(e => {
                // console.log(props.client)
                // console.log(channel)
                console.log(e)
            })
        }
        props.onTaskClick(props.task.id.toString())
    }

    useEffect(() => {
        if(props.channelId === props.task.id) {
            setOpen(true)
            setUnread(false)
        }
        else {
            setOpen(false)
        }
    }, [props.channelId, props.task.id])

    useEffect(() => {
        joinOrCreate()
    }, [joinOrCreate])

    useEffect(() => {
        if(channel.lastConsumedMessageIndex < lastMessage.index && !open) {
            setUnread(true)
        }
    }, [channel.lastConsumedMessageIndex, lastMessage, open])

return (
        <Row key={props.task.id} >
            <Col className='justify-center'>
                <Card className={'more-than-90 ' + (open? 'background-active' : null)}
                    onClick={e => onTaskSelect()}
                >
                    <Row>
                        <Col md={2} style={{alignSelf: 'center', paddingLeft:'15px'}}>
                            {
                                props.task.worker.pic_url === "" || props.task.worker.pic_url === null ?

                                    {props.task.worker.first_name[0] + props.task.worker.last_name[0]}

                                :
                                <Image width={50} height={50} src={props.task.worker.pic_url} roundedCircle />
                            }
                        </Col>
                        <Col md={10}>
                            <Row>
                                <Col md={8}>

{props.task.worker.name}

                                </Col>
                                <Col>

{lastMessage.time? moment(lastMessage.time).format('hh:mm A') : null}

                                </Col>
                            </Row>
                            <Row>
                                <Col md={8}>

{lastMessage.body? lastMessage.body : null}

                                </Col>
                                <Col>
                                    {
                                        unread ?
                                        <FontAwesomeIcon
                                            icon={faEnvelopeOpenText}
                                            size="lg"
                                            color={"#0064bb"}
                                        />
                                        :
                                        null
                                    }
                                </Col>
                            </Row>
                        </Col>
                    </Row>
                </Card>
            </Col>
        </Row>
    )
}

A: Twilio developer evangelist here.
I think Will Sams has a good point in their comment. You do need to set an unread index to start with for a channel to then have a valid unread index. From the docs:

Note: Chat does not automatically set the Consumption Horizon. If you do not explicitly set this within your application, no Consumption Horizon will exist for a User within the Channel. Without a Consumption Horizon, your user's Consumption Horizon (read status) will not synchronize correctly across clients. If a user does not have a Consumption Horizon set on a channel, getting unconsumed messages will always return 0. If a member of a Channel has no consumption status, their last consumed index and timestamp will be null or 0 depending on the platform.

So, when creating a channel, I would set the channel's messages to unconsumed to kick off that measure. You can also use the function setAllMessagesConsumed rather than having to read the index of the last message.
I also noticed that when you set the last message you miss setting its index at one point:
                        const recent_message = messages.items[messages.items.length - 1]
                        setLastMessage({
                            body: recent_message.body,
                            time: recent_message.timestamp,
                        })

which could cause trouble.
I am concerned about the way your callbacks and effects are set up. When you trigger onTaskSelect it looks as though you send the task ID back to the parent.
props.onTaskClick(props.task.id.toString());

Presumably this is so you can see all the messages in the main panel.
However, I also assume this sets a task in the parent, which is then passed as props.tasks to this child. The joinOrCreate callback is set to update when props.task.id is updated and useEffect is predicated on joinOrCreate changing. So my guess is that whenever you change between tasks you trigger the cleanup and re-evaluation of joinOrCreate. Except there is no cleanup function, so you end up reloading the channel, for each of these components, each time. I would guess that had something to do with breaking the events and the eventual errors you get when you click again.
Instead, I would probably re-architect this so that the TaskCard component doesn't control the lifecycle of the channel object. I would load and join the list of channels you intend to render in a parent component and then pass the channel object to the TaskCard. That would simplify the components as the parent would deal with the data and the TaskCard could handle just rendering. It would also mean that when the status of a card is changed (from showing to not showing) then you are only re-rendering the data. This way, you could also share the channel object between the TaskCard and the chat view on the right of your screenshot (otherwise I'm guessing you have to load it in that component too, and that's probably not helping either).
These are just some ideas based on what I can see in your application. I hope they help!


text:
Q: Multiple projects not showing up on SONARQUBE dashboard I am trying to show multiple projects on which I run the analysis on my SONARQUBE dashboard. However when I start analyzing a new project, the old one goes away from the dashboard and just the new one shows up.
I am using SONARQUBE 5.2
Can it be achieved? The dashboard should show all the projects on which I run the analysis.

A: At a guess, you're using the same sonar.projectKey value for each analysis, forcing a replacement each time. Provide a unique value for the project key, and you should get the behavior you expect.
AND you should upgrade at your earliest convenience. At this writing, the current version of SonarQube is 7.1, and the current LTS is 6.7.3. Note that the migration path from 5.2 is first 5.6.*, then 6.7.3, and then optionally 7.1.