text:
Q: what is the difference (system resource wise) between using views and temporary tables? what is the difference (system resource wise) between using views and temporary tables? I have a complex report that will be built from numerous tables. I am trying to determine if I should use a series of views or temp tables (SQL 2008). Is there a difference?

A: A view is just an alias for the query.
A temporary table materializes the resultset.
Views, being just aliases, don't take time to be filled, but they may be less performant when being selected from.
Temporary tables take some time (and effort) to be populated but can be more efficient.
Note that SQL Server optimizer can create a temporary table in runtime from a view (which you will see in the query statistics and plan as Worktable in tempdb), index it and populate it with the rows, and even add the missing rows on demand (these operations are called Eager Spool and Lazy Spool)
This makes the view rewinding much more efficient: instead of reevaluating the whole view each time its results are needed, the results are stored in a temporary table either all at once (as in Eager Spool), or incrementally (as in Lazy Spool).
SQL Server, though, can materialize views by creating clustered indexes on them, though not all views can be indexed (to be indexable, the view must meet certain conditions described here).

A: View is just a "fixed" SELECT statement with a name. If you have complex query, or in other case, if you want to show only partial data from the table you use view. Views exists in the database you have created it in.
Temporary table is the table like any others, but it is stored in tempdb database and is deleted after you finish stored procedure, etc. (local table). There can be seen only in the scope of the procedure you use it in. There are also global temporary tables, which can be seen outside the procedure.

A: chances are that an indexed view would probably work for you more than inserting data into temp table/s.  also, instead of using a series of views you'd be better of consolidating into one view.  it's much easier to manage and will most likely improve performance.  also, the right indexes on your source tables will also improve performance.


text:
Q: WordPress pre_get_posts causing custom menu to fail I'm trying to target the tag template with the pre_get_posts function to add post types to the query. The code I am using seems super basic and should work no problem. However, it's not and is breaking the query and more importantly, somehow it's breaking the custom menus from being returned on that tag template only.
function tags_support_query($query) {
    if ( is_tag() ) {
        $query->set('post_type', 'any');
    }
}

add_action('pre_get_posts', 'tags_support_query');

Thank you in advance for any input/advice.

A: Add $query->is_main_query() constraint to if statement like below :
function tags_support_query($query) {
    if( is_tag() && $query->is_main_query() ) {
        $query->set('post_type', 'any');
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to change mouse scrolling speed in Ubuntu? I use Ubuntu 22.04.
How to change mouse scrolling speed in Ubuntu?
I went to mouse settings and I found a mouse speed option, but nothing for the mouse wheel scrolling.

A: This is a long standing issue in Ubuntu and other Linux distributions. You can increase the amount of steps per scroll using imwheel.
In some cases you'll still want to use single step scrolling. You can configure imwheel to use single steps when a key such as Alt is held down.
https://fostips.com/mouse-wheel-touchpad-scroll-speed-ubuntu/
You will need to switch from Wayland to Xorg to make this work. Hopefully a better solution will be developed some day.

A: tl;dr: imwheel is the easiest and possibly the only one that will work for you. Here's a quick & simple guide https://askubuntu.com/a/1441416/1654422
Be aware if you are using a laptop and lets say you "undock" and want to use the touchpad for a while, you will have to pkill imwheel otherwise scrolling will get jumpy, as mentioned here
Why does that happen? Believe it or not, changing the scroll speed is not supported (at least not out of the box) by neither gnome or libinput. This has been reported to libinput maintainers but they believe people are barking at the wrong tree and this should be fixed somewhere else.
There's also this work-around but it didn't work for me, but some had success.


text:
Q: object from two-level array. causes Unexpected token [ var data=[['a','1'],['b','2']];

This should be simple to make into an object
var Obj={data[0][0]:data[0][1],data[1][0]:data[1][1]}

But instead creates SyntaxError: Unexpected token [
Why does JavaScript not see the array part properly when I try to construct an object in this way? When outside of the {} object
console.log(data[0][0]);    // "a"

I am puzzled as to why this is throwing an error as if there is a no-no rule I am missing. Am I forced into storing the data parts in temporary vars? like so:
var data=[['a','1'],['b',2]];

var t1=data[0][0]
,   t2=data[0][1]
,   t3=data[1][0]
,   t4=data[1][1];

var obj={t1:t2,t3:t4};     // no error

That would seem too restrictive for JavaScript I am definitely missing something here!

A: You can't do this, it's not a valid syntax for an object literal:
var Obj= {
     data[0][0]:data[0][1],
     data[1][0]:data[1][1]
}

You can't use a variable as the name of a property in an object literal like that. In your second example:
var obj={t1:t2,t3:t4};     // no error

You get no error, but you also don't get what you expected either. If you look at the object generated, you'll see this:
{ t1: "1", t3: 2 };

In other words you created an object with properties t1 and t3, not a and b.
You have to create an empty object and populate it using the bracket notation []:
var obj = {};
obj[data[0][0]] = data[0][1];
obj[data[1][0]] = data[1][1];

Any time you want to use a variable as a property name for an object, you need to use the bracket notation. In other words this:
var t1 = "B";
obj[t1] = "foo";

is different from this:
var t1 = "B";
obj.t1 = "foo";

In the first case you set a property called B on obj to the string "foo". In the second case you set a property t1 on obj to "foo". The object literal syntax is more like using the dot notation.
To make what you want to do simpler, you can loop through the array as in @Nikos' answer. Or you can get fancy and use .reduce:

var data = [
  ['a', '1'],
  ['b', 2]
];

var obj = data.reduce(function(curr, next) {
  curr[next[0]] = next[1];
  return curr;
}, {});

alert(JSON.stringify(obj));

A: iI think this is much simpler for what you want to do.
var data=[['a','1'],['b','2']];
var Obj={};
for (i=0; i<data.length; i++) {
    Obj[data[i][0]]=data[i][1]
}
console.log(Obj); // returns  Object { a="1", b="2"}


text:
Q: Call LaTeX (not PDFLaTeX) in Miktex I am a bit confused because in the "good old days", the command latex seemed to create a dvi document.
Now, when I run latex, obviously pdflatex is run, even if I specify an output format:
C:\Users\jfabi\OneDrive\LaTeX>latex previewTest.tex -output-format=dvi
This is pdfTeX, Version 3.141592653-2.6-1.40.22 (MiKTeX 21.3)

Can somebody tell me how to generate a plain old dvi document from a tex source?


text:
Q: MySQL How to add a "total" row (with addition and subtraction) to a query result  Problem:
So, I have two tables like such:
main_table:                      property_table:
+----------------------------+   +-------------------------+
| event| property_id | value |   | property_id | name      |
+----------------------------+   +-------------------------+
| 1    | 1           | 100   |   | 1           | property1 |
| 2    | 1           | 200   |   | 2           | property2 |
| 3    | 2           |  50   |   | 3           | property3 |
| 4    | 3           |  10   |   +-------------+-----------+
| 5    | 3           |  30   |

And using the following query:
SELECT pt.name, SUM(value) as subtotal
    FROM main_table as mt
LEFT JOIN property_table as pt
    ON mt.property_id = pt.property_id
GROUP BY pt.name;

I obtain the following table:
+-------------------------+
| name         | subtotal |
---------------------------
| property1    | 300      |
| property2    |  50      |
| property3    |  40      |

Now I would like to add a row to this table which will calculate the total among all properties. But here is the catch, some properties are to be added and some subtracted. So for the sake of argument lets say it is total = property1 - property2 + property3.
 Expected output:
+-------------------------+
| name         | subtotal |
---------------------------
| property1    | 300      |
| property2    |  50      |
| property3    |  40      |
| total        | 290      |

 Note:
I now "GROUP BY" can be used with "WITH ROLLUP", but this would exclusively add all the values. I guess you could technically allow negative numbers into the table and solve everything with "WITH ROLLUP", but this seems prone to user error. Is it over the top to avoid the negative integers?

A: You could use a subquery based  on a union all
one select for values and one for total
select name, subtotal
from  (
    SELECT pt.name, SUM(value) as subtotal , 0  ord
    FROM main_table as mt
    LEFT JOIN property_table as pt ON mt.property_id = pt.property_id
    GROUP BY pt.name
    union  all
    SELECT 'Total', SUM(value) , 1
    FROM main_table as mt
    LEFT JOIN property_table as pt ON mt.property_id = pt.property_id
    group by 1
) t
order by ord, name

A: At the end I found that a case could be implemented inside the SUM when using GROUP BY WITH ROLLUP:
    SELECT  pt.name,
            SUM(
                CASE
                    WHEN pt.name = 'property2' THEN -mt.value
                    ELSE mt.value
                END
            ) as subtotal
    FROM    main_table as mt
    LEFT JOIN property_table as pt
        ON mt.property_id = pt.property_id
    GROUP BY pt.name WITH ROLLUP;

But it the actual implementation I choose to add a column called action:
property_table:
+-------------------------+---------+
| property_id | name      | action  |
+-------------------------+---------+
| 1           | property1 |   '+'   |
| 2           | property2 |   '-'   |
| 3           | property3 |   '+'   |
+-------------+-----------+---------+

And replace the CASE with an IF:
    SELECT  pt.name,
            SUM(IF(pt.action='-', -mt.value, mt.value) as subtotal
    FROM    main_table as mt
    LEFT JOIN property_table as pt
        ON mt.property_id = pt.property_id
    GROUP BY pt.name WITH ROLLUP;


text:
Q: How can i change color of Saturdays and Sundays in Calender dates? I want change the color of Saturdays and  Sundays in a Calendar Control in Android .how can it possible please provide any sample code for that?
Thanks in Advance......


text:
Q: Making button enable and disabled for a certain time I'm new in Android Studio. I want to make a chat apps.
So, I want to make a delay after he/she send a message.
For an example, I write input "Hello", if I send again, it will display Toast to show time, 5 seconds, 4 seconds until finish. Then I will able to send the message again.
And, if I press the button within that time, it will show how many seconds to able to send the message.
I made one, but not run as expected.
private void buttonFabSend() {
        floatingActionButtonSendText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new CountDownTimer( 5000, 1000){
                    @Override
                    public void onTick(long millisUntilFinished) {
                        Toast.makeText(getApplicationContext(),millisUntilFinished/1000 +"seconds",Toast.LENGTH_SHORT ).show();
                        floatingActionButtonSendText.setEnabled(false);
                    }
                    @Override
                    public void onFinish() {
                        editTextInput = findViewById(R.id.editTextChat);
                        if (TextUtils.isEmpty(editTextInput.getText().toString())) {
                            editTextInput.setError("Enter your message");
                            editTextInput.requestFocus();
                            return;
                        }
                        floatingActionButtonSendText.setEnabled(true);
                        FirebaseDatabase.getInstance().getReference().child("chat").push().setValue(new chatMessage(editTextInput.getText().toString(), FirebaseAuth.getInstance().getCurrentUser().getDisplayName(), String.valueOf(FirebaseAuth.getInstance().getCurrentUser().getPhotoUrl())));
                        editTextInput.setText("");
                    }
                }.start();
            }
        });
    }

A: Uncomment your code Of Sending message
    int _count = 5;//5 seconds
    private boolean canSendMessage = true;
    private Runnable countDown = new Runnable() {
        @Override
        public void run() {
            while (_count > 0) {
                _count--;
                try {
                    Thread.sleep(1000);//1 second
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            _count = 5;//again set to 5 seconds
            canSendMessage = true;//enable send

        }
    };

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

        final Button send = (Button) findViewById(R.id.send);
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (canSendMessage) {
                    //
//                    editTextInput = findViewById(R.id.editTextChat);
//                    if (TextUtils.isEmpty(editTextInput.getText().toString())) {
//                        editTextInput.setError("Enter your message");
//                        editTextInput.requestFocus();
//                        return;
//                    }
//                    floatingActionButtonSendText.setEnabled(true);
//                    FirebaseDatabase.getInstance().getReference().child("chat").push().setValue(new chatMessage(editTextInput.getText().toString(), FirebaseAuth.getInstance().getCurrentUser().getDisplayName(), String.valueOf(FirebaseAuth.getInstance().getCurrentUser().getPhotoUrl())));
//                    editTextInput.setText("");
                    canSendMessage = false;
                    Thread t = new Thread(countDown);
                    t.start();
                } else {
                    Toast.makeText(UploadTest.this, "You can send After " + _count + " Seconds", Toast.LENGTH_SHORT).show();
                }

            }
        });

    }

