text:
Q: Why cURL send me 400 and 200 on last url I have some code to get the Status Code with cURL. All the code works fine, but when I put more than 1 line on the textarea, the response return me just 200 on the last url
1.Define my own function
2.Trim the line from textarea
3.Call the function N times

Somebody know why?
<?php
function get_http_response_code($url) {

    $handle = curl_init($url);

    curl_setopt($handle, CURLOPT_NOBODY, true);
    curl_setopt($handle, CURLOPT_HEADER, true);
    curl_setopt($handle, CURLOPT_HTTPGET, true);
    curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);

    /* Get the HTML or whatever is linked in $url. */
    $response = curl_exec($handle);

    /* Check for 404 (file not found). */
    $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
    if($httpCode == 200 || $httpCode == 300  ) {
        echo "url buscada OK : " . $url . "status: ".$httpCode."
";

    }else{
        echo "url buscada : " . $url . "status: ".$httpCode."
";
    }

    curl_close($handle);

    }

    $text = trim($_POST['textareaname']);
    $textAr = explode("\n", $text);
    $textAr = array_filter($textAr, 'trim'); // remove any extra \r characters left behind

    foreach ($textAr as $line) {

    sleep(1);
    get_http_response_code($line);

    }

?>

<form action="" method="POST" role="form">
    <legend>Form title</legend>

        label
<textarea name="textareaname" id="input" class="form-control" rows="15" required="required"></textarea>

    <button type="submit" class="btn btn-primary">Submit</button>
</form>


text:
Q: What type of motor is this? So I recently bought a motorised pedicure set thinking it would be some amazing thing. However, I used it once and the batteries (4 AA) died after about half an hour and not before getting ridiculously hot.
I decided I would take it apart to see what mad electronics have gone into it, and it turns out it is literally just a button and then wired straight into the motor. So I have decided I would like to replace the motor with one that has a higher torque (was really not very powerful so didn't have much effect) as well as possibly a higher RPM.
After taking it apart and finding the motor, I tried to find out what type of motor it currently is but it has no markings or part numbers on it at all so I couldn't find out. I wanted to know this so I could know the characteristics of it and things like that so I know how to get a better motor that would provide a better product!
Here are some pictures of the motor in various stages of assembly and I was wondering if anyone could help out with regards to what type of motor it is, and if anyone has any comments/solutions to some of the issues I mentioned they would also be greatly welcomed!

As it might not be clear from the pictures, inside the 'drum' of the motor are two magnets that the coiled wire sits in.
I have taken the voltage and current readings of it and it is as follows:
Voltage: Anywhere between 4V - 12V it seems to work, towards 12V it starts going a little bit mental.
Current: Around 500 - 600mA.

A: It's just an ordinary brushed DC permanent-magnet motor.

A: It is a DC motor, like those used in radio-controlled toys or models. This in particular is a permanent magnet motor. You should try to determine the supply voltage.
Append: For a 6V DC motor, maybe this is a good reference.

A: You don't want a motor with higher torque.  The torque is low on purpose.
If it had higher torque, you could grind right through a finger nail or the tip of your finger - ouch.  Even a buffing wheel could rub hard enough to get painfully hot.
If the motor is really horrible (real cheap trash) then you might need a better motor - but then I'd suggest a current limiter to keep the torque down.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Camera Orientation Change When Picture Taken. Even When Orientation is locked. I have an app that takes pictures. I want the orientation of the camera view to change when the device is rotated so the picture comes out in the correct orientation that it was taken as. I want this to work even when the device orientation is locked. What is the best way to go about doing this? Accelerometer/Core Motion? Advice and tutorials are much appreciated.

A: Seems like there is no way around CoreMotion. Reading out x/y accelerometer data is enough for determining the orientation. This blog post gives a good introduction: http://nshipster.com/cmdevicemotion/

A: Just an initial thought, have you considered rotating the picture after it's taken? I'm not sure whether this is the right solution for you as the display will still be oriented on the side when the photo is being taken. this would certainly get around the screen locking issue.
I hope this helps.
Kiran


text:
Q: How can I find all monitor purchases (not with monitor ID value, instead should use the term 'Monitor') I have two tables,

I need to find all monitor purchases (but not with monitor ID, instead I should use 'Monitor'). I have made code, but it takes the quantity for all products, not only for 'Monitor'.
The code I made:
select name, Price,sum(quantity)
from Products, Orders
where name='Monitor'

How can I fix this problem?

A: You need to link the rows of both tables. Right now you are creating the cartesian product, containing every row from the first table combined with every row from the second table. With your screenshot, that's going to be 9 rows in total.
SELECT name, Price, SUM(quantity)
FROM Products, Orders
WHERE name='Monitor'
AND Products.ProductId = Orders.ProductId

Or use JOIN directly to separate the filter condition from the join condition:
SELECT name, Price, SUM(quantity)
FROM Products
INNER JOIN Orders
ON Products.ProductId = Orders.ProductId
WHERE Products.name='Monitor'


text:
Q: pandas: Find closest matching dataframe I am working on personal project (work on spare time, by myself) and would like to ask if anyone can propose simple strategies for finding a similar dataframe to a selected one.
I have dataframes describing daily events, like temperature and humidity, sampled every 10 minutes. I want to get a dataframe of a day, and find among the other daily dataframes the one the best resembles the one I am looking for.
Now I understand this is a VERY large topic, which could involve AI in the end of the day. I am hoping people can point me to a simple to implement strategies, like minimal square differences, or share directions, experiences and/or links.
If you do feel I should study entry level AI, please let me know. Because I am doing this completely solo, with limited time, I am willing to compromise on the end result in detriment of getting this done at all.

A: One simple statistical approach would be to look at the correlation and/or covariance of the two data series.
Correlation : corr
Covariance : cov
See, http://pandas.pydata.org/pandas-docs/version/0.15.0/computation.html#correlation for usage


text:
Q: How to preg_match_all a set of words in any possible language? I have a website that people enter lists of words into.
These lists of words could be written in any language in the world.
How can I extract these lists of words from their input data if I do not know what language they are entering?
Is there some kind of match-all international alphabet symbol I am missing, or do I have to manually write up a set of brackets that will match every possible international letter?
Is this what I am looking for and just don't know it yet?

A: You can use Unicode character properties, for example:
preg_match_all('#[\p{L}\p{Pc}]+#u', $str, $matches);

[\p{L}\p{Pc}]+ gives you letters and connector punctuation. You can shorten that to \pL+.
Either way, you'd want to define "word" better. It is probably more than a sequence of some letters...

A: My recommendation is to define your own input convention - force them to input one word at a time, or one word per line in a textbox. Else, you will need a segmentation algorithm for each script (granted, it will be something trivial like "split on characters which have the Unicode word separator property" for the vast majority of scripts, but the remaining special cases are basically still open AI research topics).


text:
Q: how to fix kendo NumericTextBox format i'm building app using kendo (v. 2019.2.514). And i have strange error with number format by NumericTextBox.
At this moment i'm creating a form to modify products. Problem is that, i'm getting different results for my values.
Values are stored in database as floats. In model as well.
And i'm pretty sure that problem is with the format because when value is a natural number it's fine, but:
(first control format)
0.1 gives 1
0.05 gives 5
(2nd format)
1.2 gives 120000004768372 (which means the original value was multiplied by 1e+14)
0.3 gives 300000011920929 (* 1e+15)
that are my 2 kinds of NumericTextBox formats
@(Html.Kendo().NumericTextBox<float>().Name("Weight").Min(0).Value(Model.Weight).Format("#.## kg")
                    .Placeholder($"{Language.translate("Weight")} (kg)").HtmlAttributes(new { validate = true })
                )

@(Html.Kendo().NumericTextBox<float>().Name("upTo7").Min(0).Format("#.## €").Value(Model.Price)
                    .Placeholder(Language.translate("Price up to x days").Replace("x", "7")).HtmlAttributes(new { validate = true })
                )

I've already tried formats like #.00, n2 and nothing works for me
I just want to display these numbers properly

A: The problem seems to be in with your Model because I just tried the following code and it works fine:
@(Html.Kendo().NumericTextBox<float>().Name("Weight").Min(0).Value(0.05f).Format("#.## kg")
                    .Placeholder("Weight (kg)").HtmlAttributes(new { validate = true })
                )

@(Html.Kendo().NumericTextBox<float>().Name("upTo7").Min(0).Format("#.## €").Value(1.2f)
                    .Placeholder("Price up to 7 days").HtmlAttributes(new { validate = true })
                )

Output:
0.05 kg
1.2 €

I suggest using decimal data type in your database instead of float because approximate numeric data types do not store the exact values specified. See Difference between numeric, float and decimal in SQL Server for more details.

A: You can try the this..NumericTextBox

@(Html.Kendo().NumericTextBox<decimal>().Name("Weight").Min(0).Value(0.05f).Format("#.## kg")
 .Decimals(3)
                    .Placeholder("Weight (kg)").HtmlAttributes(new { validate = true })

And add Decimal attribute to show how many decimal places need to see in your textbox


text:
Q: How to validate add row functionality in using ids in jQuery I have add row functionality. I created dynamic IDs for those input boxes. now I want to validate. When I type department name automatically highlight relationship field (this is my requirement). I tried to work this functionality but failed. Please help how to do this work.

      Dependent Name(s)

        <input type="text" class="form-control name1" id="name1" onblur="getValue(this)" name="name1[]"/>

     Relationship(s)

        <input type="text" class="form-control relationship1" id="relationship1" name="relationship1[]"  />

A: The problem lies in $(selectedid)
You must change to $("#"+selectedid)

A: Problem is obj.id is gives you only plain id you have to concate with # when you apply any jquery.
Just try this.
 selectedid = $(obj).attr('id');
 selectedindexid =  $("#"+selectedid).parent().parent().next('div').next('div').find('input:text').attr('id');
 alert(selectedindexid);


text:
Q: List view with button and popup Am really struck with this issue..
I have a list view which contains one button and when click on that button it should show a pop up. I have implemented the list view but pop up is not showing on the clicked button position..
sample code given below
public View getView(int position, View convertView, final ViewGroup parent) {
    View vi=convertView;
    if(convertView==null)
        vi = inflater.inflate(R.layout.list_row, null);

    vi.findViewById(R.id.statusImage).setOnTouchListener(new View.OnTouchListener(){
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
             x=(int) event.getX();
             y=(int) event.getY();
            showPopup(x,y);// calls popup
            return false;

    public void showPopup(int xk , int ys) {

  LayoutInflater inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 View layout = inflater.inflate(R.layout.popup_layout,null);
    pwindo = new PopupWindow(layout, 300, 250, true);
    pwindo.showAtLocation(layout, Gravity.NO_GRAVITY, xk,ys);
    pwindo.setOutsideTouchable(true);
     pwindo.setTouchable(true);
     pwindo.setBackgroundDrawable(new BitmapDrawable());
     layout.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {
                pwindo.dismiss();
                return true;
            }

        });

}

public class MyAdapter extends BaseAdapter{

private Activity activity;
private PopupWindow pwindo;
Point p;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
String value="0";
ImageButton imgBn ;
int x,y;
public MyAdapter (Activity a, ArrayList<HashMap<String, String>> d) {
    activity = a;
    data=d;
    inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

}

public int getCount() {
    return data.size();
}
/*
public boolean onTouchEvent(MotionEvent event) {
    // MotionEvent object holds X-Y values
    if(event.getAction() == MotionEvent.ACTION_DOWN) {

        x=(int) event.getX();
        y=(int) event.getY();

    }

    return true;
}*/
public Object getItem(int position) {

    HashMap<String, String> song = new HashMap<String, String>();
    song = data.get(position);
    return (song.get(JobsListing.KEY_ID));
}

public long getItemId(int position) {
    return position;
}

public View getView(int position, View convertView, final ViewGroup parent) {
    View vi=convertView;
    if(convertView==null)
        /*
           vi = inflater.inflate(R.layout.list_row, null);
    View imgView =   vi.findViewById(R.id.statusImage);
    imgView.setTag(position);
         */
        vi = inflater.inflate(R.layout.list_row, null);
    ImageView button = (ImageView) vi.findViewById(R.id.statusImage);
    // Get the x, y location and store it in the location[] array
    // location[0] = x, location[1] = y.
    button.setTag(position);

    button.setOnTouchListener(new View.OnTouchListener(){
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
              int y;
              if(v.getTag() == null ) {
                   y=100;
              } else {
                  int position  = (Integer) v.getTag();
                   y = (1+position)*v.getHeight();
              }

              int x= (int) v.getRight();
              showPopup(x,y);// calls popup
              return false;
        }
    });
    /*
   vi.findViewById(R.id.statusImage).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            //int OFFSET_X = 30;
              // int OFFSET_Y = 30;
            showPopup();
            //LayoutInflater inflater = (LayoutInflater) vi.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
             //  LayoutInflater inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            //LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        //  View layout = inflater.inflate(R.layout.popup_layout,null);
            //pwindo = new PopupWindow(layout, 300, 250, true);
            //pwindo.showAtLocation(layout, Gravity.RIGHT, p.x + OFFSET_X, p.y + OFFSET_Y);
            //pwindo.setOutsideTouchable(true);
            // pwindo.setTouchable(true);
            // pwindo.setBackgroundDrawable(new BitmapDrawable());

        }
    });*/
   TextView artistd = (TextView)vi.findViewById(R.id.artistd);
   TextView titleB = (TextView)vi.findViewById(R.id.titleB);
   TextView title = (TextView)vi.findViewById(R.id.title); // title
   TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name
   ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image
   String fontPaths = "fonts/HelveticaNeue-Bold.otf";
    Typeface tfs = Typeface.createFromAsset(activity.getAssets(), fontPaths);
    title.setTypeface(tfs);
    artist.setTypeface(tfs);
    titleB.setTypeface(tfs);
    artistd.setTypeface(tfs);

    HashMap<String, String> song = new HashMap<String, String>();
    song = data.get(position);

    // Setting all values in listview
    title.setText(song.get(JobsListing.KEY_TITLE));
    artist.setText(song.get(JobsListing.KEY_ARTIST));
    artistd.setText(song.get(JobsListing.KEY_PLACE));
    titleB.setText(song.get(JobsListing.KEY_CLIENTNAME));
    return vi;
}

public void showPopup(int xk , int ys) {
    System.out.println("xk>>>"+xk+"xk<<<<"+ys);
  LayoutInflater inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 View layout = inflater.inflate(R.layout.popup_layout,null);
    pwindo = new PopupWindow(layout, 300, 250, true);
    pwindo.showAtLocation(layout, Gravity.NO_GRAVITY, xk,ys);
    pwindo.setOutsideTouchable(true);
     pwindo.setTouchable(true);
     layout.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {
                pwindo.dismiss();
                return true;
            }

        });

}

}