A: You may use some logic like this:
private long delay = 4000;

void onViewClick(View view) {
    view.setEnabled(false);
    view.postDelayed(() -> {
        view.setEnabled(true);
    }, delay);
}

Better you may want to check if after the delay the view is still attached to window or not
private long delay = 4000;
void onViewClick(View view) {
    view.setEnabled(false);
    view.postDelayed(() -> {
        if (ViewCompat.isAttachedToWindow(view) {
            view.setEnabled(true);
        }
    }, delay);
}

A: In your code, everytime new countdown timer will initialize, so it will not work proper, what you need to do is only start countdown timer once until its finish. please try below code
boolean isRunning = false;
long currentMillisUntilFinished = 0;

and replace floatingActionButtonSendText click event with below code
floatingActionButtonSendText.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        if (isRunning) {
            Toast.makeText(getApplicationContext(), "seconds remaining: " + currentMillisUntilFinished / 1000, Toast.LENGTH_SHORT).show();
            return;
        }

        new CountDownTimer(5000, 1000) {

            public void onTick(long millisUntilFinished) {
                currentMillisUntilFinished = millisUntilFinished;
                isRunning = true;

            }

            public void onFinish() {
                isRunning = false;
                editTextInput = findViewById(R.id.editTextChat);
                if (TextUtils.isEmpty(editTextInput.getText().toString())) {
                    editTextInput.setError("Enter your message");
                    editTextInput.requestFocus();
                    return;
                }
                FirebaseDatabase.getInstance().getReference().child("chat").push().setValue(new chatMessage(editTextInput.getText().toString(), FirebaseAuth.getInstance().getCurrentUser().getDisplayName(), String.valueOf(FirebaseAuth.getInstance().getCurrentUser().getPhotoUrl())));
                editTextInput.setText("");
            }

        }.start();
    }
});


text:
Q: Objective-C Translate UIImageView on z-axis I am wondering if it is possible to take an image view and turn it on the z-axis so that the left side appears closer to the user viewing the application and the right side gets narrower as if it was getting farther away. I was thinking of doing this with OpenGL, but was hoping it could be done with Core Animations.  Has anyone had any experience with this?
 UIImageView *front = [[UIImageView alloc] init];
 UIImageView *left = [[UIImageView alloc] init];

 float trialSide = 30 * 5.7;
 front.frame = CGRectMake(180, 280, 360, 295);
 front.image = [img croppedImage:CGRectMake(trialSide, trialSide, imgWidth - (trialSide *2), imgHeight - (trialSide * 2))];
 left.frame = CGRectMake(149, 280, 30, 295);
 left.image = [img croppedImage:CGRectMake(0, trialSide, trialSide, imgHeight - (trialSide * 2))];

 [self.view addSubview:front];
 [self.view addSubview:left];

 CALayer *layer = front.layer;

 CATransform3D rotationAndPerspectiveTransform = CATransform3DIdentity;
 rotationAndPerspectiveTransform.m34 = 1.0 / -1000;
 front.frame = CGRectMake(180, 280, 360, 295);
 rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, 30.0f * M_PI / 180.0f, 0.0f, 1.0f, 0.0f);
 layer.transform = rotationAndPerspectiveTransform;
 [self.view layoutSubviews];


text:
Q: Getting count groupby right on pandas I have this dataframe:
    code
0   0000
1   0000
2   0123
3   0123
4   4567

I want to groupby code and count how many of each code there is in the dataframe, so it get to look like this:
   code  count
0  0000      2
1  0123      2
2  4567      1

I was using: group=df.groupby('code').agg('count')
However I wasn't getting it right.
Can someone help?

A: Had a similar problem and I'm forming @user3483203's comments into an answer so the question can be marked as answered.
Using:
df.groupby('code').size()

# OR

df.code.value_counts()

This groups all rows with matching codes and outputs the total for each code.


text:
Q: How to find which thread currently owns the lock in java I have a synchronized method in a singleton class which is called by many threads simultaneously. Is there any java API available to check which thread is currently owning the lock ?

A: Precise answer given by erickson [here]

Question:  Programmatically determine which Java
thread holds a lock ?

Answer :
You can only tell whether the current
thread holds a normal lock
(Thread.holdsLock(Object)). You can't
get a reference to the thread that has
the lock without native code.
However, if you're doing anything
complicated with threading, you
probably want to familiarize yourself
with the java.util.concurrent
packages. The ReentrantLock does allow
you to get its owner (but its a
protected method, so you'd have to
extend this). Depending on your
application, it may well be that by
using the concurrency packages, you'll
find that you don't need to get the
lock's owner after all.
There are non-programmatic methods to
find the lock owners, such as
signaling the JVM to issue a thread
dump to stderr, that are useful to
determine the cause of deadlocks.

By the way,please have a look at the following link. It provides all information about thread related aspects :

*

*JVM's ThreadMXBean

A: You could perhaps print out Thread.currentThread() in your synchronized method.

A: The jvm ThreadMXBean gives you access to all kinds of thread related info, including which threads own which locks.

A: If you're simply looking into debugging the software to figure out which thread is causing the blocking and which one being blocked, I'd suggest simply getting a thread dump of the live situation. I wouldn't use this kind of logic as part of normal program flow.
http://java.sun.com/developer/technicalArticles/Programming/Stacktrace/


text:
Q: C# login bot, .Net Framework 4 I am trying to do a simple web bot, that connects to target web page, and fills login data and than sends the information. Unfortunately I need it to be Windows XP compatible, so I am forced to use .Net Framework 4.
I know the login fill bar and password fill bar ids from firebug. Normally I would use WebBrowser with GetElementById method, but it's not an option in .Net 4. Is there any alternative how to do this in HttpWebRequest class for example?
I don't have to see anything, just need to fill in the informations and than be able to "click" in the navigation menu and download some data.
Edit: added not working afford

    public void Send(string login, string password)
    {
        MyWebBrowser.Document.GetElementById("username_vmlogin"); //the GetElementById is red underlined in VS 2013
    }

It says this error:
Error   1   'object' does not contain a definition for 'GetElementById' and no extension method 'GetElementById' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

A: WPF's WebBrowser is a wrapper over the MSHTML Web Browser control.
The WPF WebBrowser's Document property is an 'object', not a strongly typed HtmlDocument as in Windows Forms. As the documentation explains, The Document object needs to be cast to the COM interface you are expecting..
The Document property implements several of the IHTMLDocumenX interfaces. getElementById is defined in IHTMLDocument3, which means you'd have to write:
IHTMLDocument3 doc=MyWebBrowser.Document;
IHTMLElement elt=doc.getElementById("abc");

You can avoid casting by using a dynamic variable, eg:
dynamic doc=MyWebBrowser.Document;
dynamic elt=doc.getElementById("abc");
...


text:
Q: Optimization Nurse Assignment I'm new in CPLEX Optminization and at the moment, I'm writing a model that should assign nurses to surgery cases that fit their competences, specialty…
Actually I thought that the model is working correctly, but when I am trying it, it assigns nurses to cases, in which they are not allowed to work.
I hope somebody here will make time to look at the model and can help me. So here is the existing model (very easy at the moment with 5 nurses and one case):
.mod:
  // indices

    tuple nurses {
      key int number_nurses ;
      string roles ;
      string specialty ;
      string compentency ;
      int shift_start ;
      int shift_end ;
      }

 tuple shifts {
 int shift_start ;
 int shift_end ;
 }
 {shifts} shift = ... ;

 {nurses} nurse = ... ;

 int  j = ... ;
 range available_ORs = 1..j ;

 {string} roles = ... ;

 {string} specialty = ... ;

 tuple cases {
  key int number_cases ;
  int start_time ;
  int end_time ;
  int duration ;
  int demand_RN ;
  int demand_ST ;
  int available_ORs ;
  string specialty_needed ;
  string competency_needed ;
}
 {cases} case = ... ;

 //{string} shifts = ... ;

 {string} competency = ... ;

 int h = ... ;
 range time_intervals = 1..h ;

 // parameters

 int P1 [nurse][shift] = ... ;
 int P2 [nurse][roles][specialty][competency] = ... ;
 int P3 [case][available_ORs] = ... ;
 int P4 [time_intervals][case][specialty][competency] = ... ;    // Auf Complexity innerhalb des Cases zugreifen
 int P5 [time_intervals][case][roles] = ... ;
 int P6 [case][time_intervals] = ... ;
 int P7 [case] = ... ;
 int P8 [time_intervals][shift] = ...;
 int M = ... ;

 // decision variables

 dvar boolean y [nurse][case][roles][time_intervals] in 0..1 ;      // 1: Nurse is assigened to case to perform role in time interval, 0: otherwise
 dvar boolean x [nurse][case][roles] in 0..1 ;

 dvar int de [time_intervals][case][roles] in 0..1 ;
 dvar int dev [time_intervals][nurse] in 0..1  ;
 dvar int dev2 [nurse][time_intervals] in 0..1 ;
 dvar int xdev [nurse][available_ORs] in 0..1  ;
 dvar int nc [nurse][case] in 0..1  ;
 dvar int cd [nurse][case] in 0..1  ;

  // deviation variable

  dvar int DE ;
  dvar int DS ;
  dvar int DF ;
  dvar int XDEV ;
  dvar int NCT ;
  dvar int CDT ;

 // Objective function

  minimize (DE+DF+DS+XDEV+NCT+CDT) ;

 // Hard Constraints

  subject to {

   forall (i in nurse, h in time_intervals)
     cons_01:      // each nurse is assigned to at most one case in each time interval and performs a single role
     sum (c in case,k in roles) y[i][c][k][h] <= 1 ;

   forall (i in nurse, c in case, k in roles, h in time_intervals)
    cons_02:      // in each shift, cases will be assigned to the nurses who are working during their regular or authorized overtime hours
     y[i][c][k][h] <= sum (s in shift) ((P1[i][s])*P8[h][s]) ;

   forall (i in nurse)
     cons_03:      //total working hours for a nurse each day must be less than his or her total regular and overtime working hours
     sum (c in case, k in roles, h in time_intervals) y[i][c][k][h] <= sum (s in shift, h in time_intervals) ((P1[i][s])*P8[h][s]) ;

   forall (i in nurse, c in case, k in roles, h in time_intervals)
     cons_04:      // assigned to a case only if their skill level is high enough to handle the specialty requirements and have sufficient competency to deal with its procedural complexities
     y[i][c][k][h] <= P6[c][h]*sum (q in specialty, p in competency) (P4[h][c][q][p]*P2[i][k][q][p]) ;

   forall (c in case, k in roles, h in time_intervals)
     cons_05:      // see cons_04
     sum (i in nurse) y[i][c][k][h] >= P6[c][h] ;

   forall (i in nurse, c in case, k in roles)
     cons_06:      //nurses perform the same role for the entire duration of a case
     sum (h in time_intervals) y[i][c][k][h] <= M * x[i][c][k] ;

   forall (i in nurse, c in case)
     cons_07:      // see cons_06
     sum (k in roles) x[i][c][k] <= 1 ;

  }

  // soft constraints
  subject to {

    forall (c in case, k in roles, h in time_intervals)
     cons_08:      // permit undercoverage, preferred that nurses work continuously during their regular hours rather than having idle perijjjods
     sum (i in nurse) y[i][c][k][h] * de[h][c][k] >= P5[h][c][k] * P6[c][h] ; //momentan zu viele nurses, daher zu viele Zuordnungen

   forall (c in case, k in roles)
     cons_09:      // see cons_08
     DE >= sum (h in time_intervals) de[h][c][k] ;

   /*forall (i in nurse, h in time_intervals)
     cons_10:      // avoid idle times: maximum number of times that nurses work nonconsecutive hours will be minimized along with idle time hours during the shift
   -dev[h][i] <= sum (c in case, k in roles) y[i][c][k][h+1] - sum (c in case, k in roles) y[i][c][k][h] <=dev[h][i] ;*/

 forall (i in nurse)
   cons_11:      // see cons_10
     DS >= sum (h in time_intervals) dev[h][i] ;

   forall(i in nurse, j in available_ORs)
     cons_12:      // account for the preference that nurses work continuously in one operating room: maximum number of ORs is reduced as much as possible
     sum (c in case, k in roles, h in time_intervals) (y[i][c][k][h] * P3[c][j]) <= M * xdev[i][j] ;

   forall (i in nurse)
     cons_13:     // see cons_12
     sum (j in available_ORs) xdev[i][j] <= XDEV ;

   forall (i in nurse, h in time_intervals)
     cons_14:      // record overtime: maximum number of times a nurse is working during overtime is as low as possible
     sum (s in shift) P1[i][s] * 1 * sum (c in case, k in roles) y [i][c][k][h] <= dev2[i][h] ;

   forall (i in nurse)
     cons_15:      // see cons_14
     DF >= sum (h in time_intervals) dev2[i][h] ;

   forall (i in nurse, c in case)
     cons_16:      // if nurse assigned to surgery, (s)he will stay for entire duration of the case unless there is a greater need for that nurse elseway, limit the movement of nurses between cases
     sum (k in roles, h in time_intervals) y[i][c][k][h] - P7[c] + M * cd[i][c] + M * (1 - nc[i][c]) >= 0 ;

   forall (i in nurse, c in case)
     cons_17:      // see cons_16
     sum (k in roles, h in time_intervals) y[i][c][k][h] <= M * nc[i][c] ;

   forall (i in nurse)
     cons_18:      // see cons_16
     sum (c in case) nc[i][c] <= NCT ;

   forall (i in nurse)
     cons_19:      // see cons_16
     sum (c in case) cd[i][c] <= CDT ;

  }

dat.
 nurse = {
    < 1, "RN", "cardio", "high", 6, 14 > ,
    < 2, "ST", "cardio", "high", 10, 18 > ,
    < 3, "RN", "neuro", "high", 14, 22 > ,
    < 4, "RN", "cardio", "intermediate", 14, 22 > ,
    < 5, "RN", "cardio", "high", 22, 6 > ,
    } ;

 j = 2 ;

 roles = { "RN" , "ST" } ; // RN can work as ST if necessary, but a ST can not work as RN

 specialty = { "ortho", "neuro", "cardio" } ;

 case = {
    < 1, 8, 15, 7, 1, 0, 1, "cardio", "intermediate" > ,
    } ;

  shift = { < 6, 14 > < 10, 18 > < 14, 22 > < 22, 6 >} ;

  competency = { "low", "intermediate", "high" } ;

  h  = 24 ;

  // Parameter

  P1 = [
  [1 0 0 0]
  [0 1 0 0]
  [0 0 1 0]
  [0 0 1 0]
  [0 0 0 1]
  ] ;

  P2 = [
  [[[1 1 1][0 0 0][0 0 0]][[1 1 1][0 0 0][0 0 0]]]
  [[[0 0 0][0 0 0][0 0 0]][[1 1 1][0 0 0][0 0 0]]]
  [[[0 0 0][1 1 1][0 0 0]][[0 0 0][1 1 1][0 0 0]]]
  [[[1 1 0][0 0 0][0 0 0]][[1 1 0][0 0 0][0 0 0]]]
  [[[1 1 1][0 0 0][0 0 0]][[1 1 1][0 0 0][0 0 0]]]
  ] ;

  P3 = [
  [1 0]
  ] ;

  P4 = [
  [[[0 0 0][0 0 0][0 0 0]]]
  [[[0 0 0][0 0 0][0 0 0]]]
  [[[0 0 0][0 0 0][0 0 0]]]
  [[[0 0 0][0 0 0][0 0 0]]]
  [[[0 0 0][0 0 0][0 0 0]]]
  [[[0 0 0][0 0 0][0 0 0]]]
  [[[0 0 0][0 0 0][0 0 0]]]
  [[[0 1 0][0 0 0][0 0 0]]]
  [[[0 1 0][0 0 0][0 0 0]]]
  [[[0 1 0][0 0 0][0 0 0]]]
  [[[0 1 0][0 0 0][0 0 0]]]
  [[[0 1 0][0 0 0][0 0 0]]]
  [[[0 1 0][0 0 0][0 0 0]]]
  [[[0 1 0][0 0 0][0 0 0]]]
  [[[0 0 0][0 0 0][0 0 0]]]
  [[[0 0 0][0 0 0][0 0 0]]]
  [[[0 0 0][0 0 0][0 0 0]]]
  [[[0 0 0][0 0 0][0 0 0]]]
  [[[0 0 0][0 0 0][0 0 0]]]
  [[[0 0 0][0 0 0][0 0 0]]]
  [[[0 0 0][0 0 0][0 0 0]]]
  [[[0 0 0][0 0 0][0 0 0]]]
  [[[0 0 0][0 0 0][0 0 0]]]
  [[[0 0 0][0 0 0][0 0 0]]]
  ] ;

  P5 = [
  [[0 0]]
  [[0 0]]
  [[0 0]]
  [[0 0]]
  [[0 0]]
  [[0 0]]
  [[0 0]]
  [[1 0]]
  [[1 0]]
  [[1 0]]
  [[1 0]]
  [[1 0]]
  [[1 0]]
  [[1 0]]
  [[0 0]]
  [[0 0]]
  [[0 0]]
  [[0 0]]
  [[0 0]]
  [[0 0]]
  [[0 0]]
  [[0 0]]
  [[0 0]]
  [[0 0]]
  ] ;

  P6 = [
  [0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 ]
  ] ;

  P7 = [7] ;

  P8 = [
  [0 0 0 1]
  [0 0 0 1]
  [0 0 0 1]
  [0 0 0 1]
  [0 0 0 1]
  [1 0 0 0]
  [1 0 0 0]
  [1 0 0 0]
  [1 0 0 0]
  [1 1 0 0]
  [1 1 0 0]
  [1 1 0 0]
  [1 1 0 0]
  [0 1 1 0]
  [0 1 1 0]
  [0 1 1 0]
  [0 1 1 0]
  [0 0 1 0]
  [0 0 1 0]
  [0 0 1 0]
  [0 0 1 0]
  [0 0 0 1]
  [0 0 0 1]
  [0 0 0 1]
  ] ;

  M = 10 ;

When I run it, it assigns the second nurse to the case, but actually the nurse 2 is not allowed to work in this case because a RN is needed. I already tried different possibilities to write it, but I don't find the reason why…
At the moment, nurse 1 and nurse 4 are assigned as RN (which is right) and additionally also Nurse 2.
Can anybody give me some tipps or help to solve the optimization problem correctly? I would be very grateful, thank you in advance.

A: Your model is not feasible and CPLEX relaxed it. It relaxed some labeled constraints and gave you the relaxed solution. Having a look at the relaxed solution will help you debug your model.
In cplex documentation you could have a look at:

*

*IDE and OPL > CPLEX Studio IDE > IDE Tutorials

*Relaxing infeasible models


text:
Q: Referencing object from user input string I'm having a problem referencing the fields of my object from a string. Apparently I'm not allowed to do that and I'm guessing it's because the string references an entirely different memory location since it is it's own object. But I have no idea how I can do this better. Here's the code
class Truck:

    width = 48

    def __init__(self):
        self.length = 480
        self.height = 108

standardTruck = Truck()

class Bale:

    def __init__(self, length, height, width):
        self.length = length
        self.height = height
        self.width = width

sewer1 = Bale(240, 18, 24)
c9001 = Bale(480, 8, 32)
ips1 = Bale(120, 30, 30)
sewer2 = Bale(240, 20, 28)
c9002 = Bale(480, 10, 30)
ips2 = Bale (120, 12, 60)
sewer3 = Bale(240, 32, 40)
c9003 = Bale(480, 10, 40)
ips2 = Bale(120, 32, 48)

bale1 = input("What bale do you want?")
bale1Q = input("How many do you want?")

print("You chose " + bale1Q + " bales of " + bale1 + ". This bale has a width of " + bale1.width + " a height of " + bale1.height + " and a length of " + bale1.length + ".")

A: It's not really to do with memory locations. It's just that the variable bale1, even if it contains the string "sewer1", has nothing to do with the actual variable named sewer1.
To do this you probably want a dictionary instead of all those separate variables.
bales = {
    "sewer1": Bale(240, 18, 24),
    "c9001": Bale(480, 8, 32),
    "ips1": Bale(120, 30, 30),
    "sewer2": Bale(240, 20, 28),
    "c9002": Bale(480, 10, 30),
    "ips2": Bale (120, 12, 60),
    "sewer3": Bale(240, 32, 40),
    "c9003": Bale(480, 10, 40),
    "ips2": Bale(120, 32, 48)
}

Now you can do:
bale_requested = input("What bale do you want?")
bale1 = bales[bale_requested]

which looks up the given name in the dictionary, to find the corresponding Bale object.


text:
Q: Copying png file from a folder to another I have a PNG file in a folder, I want to copy this file to another folder. Is there a easy way to do this ?
Example:
//Creating PNG

              File file = new File(Environment.getExternalStorageDirectory()
                + File.separator+"/S_Temp/temp_"+formattedDate+".png");

              FileOutputStream  out = new FileOutputStream(file);
              view.mBitmap.compress(Bitmap.CompressFormat.PNG,100, out);

So, I have the PNG in the SD card in the folder "S_Temp", now I want to copy this file to a new folder in the SD card itself, say "S".
Thanks in advance
Happy Coding

A: private static void copyfile(String srFile, String dtFile){
try{
  File f1 = new File(srFile);
  File f2 = new File(dtFile);
  InputStream in = new FileInputStream(f1);

  //For Append the file.
  //OutputStream out = new FileOutputStream(f2,true);

  //For Overwrite the file.
  OutputStream out = new FileOutputStream(f2);

  byte[] buf = new byte[1024];
  int len;
  while ((len = in.read(buf)) > 0){
    out.write(buf, 0, len);
  }
  in.close();
  out.close();
  System.out.println("File copied.");
}
catch(FileNotFoundException ex){
  System.out.println(ex.getMessage() + " in the specified directory.");
  System.exit(0);
}
catch(IOException e){
  System.out.println(e.getMessage());
}
}