A: event.getY() return Y position relative to parents so we have to find position of row which  is clicked and height of each row to calculate y position.
This code display popup at which row imageview is clicked and with littele modification it will be your use.
    @Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder = null;
    if(convertView == null) {
        LayoutInflater inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.list_row, null);
        holder = new ViewHolder();
        convertView.setTag(holder);

        holder.imgView = (ImageView) convertView.findViewById(R.id.txtViewClientName);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    holder.imgView.setTag(position);

    holder.imgView.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
             int y;
                if(v.getTag() == null ) {
                     y=100;
                } else {
                    int position  = (Integer) v.getTag();
                     y = (1+position)*v.getHeight();
                }

                int x= (int) v.getRight();
                showPopup(x,y);// calls popup
                return false;
        }

         private void showPopup(int x, int y) {
                LayoutInflater inflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View layout = inflater.inflate(R.layout.popup_layout,null);

                final PopupWindow pwindo = new PopupWindow(layout, 200, 300, true);
                pwindo.showAtLocation(layout, Gravity.NO_GRAVITY, x, y);
                pwindo.setOutsideTouchable(true);
                pwindo.setTouchable(true);

                layout.setOnTouchListener(new OnTouchListener() {

                    @Override
                    public boolean onTouch(View arg0, MotionEvent arg1) {
                        pwindo.dismiss();
                        return true;
                    }
                });

            }

    });

    return  convertView;
}

private static class ViewHolder {
    public ImageView imgView = null;
}

// popup_layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="200dp"
android:layout_height="200dp"
android:background="@android:color/darker_gray"
android:orientation="vertical" >

<TextView
    android:id="@+id/editText1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:ems="10"
    android:text="Popup" >
</TextView>

</LinearLayout>

   /// list_row   layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >

<ImageView
    android:id="@+id/statusImage"
    android:layout_width="wrap_content"
    android:src="@drawable/ic_launcher"
    android:layout_height="wrap_content"
    android:text="Button" />

</LinearLayout>

A: use this for the popup:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage(x + " - " + Y)
               .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {

                   }
               })
builder.create();


text:
Q: How does `sub rsp, 16` aligns the stack on Mac OSX? I'm currently learning x64 asm on Mac OSX using nasm.
I've come across the problem of aligning the stack, a necessary step for some system calls such as malloc, which is done with these instructions:
push rbp
mov rbp, rsp
sub rsp, 16
Can anyone explain me how the function prolog does align the stack ? I mean, if it's not already on a multiple of 16, why would sub rsp, 16 correct it ?
Let's say that esp = 0x35 , after sub rsp, 16, esp = 0x25 right ? So esp wasn't aligned on a multiple of 16 before the sub, and the sub didn't align it neither so I think I haven't quite understood what "aligning the stack" means.
Can someone tell me what I should understand when I read "the stack needs to be aligned on a 16 bytes boundary" ?

A: It doesn't align it, as you say it just keeps alignment. Obviously the sub rsp, 16 is only needed if you want to allocate space for 1-15 bytes of local variables. You should make sure the number there is the next multiple of 16 above the space needed, assuming the stack is already aligned. Note that the return address and the frame pointer also add up to 16 bytes, if you don't use a frame pointer you need to account for that too.
In general, the calling convention mandates that it be aligned in a particular way upon entry to all functions, so you just have to maintain that. The only place that is normally not the case is possibly at process or thread startup but that is usually taken care of by the system libraries.


text:
Q: Questions on supremum Is it true that $$\sup_{x\in\mathbb{R}}\frac{\left|\left(1+s\right)+tx\right|+\left|\left(1+t\right)x+s\right|}{1+\left|x\right|+\left|s+tx\right|}\geq1$$
for all $s,t\in\mathbb{R}$? Is it also true that $$\sup_{x\in\mathbb{R}}\frac{\left|\left(1+s\right)x+t\right|+\left|\left(1+t\right)+sx\right|}{1+\left|x\right|+\left|sx+t\right|}\geq1 \ ?$$
Any answer to either of the two questions would be highly appreciated.

A: If I denote
$$
f(s,t;x)=\frac{\left|\left(1+s\right)+tx\right|+\left|\left(1+t\right)x+s\right|}{1+\left|x\right|+\left|s+tx\right|},
$$
then for $t\ne0$
$$
f\left(s,t;-\frac{s}{t}\right)=\frac{1+|s/t|}{1+|s/t|}=1,
$$
hence the supremum over all $x\in\mathbb R$ is at least 1. If $t=0$, then
$$
f(s,0;x)=\frac{|1+s|+|x+s|}{1+|s|+|x|}
$$
and
$$
\lim_{x\to\pm\infty}f(s,0;x)=1,
$$
so the supremum is (at least) 1 as well.
A similar substitution $x=-t/s$ works for the second supremum.


text:
Q: Return distinct and null records from a mysql join query Is there any way to return distinct values with blank/null data from a table join. Best to explain with my example below.
Table "orders"
order_id | order_total
1        | 10
2        | 20
3        | 50

Table "order_items"
item_id | order_id | name     | qty_ordered | base_price | row_total
1       | 1        | Product  | 1           | 10         | 10
2       | 2        | Product  | 1           | 10         | 10
3       | 2        | Product2 | 1           | 10         | 10
4       | 3        | Product  | 2           | 10         | 20
5       | 3        | Product2 | 3           | 10         | 30

I'm trying to produce a result set that looks like this.
order_id | item_id | name     | qty_ordered | base_price | row_total | order_total
1        | 1       | Product  | 1           | 10         | 10        | 10
2        | 2       | Product  | 1           | 10         | 10        | 20
null     | 3       | Product2 | 1           | 10         | 10        | null
3        | 4       | Product  | 2           | 10         | 20        | 50
null     | 5       | Product2 | 3           | 10         | 30        | null

I only want the order_id and order_total once per order. I figure this is possible with some sort of join/distinct/sub query but alas nothing I've tried has worked so far.

A: Use:
SELECT x.order_id,
       x.item_id,
       x.name,
       x.qty_ordered,
       x.base_price,
       x.row_total,
       x.order_total
  FROM (SELECT CASE
                  WHEN @order = o.order_id THEN NULL
                  ELSE o.order_id
               END AS order_id,
               oi.item_id,
               oi.name,
               oi.qty_ordered,
               oi.base_price,
               oi.row_total,
               o.order_total,
               CASE
                  WHEN @order = o.order_id THEN NULL
                  ELSE o.order_total
               END AS order_total,
               @order := o.order_id
          FROM ORDER_ITEMS oi
          JOIN ORDERS o ON o.order_id = oi.order_id
          JOIN (SELECT @order := -1) r
      ORDER BY o.order_id, oi.item_id) x

A: SELECT * FROM order_items
LEFT JOIN orders
ON (
     order_items.order_id=orders.order_id
AND
     order_items.item_id=(
         SELECT MIN(item_id)
         FROM order_items a
         WHERE a.order_id=order_items.order_id
     )
)

This should work because the nested query always returns the same MIN(item_id) for each order, and it only joins for that item.
But this is a very, very ugly piece of sql. Don't do this.


text:
Q: How to pass the row number as argument to SUMIF() function? I have used the below code in my excel, getting run time error as object required.
Dim FoundCell As Excel.Range
Dim rows As Integer
Set FoundCell = Sheets("Sheet2").Range("A:A").Find(what:="Total", lookat:=xlWhole)
rows = FoundCell.row
rows = rows - 1
Range("C9").value = Application.WorksheetFunction.SumIfs(Range("A1:A" & rows), B9, Range("B1:B" & rows))