try this.


text:
Q: ngx-spinner not working for synchronous code Using ngx-spinner for asynchronous operations (service calls, timeouts) is working fine. When its used for synchronous code(for loop) its not showing the spinner.
Created a stackblitz demo with loop and an alert is added to stop execution of code and then spinner hide code is written, but cannot see the spinner.
 this.spinner.show();
let i;
for(i=2; i<100; i++) {
  this.numbers.push(i);
}
alert(i);
this.spinner.hide();

You can find the code here.

A: Try this...
async myFunction()
{
 this.spinner.show();
 await showSpinner2();
 this.spinner.hide();
}
showSpinner2()
{
  let i;
  for(i=2; i<100; i++) {
    this.numbers.push(i);
  }
  alert(i);
}


text:
Q: Break date range into calendar days Here is a business scenario with data:
There is a hospital with several rooms in which patients are being admitted and discharged. You are asked to generate a report that displays the 'cumulative' Length of Stay in day to day basis.
Source Table (Visit)
Visit#(int)   AdmissionDate(datetime)  DischargeDate(datetime)
1             2012-01-01               2012-01-05
2             2012-01-03               2012-01-06
3             2011-12-29               2012-01-04

The requirements is that the returned data set is in the following structure. You see, the length of stay grows incrementally with time. each record displays the number of patients in a given day and the cumulative length of stay (admission to date).
CalendarDay LenghthOfStay(day) NumberOfPatients
2011-12-29  1                  1
2011-12-30  2                  1
2011-12-31  3                  1
2012-01-01  5                  2
2012-01-02  7                  2
2012-01-03  10                 3
2012-01-04  13                 3
2012-01-05  15                 2
2012-01-06  16                 1

Thanks for your input, in advance.

A: I feel like this is very similar to your previous post, and while this isn't 100% what you want, should help get you started:
select
   CONVERT(char(10), AdmissionDate+v.number, 112)  as CalendarDay,
   ROW_NUMBER() OVER (ORDER BY CONVERT(char(10), AdmissionDate+v.number, 112))  LenghthOfStay,
   COUNT(*) NumberOfPatients
from Visit t
inner join master..spt_values v
  on v.type='P' and v.number <= DATEDIFF(d, AdmissionDate, DischargeDate)
group by CONVERT(char(10), AdmissionDate+v.number, 112)
order by CONVERT(char(10), AdmissionDate+v.number, 112)

Dates are correct and patients are correct.  Not sure you can get the length of stay with pure SQL or not.
Good luck.


text:
Q: Taurus - No module named 'molotov' I am trying to install Taurus on Windows 10 following the official guide here: https://gettaurus.org/install/Installation/#Windows
I have:

python --version

Python 3.10.4

pip --version

pip 22.0.4 from [...]\python\Lib\site-packages\pip (python 3.10)

When I run:

pip install bzt

I got errors
Collecting molotov!=2.3
  Using cached molotov-2.4.tar.gz (39 kB)
  Preparing metadata (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py egg_info did not run successfully.
  │ exit code: 1
  ╰─> [6 lines of output]
      Traceback (most recent call last):
        File "<string>", line 2, in <module>
        File "<pip-setuptools-caller>", line 34, in <module>
        File "[...]\pip-install-wxsat9xk\molotov_e61929518d6e4f7792bc3e8da8c68117\setup.py", line 7, in <module>
          from molotov import __version__  # NOQA
      ModuleNotFoundError: No module named 'molotov'

If I try to install molotov module:

pip install molotov

I got the same error:
Collecting molotov
  Downloading molotov-2.4.tar.gz (39 kB)
  Preparing metadata (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py egg_info did not run successfully.
  │ exit code: 1
  ╰─> [6 lines of output]
      Traceback (most recent call last):
        File "<string>", line 2, in <module>
        File "<pip-setuptools-caller>", line 34, in <module>
        File "[...]\pip-install-dn2q9si7\molotov_23951726c6084d76ba3fa2e918aef656\setup.py", line 7, in <module>
          from molotov import __version__  # NOQA
      ModuleNotFoundError: No module named 'molotov'
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

It seems to me crazy!
Any suggests?
Thanks
Andrea


text:
Q: Sublime text 3 with Git-Bash I was wondering how you can open Sublime text 3 with Git-Bash I keep getting errors saying that bash: subl: command not found does anyone know how to get the file to open up??

A: You need to add the folder containing subl.exe to your PATH. Here's how to do that in Windows 10:

*

*Open the Windows menu and click on Settings.

*In the search box, type in path. Choose the following from the dropdown: Edit environment variables for your account. This window should open:

*In the top pane, click on Path, then click the Edit… button. A new window will open up.

*Click the New button, then (carefully) type in C:\Program Files\Sublime Text 3. This is assuming you used the installer and didn't choose a custom location for a portable install. If you do have a portable install, use the Browse… button and select the installation folder that way.

*Hit OK to close the window, then OK again to close the other one. Finally, close out of Settings.

*Completely close out of and restart Git Bash. subl should now be available on the command line.


text:
Q: Who has done gitops with aws ssm and secrets parameters in codepipeline? Just wondering who has implemented the use of github and updating ssm parameters and secrets within a codepipeline and what's the best practices around that.
I was thinking of putting some cli commands in a shell script in github and use codepipeline to migrate it. Any thoughts?

A: Whenever a command or API execution is required in CodePipeline, think about these 3 options (i.e. Actions):

*

*CodeBuild (best to execute a command)

*Lambda (More suited for API execution)

*Custom Action (for advanced usage, you control the action completely)

So based on this, I would say CodeBuild will be the easiest option for your use case to run the command. Use a "latest" "curated image" so the execution is fastest for your CodeBuild job.


text:
Q: Keep Two Layouts Centre of each other with Constraint Layout I was trying to put two layouts one after another and keeping the next layout in the center of the first one. The layout in XML is similar to the following
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.google.android.material.button.MaterialButton
        android:id="@+id/button"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:text="@string/app_name"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <com.google.android.material.button.MaterialButton
        android:id="@+id/button1"
        android:layout_width="100dp"
        android:layout_height="70dp"
        android:text="@string/app_name"
        app:layout_constraintBottom_toBottomOf="@+id/button"
        app:layout_constraintStart_toEndOf="@+id/button"
        app:layout_constraintTop_toTopOf="@+id/button" />
</androidx.constraintlayout.widget.ConstraintLayout>

The output is like the following

The problem is that the second layout's height is variable and if it's bigger (let's say 170dp instead of 70dp) than the first one then the output is

Part of the second layout has been cut off. How can I bring both of them inside and keep the second layout still in the center of the first one.

A: One possible solution for your problem is to use a Barrier at the Bottom of the buttons and set the constraintBottom to the Barrier and set the constraintTop to the parent to both Buttons. Like the code:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.google.android.material.button.MaterialButton
        android:id="@+id/button"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:text="@string/app_name"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toTopOf="@id/barrier"
        app:layout_constraintStart_toStartOf="parent" />

    <com.google.android.material.button.MaterialButton
        android:id="@+id/button1"
        android:layout_width="100dp"
        android:layout_height="70dp"
        android:text="@string/app_name"
        app:layout_constraintBottom_toTopOf="@id/barrier"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toEndOf="@+id/button" />

    <androidx.constraintlayout.widget.Barrier
        android:id="@+id/barrier"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:barrierDirection="bottom"
        app:constraint_referenced_ids="button,button1"/>
</androidx.constraintlayout.widget.ConstraintLayout>

A: set layout gravity of constraintlayout to center can help you


text:
Q: registerReceiver(...) getting passed ClickListener I am having some difficulty passing the right information to set up Bluetooth discovery and pairing.  I have been following the Android developer example documents pretty closely and have not been able to figure out what I need to pass to this method.  This is the site I have been using, for reference.
http://developer.android.com/guide/topics/connectivity/bluetooth.html
TransferFragment:
//some code used from
//   http://examples.javacodegeeks.com/android/core/ui/progressdialog/android-progressdialog-example/
//   http://developer.android.com/guide/topics/connectivity/bluetooth.html

package com.project.BluetoothTransfer_v1000;

import java.util.Set;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class TransferFragment extends Fragment{

    private TextView filePathTextView;
    private Button startTransferButton;
    private ImageView bluetoothImage;
    ProgressDialog transferDialog;
    Handler updateBarHandler;
    private static final int REQUEST_BLUETOOTH = 1;
    private static final int DISCOVER_DURATION = 300;
    Context context;
    ArrayAdapter mArrayAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup parent, final Bundle savedInstanceState){

        super.onCreate(savedInstanceState);

        //set the user interface layout for this activity
        setRetainInstance(false);
        View v = inflater.inflate(R.layout.activity_bluetooth_transfer, parent, false);

        context = this.getActivity();
        filePathTextView = (TextView) v.findViewById(R.id.file_path_textView);
        startTransferButton = (Button) v.findViewById(R.id.start_transfer_button);
        bluetoothImage = (ImageView) v.findViewById(R.id.bluetooth_imageView);
        bluetoothImage.setClickable(true);

        startTransferButton.setOnClickListener(new View.OnClickListener() {
            //start transfer processes
            @SuppressWarnings("unchecked")
            @Override
            public void onClick(View v){
                //check to make sure the file path text view != null
                BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
                int REQUEST_ENABLE_BT = -1;
                //ensure the device being used has bluetooth capability
                if (btAdapter != null){
                    //check-enable bluetooth
                    if (!btAdapter.isEnabled()) {
                        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                        }
                    //ensure the textview isn't empty
                    //check if filepath is null
                    if (filePathTextView.getText().toString().length() != 0){
                        Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices();
                        //check if there are paired devices
                        if (pairedDevices.size() > 0){
                            //loop through paired devices
                            for (BluetoothDevice device: pairedDevices){
                                //add the name and address to an array adapter to show in a ListView
                                mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                            }
                        }//end found paired devices if

                        // Create a BroadcastReceiver for ACTION_FOUND
                        final BroadcastReceiver mReceiver = new BroadcastReceiver() {
                            public void onReceive(Context context, Intent intent) {
                                String action = intent.getAction();
                                // When discovery finds a device
                                if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                                    // Get the BluetoothDevice object from the Intent
                                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                                    // Add the name and address to an array adapter to show in a ListView
                                    mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                                }
                            }
                        };
                        // Register the BroadcastReceiver
                        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

                        //COMPILER ERROR BELOW @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
                        //"This method registerReceiver(BroadcastReceiver, IntentFilter)
                        //is undefined for type new View.OnClickListener
                        registerReceiver(mReceiver, filter);

                        Intent discoverableIntent = new
                        Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
                        startActivity(discoverableIntent);
                        btAdapter.cancelDiscovery();
                    }//
                    else {
                        //alert user to input file path
                        new AlertDialog.Builder(context).setTitle("Error")
                        .setMessage("Please insert a filename to send.")
                        .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {}
                        }).show();
                    }//ifnull (else)
                }//bt equipped check
            }//end anon class
        });

        bluetoothImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //display dialog showing program specs and creators
                new AlertDialog.Builder(context).setTitle("About")
                .setMessage("Created by:"+"\n"+ "Hal, Chris, and Roger")
                .setPositiveButton("Awesome!", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                }).show();
            }
        });
        return v;
    }
}

TransferActivity:
package com.project.BluetoothTransfer_v1000;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

public class TransferActivity extends FragmentActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_transfer);
        TransferFragment fragment = new TransferFragment();
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.container, fragment);
        fragmentTransaction.commit();
    }
}

A: Try:
TransferFragment.this.getActivity().registerReceiver(mReceiver, filter);

Instead of:
registerReceiver(mReceiver, filter);

Because the method registerReceiver is part of the Activity and not the OnClickListener. This is why the error message complains about not found method in OnClickListener:

This method registerReceiver(BroadcastReceiver, IntentFilter)
  is undefined for type new View.OnClickListener


text:
Q: How to fix Instance member cannot be used on type segmentedControl I have the following code:
import UIKit

extension UISegmentedControl {
    func removeBorder(){
        let backgroundImage = UIImage.getColoredRectImageWith(color: UIColor.white.cgColor, andSize: self.bounds.size)
        self.setBackgroundImage(backgroundImage, for: .normal, barMetrics: .default)
        self.setBackgroundImage(backgroundImage, for: .selected, barMetrics: .default)
        self.setBackgroundImage(backgroundImage, for: .highlighted, barMetrics: .default)

        let deviderImage = UIImage.getColoredRectImageWith(color: UIColor.white.cgColor, andSize: CGSize(width: 1.0, height: self.bounds.size.height))
        self.setDividerImage(deviderImage, forLeftSegmentState: .selected, rightSegmentState: .normal, barMetrics: .default)
        self.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.gray], for: .normal)
        self.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor(red: 67/255, green: 129/255, blue: 244/255, alpha: 1.0)], for: .selected)
    }

    func addUnderlineForSelectedSegment(){
        removeBorder()
        let underlineWidth: CGFloat = self.bounds.size.width / CGFloat(self.numberOfSegments)
        let underlineHeight: CGFloat = 2.0
        let underlineXPosition = CGFloat(selectedSegmentIndex * Int(underlineWidth))
        let underLineYPosition = self.bounds.size.height - 1.0
        let underlineFrame = CGRect(x: underlineXPosition, y: underLineYPosition, width: underlineWidth, height: underlineHeight)
        let underline = UIView(frame: underlineFrame)
        underline.backgroundColor = UIColor(red: 67/255, green: 129/255, blue: 244/255, alpha: 1.0)
        underline.tag = 1
        self.addSubview(underline)
    }

    func changeUnderlinePosition(){
        guard let underline = self.viewWithTag(1) else {return}
        let underlineFinalXPosition = (self.bounds.width / CGFloat(self.numberOfSegments)) * CGFloat(selectedSegmentIndex)
        UIView.animate(withDuration: 0.1, animations: {
            underline.frame.origin.x = underlineFinalXPosition
        })
    }
}

extension UIImage {

    class func getColoredRectImageWith(color: CGColor, andSize size: CGSize) -> UIImage{
        UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
        let graphicsContext = UIGraphicsGetCurrentContext()
        graphicsContext?.setFillColor(color)
        let rectangle = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height)
        graphicsContext?.fill(rectangle)
        let rectangleImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return rectangleImage!
    }
}

I then call the function in the ViewDidLoad by:
segmentedControl.changeUnderlinePosition()

I end up getting the following error message:

Instance member 'changeUnderlinePosition' cannot be used on type
'segmentedControl'; did you mean to use a value of this type instead?

What am I doing wrong?
Here is an image of what the error message is

A: You seem to have made a custom type named segmentedControl and calling the method on it. You need to remove or rename if there is such a declaration in your code. Better to rename it to MyCustomSegmentedControl from segmentedControl.
class segmentedControl: UISegmentedControl { ... } // rename or remove

You need to call the method on it's instance instead, like this:
let segmentedControl = UISegmentedControl()
segmentedControl.changeUnderlinePosition()


text:
Q: PHPUnit 5.7.4 Stubbing base class method in child class not working. Original method is being called instead of mocked. class baseClass
{
    public function __construct()
    {

    }
    public function methodToBeMocked()
    {
        // do somthing
    }

}

class childClass extends baseClass
{

    public function __construct()
    {
        parent::__construct($doctrine, $securityContext);
    }

    public function methodUsingMethodToBeMocked()
    {
        // do somthing
        $this->methodToBeMocked();
    }
}

When I am trying to mock the methodToBeMocked in stubbed childClass.
$this->mockChildClass = $this->getMockBuilder('\childClass')
    ->setMockClassName('Mock_Child_Class')
    ->setConstructorArgs(
        [
          // arguments
        ]
     )
    ->setMethods(['methodToBeMocked'])
    ->getMock();

$this->mockChildClass
    ->expects($this->once())
    ->method('methodToBeMocked')
    ->will($this->returnValue(null));

Instead of calling mocked method and return value, actual baseClass method is called. Need to call the mocked method.


text:
Q: check a string for a substring where the end of the string loops around to the start So let's say I have a string, 'string', and I know the length of the string, 'length'. I want to check if a word of the same length, 'checkfor', is inside string.
I know that to do this I can use:
if(string[0:length-1]==checkfor):
   Return True

but I also want to check if the string is just wrongly positioned, for example let's say checkfor=iwantpie which is length=8. I want to return True if string is 'iwantpie' or 'wantpiei' or 'antpieiw' etc.
I know I could use a statement like:
if((string[0:length-1] or string[length-1]+string[0:length-2] or string[length-2:length-1]+string[0:length-3] or ... or string[length-length:length-1])==checkfor):
   Return True

where ... is representing repeating that same pattern. It's like making the string circular and checking for a substring.
Obviously this becomes cumbersome as length becomes larger.
Is there a way to consolidate maybe with a for loop?
Writing this I found a possible solution but it's probably not the best and if there's a for loop solution I'd like to see it regardless.

A: How about something like
>>> def checkOccurence(string, checkfor):
...     for i in range(len(string)):
...             if  string[i:]+string[:i] == checkfor:
...                     return True
...     return False
...

Test
>>> string = "antpieiw"
>>> checkfor = "iwantpie"
>>> checkOccurence(string, checkfor)
True

>>> checkfor = "iwantpie234"
>>> checkOccurenct(string, checkfor)
False

A: Make string=string+string and then check for checkfor as a substring. There are a lot of questions on parsing for substrings already answered so I'll leave you to find those.


text:
Q: RegEx for extracting a value from Open3.popen3 stdout How do I get the output of an external command and extract values from it?
I have something like this:
stdin, stdout, stderr, wait_thr = Open3.popen3("#{path}/foobar", configfile)

if /exit 0/ =~ wait_thr.value.to_s
    runlog.puts("Foobar exited normally.\n")
    puts "Test completed."
    someoutputvalue = stdout.read("TX.*\s+(\d+)\s+")
    puts "Output value: " + someoutputvalue
end

I'm not using the right method on stdout since Ruby tells me it can't convert String into Integer.
So for instance, if the output is
"TX So and so:     28"

I would like to get only "28". I validated that the regex above matches what I need to match, I'm only wondering how to store that extracted value in a variable.
What is the right way of doing this? I can't find anywhere in the documentation the methods available for stdout. I'm using stout.read from Ruby 1.9.3.

A: All the information needed is in the Popen3 documentation, but you have to read it all and look at the examples pretty carefully. You can also glean useful information from the Process docs too.
Maybe this will 'splain it better:
require 'open3'

captured_stdout = ''
captured_stderr = ''
exit_status = Open3.popen3(ENV, 'date') {|stdin, stdout, stderr, wait_thr|
  pid = wait_thr.pid # pid of the started process.
  stdin.close
  captured_stdout = stdout.read
  captured_stderr = stderr.read
  wait_thr.value # Process::Status object returned.
}

puts "STDOUT: " + captured_stdout
puts "STDERR: " + captured_stderr
puts "EXIT STATUS: " + (exit_status.success? ? 'succeeded' : 'failed')

Running that outputs:
STDOUT: Wed Jun 12 07:07:12 MST 2013
STDERR:
EXIT STATUS: succeeded

Things to note:

*

*You often have to close the stdin stream. If the called application expects input on STDIN it will hang until it sees the stream close, then will continue its processing.

*stdin, stdout, stderr are IO handles, so you have to read the IO class documentation to find out what methods are available.

*You have to output to stdin using puts, print or write, and read or gets from stdout and stderr.

*exit_status isn't a string, it's an instance of the Process::Status class. You can mess with trying to parse from its to_s version, but don't. Instead use the accessors to see what it returned.

*I passed in the ENV hash, so the child program had access to the entire environment the parent saw. It's not necessary to do that; Instead you can create a reduced environment for the child if you don't want it to have access to everything, or you can mess with its view of the environment by changing values.

*The code stdout.read("TX.*\s+(\d+)\s+") posted in the question is, um... nonsense. I have no idea where you got that as nothing like that is documented in Ruby's IO class for IO#read or IO.read.

It's easier to use capture3 if you don't need to write to STDIN of the called code:
require 'open3'

stdout, stderr, exit_status = Open3.capture3('date')

puts "STDOUT: " + stdout
puts "STDERR: " + stderr
puts "EXIT STATUS: " + (exit_status.success? ? 'succeeded' : 'failed')

Which outputs:
STDOUT: Wed Jun 12 07:23:23 MST 2013
STDERR:
EXIT STATUS: succeeded

Extracting a value from a string using a regular expression is trivial, and well covered by the Regexp documentation. Starting from the last code example:
stdout[/^\w+ (\w+ \d+) .+ (\d+)$/]
puts "Today is: " + [$1, $2].join(' ')

Which outputs:
Today is: Jun 12 2013

That's using the String.[] method which is extremely flexible.
An alternate is using "named captures":
/^\w+ (?<mon_day>\w+ \d+) .+ (?<year>\d+)$/ =~ stdout
puts "Today is: #{ mon_day } #{ year }"

which outputs the same thing. The downside to named captures is they're slower for what I consider a minor bit of convenience.

"TX So and so: 28"[/\d+$/]
=> "28"


text: Q: Proof that any hyperbolic group has Rapid Decay property A classic result that states that any hyperbolic group in the sense of Gromov has Rapid Decay property in the sense of Jolisaint. But the original proof of that fact is contained in an old Ph.D. dissertation, written in French. Can someone help me to find the proof in English?