Thing is i knew the starting range of column, i need to pass the criteria and ending range of column as argument. can anyone help me to find the solution.???

A: You only need SUMIF. Additionally, condition in B9 is not properly qualified. Also, change rows to Long. See below:
Dim FoundCell As Range
Dim rows As Long
Set FoundCell = Sheets("Sheet2").Range("A:A").Find(what:="Total", lookat:=xlWhole)
rows = FoundCell.row
rows = rows - 1
Range("C9").Value = Application.WorksheetFunction.SumIf(Range("A1:A" & rows), Range("B9").Value, Range("B1:B" & rows))

Hope this helps.

A: First, I doubt if you have passed correct parameters to the function SumIfs.
You can refer to http://msdn.microsoft.com/en-us/library/office/bb239775(v=office.12).aspx for the syntax of the function.
And second, you are right in passing the range like this Range("A1:A" & rows)

A: Either you can send formula as string or use Worksheetfunction.Sumifs
Syntax
WorksheetFunction.SumIfs(<Sum Range>, <Criteria range>, <Criteria>)
Method 1 :
Range("C9").Formula = "=SUMIFS(B1:B6,A1:A6,B9)"
Method 2:
Range("C9").Value = WorksheetFunction.SumIfs(Range("B1:B" & rows), Range("A1:A" & rows), Range("B9"))


text:
Q: macOS users: PDF looks fuzzy in pdf-tools in emacs For all Mac users that have emacs installed, I have successfully installed pdf-tools but the PDF files looks fuzzy. Has anyone managed to increase the resolution?
In case it helps, I have a macOS Catalina (version 10.15.4)
Thanks a lot

A: You need to add
(setq pdf-view-use-scaling t
        pdf-view-use-imagemagick nil)

To enable the retina screen support


text:
Q: stackoverflowException I have written code below.but it will print this exception and i really don't know what is its problem,please help me thanks
CODE:
    private void fillMinAverageTime() {   //T(n) = O(n^3)
    for (int i = list.size() - 2; i >= 0; i--) {
        for (int j = i + 1; j < list.size(); j++) {
            for (k = i; k <= j; k++) {
                minOne = fillMinAverageTimeArray(i, j);
                if (min == 0.0) {
                    min = minOne;
                } else if (minOne < min) {
                    min = minOne;
                }
            }
            min = 0.0;
            minOne = 0.0;
            minAverageTimeArray[i][j] = min + probability[i][j];

        }

    }
}

private double fillMinAverageTimeArray(int i, int j) {
    if (i > j) {
        return 0.0;
    }
    if (i == j) {
        return minAverageTimeArray[i][i];
    }
   System.out.println(k+","+j+","+i);//EDITED

 **return (fillMinAverageTimeArray(i, k - 1) + fillMinAverageTimeArray(k + 1, j));**//the line tat throws this exception
}

Exception:
at OBST.MemoizedVersion.fillMinAverageTimeArray(MemoizedVersion.java:118)
at OBST.MemoizedVersion.fillMinAverageTimeArray(MemoizedVersion.java:118)
at OBST.MemoizedVersion.fillMinAverageTimeArray(MemoizedVersion.java:118)

EDITED: it will print:
2,3,2
3,3,2
1,2,1
2,2,1
1,3,1
1,3,2
1,3,2
1,3,2
1,3,2
1,3,2
1,3,2
1,3,2
1,3,2
1,3,2
1,3,2
1,3,2
1,3,2
1,3,2
1,3,2

A: You have written a recursive method. You have to be sure that it will terminate by reaching the base case, otherwise it could go into a loop until a stack overflow exception occurs - which is what is happening here. The easiest way to guarantee termination is to always ensure that you get closer to your base case on every call. Your base case here is that the arguments i and j at some point must become equal, so you should try to bring them at least one closer to each other at every step.
Here's the line that gives the problem:
return (fillMinAverageTimeArray(i, k - 1) + fillMinAverageTimeArray(k + 1, j));

This is just going to call your method with the same values repeatedly. Are you sure you didn't mean i + 1 and j - 1 instead of k + 1 and k - 1?

A: As Mark already said make sure that your recursive call terminates correctly.
If it still overflows then your recursion simply is to deep.
Hacky solution, use the JVM's -Xss flag to change the stack size.
Correct solution, use an iterative approach and roll your own stack.


text:
Q: There is Any response during getting data from SQLite database First, my situation has no error but any response when I touch the context menu 'delete'. It seem to computer remain can't readable state.
getAmount calss of DBHelper.java
public int getAmount(Integer id){
    int amount = 0;
    SQLiteDatabase db=this.getReadableDatabase();
    Cursor res = db.rawQuery("SELECT id, amount FROM uselist WHERE id="+id,null);
    amount=res.getInt(res.getColumnIndex(USELIST_COLUMN_AMOUNT));
    return amount;
}

Code above getAmount have used
@Override
public boolean onContextItemSelected(MenuItem item){
    int itemId = item.getItemId();
    switch (itemId){
        case R.id.context_item1 :
            Toast.makeText(this,"edit",Toast.LENGTH_SHORT).show();
            return true;
        case R.id.context_item2 :
            int amt=-mydb.getAmount(position);
            Toast.makeText(this,"delete",Toast.LENGTH_SHORT).show();
            mydb.deleteUseList(position);
            mydb.update("UPDATE uselist SET id = (id-1) WHERE id >"+ position+";");
            mydb.update("UPATE uselist SET balance = (balance+"+amt+") WHERE id>"+position+";");
            histories.clear(); //
            finish();
            startActivity(getIntent());
            return true;
    }
    return super.onContextItemSelected(item);
}

I guess something wrong in 'int amt=-mydb.getAmount(position);'code or getAmount class since the delete Toast not appear.

A: Try this:
public int getAmount(Integer id){
    int amount = 0;
    SQLiteDatabase db=this.getReadableDatabase();

    Cursor res = db.rawQuery("SELECT id, amount FROM uselist WHERE id="+id,null);

            // looping through all rows and setting value to variable
            if (res.moveToFirst()) {
                do {
                    amount=res.getInt(res.getColumnIndex(USELIST_COLUMN_AMOUNT));
                } while (res.moveToNext());
            }

     return amount;
   }


text:
Q: Is there a programmatical way to get Google Earth imagery dates for specific coordinates? I need to cite about 400 imagery locations in Google Earth for a project using this citation model: https://sites.google.com/a/tas.tw/mscitation/how/ge. This requires that I have the imagery date for each location (handily stored in a KML.  Unfortunately for me, I didn't know that I needed this when I initially created the KML placemarks. Is there a way to extract the imagery date somehow based on either the KML or the placemark coordinates? If I could get a KML file that shows imagery coverage by date, that would be sufficient. I am a GIS Specialist and could easily convert the KML to a shapefile in ArcGIS and do a simple location query to get the dates. I haven't been able to locate any such KML, however. Otherwise, I'll have to revisit each placemark and manually copy over the imagery date from the information bar in GE. Not a huge deal (I have already done that for about a quarter of them), but it occurred to me that there may be an easier (and quicker) way to do this in an automated fashion.
It seems like this may be helpful for anyone that needs to cite hundreds or thousands of Google Earth locations. I doubt this will be the last time I need to do this, as well.
Any suggestions are appreciated. Thanks!

A: If I understand your question correctly, you need the dates (like 1.2.2012) of when the particular images below your locations where taken / updated by Google?
From within GoogleEarth, I do not see a chance other then doing this manually for each of your bookmarks. There is simply no scripting capability.
As a chance, you might want to look at the GoogleEarth-plugin (Windows and MacOS only) for web-browsers. It has a javascript-API, which is documented here: https://developers.google.com/earth/documentation/reference/interface_g_e_plugin
Maybe digging deep in here ... solves your problem.
One last note: GoogleMaps also has an API, but the imagery sometimes differs with respect to GoogleEarth.


text:
Q: How to remove bullets from jquery autocomplete result My jquery-ajax autocomplete result shows a bulleted list. I want to remove the bullets. I don't understand where and what i need to change in jquery-ui-1.8.21.custom.css (downloaded from JQuery UI website).
Any suggestions would be highly appreciated.
Thanks in advance.

A: jQuery-ui-1.10.3
This works in Chrome, IE, and Firefox. It also removes the left margin where the bullet used to be. It's derived from w3Schools http://www.w3schools.com/CSS/css_list.asp
ul.ui-autocomplete {
    list-style: none;
    list-style-type: none;
    padding: 0px;
    margin: 0px;
}

A: change the css where it shows bullet property to

list-style:none

A: make sure the default ui autocomplete class contains list-style: none.
ul.ui-autocomplete {
    list-style: none;
}

A: This is a bug in jquery-ui v1.9.1 and was fixed in v1.10.3. It happens for IE10 and not 11 as noted in the jquery-ui defect report (8844).
The cross-browser workaround (tested in IE6 - 10, Firefox, Chrome, Safari, and Opera) is to apply the following CSS:
.ui-menu-item
{
  /* IE10 fix to remove bullets from showing outside of div*/
    list-style-image: url(data:0);
}

or just use a later version of jquery after v1.9.1.
NOTE: this is different than chrisvillanueva's answer to use list-style: none; just as one user posted similarly in the defect report, however that workaround wasn't accepted as cross-browser and it would seem that list-style-image: url(data:0); is a better alternative according to the defect.


text:
Q: How to call python script form java class I have a java web app where i need to use a simple web crawler to read html from webpages. I could not find any simple solution for this in java. But got a very simple python script that solve my problem. Now how to call that python script (.py) from my java class and also get the returned value from the python script .Thanks in advance .

A: First check out Calling Python in Java?
Another approach might be to call the python interpreter from the command line with a Java Process.  See Java Process with Input/Output Stream and Call python script within java code (runtime.exec)


text:
Q: Can't locate SBS 2011 Certification Authority Web interface Certification Authority    Installed
Certification Authority Web Enrollment Installed
Certification Enrollment Web Services Not Installed
Certification Enrollment policy web service Not Installed
This is under role services: I can't access
'http://$erverName/certserv'
What Is missing? any clue

A: After reinstalling Certification authority web Enrollment problem was fixed and now accissible via localhost --> certsrv