text:
Q: why should I need Explicit Type Conversion When Using JSONObject inside JsonArray? I'm getting a JsonArray response from RestApi.
it looks like this.
[{"symbol":"BTC","volumeUsd24Hr":"9933608358.6769638763447470","marketCapUsd":"373762242595.8886412421003192","priceUsd":"19494.3435967958368457","vwap24Hr":"19703.2611157615056124","changePercent24Hr":"-2.4906058989768847","name":"Bitcoin","explorer":"https://blockchain.info/","rank":"1","id":"bitcoin","maxSupply":"21000000.0000000000000000","supply":"19172856.0000000000000000"},{"symbol":"ETH","volumeUsd24Hr":"3241023190.3730390178381998","marketCapUsd":"163079674691.9858451324912645","priceUsd":"1329.0704167150164988","vwap24Hr":"1337.1800236177182353","changePercent24Hr":"-2.1575264116384809","name":"Ethereum","explorer":"https://etherscan.io/","rank":"2","id":"ethereum","maxSupply":null,"supply":"122702057.4990000000000000"},{"symbol":"USDT","volumeUsd24Hr":"13840788061.6519189957942816","marketCapUsd":"68364449761.2046855857488307","priceUsd":"1.0004593774481033","vwap24Hr":"1.0004839031623615","changePercent24Hr":"0.0536998153626522","name":"Tether","explorer":"https://www.omniexplorer.info/asset/31","rank":"3","id":"tether","maxSupply":null,"supply":"68333059094.8965800000000000"},{"symbol"...
There are JsonArrays inside JsonObject.
And I wanna extract values from Each JsonObject(symbol).
So I checked the data type of JsonObject by printing jsonArray.get(0).getClass(), and it gives me  "class org.json.simple.JSONObject" as expected.
so I tried to extract value by using
        jsonArray.get(0).get("symbol");

but this code makes compile error saying " Cannot resolve method 'get' in 'Object' "
So I needed to explicitly convert data type into JSONObject like this
((JSONObject) jsonArray.get(0)).get("symbol")

then I got what I want.
What I'm wondering is that why should I explicitly convert jsonArray.get(0) to JSONObject,
even though .getclass() says that the type of data is JSONObject
Here are my Full Code .. Thanks in advance!!
public static void main(String[] args) throws IOException, ParseException {
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("text/plain");
        Request request = new Request.Builder()
                .url("http://api.coincap.io/v2/assets")
                .get()
                .build();

        Response response = client.newCall(request).execute();

        JSONParser jsonParser = new JSONParser();
        Object obj = jsonParser.parse(response.body().string());

        JSONArray jsonArray = (JSONArray) ((JSONObject) obj).get("data");
        // JSONObject inside JSONArray

        System.out.println(jsonArray.get(0).getClass());

        System.out.println(((JSONObject) jsonArray.get(0)).get("symbol"));

    }

A: Maybe you can try it
jsonArray.getJSONObject(0);


text:
Q: Compare Word documents without tracking formatting changes I have written a VBA routine for comparing docx files and saving the delta. I need to deactivate TrackFormatting in the delta but adding .trackFormatting = False does not do anything. In the compare method the CompareFormatting is false as well! How should I do this?
Sub ProduceDeltas()
   Dim strFolderA As String
   Dim strFolderB As String
   Dim strFolderC As String
   Dim strFileSpec As String
   Dim strFileName As String
   Dim objDocA As Word.Document
   Dim objDocB As Word.Document
   Dim objDocC As Word.Document
   Dim dc As Word.Document
   Dim FldrPickerInputA As FileDialog
   Dim FldrPickerInputB As FileDialog
   Dim FldrPickerOutput As FileDialog
  Application.ScreenUpdating = False
  Set FldrPickerInputA = Application.FileDialog(msoFileDialogFolderPicker)
  Set FldrPickerInputB = Application.FileDialog(msoFileDialogFolderPicker)
  Set FldrPickerOutput = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPickerInputA
  .Title = "Choose first file: "
  .AllowMultiSelect = False
    If .Show <> -1 Then GoTo NextCode
    strFolderA = .SelectedItems(1) & "\"
   End With
   With FldrPickerInputB
  .Title = "Choose second file: "
  .AllowMultiSelect = False
    If .Show <> -1 Then GoTo NextCode
    strFolderB = .SelectedItems(1) & "\"
   End With
  With FldrPickerOutput
  .Title = "Choose output file: "
  .AllowMultiSelect = False
    If .Show <> -1 Then GoTo NextCode
    strFolderC = .SelectedItems(1) & "\"
 End With

 NextCode:
 strFolderA = strFolderA
 strFolderB = strFolderB
 strFolderC = strFolderC
 If strFolderA = "" Then GoTo ResetSettings
 strFileSpec = "*.docx"
 strFileName = Dir(strFolderA & strFileSpec)
 Do While strFileName <> vbNullString
 Set objDocA = Documents.Open(strFolderA & strFileName)
 Set objDocB = Documents.Open(strFolderB & strFileName)
 If objDocA.TablesOfContents.Count = 1 Then _
   objDocA.TablesOfContents(1).Update
 If objDocB.TablesOfContents.Count = 1 Then _
   objDocB.TablesOfContents(1).Update
 Set dc = Application.CompareDocuments(objDocA, objDocB,           wdCompareDestinationNew, _
   Granularity:=wdGranularityWordLevel, _
   CompareFormatting:=False, RevisedAuthor:="IQTIG",        CompareFootnotes:=False,   CompareHeaders:=False)

dc.TrackFormatting = False
objDocA.Save
objDocB.Save
objDocA.Close
objDocB.Close

If dc.TablesOfContents.Count = 1 Then _
 dc.TablesOfContents(1).Update

dc.SaveAs strFolderC & strFileName
dc.Close SaveChanges:=False
strFileName = Dir
Loop

Set objDocA = Nothing
Set objDocB = Nothing

ResetSettings:
Application.ScreenUpdating = True
End Sub

A: Which version of Word?  On Word 2013, CompareFormatting:=False works for me.
One option is to accept (or reject) all formatting revisions after running the comparison.  Before dc.SaveAs, insert the following:
dim oRevision as Revision
For Each oRevision In dc.StoryRanges(wdMainTextStory).Revisions
    If (oRevision.Type<> wdRevisionInsert) and (oRevision.type <> wdRevisionDelete) then
        oRevision.Accept    ' or .Reject
    End If
Next oRevision

(code modified from ExtractTrackedChangesToNewDoc by Lene Fredborg, supplied as-is with no warranty.)


text:
Q: Swift 2.1 | Swift условия оператора if Всем привет!
Подскажите пожалуйста, почему Swift не принимает подобное условия:
let x = 1
let y = 2
let z = 3

if x < y < z {
    print("Yes")
} else {
    print("No")
}

Как правильно его записать?
Альтернативный вариант записи такой.
if (x < y) && (y < z) {
    print("Yes")
} else {
    print("No")
}

Но возможно ли записать условие как в первом варианте?

A: Есть еще 1 вариант, если вы хотите чтобы явно было видно что вы проверяете входит ли число в диапазон:
if (x..< z).contains(y) {
    print("Yes")
} else {
    print("No")
}

Либо используйте свой альтернативный вариант.

A:
Как правильно его записать?

if (x < y) && (y < z)

Но возможно ли записать условие как в первом варианте?

Невозможно по правилам языка.


text:
Q: Why are property values "undefined"? Javascript:
This is my example code below. I use prompt() variables to create string values for each loop.
var team = new Object;
team["fwd"] = "forwards";

for (i=1; i <2+1; i++){
      var fwdName = prompt("enter player name");
      team["fwd"]["p" + i] = fwdName;
   }

It is my understanding with the above that in each loop, I get user input to read in a value for each new property (that is created by ["p"+i]) to be set to. The fwdName variable is overwritten with each loop.
I use the following to check that I actually put in values that can be used;
console.log(team.fwd.p1);
console.log(team.fwd.p2);

and I get undefined as output for each statement.

A: i belive the fwd property of your main object should be an object not a string.
team["fwd"] = {};


text:
Q: Best practices for application security with MSSQL We are setting up a new application framework and we are wondering the best practices for setting up database security for our users.  In our old framework, there was a user logon process and once the user was logged on, the framework controlled what forms and menu options a user was permitted to.  All users accessed the database with the same user account.
The disadvantage to this approach is that you cant use SYSTEM_USER to find out who is making a particular database request.
The new framework will still have a logon form and it will control what menu options a person can access.  Should we be setting up a database user account every time a new user is added to our application?  Would this cause any licensing concerns since you cant use connection pooling?

A: It won't cause licensing issues, but it will generate a large number of connections which may cause performance issues.
A better solution would be to add a parameter to your stored procedures to pass in the UserID of the current user so that it can be logged.
If passing in the parameter is undesirable, you can put the current user in CONTEXT_INFO(), or if you are using SQL 2016, SESSION_CONTEXT() and log it from there.  https://www.mssqltips.com/sqlservertip/4094/phase-out-contextinfo-in-sql-server-2016-with-sessioncontext/


text:
Q: How to exclude column in sql server 2008 i have question here. How can I exclude one column from both inserted and deleted table in sql server 2008? I am currently using After update trigger.
Code is as below:
select * into #ins from inserted
select * into #del from deleted

I want to exclude some column from the 2 tables

A: You should state the column names instead of the '*'.
select col1, col2, ... , coln into #ins from inserted


text:
Q: How to make conditional replacement of values in a column depending on values in another column? I have data that looks like this:
currency    country
GBP         GB
USD         NaN
USD         US
AUD         AUD
GBP         NaN

Basically I'm trying to make conditional replacements of NaN in the country column to a value that's dependent on what the currency in that row is. (E.g. for GBP it should be GB).
I have a separate dict that maps currencies to country. But I'm not sure how to replace values in the country column

A: Assume you have dict d, you may use set_index, fillna and reset_index
d = {'GBP': 'GB', 'USD': 'US', 'AUD': 'AUD'}

df = df.set_index('currency').country.fillna(d).reset_index()

Out[39]:
  currency country
0      GBP      GB
1      USD      US
2      USD      US
3      AUD     AUD
4      GBP      GB

A: Use Series.fillna with Series.map by dict, also solution working if more columns in DataFrame:
#one possible solution is generate dictionary from existing values
d = df.dropna().set_index('currency')['country'].to_dict()
#or use dictionary
#d = {'GBP': 'GB', 'USD': 'US', 'AUD': 'AUD'}
df['country'] = df['country'].fillna(df['currency'].map(d))
print (df)
  currency country
0      GBP      GB
1      USD      US
2      USD      US
3      AUD     AUD
4      GBP      GB

EDIT:
If all values of currency are in dictionary then solution should be simplify:
d = {'GBP': 'GB', 'USD': 'US', 'AUD': 'AUD'}
df['country'] = df['currency'].map(d)
print (df)
  currency country
0      GBP      GB
1      USD      US
2      USD      US
3      AUD     AUD
4      GBP      GB

If not, then if use only map it replace only matched values:
print (df)
  currency country
0     GBP1     GB1
1      USD     NaN
2      USD      US
3      AUD     AUD
4      GBP     NaN

d = {'GBP': 'GB', 'USD': 'US', 'AUD': 'AUD'}
df['country'] = df['currency'].map(d)
print (df)
  currency country
0     GBP1     NaN
1      USD      US
2      USD      US
3      AUD     AUD
4      GBP      GB

So if need original values which are not in dict (here GBP1) not replaced to NaNs use first solution:
d = {'GBP': 'GB', 'USD': 'US', 'AUD': 'AUD'}
df['country'] = df['country'].fillna(df['currency'].map(d))
print (df)
  currency country
0     GBP1     GB1
1      USD      US
2      USD      US
3      AUD     AUD
4      GBP      GB


text:
Q: Sieve of Eratosthenes implementation I am trying to implement algorithm for Sieve of Eratosthenes but I don't know why this program crashes for larger programs. Initially I was using vector but now I am implementing this using dynamic memory allocation.
#include<iostream>
#include<cmath>
#include<cstdlib>
using namespace std;

unsigned isqrt(unsigned value) {
  return static_cast<unsigned>(sqrt(static_cast<float>(value)));
}

int main()
{
    int t;
    cin >> t;
    long long * N;
    long long * M;
    long long n, m;
    N = new long long[t];
    M = new long long[t];
    for(int i = 0; i < t ; i++){
        cin >> M[i] >> N[i];
    }

    for(int i = 0; i < t ; i++){
        n = N[i];
        m = M[i];

        bool * A;
        A = new bool[n];
        if(A == 0)
        {
            cout << "Memory cannot be allocated";
            return 0;
        }

        for(int i=0;i < n;i++){
            A[i]=true;
        }
        A[0] = false;
        A[1] = false;

        unsigned sqrt = isqrt(n);
        for(int i = 2; i <= sqrt; i++)
        {
            if(A[i] == true){
                for(int j = i*i; j <= n; j = j + i)
                {
                    A[j] = false;
                }
            }
        }

        for(int i = m;i < n;i++)
        {
            if(A[i] == true )
                cout << i << "\n";
        }

        delete[] A;
    }

    delete[] M;
    delete[] N;
    return 0;
}

The program crashes for larger values of n and m (~10^16). Kindly help me out.

A: for(int j = i*i; j <= n; j = j + i)
                   ^^

If j == n then A[j] = false will assign to an element past the end of the array. The test should be j < n.

A: If you're going to write a sieve of Eratosthenes in C++, how about if you actually use C++, not try to treat it as some demented cross between C and assembly language.
#include <vector>
#include <iostream>

unsigned long primes = 0;

int main() {
    int number = 10000000;
    std::vector<bool> sieve(number,false);
    sieve[0] = sieve[1] = true;

    for(int i = 2; i<number; i++) {
        if(!sieve[i]) {
            ++primes;
            for (int temp = 2*i; temp<number; temp += i)
                sieve[temp] = true;
        }
    }
    std::cout << "found: " << primes << " Primes\n";
    return 0;
}

A: If n is big enough to cause memory allocation error program will crash due to incorrect memory allocation error handling here
 A = new bool[n];
        if(A == 0)
        {
            cout << "Memory cannot be allocated";
            return 0;
        }

new doesn't return 0 on error, but throws std::bad_alloc that doesn't get catched, which in turn will lead to unexpected() then terminate() and finally abort() to be called.
Correct version would be:
  try
  {
    A = new bool[n];
  }
  catch (std::bad_alloc& ba)
  {
    std::cerr << "Memory cannot be allocated: " << ba.what() << '\n';
  }

A: Run this in a debugger to determine where the crash is and debug from there.  It will most likely be apparent at that point.
You can do this either from an IDE or from command line.  In the latter case compile with -g and run in a program such as gdb.  Google something like "gdb cheatsheet" to get started.


text:
Q: Xamarin, UWP and a dependence I thought my problem was very simple to resolve but it isn't. I'm creating some new components for Xamarin. I have a main Xamarin project where I'm testing my components.
My components are a main portable project and for each platform there is specific implementation.
The implementation for UWP generates a compatibility error

Project PSC.Xam.Controls.BindableRadioButton.UWP is not compatible
  with uap10.0 (UAP,Version=v10.0). Project
  PSC.Xam.Controls.BindableRadioButton.UWP supports: uap10.0.10240
  (UAP,Version=v10.0.10240) One or more projects are incompatible with
  UAP,Version=v10.0. Project PSC.Xam.Controls.BindableRadioButton.UWP is
  not compatible with uap10.0 (UAP,Version=v10.0) / win10-arm. Project
  PSC.Xam.Controls.BindableRadioButton.UWP supports: uap10.0.10240
  (UAP,Version=v10.0.10240) One or more projects are incompatible with
  UAP,Version=v10.0 (win10-arm). Project
  PSC.Xam.Controls.BindableRadioButton.UWP is not compatible with
  uap10.0 (UAP,Version=v10.0) / win10-arm-aot. Project
  PSC.Xam.Controls.BindableRadioButton.UWP supports: uap10.0.10240
  (UAP,Version=v10.0.10240) One or more projects are incompatible with
  UAP,Version=v10.0 (win10-arm-aot). Project
  PSC.Xam.Controls.BindableRadioButton.UWP is not compatible with
  uap10.0 (UAP,Version=v10.0) / win10-x64. Project
  PSC.Xam.Controls.BindableRadioButton.UWP supports: uap10.0.10240
  (UAP,Version=v10.0.10240) One or more projects are incompatible with
  UAP,Version=v10.0 (win10-x64). Project
  PSC.Xam.Controls.BindableRadioButton.UWP is not compatible with
  uap10.0 (UAP,Version=v10.0) / win10-x64-aot. Project
  PSC.Xam.Controls.BindableRadioButton.UWP supports: uap10.0.10240
  (UAP,Version=v10.0.10240) One or more projects are incompatible with
  UAP,Version=v10.0 (win10-x64-aot). Project
  PSC.Xam.Controls.BindableRadioButton.UWP is not compatible with
  uap10.0 (UAP,Version=v10.0) / win10-x86. Project
  PSC.Xam.Controls.BindableRadioButton.UWP supports: uap10.0.10240
  (UAP,Version=v10.0.10240) One or more projects are incompatible with
  UAP,Version=v10.0 (win10-x86). Project
  PSC.Xam.Controls.BindableRadioButton.UWP is not compatible with
  uap10.0 (UAP,Version=v10.0) / win10-x86-aot. Project
  PSC.Xam.Controls.BindableRadioButton.UWP supports: uap10.0.10240
  (UAP,Version=v10.0.10240) One or more projects are incompatible with
  UAP,Version=v10.0 (win10-x86-aot). NuGet package restore failed.

I checked the configuration of UWP main project and the implementation project and both are the same settings.

In the implementation project, I have a reference to the portable project and its settings are:

If I deploy the project and run it, it seems working fine on my desktop.
Also, I receive two other errors:

Duplicate Entry
0xdef00532 - Conflicting values for resource 'Files/Xamarin.Forms.Platform.UAP/TabbedPageStyle.xbf' GENERATEPROJECTPRIFILE

I checked my Package.appxmanifest and Dependencies is as requested.
  <Dependencies>
    <TargetDeviceFamily Name="Windows.Universal"
                        MinVersion="10.0.0.0"
                        MaxVersionTested="10.0.0.0" />
  </Dependencies>

A: In order to use .NET Standard 2.0 in UWP, you need to target Fall Creators Update (FCU) as the minimum version of your UWP project. That's because .NET Standard 2.0 contains many APIs that require FCU to make them work in the context of the UWP execution environment, specifically AppContainer.
https://blogs.msdn.microsoft.com/dotnet/2017/08/25/uwp-net-standard-2-0-preview/
https://blogs.msdn.microsoft.com/dotnet/2017/10/10/announcing-uwp-support-for-net-standard-2-0/

A: Find project.json file and replace "uap10.0" with "uap10.0.10586"


text:
Q: I get this error when I was using pytorch: RuntimeError: gather_out_cuda(): Expected dtype int64 for index I'm trying to reproduce meshed memory transformer https://github.com/aimagelab/meshed-memory-transformer, but I get this error: RuntimeError: gather_out_cuda(): Expected dtype int64 for index.
The detailed error information are as follows:
Traceback (most recent call last):
  File "/home/ai/data/meshed-memory-transformer/train.py", line 252, in <module>
    scores = evaluate_metrics(model, dict_dataloader_val, text_field)
  File "/home/ai/data/meshed-memory-transformer/train.py", line 55, in evaluate_metrics
    out, _ = model.beam_search(images, 20, text_field.vocab.stoi['<eos>'], 5, out_size=1)
  File "/home/ai/data/meshed-memory-transformer/models/captioning_model.py", line 70, in beam_search
    return bs.apply(visual, out_size, return_probs, **kwargs)
  File "/home/ai/data/meshed-memory-transformer/models/beam_search/beam_search.py", line 82, in apply
    visual, outputs = self.iter(t, visual, outputs, return_probs, **kwargs)
  File "/home/ai/data/meshed-memory-transformer/models/beam_search/beam_search.py", line 132, in iter
    self.model.apply_to_states(self._expand_state(selected_beam, cur_beam_size))
  File "/home/ai/data/meshed-memory-transformer/models/containers.py", line 30, in apply_to_states
    self._buffers[name] = fn(self._buffers[name])
  File "/home/ai/data/meshed-memory-transformer/models/beam_search/beam_search.py", line 38, in fn
    beam.expand(*([self.b_s, self.beam_size] + shape[1:])))
RuntimeError: gather_out_cuda(): Expected dtype int64 for index

GPU version:RTX3090
Cuda compilation tools, release 11.2, V11.2.142
Build cuda_11.2.r11.2/compiler.29558016_0

PyTorch version:1.9.1   build:py3.7_cuda11.1_cudnn8.0.5_0


text:
Q: Not playing sounds from stream_url ing SoundCloud API I can display the songs in the table view but i cant play it.
here's my code when get tracks button is tapped
- (IBAction) getTracks:(id) sender
{

    SCRequestResponseHandler handler;
    handler = ^(NSURLResponse *response, NSData *data, NSError *error) {
        NSError *jsonError = nil;
        NSJSONSerialization *jsonResponse = [NSJSONSerialization
                                             JSONObjectWithData:data
                                             options:0
                                             error:&jsonError];
        if (!jsonError && [jsonResponse isKindOfClass:[NSArray class]]) {
            SCTTrackListViewController *trackListVC;
            trackListVC = [[SCTTrackListViewController alloc]
                           initWithNibName:@"SCTTrackListViewController"
                           bundle:nil];
            trackListVC.tracks = (NSArray *)jsonResponse;
            NSLog(@"json %@",(NSArray *)jsonResponse);
            [self presentViewController:trackListVC
                               animated:YES completion:nil];
        }
    };

    NSString *resourceURL = @"https://api.soundcloud.com/users/54237635/tracks.json?client_id=8a58d84d48322f5661cf14a3d80e005d";

    [SCRequest performMethod:SCRequestMethodGET
                  onResource:[NSURL URLWithString:resourceURL]
             usingParameters:nil
                 withAccount:nil
      sendingProgressHandler:nil
             responseHandler:handler];
}

here's my code in didselect in tableview :
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    NSDictionary *track = [self.tracks objectAtIndex:indexPath.row];
    NSString *streamURL = [track objectForKey:@"stream_url"];

    [SCRequest performMethod:SCRequestMethodGET
                  onResource:[NSURL URLWithString:streamURL]
             usingParameters:nil
                 withAccount:nil
      sendingProgressHandler:nil
             responseHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                 NSError *playerError;
                 player = [[AVAudioPlayer alloc] initWithData:data error:&playerError];
                 [player prepareToPlay];
                 [player play];
             }];

    NSLog(@"streamURL %@", [track objectForKey:@"stream_url"]);
}

A: Solved by the OP:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)
{

NSDictionary *track = [self.tracks objectAtIndex:indexPath.row];
    NSString *streamURL = [track objectForKey:@"stream_url"];

NSString *urlString = [NSString stringWithFormat:@"%@?client_id=%@", streamURL,CLIENT_ID];//Your client ID

[SCRequest performMethod:SCRequestMethodGET
              onResource:[NSURL URLWithString:urlString]
         usingParameters:nil
             withAccount:nil
  sendingProgressHandler:nil
         responseHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
             NSError *playerError;

             NSLog(@"data:%@",data);
             player = [[AVAudioPlayer alloc] initWithData:data error:&playerError];
             [player prepareToPlay];
             [player play];
         }];
}


text:
Q: .htaccess multiple rules RewriteEngine On
RewriteBase /
# Use the following rule if you want to make the page like a directory
RewriteRule ^(v)$ /$1/
# The following rule does the rewrite.
RewriteRule ^(.+)/$ profile.php?name=$1
# The following rewrite the other way round:
RewriteCond %{REQUEST_URI} ^/profile.php
RewriteCond %{THE_REQUEST} ^(GET|POST|HEAD|TRACE)\ /profile.php
RewriteCond %{QUERY_STRING} name=([^&]+)
RewriteRule ^profile.php$ %1?

I'm doing this code above in my .htaccess file, this works fine in my profile.php page because before, my profile.php is displaying this kind of URL:
http://mysite.com/profile.php?name=john

but when I wrote that code this is the result:
http://mysite.com/john/

I also wanted to apply this code to my category.php, so what I did was just to copy the code above and my whole .htaccess file looks like this one:
RewriteEngine On
RewriteBase /