text:
Q: Laravel: How do I time limit a user to access a Route/Page? Example:
If a user clicks the 'Profile' button (which redirects to /profile route), so basically the Web will query like this ('select * from profile where id=1).
As far as my boss concern, he don't want the database flooded with query request. He wants a 20 seconds time limit, so if a user clicks the profile again (or refresh) less than 20 sec, then a prompt message would display "Checking your profile, please wait" instead of saying "Hey you are overloading database, please get back after 30sec".
He said that the purpose of this is to protect the database from multiple query request.
The profile is just an example.

A: Simple solution is using throttle middleware
In __contruct method in your controller. Add these line of code
// This mean: 3 hits per 1 minute
$this->middleware('throttle:3,1');


text:
Q: Change Detector Ref not working with Angular Material Dialog Box I need help to properly implement the ChangeDetectorRef.
What I am trying to do open a Mat Dialog Box on a click, but everytime I add the ChangeDetectorRef contructor the Dialog Box breaks, giving me the error
    NullInjectorError: StaticInjectorError(AppModule)[ViewAdvertComponent -> ChangeDetectorRef]:
      StaticInjectorError(Platform: core)[ViewAdvertComponent -> ChangeDetectorRef]:
        NullInjectorError: No provider for ChangeDetectorRef!
I might just be referencing them wrong, but even the documentation is too complex for my knowledge.
HomePage.ts
import { Component, OnInit, NgModule, ViewChild, ChangeDetectorRef } from '@angular/core';
import { MaterialModule } from 'src/materialModule';
import { LoginService, iMakes } from '../login-popup/login.service';
import { HomePageService } from './home-page.service';
import { environment } from 'src/environments/environment';
import { HttpClient } from '@angular/common/http';
import { MatSnackBar } from '@angular/material/snack-bar';
import { RegisteredUserService } from '../registered-user/registered-user.service';
import { MatDialog } from '@angular/material/dialog';
import { ViewAdvertComponent } from '../view-advert/view-advert.component';
import { SendAdvertIDService } from './sendAdvertID.service';
import { MatPaginator } from '@angular/material/paginator';
import { Observable } from 'rxjs';
import { MatTableDataSource } from '@angular/material/table';
@NgModule({imports:[MaterialModule]})

@Component({
  selector: 'app-home-page',
  templateUrl: './home-page.component.html',
  styleUrls: ['./home-page.component.css'],
  providers:[ViewAdvertComponent]
})

export class HomePageComponent implements OnInit {

  @ViewChild(MatPaginator,{static:false}) paginator: MatPaginator;

  public apiURL = environment.api;
  public isImageLoading:any;
  public adverts:any=[];
  public imageToLoad:any=[];
  public obs: Observable<any>;
  public dataSource:MatTableDataSource<Card>;
  public selected;
  public advertID:any;

  constructor(private cd: ChangeDetectorRef,private advertIDService:SendAdvertIDService, private popup:MatDialog,private http:HttpClient,private lservice:LoginService, private snack:MatSnackBar,private registeredUserService:RegisteredUserService) {}

  ngOnInit() {
    this.registeredUserService.GetAllAdverts().subscribe(val=>
      {
        this.dataSource = new MatTableDataSource<Card>(val);
        this.dataSource.paginator = this.paginator;
        this.obs = this.dataSource.connect();
        let numOfAds=0;
        for(let a of val)
        {
         this.imageToLoad[numOfAds]={url:this.apiURL+'/api/Images/'+a.advertID+'_1'};

          numOfAds++;
        }
      },error => this.snack.open("Something went wrong. Please try again later")._dismissAfter(5000));
  }

ViewAdvert(e) //method that opens the dialog box
  {
    this.cd.markForCheck();
    this.advertIDService.SetAdvertID(e);
    this.popup.open(ViewAdvertComponent,{
      width: '500px',
    });
  }

ViewAdvert.ts (which executes inside the Dialog Box)
import { Component, ViewChild, ChangeDetectorRef, ChangeDetectionStrategy} from '@angular/core';
import { HomePageComponent } from '../home-page/home-page.component';
import { SendAdvertIDService } from '../home-page/sendAdvertID.service';
import { ViewAdvertService, iAdvertID } from './view-advert.service';
import { environment } from 'src/environments/environment';

@Component({
  selector: 'app-view-advert',
  changeDetection: ChangeDetectionStrategy.OnPush,
  templateUrl: './view-advert.component.html',
  styleUrls: ['./view-advert.component.css']
})
export class ViewAdvertComponent {
  @ViewChild('slideshow',{static:false}) slideshow:any;
  public advertID:String;
  public apiURL = environment.api;
  public imageID:any;
  public imageSource:any=[];
  public imageToSlideShow:any=[];
  public counter:any=0;
  public faultyImages:any=[];
  constructor(private cd: ChangeDetectorRef,public home:HomePageComponent,private advertIDService:SendAdvertIDService, private viewService:ViewAdvertService) {
    this.advertID=home.advertID;

  }
  ngOnInit(e) {
    this.cd.markForCheck();
    this.advertID= this.advertIDService.GetAdvertID();
    let param:iAdvertID={
     id:this.advertID
    }
   this.viewService.AdvertDetails(param).subscribe(val=>
    {
      this.imageID=val[0].advertID;
      this.counter=1;
      for(let i=0;i<=4;i++)
      {
        this.imageSource[i]=this.apiURL+'/api/Images/'+this.imageID+'_'+this.counter;
        this.faultyImages[i]=e;
        if(this.imageSource[i]==this.faultyImages[i])
        {
          console.log(this.faultyImages[i]);
        }
        else{
          this.imageToSlideShow[i]=this.imageSource[i];
        }
        this.counter++;
      }
    });
  }

}

A: You cannot inject a component (ViewAdvertComponent) into another component (HomePageComponent).
But I think you don't need that, but this https://material.angular.io/components/dialog/.

A: I suspect you are receiving the errors because you are not using dependency injection correctly. When you want to inject a class into another you need to add the @Injectable({}) decorator to the injected class. In Angular such a class is conventionally referred to as a Service.  Take a look at the dependency injection documentation.


text:
Q: How differently would we model the distribution of primes if prime gap is larger? Cramer's conjecture based on his random model provides prime gaps are bound by $O(\log^2p_n)$ where the gap is between $(n+1)$th and $n$th prime.

*

*How differently would primes be modeled if gaps of $O(2^{\mathsf{poly}(\log\log p_n)})$ were indeed accurate?

*$RH$ supports a gap hypothesis of $O(\sqrt{p_n}\log p_n)$ and so if this much larger gap were true will we be much off from 1. and would any 'random' model have any relevance?

A: I think a short answer is we don't have a supply of alternative models for prime numbers lying around that make very different predictions for gaps.
If a proof was found of larger prime gaps than predicted, or any other property of primes counter current predictions, I think analytic number theorists would look to the method of proof for clues about a revised random model of the primes. For instance if the proof relied crucially on a newfound correlation between the primes and some arithmetic function $f(n)$, a random model might begin by modeling $f$ and then viewing the primes as random variables depending on $f$.
In particular, for gaps so large that they imply a failure of RH, the first approach tried would surely be to look at the zeroes of zeta off the critical line and how they might be distributed, and use those to get an estimate for the density of primes in a certain region.


text:
Q: Connecting Multiple database in Codeigniter using LIVE database connection to LAN(XAMPP) database connection? Is it possible to connect a hosted PHP server on the internet to a database on my home LAN?
What should I do? Here's my Example Connection Database:
$active_group = 'default';
$active_record = TRUE;

$db['default']['hostname'] = 'www.mydomainname.com';
$db['default']['username'] = 'myusername';
$db['default']['password'] = 'mypassword';
$db['default']['database'] = 'mydabatasenameoncloud';
$db['default']['dbdriver'] = 'mysqli';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = FALSE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;

//-- Poll.php (My LAN Connection.)

$config['hostname'] = 'localhost';
$config['username'] = 'root';
$config['password'] = '';
$config['database'] = 'mydatabasenameonlan';
$config['dbdriver'] = 'mysqli';
$config['dbprefix'] = '';
$config['pconnect'] = FALSE;
$config['db_debug'] = FALSE;
$config['cache_on'] = FALSE;
$config['cachedir'] = '';
$config['char_set'] = 'utf8';
$config['dbcollat'] = 'utf8_general_ci';
$config['swap_pre'] = '';
$config['autoinit'] = TRUE;
$config['stricton'] = FALSE;

$DB2 = $this->load->database($config, TRUE);
$DB3 = $this->load->database('default', TRUE);

$check_if_connected = $DB2->initialize();

So, this is my Reversed database connection. Cloud to Lan database connection. But I'm getting an error. Can I Remote MySQL on XAMPP?

A: You're making default connection correctly as below -
$db['default']['hostname'] = "localhost";
$db['default']['username'] = "root";
$db['default']['password'] = "";
$db['default']['database'] = "mydabatasenameonlan";
$db['default']['dbdriver'] = "mysql";
$db['default']['dbprefix'] = "";
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = FALSE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = "";
$db['default']['char_set'] = "utf8";
$db['default']['dbcollat'] = "utf8_general_ci";
$db['default']['swap_pre'] = "";
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;

But in your second database connection define cofigurations as below -
$db['otherdb']['hostname'] = "www.mydomainname.com";
$db['otherdb']['username'] = "myusername";
$db['otherdb']['password'] = "mypassword";
$db['otherdb']['database'] = "mydatabasenameoncloud";
$db['otherdb']['dbdriver'] = "mysql";
$db['otherdb']['dbprefix'] = "";
$db['otherdb']['pconnect'] = TRUE;
$db['otherdb']['db_debug'] = FALSE;
$db['otherdb']['cache_on'] = FALSE;
$db['otherdb']['cachedir'] = "";
$db['otherdb']['char_set'] = "utf8";
$db['otherdb']['dbcollat'] = "utf8_general_ci";
$db['otherdb']['swap_pre'] = "";
$db['otherdb']['autoinit'] = TRUE;
$db['otherdb']['stricton'] = FALSE;

Then you can connect to cloud database as below -
$otherdb = $this->load->database('otherdb', TRUE);

You can also see this answer -
Codeigniter - multiple database connections


text: Q: Automatic conversion of UML diagram from NClass to yEd? I can't find a way to automatically convert a NClass-generated file into yEd...I wanted to know if some of you guys have ever come across this issue - I am not optimistic about it, I just wanted the last confirmation before I start converting it by hand... :(


text:
Q: Node.JS: Cannot find module './abort.js' I'm using node.js v17.3.0 and im trying to upload my Discord bot to my raspberry pi. On my local PC it works, but on my raspi i get this error:
Anyone has a solution for that?
[Bot-Handler] Starting Bot...
node:internal/modules/cjs/loader:936
 throw err;
 ^

Error: Cannot find module './abort.js'
Require stack:
- /home/excerz/node_modules/combined-stream/lib/combined_stream.js
- /home/excerz/node_modules/form-data/lib/form_data.js
- /home/excerz/node_modules/discord.js/src/rest/APIRequest.js
- /home/excerz/node_modules/discord.js/src/rest/RESTManager.js
- /home/excerz/node_modules/discord.js/src/client/BaseClient.js
- /home/excerz/node_modules/discord.js/src/index.js
- /home/excerz/main.js
   at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
   at Function.Module._load (node:internal/modules/cjs/loader:778:27)
   at Module.require (node:internal/modules/cjs/loader:999:19)
   at require (node:internal/modules/cjs/helpers:102:18)
   at Object.<anonymous> (/home/excerz/node_modules/combined-stream/lib/combined_stream.js:1:13)
   at Module._compile (node:internal/modules/cjs/loader:1097:14)
   at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10)
   at Module.load (node:internal/modules/cjs/loader:975:32)
   at Function.Module._load (node:internal/modules/cjs/loader:822:12)
   at Module.require (node:internal/modules/cjs/loader:999:19) {
 code: 'MODULE_NOT_FOUND',
 requireStack: [
   '/home/excerz/node_modules/combined-stream/lib/combined_stream.js',
   '/home/excerz/node_modules/form-data/lib/form_data.js',
   '/home/excerz/node_modules/discord.js/src/rest/APIRequest.js',
   '/home/excerz/node_modules/discord.js/src/rest/RESTManager.js',
   '/home/excerz/node_modules/discord.js/src/client/BaseClient.js',
   '/home/excerz/node_modules/discord.js/src/index.js',
   '/home/excerz/main.js'
 ]
}

Node.js v17.3.0```


text:
Q: Mode of a frequency distribution with unequal class length How can I find the mode for a grouped frequency distribution with unequal class lengths? I have to find the mode for the following problem:
\begin{array}{c|c}
\text{Marks} & \text{# of Students} \\ \hline
\text{0 - 20} & 32 \\ \hline
\text{20 - 50} & 45 \\ \hline
\text{50 - 70} & 15 \\ \hline
\text{70 - 100} & 8 \\ \hline
\end{array}$$
For equal class lengths, we use the formula
$$\text{Mode} = l+\frac{(f_0-f_{-1})}{2f_0-f_{-1}-f_{+1}}W_o$$
where
$l$ is the lower class boundary of the modal class,
$f_0$ is the frequency of the modal class,
$f_{-1}$ is the frequency preceding the modal class,
$f_{+1}$ is the frequency following the modal class,
$W_{o}$ is the class width of the modal class
But how to proceed for the above example?

A: Here is an outline of what I intend to do:
(1) 'Reconstruct' the original data by using R to spread the
observations in each interval at random within the interval.
Here is a density histogram (intervals of equal length) of one such
reconstruction.
 x = c(runif(32,0,20),runif(45,20,50),runif(15,50,70),runif(8,70,100))
 hist(x, prob=T, col="wheat")

(2) Use a modern density estimator to 'smooth' this histogram,
and determine the location of the highest point of the density
estimator, which is a reasonable estimate of the mode of
the reconstructed data. For this reconstruction, the mode is 22.4.
 hist(x, prob=T, col="wheat")
 lines(density(x), col="blue")
 dxy = density(x);  dx = dxy$x; dy = dxy$y # (x,y) components of 'smooth'
 dx[dy == max(dy)]  # x-value at which 'smooth' has its max
 ## 22.36885   # estimated density

(3) Of course, each random reconstruction of the data will be
somewhat different. Repeat steps (1) and (2) 2000 times and
keep track of the 2000 modes produced. The median of these
estimated modes was 23.6.  Take this value to be a reasonable
estimator of the mode of the distribution from which the
original data were sampled.
However, these estimated modes
where quite variable (mainly because so much information
was lost in the original summary of the data into four
groups of unequal lengths). Below is a boxplot of the
2000 mode estimates. (Note: The histogram and density-estimator
curve in the figure above happen to be for the last of
the 2000 reconstructions of the data in my simulation.)
I doubt that this is anything like the method you were
expected to use, but I believe this is a responsible
approach to solving the problem. (Certainly better than the
approaches I initially suggested in my Comment an hour ago.
Maybe I should delete the Comment now, but that seems like
cheating.)


text:
Q: Can I safely ignore these pthread warnings via glibc? I am getting a pair of warnings with version 2.22 of glibc:
In file included from /net/module/sw/glibc/2.22/include/pthread.h:23:0,
                 from foo.h:48,
                 from foo.c:23:
/net/module/sw/glibc/2.22/include/sched.h:74:57: warning: 'struct timespec' declared inside parameter list
 extern int sched_rr_get_interval (__pid_t __pid, struct timespec *__t) __THROW;
                                                         ^
/net/module/sw/glibc/2.22/include/sched.h:74:57: warning: its scope is only this definition or declaration, which is probably not what you want
In file included from foo.h:48:0,
                 from foo.c:23:
/net/module/sw/glibc/2.22/include/pthread.h:1002:21: warning: 'struct timespec' declared inside parameter list
        const struct timespec *__restrict __abstime)
                     ^

And:
In file included from /net/module/sw/glibc/2.22/include/sys/param.h:26:0,
                 from foo.h:51,
                 from foo.c:23:
/net/module/sw/glibc/2.22/include/limits.h:123:3: warning: #include_next is a GCC extension
 # include_next <limits.h>
   ^

I am using GCC 5.3.0 with this version of glibc.
Since these warnings are referencing an external library I do not control, can I safely ignore these warnings if my application otherwise appears to pass tests?
My concern is that these warnings (particularly those related to pthread) may indicate the introduction of subtle bugs that I do not have tests to catch.

A: Yes, these warnings should be harmless, but the struct timespec warning is certainly odd.  Usually, they would be masked by GCC's warning suppression for system headers.


text:
Q: Bootstrap 4 row columns not breaking row I'm trying to create a bootstrap grid where every row has to columns, bootstrap has a class that does this, row-cols-*, but when I place the example on bootstrap website in a jsfiddle it doesn't break row like it is supposed to do. What am I doing wrong?
HTML:

Column

Column

Column

Column

A: The .row-cols-* class is new to Bootstrap 4.4: https://github.com/twbs/bootstrap/releases. Your problem might be due to the fact that you're referencing the prior version of Bootstrap. At least your jsfiddle was doing that.
Reference the correct Bootstrap 4.4 files fixes the issue:

demo: https://jsfiddle.net/davidliang2008/1Ltc9zos/1/

A: External resources in JSFiddle (Adding Twitter Bootstrap CDN)
The logic is the same as when you set it up in an editor, like Brackets.
Try this:

Column

Column

Column

Column


text:
Q: DNS no longer working after Ubuntu-Desktop installed I built a Ubuntu Server 18.04 server to play with Docker and a few other things. When I initially installed Server I had some issues with Netplan and getting DNS (my own server) to work, but I go there in the end and all was working fine.
There were a few other things I wanted to do, that I felt required me to have a GUI installed, so I installed Ubuntu-Desktop using apt install --no-install-recommends
 Ubuntu-Desktop. After a reboot, there was the GUI and I was able to login. Great!
However, I no longer have DNS working again, and I didn't record what I did first time to sort it!. If I do an nslookup of a local host I get: ;; reply from unexpected source: 127.0.0.1#53, expected 127.0.0.53#53
As always my first response is to Google for assistance, but I don't relly understand the various suggestions so don't want to wildly start typing commands in the terminal.
All I have done thus far is to confirm my netplan config is still there and reapplied it. I also installed resolvconf which was one of the suggestions. If I open /etc/resolv.conf I see Generated by NetworkManager. I am more familiar with CentOS and have no experience of Netplan other than what I did earlier when I first installed.
Any advice and explanation would be appreciated....
UPDATE 1: I'm wondering if this has anything to do with Docker being installed on this system??
UPDATE 2: As requested, here are the outputs of those commands:
$ dpkg -l *dnsmasq*
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name                        Version            Architecture       Description
+++-===========================-==================-==================-============================================================
un  dnsmasq                     <none>             <none>             (no description available)
ii  dnsmasq-base                2.79-1             amd64              Small caching DNS proxy and DHCP/TFTP server
un  dnsmasq-base-lua            <none>             <none>             (no description available)

$ ls -al /etc/resolv.conf
lrwxrwxrwx 1 root root 39 May  8 16:06 /etc/resolv.conf -> ../run/systemd/resolve/stub-resolv.conf

$ cat /etc/resolv.conf
# This file is managed by man:systemd-resolved(8). Do not edit.
#
# This is a dynamic resolv.conf file for connecting local clients to the
# internal DNS stub resolver of systemd-resolved. This file lists all
# configured search domains.
#
# Run "systemd-resolve --status" to see details about the uplink DNS servers
# currently in use.
#
# Third party programs must not access this file directly, but only through the
# symlink at /etc/resolv.conf. To manage man:resolv.conf(5) in a different way,
# replace this symlink by a static file or a different symlink.
#
# See man:systemd-resolved.service(8) for details about the supported modes of
# operation for /etc/resolv.conf.

nameserver 127.0.0.53
options edns0
search home.domain

$cat /etc/netplan/*.yaml
network:
  version: 2
  renderer: networkd
  ethernets:
    enp2s0:
      dhcp4: no
      dhcp6: yes
      addresses: [192.168.1.6/24]
      gateway4: 192.168.1.1
      nameservers:
        addresses:
          - 192.168.1.3
        search:
          - home.domain

$ cat /etc/network/interfaces
# ifupdown has been replaced by netplan(5) on this system.  See
# /etc/netplan for current configuration.
# To re-enable ifupdown on this system, you can run:
#    sudo apt install ifupdown

auto eth0
iface etho inet static
        address 192.168.1.6
        netmask 255.255.255.0
        netowrk 192.168.1.0
        broadcast 192.168.1.255
        gateway 192.168.1.1
        dns-nameservers 192.168.1.3
        dns-domain home.domain
        dns-search home.domain

UPDATE 3: Heynnema tried to help me. We corrected the /etc/network/interfaces file as per his comments, and uninstalled dnsmasq-base which we believe was left over from a removed Pi-hole install. Now nslookup returns a failure trying 127.0.0.1.
UPDATE 4: Output of ps auxw |grep systemd
root       474  0.0  0.2 118876 33216 ?        S<s  May08   0:01 /lib/systemd/systemd-journald
root       519  0.0  0.0  47160  5784 ?        Ss   May08   0:02 /lib/systemd/systemd-udevd
systemd+   747  0.0  0.0 141924  3348 ?        Ssl  May08   0:00 /lib/systemd/systemd-timesyncd
systemd+   881  0.0  0.0  71968  5996 ?        Ss   May08   0:00 /lib/systemd/systemd-networkd
root       987  0.0  0.0  70604  6192 ?        Ss   May08   0:01 /lib/systemd/systemd-logind
message+  1041  0.0  0.0  51620  6140 ?        Ss   May08   0:04 /usr/bin/dbus-daemon --system --address=systemd: --nofork --nopidfile --systemd-activation --syslog-only
gdm       1789  0.0  0.0  76984  7948 ?        Ss   May08   0:07 /lib/systemd/systemd --user
neild+  8004  0.0  0.0  77024  7928 ?        Ss   May08   0:07 /lib/systemd/systemd --user
neild+ 26628  0.0  0.0  13136  1072 pts/0    S+   19:37   0:00 grep --color=auto systemd

UPDATE 5: I managed to get systemd-resolved working again and thus /etc/resolv.conf to exist by running systemctl enable systemd-resolved.service and then systemctl start systemd-resolved.service
nslookup now gives ;; reply from unexpected source: 127.0.0.1#53, expected 127.0.0.53#53 again
UPDATE 6: Found the issue, but no idea why it only started being an issue. So I have Docker running with a Pi-Hole container (I hear you all grown!) which is using port 53 and preventing systemd from working correctly. The docker-proxy process had the port instead.
When I stop the docker service and restart systemd-resolve all works as expected, so I have temporarily removed my Pi-Hole container.
Is there a way to get both working together?


text:
Q: A homogenous polynomial of degree $k$. $f: \mathbb R^n \to \mathbb R$ is a smooth map such that $f(rv)=r^kf(v)$ for all $v\in \mathbb R^n$ and $r\in\mathbb R$. So $f$ has to be a homogenous polynomial of degree $k$?
This is an assertion from Differential Geometry by Taubes.

A: Let $r \in R \setminus \{0\}$ and $x \in R^n$. Therefore, $f(rx)= r^k f(x),$ now by taking derivative from both sides w.r.t $x$,  we get $rf'(rx)= r^k f'(x)$ thus $f'(rx)= r^{k-1} f'(x)$ now if we take derivative $k$ times w.r.t $x$ we get $$f^{k}(rx)=  f^{k}(x)$$. By letting $r \rightarrow 0$ we get $f^{k}(0)=  f^{k}(x)$ for all $x \in R^n$. Again by taking derivate we get $f^{n}(x)= 0$ for all $n > k$
 Using taylor expansion we may rewrite $f$ as $$f(x)= P(x) + f^{k+1}(y) \times \{\text{a bunch of vectors}\} =P(x) $$
where $P$ is a polynomial of degree at most $K$. Now if $f \neq 0$ taking into account that  $P(rx)= r^k P(x)$, one can easily conclude  that $P$ has to be a homogenous polynomial of degree $k$


text:
Q: importing several text files into R I have four folders which contain text files (tab delimited) of the same names, I would like to import all of these text files into a data.frame. For example:
TopFolder = "G:\\University"
SubFolder = list.files(TopFolder)
#find the name of the folders in the current directory
DateTime = rbind(read.table(paste(TopFolder,SubFolder[1],"Data.txt",sep = "\\"),sep="\t"),
                read.table(paste(TopFolder,SubFolder[2],"Data.txt",sep = "\\"),sep="\t"),
                 read.table(paste(TopFolder,SubFolder[3],"Data.txt",sep = "\\"),sep="\t"),
                 read.table(paste(TopFolder,SubFolder[4],"Data.txt",sep = "\\"),sep="\t"))

This example works fine, although I was hoping of using a loop or some other function to generate this variable without having to import all of the files individually. Does anyone have any suggestions?

A: How about this?
lf = list.files(path = "G:\\University", pattern = "Data.txt",
                full.names = TRUE, recursive = TRUE, include.dirs = TRUE)

library(plyr)
DateTime = ldply(lf, read.table, sep = "\t")


text:
Q: ASP.net digits always rendering as Latin regardless of culture I'm trying to render integers in their native form.  I set the culture info as follows:
CurrentCulture = new CultureInfo(ViewingLanguage.LanguageTag)
{
    NumberFormat = new NumberFormatInfo{DigitSubstitution = DigitShapes.NativeNational}
};

And have the function:
public static string NiceNumber(CultureInfo culture, int number)
{
    return number.ToString(culture);
}

Whatever the culture is set to ar-QA, zh-HANS etc, the digits always render in their latin form.
How do I render the digits in their native form?

A: This is the first thing I do in multilingual web apps.  It should work for you too.  Although note this comment from MSDN:
The CultureInfo.CreateSpecificCulture method throws ArgumentException for the neutral cultures "zh-Hant" ("zh-CHT") and "zh-Hans" ("zh-CHS").
protected override void InitializeCulture()
{
    if (Request.QueryString["lang"] != null)
    {
        string m_selectedLanguage = Request.QueryString["lang"];
        UICulture = m_selectedLanguage;
        Culture = m_selectedLanguage;

        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(m_selectedLanguage);
        Thread.CurrentThread.CurrentUICulture = new CultureInfo(m_selectedLanguage);
    }

    base.InitializeCulture();
}


text:
Q: Zabbix user-defined parameters with PSK encryption I am trying to configure a user defined parameter on a Windows host.  All my hosts are configured with PSK encryption and Zabbix server is able to get data without any issues.
However I cannot figure out how to use the zabbix_get manually with PSK encryption enabled.
zabbix_get -s x.x.x.x -p 10050 -k "internet.connection.check" --tls-connect=psk --tls-psk-identity="name" --tls-psk-file=cannot find any psk file on zabbix server
The problem is I cannot locate any PSK file on the zabbix server. Can I pass the PSK somehow?

A: The serverside PSK is configured in the GUI and stored in the database.
The Zabbix agent stores the PSK in a file.
I see 3 options:

*

*Manually create a psk-file.
Remember that a change of the key must be done in the GUI, at the agent and in your special file.

*Make a script that reads the key from the database.
Remember that direct access to the database of an application is most times forbidden and  can cause compatibility issues after updating the application. Read-only access should be possible.

*Use the same keys for all your agents;
When you install a Zabbix Agent on the Zabbix Server (allowing you to monitor the server), you do have a file on a normal place.
I wouldn't try to use an API or some smart script during Discovery, this will make the solution hard to maintain. I withdraw my last remark, when you have thousands of servers to monitor and a team working with Zabbix.


text:
Q: Make subdomain files only accessible via subdomain On a shared hosting I have a public_html directory where the site is located. There are multiple subdomains created and they are located in the public_html like public_html/subdomain1, public_html/subdomain2 etc.
This makes these sub sites accessible in two ways:
1.) domain.com/subdomain1
2.) subdomain.domain.com
What I need is to forbid the first option for every subdomain.

A: This was the first question I stumbled upon while looking for this, and unfortunately it didn't get answered in over 5 years. So I figured it out and would like to share my approach here.
Using an <If> statemente (available from Apache 2.4 onwards), here's what you can do:
Put the following in an .htaccess file in the subdirectory.
<If "%{HTTP_HOST} != 'mysubdomain.mydomain.tld'">
    Deny from all
</If>

If you need more control, e.g. to allow access for multiple (sub)domains, you can also you use RegEx:
<If "! %{HTTP_HOST} =~ m#^mysubdomain\.mydomain\.tld$#">
    Deny from all
</If>


text:
Q: How to map the file path in the provider xml file that matches files downloaded to the 'DirectoryDownloads' location A request has been composed to the DownloadManager that specifies the download directory.
request.SetDestinationInExternalFilesDir(_context, Android.OS.Environment.DirectoryDownloads, downloadName);

This on the system being tested results in a file at the following file path
file:/storage/emulated/0/Android/data/com.myco.myapp/files/Download/com.myco.myapp.version.apk
Question is what needs to go in the file_paths.xml file?
The file_paths.xal file is referenced by
<provider android:name="android.support.v4.content.FileProvider" android:authorities="com.myco.myapp.fileprovider" android:exported="false" android:grantUriPermissions="true">
      <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" />
    </provider>

In the manifest
And is used by GetUriForFile like this:
var uri = global::Android.Support.V4.Content.FileProvider.GetUriForFile(this._context.ApplicationContext, providerName, apkPath);

where providerName is ="com.myco.myapp.fileprovider"
and apkPath is the download path above.
I have not found an entry for the file_paths.xml file that does not result in
Java.Lang.IllegalArgumentException: 'Failed to find configured root that contains file:/storage/emulated/0/Android/data/com.myco.myapp/files/Download/com.myco.myapp.version.apk
Except for:
<root-path name="root" path="." />

Which results in an output content uri of
content://com.myco.myapp.fileprovider/root/file%3A/storage/emulated/0/Android/data/com.myco.myapp/files/Download/com.myco.myapp.version.apk
Which not surprisingly fails to install.
I am anticipating that a line along the lines of
<SOMETHING-path name="downloads" path="Download/" />

Will result in content://downloads/com.myco.myapp.version.apk
But all the SOMETHING-path variants I have tried have failed.
I have also tried path="Download" path="Download/"and path="/Download"
On all the varients.


text:
Q: Using $scope within angular.element function I'm setting an attribute on my directive and I can access the value from within the controller but I can't access it within my angular.element which is in the controller:
controller: ['$scope', '$window', function($scope, $window) {
      console.log('my value is logged: ' + $scope.myvalue)
    angular.element($window).bind("scroll", function() {
      console.log('my value is not logged: ' + $scope.myvalue)
    }
}],

I want to append elements to the dom only if $scope.myvalue is true and when a scroll point has been reached on the page.
How would I do this?


text:
Q: ToDictionnary() from List in C# I want to use linq to get Dictionnary from a List in c# i use this code
List<Jointure> lj = table.jointures.GetJointures(Visibilites.Liste, false)
                        .ConvertAll(o => new Jointure(o, table.nom, tabloidConfig.config.tables[o.nomTable].corbeille));

jointures=new Dictionary<string,Jointure>(StringComparer.OrdinalIgnoreCase);

jointures = lj.ToDictionnary(o => o.nom, o => o);

But it throws the following exception:

Erreur    109 'System.Collections.Generic.List' ne
  contient pas une définition pour 'ToDictionnary' et aucune méthode
  d'extension 'ToDictionnary' acceptant un premier argument de type
  'System.Collections.Generic.List' n'a été trouvée
  (une directive using ou une référence d'assembly est-elle
  manquante ?)  D:\dev\Visual
  studio\Tanloid\Transport\base.aspx.cs 366 32  Tabloid

A: You spelled the method name incorrectly.  toDictionnary should be ToDictionary.


text:
Q: Unable To Create An Event With Microsoft Graph API I'm trying to create an Event using The Microsoft Graph API in .Net 5 with ASP.I have been to The Graph Explorer and as weird as its sounds, sometimes but not always an event wont create using the demo code provided (see below)
{
    "subject": "My event 0",
    "start": {
        "dateTime": "2021-04-09T00:00:36.595Z",
        "timeZone": "UTC"
    },
    "end": {
        "dateTime": "2021-04-16T00:00:36.595Z",
        "timeZone": "UTC"
    }
}

"error": {
"code": "RequestBodyRead",
"message": "The property 'subject' does not exist on type 'Microsoft.OutlookServices.Event'. Make sure to only use property names that are defined by the type or mark the type as open type. REST APIs for this mailbox are currently in preview. You can find more information about the preview REST APIs at https://dev.outlook.com/."
}
}

Here is the payload of an Event object I am attempt to create an event with.
{
      "allowNewTimeProposals": true,
      "attendees": [
        {
          "type": "required",
          "emailAddress": {
            "address": "andrew@andrew.com",
            "@odata.type": "microsoft.graph.emailAddress"
          },
          "@odata.type": "microsoft.graph.attendee"
        }
      ],
      "body": {
       "content": "hello,world",
       "contentType": "html",
       "@odata.type": "microsoft.graph.itemBody"
       },
      "end": {
      "dateTime": "2021-04-10T11:11:00.0000000",
      "timeZone": "AUS Eastern Standard Time",
      "@odata.type": "microsoft.graph.dateTimeTimeZone"
      },
      "isAllDay": false,
      "location": {
        "displayName": "Microsoft Teams Meeting",
        "@odata.type": "microsoft.graph.location"
       },
      "start": {
        "dateTime": "2021-04-10T11:10:00.0000000",
        "timeZone": "AUS Eastern Standard Time",
        "@odata.type": "microsoft.graph.dateTimeTimeZone"
      },
      "subject": "Andrew",
      "@odata.type": "microsoft.graph.event"
    }

Status Code: BadRequest
Microsoft.Graph.ServiceException: Code: RequestBodyRead
Message: A type named 'microsoft.graph.event' could not be resolved by the model. When a model is available, each type name must resolve to a valid type. REST APIs for this mailbox are currently in preview. You can find more information about the preview REST APIs at https://dev.outlook.com/.

It might be worth mentioning that so far all other requests both Get & Post have been successful when using the SDK/API.
Scopes used
        public readonly static string[] Scopes =
        {
            "User.Read",
            "MailboxSettings.Read",
            "Calendars.ReadWrite",
        };

Code Used To Send The Request.
        var timeZone = User.FindFirst("graph_timezone").Value;

        var @event = new Event()
        {
            Subject = teamsMeetingRequest.Title,
            Attendees = attendees,
            IsAllDay = teamsMeetingRequest.IsAllDay,
            Start = new DateTimeTimeZone
            {
                DateTime = teamsMeetingRequest.StartDate.ToString("o"),
                TimeZone = timeZone
            },
            End = new DateTimeTimeZone
            {
                DateTime = teamsMeetingRequest.EndDate.ToString("o"),
                TimeZone = timeZone
            },
            Body = new ItemBody()
            {
                Content = teamsMeetingRequest.Body,
                ContentType = BodyType.Html,
            },
            Location = new Location()
            {
                DisplayName = "Microsoft Teams Meeting"
            },
            AllowNewTimeProposals = true
        };

        await this._graphClient.Me.Events.Request().AddAsync(@event);

 Update StackTrace  All other error's in both The Graph Explorer And Response From The SDK/API Are Mentioned Above.
Status Code: BadRequest Microsoft.Graph.ServiceException:
Code: RequestBodyRead
Message: A type named 'microsoft.graph.event' could not be resolved
  by the model. When a model is available, each type name must resolve
  to a valid type. REST APIs for this mailbox are currently in preview.
  You can find more information about the preview REST APIs at https://dev.outlook.com/.
Inner error:
AdditionalData:
date: 2021-04-10T02:46:11
request-id: removed for question
client-request-id: removed for question
ClientRequestId: removed for question
   at Microsoft.Graph.HttpProvider.SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
   at Microsoft.Graph.BaseRequest.SendRequestAsync(Object serializableObject, CancellationToken cancellationToken, HttpCompletionOption completionOption)
   at Microsoft.Graph.BaseRequest.SendAsync[T](Object serializableObject, CancellationToken cancellationToken, HttpCompletionOption completionOption)
   at TeamsMeetingCreator.Controllers.ValuesController.CreateTeamsMeeting(TeamsMeetingRequest teamsMeetingRequest) in Path To My File.

UpdateI have tried POSTMAN to send the request with the above payloads so there shouldnt be any ODataType issues but unfortunately the same error exists.

"The property 'subject' does not exist on type 'Microsoft.OutlookServices.Event'

UpdateI have tried creating an Event with no properties and it has successfully created, I then tried to Update the event
// Update The Event.
@event = await this._graphClient.Me.Events[emptyEvent.Id].Request().UpdateAsync(@event);

However the same error is returned

The property 'attendees' does not exist on type 'Microsoft.OutlookServices.Event

A: This is probably a bug in the client library. Try this before doing AddAsync:
@event.ODataType = null;


text:
Q: Is there anything grammatically wrong with this sentence? "A fine of $100 will be imposed upon any drivers of whom the car is illegally parked."
Is there anything wrong, in terms of grammar, with the above sentence?
1) Should driver(s) be singular or plural?
2) Should car(s) be singular or plural?
3) Should it be 'of whom' or 'whose'?

A: The sentence is at best clumsy. On close reading it doesn't appear to make sense. It's not clear what the pronoun "whom" is referring too. The context makes the intended meaning clear and there are lots of straightforward ways to express it:

A $100 fine will be imposed on the drivers of illegally parked cars.
Drivers of illegally parked vehicles are subject to a $100 fine.

In these examples I used plural drivers and plural cars (as we are referring to possibly multiple cars and drivers). I avoided "of whom" entirely. I can shorten this further to a noun phrase suitable for going on a sign:

Fine for illegal parking — $100


text:
Q: ConcurrentQueue or Queue when one thread only ever enqueues and another thread only ever dequeues I have a FIFO and two threads. One thread will only ever enqueue to the FIFO and the other thread will only ever dequeue from the FIFO. Do I need to take the  ConcurrentQueue or is the Queue enough?

A: If you have more than one thread, it will require thread safety and synchronization for your Queue object instance. In order to avoid reinventing the wheel and doing it yourself, I would suggest using Microsoft's ConcurrentQueue.
MSDN:
https://learn.microsoft.com/en-us/dotnet/api/system.collections.queue?view=netframework-4.7.1

Use ConcurrentQueue or ConcurrentStack if you need to access the
  collection from multiple threads concurrently.

If you use a Queue ( i.e., not the ConcurrentQueue) with more than one thread updating the object instance, you could encounter run time exceptions, such as:

*

*ArgumentOutOfRangeException

*ArgumentException ( InvalidOffLen)

*ExceptionResource.InvalidOperation_EmptyQueue

The exceptions are possible if the Queue's internal state is being modified but not yet completed due to CPU thread scheduling. If another thread accesses the Queue object instance while it's in an inconsistent state, you could and probably will encounter these exceptions.
Source Code to review:
.Net Framework 4.7.1
https://referencesource.microsoft.com/#System/compmod/system/collections/generic/queue.cs
Sample Console Application:
Run the following as your lab and you should encounter a System.InvalidOperationException
System.InvalidOperationException: 'Collection was modified after the enumerator was instantiated.'
class Program
{
    static Queue<string> Queue = new Queue<string>();

    static void Main(string[] args)
    {
        Thread producer = new Thread(Enqueue);
        Thread consumer = new Thread(Dequeue);

        producer.Start();
        consumer.Start();

        Console.ReadKey();
    }

    static void Enqueue()
    {
        for (int i = 0; i < 10000; i++)
        {
            Queue.Enqueue("Number : " + i);
            SimulateWork();
        }
    }

    static void Dequeue()
    {
        while (true)
        {
            if (Queue.Any())
            {
                Console.WriteLine(Queue.Dequeue());
                SimulateWork();
            }
        }
    }

    static void SimulateWork()
    {
        for (int i = 0; i < 1000000; i++)
        { }
    }
}

This lab demonstrates what can happen when an Queue instance is accessed while in an inconsistent state. Even with just one producer and one consumer you need proper synchronization.
If you add locking or synchronization around the Enqueue and Dequeue operations, you will notice it runs without issue.
            lock (lockObject)
            {
                Queue.Enqueue("Number : " + i);
                SimulateWork();
            }

            lock (lockObject)
            {
                if (Queue.Any())
                {
                    Console.WriteLine(Queue.Dequeue());
                    SimulateWork();
                }
            }

With that being said, I am NOT suggesting that you manually add locks that will block. This is more of a lab exercise to help you understand the WHY.
Microsoft has invested a lot of time in providing us thread safe collections like the ConcurrentQueue using fine-grained locking and lock-free mechanisms.

Some of the concurrent collection types use lightweight
  synchronization mechanisms such as SpinLock, SpinWait, SemaphoreSlim,
  and CountdownEvent, which are new in the .NET Framework 4. These
  synchronization types typically use busy spinning for brief periods
  before they put the thread into a true Wait state. When wait times are
  expected to be very short, spinning is far less computationally
  expensive than waiting, which involves an expensive kernel transition.
  For collection classes that use spinning, this efficiency means that
  multiple threads can add and remove items at a very high rate. For
  more information about spinning vs. blocking, see SpinLock and
  SpinWait.

As stated above, if you have more than one thread, it will require thread safety and synchronization for your Queue object instance. In order to avoid reinventing the wheel and doing it yourself, I would highly suggest using Microsoft's ConcurrentQueue.
References:
Thread Safe Collections:
https://learn.microsoft.com/en-us/dotnet/standard/collections/thread-safe/
Lock Keyword
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/lock-statement
Threading:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/threading/index

A: Short answer: Yes, you still require a thread-safe solution - even if there's only one writer thread and one reader thread.
It would be easier to use the ConcurrentQueue. You could use Queue instead if you wanted to, but you would have to do the locking yourself.


text:
Q: Most used command combos in bash history? There are nice oneliners to show the most used commands in bash history or this. Now that I optimized my aliases, this only shows me shortcuts.
As a next step, I want to optimize for combos. For example, I believe I often do a combo of git-log, git-show, git-push. I would like to have some hard data to back this up, though. There might also be combos to discover I would not have considered.
So, the input is a history of commands. The output should be something like:
123 git log
    git show
    git push
456 git show
    git log
    git push

Syntax whatever. It could as well be this, if simpler:
123 git log; git show; git push
456 git show; git log; git push

It should probably be parameterized for the number of commands to consider, although 2 and 3 are the only ones that matter for me now.
Question: Is there a nice oneliner to compute that?

A: There are issues with format in the history file, (and the name, I believe the default is .bash_history but I used .bash-history), but a first pass could be something as simple as:
sed /^#/d ~/.bash-history |
    awk '{a2=a1; a1=$0;} NR>2{a[$0 ";" a1";" a2]++}
        END {for (c in a) print a[c], c}'


text:
Q: Which public key will be added into my ~/.ssh/known_hosts? I have a RHEL 8.3 server and this is the content in the /etc/ssh folder:
[root@192 ssh]# pwd
/etc/ssh
[root@192 ssh]# tree -a
.
├── moduli
├── ssh_config
├── ssh_config.d
│   └── 05-redhat.conf
├── sshd_config
├── ssh_host_ecdsa_key
├── ssh_host_ecdsa_key.pub
├── ssh_host_ed25519_key
├── ssh_host_ed25519_key.pub
├── ssh_host_rsa_key
└── ssh_host_rsa_key.pub

1 directory, 10 files
[root@192 ssh]#

I found that when I ssh to this server from server1, the RSA public key (ssh_host_rsa_key.pub) was added in server 1's ~/.ssh/known_hosts file. But when I try another server server2, the ECDSA public key (ssh_host_ecdsa_key.pub) was added to ~/.ssh/known_hosts. Why the difference? What determines which public key will be used?

A: In the SSH protocol, the algorithms used for the cipher, MAC, key exchange, host key, and public key can be independently negotiated.  In most cases, the algorithm selected is the first of the client algorithms that the server also supports.
Typically, a server has multiple host keys, and the choice of host key used is dependent on the algorithm negotiated.  The latest versions of OpenSSH prefer Ed25519 keys, and before that, preferred ECDSA keys.  However, OpenSSH has a special rule that if no special configuration of the host key is used and at least one host key is known in the known hosts file, then it will rewrite the preferred client algorithms to prefer the host keys that it knows about.  This means that users won't see host key warnings if the server adds a new host key.
As mentioned, typically Ed25519 and ECDSA keys are preferred.  However, OpenSSH recently dropped support for automatically using RSA with SHA-1 (the ssh-rsa signature algorithm, which is insecure), while it still supports RSA with SHA-2 (rsa-sha2-256 and rsa-sha2-512).  Sometimes people choose to re-enable the ssh-rsa algorithm in the configuration despite the known security risks, and the typical pattern that people use for that puts the algorithm at the front of the list.  Hence, it is possible that on that system, such a configuration was enabled in ~/.ssh/config or /etc/ssh/ssh_config, leading to preferring the RSA key.

A: You can choose the ciphers in sshd_config. On a busy or old server, an admin might offer up for a less CPU-intensive cipher suite. Something similar happens with websites and the negotiation to secure a connection with each individual client browser in that the server and client must eventually agree on a technology that they both support. So the user does have some influence as well (ssh_config).
On a server it's in /etc/ssh/sshd_config if you want to take a look.
You can probe a server with ssh-keyscan. See here: https://serverfault.com/questions/934072/how-to-view-ecdsa-host-key-of-a-server


text:
Q: Calculus 2 integrals So I'm currently doing calc 2 and we have this relatively weird concept of "Partition" or "Division", not sure what's the correct term in English. Nevertheless, I'm struggling with it. Here's an example question with this particular concept.
Let $f: [0, 4] \rightarrow \mathbb{R}$
$$  f(x) =
\begin{cases}
1,  &  0 \leq x < 1 \\
x,  &  1 \leq x < 3 \\
4,  &  x = 3 \\
5, & 3 < x \leq 4
\end{cases}$$
and let $0, 1, 2, 3, 4$ be the "Partition" of $[0, 4]$ called $P$

*

*Compute the difference of the upper and lower sum $\bar{S}_{P}(f)$ $-$ $\underline{S}_{P}(f)$
Even the notation here is a bit sketchy. Could someone elaborate on this a bit? I think it has something to do with Riemann sums.

A: For a partition $P:x_0<x_1<x_2<\dots<x_n$ we define the upper riemann sum as
$$\bar{S}_P(f)=\sum_{k=0}^{n-1}\max_{x\in [x_k,x_{k+1}]}f(x) \cdot(x_{k+1}-x_k)$$
and the lower riemann sum as
$$\underline{S}_P(f)=\sum_{k=0}^{n-1}\min_{x\in [x_k,x_{k+1}]}f(x) \cdot(x_{k+1}-x_k)$$
Notice that if $f$ is positive, then $\bar{S}_P(f)$ will be a sum of areas of rectangles, that are above the graph, and $\underline{S}_P(f)$ a sum of areas of rectangles under the graph, so intutively we should have $$\underline{S}_P(f) \leq \int_{x_0}^{x_n}f(x)dx \leq \bar{S}_P(f)$$
In your example we get
$$\bar{S}_P(f)=\sum_{k=0}^{3}\max_{x\in [k,k+1]}f(x) \cdot(k+1-k)=1+2+4+5 = 12$$
and
$$\underline{S}_P(f)=\sum_{k=0}^{3}\min_{x\in [k,k+1]}f(x) \cdot(k+1-k)=1+1+2+4=8$$


text:
Q: Cannot disinstall PostgreSql by Script Bash - Linux - Must Not open dialog confirmation My goal is to uninstall PostgreSql (installed on a Linux host- Ubuntu 18.04 LTS) using a bash script file.
I use the following command:
apt remove --purge -y postgresql-12 && apt autoremove -y

The problem is that, launching it from the terminal, at a certain point it opens a confirmation window (you have to press enter to go on).
So when I put this command in the bash script file, it gets stuck (as I assume it is waiting for confirmation).
I tried also with 'apt-get' instead of 'apt', but nothing changed.
How can I solve the problem?


text:
Q: How to get signed envelop in docusign I am working on Docusign and PHP scripting language.
I have completed signing process and i get response from this code.
$response = $service->views->getRecipientView(
                $returnUrl,
                $envelopeId,
                $contact_name,
                $contact_email,
                $client_id,
                $authMethod);

Now i need to get envelop that are signed by user. I get signed envelop in mail but i need to download it from script or get docusign url from which i can download.It would be great help if anyone give solution or provide any link.

A: You successfully get the embedded recipient (signer) view url, redirect to it, and the signer signs.
Now you want to retrieve the signed documents? (And the Certificate of Completion too?)
Use the EnvelopeDocuments::List method. Here is a recipe which retrieves the signed files.
You should first check the envelope status to ensure that the envelope was completed.


text:
Q: SilverStripe convertDataObjectSet is stripping additional properties I am attempting to add the 'AbsoluteLink' property to each DataObject in a DataList and then convert the list to JSON with JSONDataFormatter::convertDataObjectSet().
I have the following function:
public function json() {
    $data      = ResourceCentreArticlePage::get()->filter('ShowInMenus', '1')->filter('ShowInSearch', '1')->sort('Created', 'DESC');
    $pageArray = new ArrayList();

    foreach ($data as $page) {
        $page->AbsoluteLink = $page->AbsoluteLink();
        $pageArray->push($page);
    }

    // If I dump out the content of $pageArray here the object has the AbsoluteLink property

    $jsonFormatter = new JSONDataFormatter();
    $jsonData      = $jsonFormatter->convertDataObjectSet($pageArray);

    // If I dump out the content of $jsonData here there is no AbsoluteLink property

    $this->response->addHeader("Content-type", "application/json");

    return $jsonData;
}

The problem:
The AbsoluteLink property is removed after running the $pageArray through the convertDataObjectSet method.
What am I missing?

A: Using $jsonFormatter->setCustomAddFields(); will help here.
Add the following to the Page class:
public function getMyAbsoluteLink() {
    return $this->AbsoluteLink();
}

For example to the Page.php:
class Page extends SiteTree {
    public function getMyAbsoluteLink() {
        return $this->AbsoluteLink();
    }
}

And use that "magic field" like this:
public function json() {
    $pages = Page::get()
        ->filter('ShowInMenus', '1')
        ->filter('ShowInSearch', '1')
        ->sort('Created', 'DESC');

    $jsonFormatter = new JSONDataFormatter();
    // add your custom field
    $jsonFormatter->setCustomAddFields(["MyAbsoluteLink"]);
    $jsonData = $jsonFormatter->convertDataObjectSet(
        $pages
    );

    return $jsonData;
}

Note the $jsonFormatter->setCustomAddFields(["MyAbsoluteLink"]); and I removed the array manipulation.
Also I removed your array manipulation. How the convertDataobjectSet function works it seems you can't amend the objects before it runs.


text:
Q: Navigation bar color not changing when it is set in the AppBar Minimal reproducible code:
class MyPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    int count = 0;
    Widget child = FooPage();
    return StatefulBuilder(
      builder: (_, update) {
        return Scaffold(
          floatingActionButton: FloatingActionButton(
            onPressed: () => update(() => child = (++count).isEven ? FooPage() : BarPage()),
          ),
          body: child,
        );
      },
    );
  }
}

class FooPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Foo'),
        systemOverlayStyle: SystemUiOverlayStyle(
          statusBarColor: Colors.black,
          systemNavigationBarColor: Colors.black,
        ),
      ),
    );
  }
}

class BarPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Bar'),
        systemOverlayStyle: SystemUiOverlayStyle(
          statusBarColor: Colors.grey,
          systemNavigationBarColor: Colors.grey,
        ),
      ),
    );
  }
}

As you can see, the status bar color changes but the navigation bar color stays the same. Why is it so? I am testing this on Android.
The two widgets are meant to be used in this way (not through the Navigator).

A: its better put your code in main method above of runApp() and run gain
  SystemChrome.setSystemUIOverlayStyle(
  SystemUiOverlayStyle(systemNavigationBarColor: Colors.black));


text:
Q: Query to identify contiguous ranges I'm trying to write a query on the below data set to add a new column which has some sort of "period_id_group".
contiguous  new_period  row_nr  new_period_starting_id
0           0           1       0
1           1           2       2
1           0           3       0
1           0           4       0
1           1           5       5
1           0           6       0

What I'm trying to get is:
contiguous  new_period  row_nr  new_period_starting_id    period_id_group
0           0           1       0                         0
1           1           2       2                         2
1           0           3       0                         2
1           0           4       0                         2
1           1           5       5                         5
1           0           6       0                         5

The logic is that for each 0 value in the new_period_starting_id, it has to get the >0 value from the row above.
So, for row_nr = 1 since there is no row before it, period_id_group is 0.
For row_nr = 2 since this is a new perid (marked by new_period = 1), the period_id_group is 2 (the id of this row).
For row_nr = 3 since it's part of a contiguous range (because contiguous =  1), but is not the start of the range, because it's not a new_period (new_period = 0), its period_id_group should inherit the value from the previous row (which is the start of the contiguous range) - in this case period_id_group = 2 also.
I've tried multiple versions but couldn't get a good solution for SQL Server 2008R2, since I can't use LAG().
What I have, so far, is a shameful:
select *
from #temp2 t1
left join (select distinct new_period_starting_id from #temp2) t2
    on t1.new_period_starting_id >= t2.new_period_starting_id
where 1 = case
            when contiguous = 0
                then 1
            when contiguous = 1 and t2.new_period_starting_id > 0
                then 1
            else 1
        end
order by t1.rn

Sample data script:
declare @tmp2 table (contiguous int
                   , new_period int
                   , row_nr int
                   , new_period_starting_id int);

insert into @tmp2 values (0, 0, 1, 0)
                        , (1, 1, 2, 2)
                        , (1, 0, 3, 0)
                        , (1, 0, 4, 0)
                        , (1, 1, 5, 5)
                        , (1, 0, 6, 0);

Any help is appreciated.

A: So, if I'm understanding you correctly, you just need one additional column.
SELECT t1.contiguous, t1.new_period, t1.row_nr, t1.new_period_starting_id,
    (SELECT TOP 1 (new_period_starting_id)
     FROM YourTable t2
     WHERE t2.row_nr <= t1.row_nr
         AND t2.period_id_group > 0 /* optimization */
     ORDER BY t2.row_nr DESC /* optimization */) AS period_id_group
FROM YourTable t1

A: Here is yet another option for this.
select t1.contiguous
    , t1.new_period
    , t1.row_nr
    , t1.new_period_starting_id
    , x.new_period_starting_id
from @tmp2 t1
outer apply
(
    select top 1 *
    from @tmp2 t2
    where (t2.row_nr = 1
        or t2.new_period_starting_id > 0)
        and t1.row_nr >= t2.row_nr
    order by t2.row_nr desc
) x

A: Found the solution:
select *
    , case
        when contiguous = 0
            then f1
        when contiguous = 1 and new_periods = 1
            then f1
        when contiguous = 1 and new_periods = 0
            then v
        else NULL
    end [period_group]
from (
    select *
        , (select max(f1) from #temp2 where new_period_starting_id > 0 and rn < t1.rn) [v]
    from #temp2 t1
    ) rs
order by rn


text:
Q: Dynamically cross-join multiple different-size collections together in foreach ? (laravel) want crossJoin each item in foreach with together.
foreach ($productOption as $item) {
        $productOptionValue = ProductOptionValue::->where('product_option_values.product_option_id', $item->id)->get();
        $mycrossjoin = $productOptionValue->crossJoin($productOptionValue->next->$item);
    }