# Use the following rule if you want to make the page like a directory
RewriteRule ^(v)$ /$1/

# The following rule does the rewrite.
RewriteRule ^(.+)/$ profile.php?name=$1
RewriteRule ^(.+)/$ category.php?cid=$1

# The following rewrite the other way round:
RewriteCond %{REQUEST_URI} ^/profile.php
RewriteCond %{THE_REQUEST} ^(GET|POST|HEAD|TRACE)\ /profile.php
RewriteCond %{QUERY_STRING} name=([^&]+)
RewriteRule ^profile.php$ %1?

RewriteCond %{REQUEST_URI} ^/category.php
RewriteCond %{THE_REQUEST} ^(GET|POST|HEAD|TRACE)\ /category.php
RewriteCond %{QUERY_STRING} cid=([^&]+)
RewriteRule ^category.php$ %1?

But this code gives me a weird result because when I visit
http://mysite.com/john/ the content that i'm seeing is the content of my category.php.
What should I do here? Any help would be greatly appreciated and rewarded!
Thanks!

A: i have got the problem in ur rule. the problem what i suppose is that your webserver is unable to differentiate the request is of category page / profile page whenever an request comes like
http://mysite.com/john/
so i suggest do one change in either profile page request or in category page request.
simply add http://mysite.com/profile/john/
hope this works out.

A: To answer the question as it was modified in the comments:
To differentiate between users and categories if these terms appear in the url, you only need one line per rule (untested example):
RewriteEngine On
RewriteBase /

RewriteRule ^user/(\w+)/?$ /profile.php?name=$1    // using only a limited set of chars (letters and underscore) for the user name and an optional / at the end

RewriteRule ^category/(\w+)/?$ /category.php?cid=$1    // using only a limited set of chars for the category (letters and underscore) and an optional / at the end

A: Looks like I solved it using this one:
RewriteEngine On
RewriteBase /

# Use the following rule if you want to make the page like a directory
RewriteRule ^user/(!(profile.php))$ user/$1/ [R=301,L]
RewriteRule ^category/(!(category.php))$ category/$1/ [R=301,L]

# The following rule does the rewrite.
RewriteRule ^user/(.+)/$ profile.php?id=$1
RewriteRule ^category/(.+)/$ category.php?id=$1

# The following rewrite the other way round:
RewriteCond %{REQUEST_URI} ^/profile.php
RewriteCond %{THE_REQUEST} ^(GET|POST|HEAD|TRACE)\ /profile.php
RewriteCond %{QUERY_STRING} id=([^&]+)
RewriteRule ^profile.php$ user/%1?

RewriteCond %{REQUEST_URI} ^/category.php
RewriteCond %{THE_REQUEST} ^(GET|POST|HEAD|TRACE)\ /category.php
RewriteCond %{QUERY_STRING} id=([^&]+)
RewriteRule ^category.php$ category/%1?


text:
Q: Is it possible to zoom an image in page view controller I created a page view controller that load an array of images.Now i want to zoom image.Is it possible to do without using UIscrollView controller? If possible can any one tell me how it is?

A: Inside your view controller add a UIScrollView and within that the UIImageView and hook both of these up using IBOutlets.
Then in your .h file:
Implement the <UIScrollViewDelegate>
In the .m file
    self.scrollView.minimumZoomScale=0.75; //The minimum zoom scale (currently .75x the image size)
    self.scrollView.maximumZoomScale=4.0; //Maximum zoom (currently 4x image size)
    self.scrollView.contentSize=CGSizeMake(self.imageView.frame.size.width, self.imageView.frame.size.height);
    self.scrollView.delegate=self;
    self.scrollView.clipsToBounds = YES;

Also implement the delegate method:
    - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
    {
        return self.imageView; //Needs to be the same as the outlet you created in the .h file
    }


text:
Q: How to extract data from table `tr` and `td`? I want to crawl a website here is a link (http://legacy-assignments.uspto.gov/assignments/q?db=pat&qt=rf&reel=044841&frame=0221&pat=&pub=&intn=&asnr=&asnri=&asne=&asnei=&asns=) which containd table tr and td .
If i change the reel and frame from url then the result changes so i want to make a module in which i run a loop and all the data is crawled. But I stucked in looping or  I am new to crawl html parser website.
Please help me to find out the perfect code for this website.
I give input in reel and frame from csv and i know how to do that i just want to  know how to extract data from html parser
Here is my code:-
from selenium import webdriver
from bs4 import BeautifulSoup
import requests
from time import sleep
import csv
import re
from lxml import html
import lxml.html

doc=lxml.html.parse("http://legacy-assignments.uspto.gov/assignments/q?db=pat&qt=rf&reel=044841&frame=0221&pat=&pub=&intn=&asnr=&asnri=&asne=&asnei=&asns=")

for row in doc.xpath('/html/body/table[3]/tbody/tr'):

    try:
        reelframe1=row.xpath('/html/body/table[3]/tbody/tr/td/table/tbody/tr/td/table[1]/tbody/tr/td[2]/table/tbody/tr[1]/td[2]/a/text()')[0]
        reelframe=reelframe1.strip().encode('utf8')
        print reelframe
    except:
        print error
    try:
        recorded1=row.xpath('/html/body/table[3]/tbody/tr/td/table/tbody/tr/td/table[1]/tbody/tr/td[2]/table/tbody/tr[2]/td[4]/text()')[0]
        recorded= recorded1.strip().encode('utf8')
        print recorded
    except:
        print error
    try:
        attorney1=row.xpath('/html/body/table[3]/tbody/tr/td/table/tbody/tr/td/table[1]/tbody/tr/td[2]/table/tbody/tr[3]/td[2]/span/text()')[0]
        attorney =attorney1.strip().encode('utf8')
        print attorney
    except:
        print error

    try:
        conveyance1=row.xpath('/html/body/table[3]/tbody/tr/td/table/tbody/tr/td/table[1]/tbody/tr/td[2]/table/tbody/tr[4]/td[2]/span/text()')[0]
        conveyance= conveyance1.strip().encode('utf8')
        print conveyance
    except:
        print error

    try:
        totalproperties1=row.xpath('/html/body/table[3]/tbody/tr/td/table/tbody/tr/td/table[2]/tbody/tr[1]/td/div/text()')[0]
        totalproperties= totalproperties1.strip().encode('utf8').replace('                          ','').replace('Total properties:','').strip()
        print totalproperties
    except:
        print error

    try:
        patent1=row.xpath('/html/body/table[3]/tbody/tr/td/table/tbody/tr/td/table[2]/tbody/tr[2]/td[2]/table/tbody/tr[1]/td[2]/div/a/text()')[0]
        patent= patent1.strip().encode('utf8')
        print patent
    except:
        print error

    try:
        issuedate1=row.xpath('/html/body/table[3]/tbody/tr/td/table/tbody/tr/td/table[2]/tbody/tr[2]/td[2]/table/tbody/tr[1]/td[4]/div/text()')[0]
        issuedate = issuedate1.strip().encode('utf8')
        print issuedate
    except:
        print error

    try:
        application1=row.xpath('/html/body/table[3]/tbody/tr/td/table/tbody/tr/td/table[2]/tbody/tr[2]/td[2]/table/tbody/tr[1]/td[6]/div/text()')[0]
        application=application1.strip().encode('utf8')
        print application
    except:
        print error

    try:
        filing=row.xpath('/html/body/table[3]/tbody/tr/td/table/tbody/tr/td/table[2]/tbody/tr[2]/td[2]/table/tbody/tr[1]/td[8]/div/text()')[0]
        filingdate=filing.strip().encode('utf8')
        print filingdate
    except:
        print error

    try:
        publication=row.xpath('/html/body/table[3]/tbody/tr/td/table/tbody/tr/td/table[2]/tbody/tr[2]/td[2]/table/tbody/tr[2]/td[2]/div/a/text()')[0]
        publicationno=publication.strip().encode('utf8')
        print publicationno
    except:
        print error

    try:
        pubdt=row.xpath('/html/body/table[3]/tbody/tr/td/table/tbody/tr/td/table[2]/tbody/tr[2]/td[2]/table/tbody/tr[2]/td[4]/div/text()')[0]
        publicationdate=pubdt.strip().encode('utf8')
        print publicationdate
    except:
        print error

    try:
        title1=row.xpath('/html/body/table[3]/tbody/tr/td/table/tbody/tr/td/table[2]/tbody/tr[2]/td[2]/table/tbody/tr[3]/td[2]/div/text()')[0]
        title=title1.strip().encode('utf8')
        print title
    except:
        print error


text:
Q: Reshaping rows to columns while shared key I have a two-column table, that I want to spread. I know that it is a very popular and well-explored topic here, however, I tried several approaches and didn't get what I wanted. Any suggestions and complaints are welcomed.
a = data.frame(names = c(rep(LETTERS[1:5],2)),
               values = c("car", "cat", "melon", "happy", "winter",
                          "train", "cat", "apple", "sad", "summer") )

   names values
1      A    car
2      B    cat
3      C  melon
4      D  happy
5      E winter
6      A  train
7      B    cat
8      C  apple
9      D    sad
10     E summer

I would like to from categories makes columns and from values rows.
But there is a problem with shared keys (duplicate rows 2 and 7), which makes unable to use spread or reshape.
      A   B     C     D      E
    car cat melon happy winter
  train cat apple   sad summer

A: You can use split and data.frame like:
data.frame(split(a$values, a$names))
#      A   B     C     D      E
#1   car cat melon happy winter
#2 train cat apple   sad summer

In case you don't have the same umber of values per name you can use:
x <- split(a$values, a$names)
data.frame(lapply(x, "length<-", max(lengths(x))))

A: Here is a tidyverse solution using pivot_wider and unnest.
library(tidyverse)

a %>%
  # change from long to wide format
  pivot_wider(names_from = names,
              values_from = values,
              #Add this line to suppress the warning of values not being uniquely identified
              values_fn = list(values = list)) %>%
  # Unnest each list into separate rows
  unnest(cols = everything())

# A tibble: 2 x 5
#  A     B     C     D     E
#  <chr> <chr> <chr> <chr> <chr>
#1 car   cat   melon happy winter
#2 train cat   apple sad   summer


text:
Q: How can I disable EJB on WildFly? I have a set of applications which consist of Servlet API + CDI + JPA (with JTA), basically. I'm not using EJBs.
Is it possible to disable the EJB container in WildFly, making it more lightweight?

A: well for starters you can start the Wildfly with standalone.xml instead of standalone-full.xml
not sure of the actual settings necessary for disabling EJB perhaps you can look around session beans  in the conf file


text:
Q: How to add Android.Dialogs inside scrollable fragments? I am developing the Android version of my Xamarin.iOS application, so I want to share as much code as possible between both platforms.
I am using MonoTouch.Dialog for iOS screens and the MvvmCross Android.Dialog for Android screens.
How would be the best approach to develop the right side (Android) screen?

I am targeting Android 4.0.3+ and using the Support Library v13 (Rev 18) to work with child fragments.
The DialogListFragment is a custom Android ListFragment.
I have been reading lots of questions about ListViews embedded inside a ScrollView but I could not figure it out yet what is the best practice to follow. Is there some official documentation?
When trying to implement the right (Android) screen I could see two behaviours:

*

*By using the internal ScrollView, all child fragments' ListViews are displaying just their first content row;

*By eliminating the internal ScrollView, fragments get correctly displayed. But in some cases, their height may be higher then the screen height and so they will not completely appear.