text:
Q: classcastexception edittext cannot be cast to android.view.viewgroup following is code for my xml file
  <?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/editview_scrollview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:filterTouchesWhenObscured="true"
    android:orientation="vertical"
    android:scrollbarAlwaysDrawVerticalTrack="true" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/userid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="USER ID"
            android:textSize="8pt" />

        <EditText
            android:id="@+id/edituserid"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:background="@android:drawable/editbox_background"
            android:scrollHorizontally="true"
            android:textColor="#333399" />

        <TextView
            android:id="@+id/usertype"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="USER TYPE"
            android:textSize="8pt" />

        <Spinner
            android:id="@+id/spinner"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:drawSelectorOnTop="true"
            android:entries="@array/spinner" />

        <TextView
            android:id="@+id/company"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="COMPANY"
            android:textSize="8pt" />

        <EditText
            android:id="@+id/editcompany"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:drawable/editbox_background"
            android:textColor="#333399" />

        <TextView
            android:id="@+id/firstname"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="FIRST NAME"
            android:textSize="8pt" />

        <EditText
            android:id="@+id/editfirstname"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:drawable/editbox_background"
            android:textColor="#333399" />

        <TextView
            android:id="@+id/lastname"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="LAST  NAME"
            android:textSize="8pt" />

        <EditText
            android:id="@+id/editlastname"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:drawable/editbox_background"
            android:textColor="#333399"
             />

        <TextView
            android:id="@+id/encryptionkey"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="ENCRYPTION KEY"
            android:textSize="8pt" />

        <EditText
            android:id="@+id/editencryption"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:drawable/editbox_background" >

            <TextView
                android:id="@+id/lasttagupdate"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="LAST TAG UPDATE"
                android:textSize="8pt" />

            <DatePicker
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_marginLeft="10dip"
                android:layout_weight="1"
                android:endYear="2100"
                android:startYear="1900" />

            <Button
                android:id="@+id/ok"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:layout_weight="1"
                android:text="SAVE" />
        </EditText>
    </LinearLayout>

</ScrollView>

and file where i use this layout
public class writeRFIDTag extends Activity {
    EditText userId, company, firstName, lastName, encryptionKey;
    Button save;
    Spinner spin;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rfid_write);
        userId = (EditText) findViewById(R.id.edituserid);
        company = (EditText) findViewById(R.id.editcompany);
        firstName = (EditText) findViewById(R.id.editfirstname);
        lastName = (EditText) findViewById(R.id.editlastname);

    }

}

and my logcat
08-21 17:14:51.410: E/AndroidRuntime(20353): FATAL EXCEPTION: main
08-21 17:14:51.410: E/AndroidRuntime(20353): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.securityapp/com.example.securityapp.writeRFIDTag}: java.lang.ClassCastException: android.widget.EditText cannot be cast to android.view.ViewGroup
08-21 17:14:51.410: E/AndroidRuntime(20353):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
08-21 17:14:51.410: E/AndroidRuntime(20353):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
08-21 17:14:51.410: E/AndroidRuntime(20353):    at android.app.ActivityThread.access$600(ActivityThread.java:123)
08-21 17:14:51.410: E/AndroidRuntime(20353):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
08-21 17:14:51.410: E/AndroidRuntime(20353):    at android.os.Handler.dispatchMessage(Handler.java:99)
08-21 17:14:51.410: E/AndroidRuntime(20353):    at android.os.Looper.loop(Looper.java:137)
08-21 17:14:51.410: E/AndroidRuntime(20353):    at android.app.ActivityThread.main(ActivityThread.java:4424)

A: See, You have forgotten to END following EditText.
[1] Put / sign to end it, as I've shown
[2] And remove  from XML at end.
    ......
    ......
    ......
        <TextView
            android:id="@+id/encryptionkey"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="ENCRYPTION KEY"
            android:textSize="8pt" />

        <EditText
            android:id="@+id/editencryption"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:drawable/editbox_background" />
                                                                      ^  Add this ENDING sign here
                                                                      ^

            <TextView
                android:id="@+id/lasttagupdate"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="LAST TAG UPDATE"
                android:textSize="8pt" />

            <DatePicker
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_marginLeft="10dip"
                android:layout_weight="1"
                android:endYear="2100"
                android:startYear="1900" />

            <Button
                android:id="@+id/ok"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:layout_weight="1"
                android:text="SAVE" />

     //     </EditText>    <--  REMOVE THIS FROM YOUR XML

    </LinearLayout>

</ScrollView>

A: EditText is not an ViewGroup. you can place other component by overlapping using different layout like RelativeLayout.
<RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
<EditText
        android:id="@+id/editencryption"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:drawable/editbox_background" />

<TextView
            android:id="@+id/lasttagupdate"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="LAST TAG UPDATE"
            android:textSize="8pt" />

        <DatePicker
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_marginLeft="10dip"
            android:layout_weight="1"
            android:endYear="2100"
            android:startYear="1900" />

        <Button
            android:id="@+id/ok"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_weight="1"
            android:text="SAVE" />

</RelativeLayout>


text:
Q: Session variable in PHP allows me to log in even though credentials are incorrect I have a question about sessions. I noticed something unusual when I was testing my PHP code. Basically, I have two courses and the credentials are stored in their own database.

*

*Example: Course 1: Username: abc Password: 123, database table:
flitpc

*Example: Course 2: Username: abc Password: 999, database table: itst

So the code below determines the login for the respective courses (both exactly same code for each course with the difference being the database table)
<?php
// Initialize the session
session_start();

// Check if the user is already logged in, if yes then redirect him to welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
  header("location: index");
  exit;
}

// Include config file
require_once "config.php";

// Define variables and initialize with empty values
$username = $password = "";
$username_err = $password_err = "";

// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){

    // Check if username is empty
    if(empty(trim($_POST["username"]))){
        $username_err = "Please enter username";
    } else{
        $username = trim($_POST["username"]);
    }

    // Check if password is empty
    if(empty(trim($_POST["password"]))){
        $password_err = "Please enter your password";
    } else{
        $password = trim($_POST["password"]);
    }

    // Validate credentials
    if(empty($username_err) && empty($password_err)){
        // Prepare a select statement
        $sql = "SELECT id, username, password FROM flitpcusers WHERE username = ?";

        if($stmt = mysqli_prepare($link, $sql)){
            // Bind variables to the prepared statement as parameters
            mysqli_stmt_bind_param($stmt, "s", $param_username);

            // Set parameters
            $param_username = $username;

            // Attempt to execute the prepared statement
            if(mysqli_stmt_execute($stmt)){
                // Store result
                mysqli_stmt_store_result($stmt);

                // Check if username exists, if yes then verify password
                if(mysqli_stmt_num_rows($stmt) == 1){
                    // Bind result variables
                    mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password);
                    if(mysqli_stmt_fetch($stmt)){
                        if(password_verify($password, $hashed_password)){
                            // Password is correct, so start a new session
                            session_start();

                            // Store data in session variables
                            $_SESSION["loggedin"] = true;
                            $_SESSION["id"] = $id;
                            $_SESSION["username"] = $username;

                            // Redirect user to welcome page
                            header("location: index.php");
                        } else{
                            // Display an error message if password is not valid
                            $password_err = "The password you entered was not valid";
                        }
                    }
                } else{
                    // Display an error message if username doesn't exist
                    $username_err = "No account found with that username";
                }
            } else{
                echo "Oops! Something went wrong. Please try again later.";
            }
            // Close statement
            mysqli_stmt_close($stmt);
        }
    }

    // Close connection
    mysqli_close($link);
}
?>

So here is the thing, I have both tabs open on my browser, 1 for course 1, other for course 2.
Defect

*

*Tab 1: I log into course 1 with its credentials, works fine, I don't log out.

*Tab 2: I log into course 2 with course 2 username (same username as course 1), but I also use course 1 password, it logs me in,

*Now if I log out of both courses and try the second bullet point above again, I can't log in.
So it's unusual and I want to know how to fix this and understand a little bit more about sessions as I think it's related to that.
Update
I have also found out it doesn't matter if usernames are different. It may be recognising the same password used for both login.

A: Authentication is never actually performed in tab 2. Because you already have a session you're redirected to the index when you hit this code block:
// Check if the user is already logged in, if yes then redirect him to welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
  header("location: index");
  exit;
}

You need to save course somewhere in $_SESSION and check if an appropriate session not only exists but matches the course, otherwise authentication using table 1 credentials is indistinguishable from authentication using table 2 credentials.
EDIT:
After authentication save from where the authentication occurred:
// Store data in session variables
$_SESSION["loggedin"] = true;
$_SESSION["id"] = $id;
$_SESSION["username"] = $username;
$_SESSION["authenticated_from"] = "flitpcusers";

Then when you're checking if a $_SESSION exists also check if it's for the appropriate course, so:
// Check if the user is already logged in, if yes then redirect him to welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true && $_SESSION["authenticated_from"]==="flitpcusers"){
  header("location: index");
  exit;
}

This will prevent a table 1 authenticated session as being recognized as a table 2 session.
While the above will fix the strange behaviors you're observing I'd really look at redesigning your database scheme here. It's strange that I need to authenticate differently for different courses. Ideally I authenticate once and that authentication is used for any/all services under that identity. Look at Google: I don't have to login to Youtube then login to Gmail then login to Search, I log in once and then Google servers determine which services I have access to.

A: You should use two different browser. Not the same browser.

Because browser hold session against respected web address, it doesn't metter how many tabs you have, all tabs will send same session id.

Suppose If you have logged in google chrome browser and you open another tab and hit the same web address, then the browser will request to server with the same Session Id and you will logged in automatically, because session is already exist.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Setting a default value in a QGIS creates empty field I use Qgis 2.18.3 and tried to set default values in new column in a existing shapefile via the layer properties as described here: Setting a default value in a QGIS field
or here
How to set a default value for attributes in shapefiles?.
But fields are not populated, tried several field combinations: text, real, integer but always no result. Tried some combinations with editing layer/not editing layer.
Is there kowen issue or bug with this function? Do I miss an crucial step?

A: As the comments suggest, this only applies to new features. If you want the default value to be applied to existing features, toggle editing on the layer and then use the field calculator (ctrl+i) to populate the column with the desired values.


text:
Q: SQL parameterised Insertion Union Query I have been successful with multiple insertion with around 200 records but my problem is order in which the data is being inserted.The records are inserted in SD_0, SD_1, SD_10, SD_100, ..so on.
My required order is SD_0, SD_1, SD_2, SD_3,....so on.
Here is my Query:-
insert into Coffee (coffeeName,price) select ? as coffeeName ,? as price
 UNION SELECT ? , ?
 UNION SELECT ? , ?
 UNION SELECT ? , ?
 UNION SELECT ? , ?
 UNION SELECT ? , ?
 UNION SELECT ? , ?
 UNION SELECT ? , ?
 UNION SELECT ? , ?
 UNION SELECT ? , ?

Let me know if any changes are required in this query.
I am using this query with the Objective-C code.
Below I am adding the code:
-(void)addCoffee: (NSMutableDictionary *)dictParam {
    NSString *strQuery = [NSString stringWithFormat:@"insert into Coffee (%@) select ? as %@",[[dictParam allKeys] componentsJoinedByString:@","],[[dictParam allKeys] objectAtIndex:0]];

     //For second line of query SELECT 'data1' AS 'column1', 'data2' AS 'column2'
     for (int i = 1; i<[dictParam count]; i++) {
               strQuery = [strQuery stringByAppendingFormat:@" ,? as %@",[[dictParam allKeys] objectAtIndex:i]];
     }

     strQuery = [strQuery stringByAppendingFormat:@"\n"];

     //For another union statements
     for (int j = 1; j < [[dictParam valueForKey:[NSString stringWithFormat:@"%@",[[dictParam allKeys] objectAtIndex:0]]] count]; j++) {

          strQuery = [strQuery stringByAppendingFormat:@"UNION SELECT ?"];

          for (int i = 1; i<[dictParam count]; i++) {

               strQuery = [strQuery stringByAppendingFormat:@" , ?"];
          }
          strQuery = [strQuery stringByAppendingFormat:@"\n"];

      }
      const char *sql =  [strQuery UTF8String];

      if(sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL) != SQLITE_OK)
        NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(database));

      int counter = 1;

      for (int j = 0; j < [[dictParam valueForKey:[NSString stringWithFormat:@"%@",[[dictParam allKeys]       objectAtIndex:0]]] count]; j++) {

         for (int i = 0; i<[dictParam count]; i++) {

               sqlite3_bind_text(addStmt, counter, [[NSString stringWithFormat:@"%@",[[dictParam valueForKey:[NSString stringWithFormat:@"%@",[[dictParam allKeys] objectAtIndex:i]]] objectAtIndex:j]] UTF8String], -1, SQLITE_TRANSIENT);

               counter++;

         }
       }
       if(SQLITE_DONE != sqlite3_step(addStmt))
          NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database));
       else
          coffeeID = sqlite3_last_insert_rowid(database);

   //Reset the add statement.
   sqlite3_reset(addStmt);

}


text:
Q: Ajax form with jQuery i'm making a function that makes every form in my site to submit but "from behind", so the website is not redirected.
This is the code:
$('form').each(function(data){
    var el = $(this);
    $(el).submit(function(){
        var action = el.attr('action');
        $.post(action, function(){
            console.log(action);
        });
        return false;
    });
});

The "console.log" log without problems de URL, and the same URL have the data of the form. But the $.post function doesn't submit it.
Any Ideas?, this is in symfony2.

A: dont't forget to post your form data
i havr put an example with $.ajax
$(".yourform").submit(function(e){
  e.preventDefault();
  var data = $(this).serialize();
  var action = $(this).attr('action');

  $.ajax({
       url: action,
       type: "POST",
       data: data,
       success: function(result) {
         //logic here
       });
   });

});


text:
Q: In shell script, how to give a variable the value that is shown on the screen? Supposing some strings (like 123 or abc or test123) would automatically appear on the screen after last command and I cannot know the exact value of the string in advance.
Next I want to make a new directory named after that string (like ./123/ or ./abc/ or ./test123/), which means the string should be given to a variable var so that the new directory could be created by mkdir $var.

A: You can use backticks to store the result of a command (in my example, it's uname) on a variable, then echo it onscreen, and eventually use it as argument to mkdir:
FOO=`uname -n`
echo "$FOO"
mkdir "$FOO"

The excellent Advanced Bash-Scripting Guide has a whole chapter about Command Substitution.
As @KalvinLee commented, the preferred format is now $(...):
FOO=$(uname -n)


text:
Q: How to access C++ typedef'd structures in python with SWIG interface I am trying to configure my SWIG interface to expose all defined typedefs.
Example: For the following in my C++ header file I want my python code to be able to create objects A, B, C, D, E.
//MyHeader.h
struct Common
{
    uint8_t     eId;
};
typedef Common A, B, C, D, E;

I have tested with the following structs in my header file and the objects available through the SWIG interface are Test, Test2Typedef, and Test3Typedef1, but not TestTypedef, Test2, Test3, or Test3Typedef2.
//MyHeader.h
struct Test {
    uint8_t uValue;
};
typedef Test TestTypedef;

typedef struct Test2 {
    uint8_t uValue;
} Test2Typedef;

typedef struct Test3 {
    uint8_t uValue;
} Test3Typedef1, Test3Typedef2;

I have tried adding the following typedefs to my .i file, and still cannot access TestTypedef:
//MyHeader.i
%{
#include "MyHeader.h"
typedef Test TestTypedef;
%}

typedef Test TestTypedef;
%include "MyHeader.h"

A: As a general rule SWIG tries to mirror the behaviour of C as closely as possible in the target language. Sometimes that's a little bit tricky though when there's no general case mapping of typedef semantics into many of the languages SWIG targets. In this particular instance though you can still achieve the behaviour you're looking for in Python, using one of two possible options. To simplify things though you're going to want to be more consistent in your header, so either always typedef the TestN structs, or never typedef them.
Firstly you could write a little bit of extra Python code, inside %pythoncode which makes sure there's an alias for every type in Python that matches what you're expecting. The following interface shows that:
%module test

%inline %{

struct Test {
    uint8_t uValue;
};
typedef Test TestTypedef;

struct Test2 {
    uint8_t uValue;
};
typedef Test2 Test2Typedef;

struct Test3 {
    uint8_t uValue;
};
 typedef Test3 Test3Typedef1, Test3Typedef2;

%}

%pythoncode %{
  TestTypedef = Test
  Test2Typedef = Test2
  Test3Typedef1 = Test3
  Test3Typedef2 = Test3
%}

The alternative approach however is to do some trickery within the C++ layer. All we have to do in reality is make sure that SWIG generate the interface we want and it's all legal, correct, compilable C++ code. It doesn't matter however if we lie to SWIG about what our C++ code is really like. So in practice if we claim that each of our typedefs is actually a derived class, but in reality they're simply typedefs then we'll still end up with a perfectly working interface from it. And as a bonus things will mostly be more typesafe in the target language which is probably good:
%module test

%{
// This is what the C++ compiler sees:
struct Test {
    uint8_t uValue;
};
typedef Test TestTypedef;

struct Test2 {
    uint8_t uValue;
};
typedef Test2 Test2Typedef;

struct Test3 {
    uint8_t uValue;
};
typedef Test3 Test3Typedef1, Test3Typedef2;

%}

// This is the lie we tell SWIG, but it's compatible with what the C++ code really is doing
struct Test {
    uint8_t uValue;
};

struct Test2 {
    uint8_t uValue;
};

struct Test3 {
    uint8_t uValue;
};

struct Test2Typedef : Test2 {};
struct Test3Typedef1 : Test3 {};
struct Test3Typedef2 : Test3 {};

Either of these lets us run this Python code:
import test

a = test.Test3Typedef2()

If it were me doing this I'd define a macro for the typedef generation:
#ifndef SWIG
#define MAKE_TYPEDEF(original, renamed) typedef original renamed
#else
#define MAKE_TYPEDEF(original, renamed) struct renamed : original {}
#endif

Which could live in a header file then and would allow you to use %include still.


text:
Q: $L^2\subset L^1$ in case if the measure is finite Let $(X, \mathcal B, \mu)$ be a finite measure space. Prove that $L^2(X, \mathcal B, \mu) \subset L^1(X, \mathcal B, \mu)$.
I will be glad for any idea, comment, hint or advice.

A: Hint:
Let $f: X \to \mathbb{R}$ be non-negative and in $L^2$.
Separate $f = f|_{\{f\le 1\}}+f|_{\{f> 1\}}$.
For the first part, notice that the measure space is finite.
For the second part, notice that for some (which ones?) $\mathbb{R}\ni a>0$ we have $a \le a^2$.

A: In fact, if $(X,\mu)$ is a finite measure space, you have a stronger result, for all $1\le q<p \le\infty$ then $L^p(\mu)\subset L^q(\mu)$, in particular, $q=1$ and $p=2$.
I will provide the proof for your specific case, but think about the general case... Just use Hölder's inequality.
What you need to prove is that if given a function $f\in L^2$ then $f\in L^1$. We have from the holder inequality that
$$\lVert f g \rVert_1 \le \lVert f \rVert_p \lVert g \rVert_q$$
for $1/p +1/q=1$. Note that for $p=q=2$, we can use the inequality. Consider $g=1$.
$$\int_X|f\cdot1|~d\mu\le \left(\int_X|f|^2~d\mu\right)^{1/2}\cdot \left(\int_X|1|^2~d\mu\right)^{1/2}$$
$$\int_X|f|~d\mu\le \lVert f\rVert_2\cdot \mu(X)^{1/2}$$
As $\mu(X)<\infty$ and $f\in L^2$, then we have
$$\lVert f \rVert_1=\int_X |f|~d\mu<\infty$$ so $f \in L^1$.

For the general case, the strategy is similar, instead of using $f$ you should use $|f|^q$ and $g=1$. Now you must also change the exponents, consider $s = \frac{p}{q}$ and $r = \frac{p}{p-q}$. I suggest you finish the argument for this case as well.


text:
Q: Execute Oracle Function to export data to Excel file "Using Generating excel documents on-the-fly from PHP5" function EXCEL_PER_GET(
TABLE_ID_in number,
TABLE_N_IN NUMBER,
NAME_TYPE_in number)     return varchar2

  as

    CURSOR CUR IS
    select *
    from   PER_DATA_Vw
    where  TABLE_ID=  TABLE_ID_in and  TABLE_N=TABLE_N_IN and
            NAME_TYPE = NAME_TYPE_in
    order by NAME_TYPE;

    data_V varchar2(22000);
    dt_fm_v varchar2(2000);
    cnt number:=0;

begin
    data_V:=',,,,,,';
    FOR REC IN CUR LOOP
..... ...
END LOOP;

In PHP file:
 public function ToExcel(){
          // load library
        require __DIR__ . "/../helpers/php-excel.php";
      ini_set('memory_limit', '-1');
      $filename='Report-'.date('d-m-Y');
      $res = $this->total_res_model->get_ma(NULL,'*',NULL,"D_ALL_RSFNTAL_MA_AND_DET");
       $xls = new Excel_XML('UTF-8', false, 'My Test Sheet');
      $data = array();

      array_push($data,array(

      ));
      array_push($data,array(
         0=>"ID_MID_DETTER"));

      foreach($res as $need){

          $row[1] =  $need->BLD_STATUS_NAME;
        //THIS IS A PROBLEM FOR NOW HOW PHP execute THE FUNCTION AND GET IT          USING FORLOOP.
          //  EXCEL_PKG.EXCEL_PERSONS_GET


text:
Q: how to set css for Zend form? I m New to Zend framework and I have created a login form in PHP and I want to set Its css style but I don't know how to set it.
Please Suggest some code or link.....
Thanks in Advance

A: When you are creating your form elements you have to give them names:
$form->addElement('text', 'username');
$form->addElement('password', 'password');
$form->addElement('submit', 'submit');

These become the ids of the elements. You can target these elements using CSS selectors just like any other element:
input#username,
input#password
{
    width:200px
}
input#username
{
    background-color:yellow;
}

You can also give the form a name.
Another method is to give your form elements classes:
$element->setAttrib('class', 'username');

As you become more experienced with ZF you may want to start looking at form element decorators. These allow you to show error messages, labels, and extra divs or whatever around your form elements.

A: I would recommend against being too specific with styling in your forms.  You'll notice that most of the built-in decorators are fairly basic markup.  Once you start mixing in css classes your forms become too view-layer heavy and it makes them difficult to reuse.  For example in a mobile vs. full browser context.
Instead, echo your form inside of a div and use css to style child elements.
<div class="login-form">
    <?php echo $form ?>
</div>

div.login-form input[type=text] { width: 200px; }


text:
Q: Problem with Dell XPS and AMD Polaris 22 XL videocard I've just installed Ubuntu 22.04 on this pc. When I tried to start the normal way, I get similar results as this user https://www.reddit.com/r/Ubuntu/comments/ve94yr/ubuntu_2204_amd_vegam_cant_boot_without_monitor/
When I look in the terminal with lshw -c video, I get this result:
WARNING: you should run this program as super-user.
*-display UNCLAIMED
description: Display controller
product: Polaris 22 XL [Radeon RX Vega M GL]
vendor: Advanced Micro Devices, Inc. [AMD/ATI]
physical id: 0
bus info: pci@0000:01:00.0
version: c0
width: 64 bits
clock: 33MHz
capabilities: bus_master cap_list
configuration: latency=0
resources: memory:a0000000-afffffff memory:b0000000-b01fffff ioport:e000(size=256) memory:ec400000-ec43ffff memory:ec440000-ec45ffff
*-display UNCLAIMED
description: VGA compatible controller
product: HD Graphics 630
vendor: Intel Corporation
physical id: 2
bus info: pci@0000:00:02.0
version: 04
width: 64 bits
clock: 33MHz
capabilities: vga_controller bus_master cap_list
configuration: latency=0
resources: iomemory:2f0-2ef memory:eb000000-ebffffff memory:2fa0000000-2fafffffff ioport:f000(size=64) memory:c0000-dffff
*-graphics
product: EFI VGA
physical id: 1
logical name: /dev/fb0
capabilities: fb
configuration: depth=32 resolution=3840,2160
WARNING: output may be incomplete or inaccurate, you should run this program as super-user.
I already did some searching and found these drivers for the videocard
https://linux-hardware.org/?id=pci:1002-694e-8086-2073
The kernel version is 5.15.0-53-generic
I tried a lot already but I can't get it working properly. I can use ubuntu when I start up in a sort of recovery mode but not the normal way.
Hopefully someone can help me... thx already!


text:
Q: How best to stream an SPFile stored in RBS We use Remote Blob Storage (i.e. SQL FileStream) and SharePoint 2010 to store our files.
We have a web service providing access to parts of SharePoint. One part of this web service includes serving up a stream to download a file stored in our site.
Here's how we currently do it:
    public Stream GetStream(SPFile spFile)
    {
        var memoryStream = new MemoryStream();
        using (var stream = spFile.OpenBinaryStream())
            stream.CopyTo(memoryStream);
        return memoryStream;
    }

If this is a 500MB file stored in a remote blob, this code copies the whole file to memory first. Run up 10 simultaneous downloads and we're in trouble!
Is there a better way to deliver the FileStream stream without loading it into memory first?

A: System.IO.Stream should work as it can handle streams of in theory infinite length.
[update]
https://stackoverflow.com/questions/437043/best-way-to-handle-a-large-download-site
That's a good read.


text:
Q: Is there anyone using Xbrowser for html or aspx pages testing There is a requirement for us to implement browser testing for html and aspx pages. I came across xbrowser at the below link.
http://xbrowser.codeplex.com/
I couldn't find any documentation on their website , it has only solution file. I downloaded the code but its not running fully.
Any help or guidence will be really appreciated.

A: XBrowser isn't based on Trident (IE), WebKit (Safari/Chrome), Gecko (Firefox) or any other common rendering engine so as far as "browser testing" its pretty much useless. What it is intended for is website automation. You can instantiate it in code, tell it to navigate to a webpage and then tell it various things such as "enter xyz into the search field and click the submit button". If this is what you're looking for then its also very important to understand that just because what you've tested works in XBrowser doesn't mean it will work anywhere else. It might, it might not, you won't know until you manually test every browser.
If you follow the link at the top of the codeplex site you'll see that the project has been moved to GitHub. From there the author has a link to an earlier project call SimpleBrowser that has some examples that I imagine are similar to XBrowser.


text:
Q: How to convert Procedural JavaScript into OOP where different parts extra tests I made some code to check the URL if it has a query-string and then if it did using JavaScript add the items into input fields Now the way I have done it works. However because it is more basic I keep having to add more tests to future which just drastically inflates my code. I tried converting to more object oriented method so that my function is same but I can just add a new variable to array so I don't have to keep duplicating the function but it is not working and I'm not entirely sure how come (I'm still new to the object orientated)
I have tried converting it to Object Orientated like such (some of the code I got help with) This is my attempt which did not end up working *note that the code that I am talking about is the in the function init()* Note the function init() is called above to run it auto on page load to check states of whether there is a query string or not
function getUrlVars(urlVariable) {
    var vars = {};
    window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
            if (key === urlVariable) vars[key] = value;
        }
    );

    return vars;
}

function init() {
    var screensize = screen.width;
    var itemQuery = {
        moreBikes:{
            urlVar: getUrlVars("currentbike"),
            selector: '#currentbikes',
            newElement: '
<input type="text" name="currentbike[]" class="currentbikesadd" value="${morebikes[i]}" ><button class="delete">Delete</button>
',
            oldElement: '<input type="text" name="currentbike[]" class="currentbike">'
        }
    }

    if (urlVar) {
        var item = itemQuery[item];
        let urlVaribale = item.urlVar.split('_');
        for (let i = 0; i < item.urlVaribale.length; i++){
            $(item.selector).append(decodeURI(item.newElement))
        }
    } else if (!urlVar) {
         $(item.selector).append(item.oldElement);
    }

}

I tried doing something like this however it did not work. (I think it may have to do with missing a viable in init() but not too sure. Also in future when I add my other fields as some of them have other checks in place (see code below for my older code and what i mean have some other fields). So How would I go about combining it into one Below is the Older (working) non object oriented version of the code
this is original version of my code that works
function getUrlVars(urlVariable) {
    var vars = {};
    window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
            if (key === urlVariable) vars[key] = value;
        }
    );
    return vars;
}

function init() {
    var screensize = screen.width;
    var othersocial_p = getUrlVars("kothersocial");
    var othersocialqty_p = getUrlVars("kothersocialqty");
    var morebikes_p = getUrlVars("currentbike");

    //more bikes
    if (morebikes_p['currentbike']) {
        //create the array
        let morebikes = morebikes_p['currentbike'].split('_');
        //loops
        for (let i = 0; i < morebikes.length; i++) {
            $(wrapper_bike).append(decodeURI(`<div class=""><input type="text" name="currentbike[]" class="currentbikesadd" value="${morebikes[i]}" ><button class="delete">Delete</button></div>`))
        }
    } else if (!morebikes_p['currentbike']) {
        $(wrapper_bike).append(`<input type="text" name="currentbike[]" class="currentbike">`);
    }

    //other social media
    if (othersocial_p['kothersocial'] && othersocialqty_p['kothersocialqty']) {
        //create the array
        let othersocial = othersocial_p['kothersocial'].split('_');
        let othersocialqty = othersocialqty_p['kothersocialqty'].split('_');
        if (screensize < 800) {
            //loops the length of the username
            for (let i = 0; i < othersocial.length; i++) {
                $(wrapper_othersocial).append(decodeURI(`
Other - Please specify
<input name="othersocial[]" class="othersocial addedothersocial" value="${othersocial[i]}" style="margin-bottom:5px;"> Followers Count:

<input name="otherqty[]" class="otherqtys addothersocquantity" value="${othersocialqty[i]} " style="margin-bottom:5px;" ><button style="margin-top:10px;" class="delete">Delete</button>

`));
            }
        } else {
            $(othersocialid).append(`
Other - Please specify
 Followers Count:

`);
            //loops the length of the username
            for (let i = 0; i < othersocial.length; i++) {
                $(wrapper_othersocial).append(decodeURI(`<input name="othersocial[]" class="othersocial addedothersocial" value="${othersocial[i]}" style="margin-bottom:5px;"><input name="otherqty[]" class="otherqtys addothersocquantity" value="${othersocialqty[i]} " style="margin-bottom:5px;" ><button style="margin-top:10px;" class="delete">Delete</button>
`));
            }
        }
    } else if (!othersocial_p['kothersocial']) {
        counter_social++;
        if (screensize < 800) {
            $(othersocialid).append(`

Other - Please specify
<input type="text" name="othersocial[]" id="othersocial" class="othersocial">
 Followers Count:
<input type="text" name="otherqty[]" id="otherqtys" style="margin: 10px 0">

`)
        } else {
            $(othersocialid).append(`
Other - Please specify
<input type="text" name="othersocial[]" id="othersocial" class="othersocial"> Followers Count:
<input type="text" name="otherqty[]" id="otherqtys" style="margin: 10px 0">

`)
        }
    }
}

What the code is basically doing is checking to see if the query string has the array relating to the variable that ends in variable_p[''].split('_') and is splitting up them as i saved them like that as an array in query string.
Then this is where it splits for the items that have 1 item:
like more bikes it is going straight into the for loops the output the value where it will go to check if there isn't a value in the query string and then just input an empty input field
However for the splits that have 2 items:
first check for the screen size as depending on screen size it will show up slightly different. So then depending on the screen size it will show the different layouts of the exact same information just in different order.
Else like before it will show empty inputs but also depending on screen size have slightly different layout.
Is there a way to make this into one object orientated function or should i split the function into those with 2 variables and the screen-size split or is there a way to test it and just do it as one simple function? Any help would be appreciated


text:
Q: unable to get swipe direction and distance using touchswipe plugin in android or iPad Using a jQuery plugin named touchswipe ( Touchswipe http://labs.skinkers.com/touchSwipe/ ) for a website primarily for desktops and some mobile devices like galaxy tab or iPad for left and right swipe of the third column in the page.
Link to my page made with html and jQuery is as follows:
my page
However while the events for swipe is triggered the distance and direction are given as null. The demos in the [Touchswipe ] site seem to work fine with similar code. Kindly help me on this by letting me know what I'm doing wrong.
Thanks.

A: It seems that my issue was primarily because of touchswipe1.2.4 .... the demo was on touchswipe1.2.3 so changing to the older version did the trick....hope this helps some1..


text:
Q: Can I use multiple resistors is series to approximate a precision resistor called for in schematic? I have seen in several schematics where a precision resistor, or matched resistors are called for, but every one of them talk about you going to purchase special resistors for this purpose.
I am building the Go, No-go transistor matching circuit shown here.  It stated the just about all the resistors have to be matched to 1% at the most for it to work.  I have cheapo "1% resistors", but don't trust them to be in spec.  For this particular circuit it would seem that the closer I can get to precise resistances, the more accurate the vbe measurements will be.
Question: do I really need to find resistor "pairs" for this or can I simply put resistors in series until the total resistance is exactly what I want (my 20000 count multimeter would let me get to 0.1% or even 0.01% precision this way)?  So for example, to get a perfect 20k resistor, I might use a 15k, 4.7k, 270 and maybe something small between 1-100 ohms all in series so that the total real resistance measured is 19.999-20,001 ohms.  It seems like a simple no brainer, but every time I see schematics talking about precision resistors, none of them offer this approach, which got me to wonder if there was a reason.

A: This approach works well for 'one-off' instruments designed to work at room temperature. I use it all the time. It has two drawbacks.
1) It's labour intensive, which is why it's not used for mass produced equipment, where it's cheaper to buy 0.1% resistors and just fit them, rather than muck about measuring and matching.
2) 1% resistors won't necessarily have as good a tempco of resistance as 'precision' 0.1% or 0.01% resistors. This will be mitigated to some extent if you are only after tracking between multiple resistors, but even then there is no guarrantee cheaper resistors will track well. A set of precision resistors in a pack will be specified to track to a certain extent.

A: Not suitable for high frequency or high speed circuit because the modified resistor may exhibit high stray inductance and capacitance.
But for your application it may work fine.

A: p.s. that circuit is complete overkill to find pairs of transistors with equal VBEs.
There is no reason to set the test current to any precise value -- if you want to match VBES at (say) 100 uA, then something 'close' to 100 uA would be OK -- if the 'matching' changes depending on whether you are at 100 uA or 110 uA, your application is likely not using transistors correctly.
So, if take (say) a 9 V battery, and a resistor of about (9-0.6)/100uA = 84k -- so use 82k, and connect the transistor as a diode (C&B = 1 terminal, E = other) in series, and measure the VBE with a DMM. Swap in your other devices and find matched ones.
Alternatively, use 2 82k resistors, 1 for each transistor and use the DMM to compare directly between the two collector/base connections. You don't need precision resistors -- 1 % mismatch will cause about 0.26 mV difference between the transistors -- about the same as 0.13 deg. C temperature difference.


text:
Q: Render HTML entities inside a string in React I'm facing issue while displaying curly quotes HTML entities in React JS. Ref straight and curly quotes
    render() {
      return (

              {theme == 'blue' && 'This is sample text'}
              {theme == 'red' && 'What’s your role in this project'}

            )
         }

Current Output
What’s your role in this project

Expected Output
What's your role in this project
I don't want to use dangerouslySetInnerHTML or i don't want to define these values in react state property. Thanks in advance.

A: If you really can't use " or template strings, try returning a fragment
<>What’s your role in this project</>

A: Using the String.fromCharCode method:
Check React docs : https://shripadk.github.io/react/docs/jsx-gotchas.html
MDN Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCharCode
To Find the char code: http://www.mauvecloud.net/charsets/CharCodeFinder.html
render() {
          return (

                  {theme == 'blue' && 'This is sample text'}
                  {theme == 'red' && `What ${String.fromCharCode(8217}s your role in this project`}

                )
             }

template literals `` for the text
render() {
          return (

                  {theme == 'blue' && 'This is sample text'}
                  {theme == 'red' && `What's your role in this project`}

                )
             }

Using double quotes and single quotes
render() {
          return (

                  {theme == 'blue' && 'This is sample text'}
                  {theme == 'red' && "What's your role in this project"}

                )
             }

Use escape character
 return (

                  {theme == 'blue' && 'This is sample text'}
                  {theme == 'red' && 'What \'s your role in this project'}

                )
             }

A: After doing some research I found the easiest way to achieve this using React Fragment tag
     render() {
      return (

              {theme == 'blue' && 'This is sample text'}
              {theme == 'red' && <Fragment>What’s your role in this project</Fragment>}

            )
         }

A: Simply use template string `What's your role in this project`.


text:
Q: How do I make a method that returns a Response in my utilities library? In a code-behind I have a method that consists of the following:
        Response.Clear();
        Response.ClearHeaders();
        Response.ContentType = "xxx";
        Response.AppendHeader("Content-Disposition", "xxx");
        Response.AppendHeader("Content-Length", xxx);
        Response.BinaryWrite(xxx);
        Response.Flush();
        Response.End();

Now, this code will be used in a few different places. The code will be identical in the various places it is used. Only the file name and byte array will change and those are parameters passed to the existing method.
My question is, how do I pull this code out from the current code-behind and place it in a "Utilities" class. I tried copying and pasting the code into the class where I'd like it to reside by the Response object is giving me some problems (Cannot resolve symbol 'Response'). I tried instantiating an HttpResponse to return but the constructor only takes a textwriter and upon further research, MSDN says I shouldn't be doing that anyway.
Any suggestions?

A: Use HttpContext.Current.Response, which will work in your Utilities.cs


text:
Q: material ui table delete function not working why is my code showing wrong output for
as the rows has been already populated after adding it with the handletabledata function
My code is having a table and there is a add button where we add users but on the delete function when I am trying to see the rows I am getting only that row and rows above it.
please help.
import React from 'react'
import './server.scss'
import Paper from '@mui/material/Paper';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TablePagination from '@mui/material/TablePagination';
import TableRow from '@mui/material/TableRow';
import { Button } from '@mui/material';
import DeleteOutlineIcon from '@mui/icons-material/DeleteOutline';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText';
import DialogTitle from '@mui/material/DialogTitle';
import Slide from '@mui/material/Slide';
import PersonAddAltIcon from '@mui/icons-material/PersonAddAlt';
import TextField from '@mui/material/TextField';
import InputLabel from '@mui/material/InputLabel';
import MenuItem from '@mui/material/MenuItem';
import FormControl from '@mui/material/FormControl';
import Select from '@mui/material/Select';

const columns = [
  { id: 'key', label: '#', minWidth: 70 },
  { id: 'user', label: 'User', minWidth: 100 },
  {
    id: 'signed',
    label: 'Last Signed in',
    minWidth: 170,
    align: 'right',

  },
  {
    id: 'role',
    label: 'Role',
    minWidth: 170,
    align: 'right',

  },
  {
    id: 'icon',
    label: '',
    minWidth: 170,
    align: 'right',

  },
];

function createData(user, role, key, icon, signed) {
  signed = signed.getTime()

  return { key, user, signed, role, icon };
}

//modal code

const Transition = React.forwardRef(function Transition(props, ref) {
  return <Slide direction="up" ref={ref} {...props} />;
});

const Server = () => {
  //final insertion of data
  const [rows, setrow] = React.useState([]);
// console.log(rows)

  //pagination
  const [page, setPage] = React.useState(0);
  const [rowsPerPage, setRowsPerPage] = React.useState(10);

  const handleChangePage = (event, newPage) => {
    setPage(newPage);
  };

  const handleChangeRowsPerPage = (event) => {
    setRowsPerPage(+event.target.value);
    setPage(0);
  };

  //modal code
  const [open, setOpen] = React.useState(false);

  const handleClickOpen = () => {
    setOpen(true);
  };

  const handleClose = () => {
    setOpen(false);
  };

  //setting data for row
  const [id, setid] = React.useState(0);

  const handletabledata = () => {
    setid(id + 1)
    let row = [...rows]
    row.push(createData(email, role, id, <DeleteOutlineIcon  onClick={console.log(rows)}/>, new Date()))
    setrow(row)
    setemail('')
    setrole('')
    setOpen(false);

  }

  //input field
  const [email, setemail] = React.useState('');

  const handleEmail = (event) => {
    setemail(event.target.value);
  };

  //dropdown list
  const [role, setrole] = React.useState('');

  const handleChange = (event) => {
    setrole(event.target.value);
  };

  return (

        <Button variant="contained" onClick={handleClickOpen}>Add User</Button>
        <Dialog
          open={open}
          TransitionComponent={Transition}
          keepMounted
          onClose={handleClose}
          aria-describedby="alert-dialog-slide-description"
          fullWidth={true}
        >
          <DialogTitle>{"Add User"}</DialogTitle>
          <DialogContent>
            <DialogContentText id="alert-dialog-slide-description">

                  <PersonAddAltIcon style={{ fontSize: '7rem', position: 'relative', top: '50px' }} />

                  User Information
                  <TextField placeholder="Email Address" onChange={handleEmail} value={email} />
                  <FormControl fullWidth>
                    <InputLabel id="demo-simple-select-label">Role</InputLabel>
                    <Select
                      labelId="demo-simple-select-label"
                      id="demo-simple-select"
                      value={role}
                      label="role"
                      onChange={handleChange}
                    >
                      <MenuItem value={'Owner'}>Owner</MenuItem>
                      <MenuItem value={'Sales'}>Sales</MenuItem>
                      <MenuItem value={'Admin'}>Admin</MenuItem>
                    </Select>
                  </FormControl>

            </DialogContentText>
          </DialogContent>
          <DialogActions>
            <Button onClick={handleClose}>Cancel</Button>
            <Button onClick={handletabledata}>Add</Button>
          </DialogActions>
        </Dialog>

      <Paper sx={{ width: '100%', overflow: 'hidden' }}>
        <TableContainer sx={{ maxHeight: 440 }}>

            <TableHead>
              <TableRow>
                {columns.map((column) => (
                  <TableCell
                    key={column.id}
                    align={column.align}
                    style={{ minWidth: column.minWidth }}
                  >
                    {column.label}
                  </TableCell>
                ))}
              </TableRow>
            </TableHead>
            <TableBody>
              {rows
                .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
                .map((row) => {
                  return (
                    <TableRow hover role="checkbox" tabIndex={-1} key={row.code}>
                      {columns.map((column) => {
                        const value = row[column.id];
                        return (
                          <TableCell key={column.id} align={column.align}>
                            {column.format && typeof value === 'number'
                              ? column.format(value)
                              : value}
                          </TableCell>
                        );
                      })}
                    </TableRow>
                  );
                })}
            </TableBody>

        </TableContainer>
        <TablePagination
          rowsPerPageOptions={[10, 25, 100]}
          component="div"
          count={rows.length}
          rowsPerPage={rowsPerPage}
          page={page}
          onPageChange={handleChangePage}
          onRowsPerPageChange={handleChangeRowsPerPage}
        />
      </Paper>

  );
}

export default Server


text:
Q: Assign Data To Variable from eBay JSON Object I'm experimenting with the eBay api and trying to get the value of the title from an object.
Here's view of what data looks like

I've tried the following code, with several variations, but I keep getting this error
UnhandledPromiseRejectionWarning: SyntaxError: Unexpected token o in JSON at position 1

app.get("/", (req, res) => {
  ebay.findItemsByKeywords("iphone").then(data => {
    const newdata = JSON.parse(data);
    const title = newdata[0].searchResult.item.title;
    res.render("index", {
      title: title
    });
  });

A: ok this did the trick
 const title = data[0].searchResult[0].item[0].title;
    res.render("index", {
      title: title
    });


text:
Q: How to get a display in descending order I know there is a simple answer to this question but I have searched for 2 days trying to find it. I have a program in rails that lists workers in the home building industry. I ask for the following informatio occupation, first name, second name,telephone number, email address. This information is displayed without any editing of my code. I would like to display this information using the order query and showing the information using the occupation column in descending order. Please tell me the code to use and where it goes.

A: I assume you have a method named index inside your controller. Ok, inside the index method, you can use .order method.
Make it like this:
def index
    @users = User.order(occupation: :desc)
end

Reference:
http://apidock.com/rails/ActiveRecord/QueryMethods/order


text:
Q: Navigation toggler is not working in browser but working in codeply I have tried to include navigation bar with toggler. The code is working fine in codeply but not in browser. The toggler button (hamburger button) is appearing when in mobile but not showing the lists. Below is my code.

  <title>Practice</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
   rel="stylesheet" integrity="sha384-
   1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

    WonderWeb
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-
     target="#navbarTogglerDemo02" aria-controls="navbarTogglerDemo02" aria-expanded="false"
     aria-label="Toggle navigation">

    </button>

Contact

Products

Payment

A: Many of Bootstrap 5 components require the use of JavaScript to function.
You forgot to include special links from Bootstrap 5 and You had wrong id in here

It should be like this =>

Now it's works perfectly ;-) Best regards!

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0, viewport-fit=cover"
    />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Solved ;-) </title>
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
      crossorigin="anonymous"
    />

        WonderWeb
        <button
          class="navbar-toggler"
          type="button"
          data-bs-toggle="collapse"
          data-bs-target="#navbarTogglerDemo02"
          aria-controls="navbarTogglerDemo02"
          aria-expanded="false"
          aria-label="Toggle navigation"
        >

        </button>

Contact

Products

Payment


text:
Q: System.InvalidOperationException: Unable to resolve service for type - Dependency Injection I am developing a web application - Blazor WebAssembly hosted on ASP.NET. I am trying to start getting value from database (Entity Framework using). I am using Repository and UnitOfWork patterns in my solution.
So, I faced this error:
An unhandled exception has occurred while executing the request.
      System.InvalidOperationException: Unable to resolve service for type 'ReportApp.Core.Services.TaskService' while attempting to activate 'ReportApp.Server.Controllers.TaskController'.
         at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
         at lambda_method8(Closure , IServiceProvider , Object[] )
         at Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.<>c__DisplayClass4_0.<CreateActivator>b__0(ControllerContext controllerContext)
         at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass5_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
      --- End of stack trace from previous location ---
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
      --- End of stack trace from previous location ---
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
         at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
         at Microsoft.AspNetCore.Builder.Extensions.MapWhenMiddleware.Invoke(HttpContext context)
         at Microsoft.AspNetCore.Builder.Extensions.MapMiddleware.Invoke(HttpContext context)
         at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

The structure of my project is as follows:
DbContext class:
public class ReportAppContext : DbContext
{
    public DbSet<TaskEntity> Tasks { get; set; }
        public DbSet<ReportEntity> Reports { get; set; }
        public DbSet<EmployeeEntity> Employees { get; set; }

        public ReportAppContext()
        {
        }

        public ReportAppContext(DbContextOptions<ReportAppContext> options) : base(options)
        {
        }
}

Repository interface:
public interface ITaskRepository : IGenericRepository<TaskEntity>
    {
    }

public interface IGenericRepository<TEntity> where TEntity : class
    {
        Task<TEntity> GetByIdAsync(Int32 id);
        Task InsertAsync(TEntity entity);
        Task UpdateAsync(TEntity entity);
        Task DeleteAsync(Int32 id);
        Task<IEnumerable<TEntity>> GetAllAsync();
        Task SaveAsync();
    }

public class TaskRepository : ITaskRepository
    {
        private readonly ReportAppContext _context;

        public TaskRepository(ReportAppContext context)
        {
            _context = context;
        }

Then I have UnitOfWork pattern:
public class UnitOfWork : ReportAppContext, IUnitOfWork
    {
        private readonly ITaskRepository _taskRepository;

And controller on server:
[Route("api/[controller]")]
    [ApiController]
    public class TaskController : ControllerBase
    {
        private readonly TaskService _taskService;

        public TaskController(TaskService taskService)
        {
            _taskService = taskService;
        }

        [HttpGet("get-all")]
        public async Task<ActionResult<List<TaskDto>>> GetAllTasksAsync()
        {
            var result = await _taskService.GetAllAsync();
            return Ok(result);
        }

Finally, Startup class configuration:
public void ConfigureServices(IServiceCollection services)
        {
            var connection = Configuration.GetConnectionString("DefaultConnection");
            services.AddDbContext<ReportAppContext>(options => options.UseSqlServer(connection));
            services.AddCors();

            services.AddServerSideBlazor().AddCircuitOptions(options => { options.DetailedErrors = true; });
            services.AddControllersWithViews();
            services.AddRazorPages();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseWebAssemblyDebugging();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseBlazorFrameworkFiles();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapControllers();
                endpoints.MapFallbackToFile("index.html");
            });
        }

I've tried to add this:
services.AddTransient<ITaskRepository, TaskRepository>();

and the same with AddScoped, but it didn't change anything...

A: But in your TaskController you are injecting TaskService, not TaskRepository. I think you need to register TaskService also (i assume that TaskService consumes TaskRepository. Both can be registered as Scoped).
services.AddTransient<ITaskRepository, TaskRepository>(); OR
services.AddScoped<ITaskRepository, TaskRepository>();
services.AddTransient<TaskService>(); OR
services.AddScoped<TaskService>();

The difference between scoped and transient is that when you have registered service as transient every time when it is resolved return a new instance while scoped will return you same instance during the scope.

A: The error is telling you that TaskService is not registered but your Controller needs it as an injected service.
In ConfigureServices, try something like this:
services.AddScoped<TaskService>(sp => {
    // Build your Context Options
    DbContextOptionsBuilder<ReportAppContext> optsBuilder = new DbContextOptionsBuilder<ReportAppContext>();
    optsBuilder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
    // Build your context (using the options from the builder)
    ReportAppContext ctx = new ReportAppContext(optsBuilder.options);
    // Build your unit of work (and pass in the context)
    UnitOfWork uow = new UnitOfWork(ctx);
    // Build your service (and pass in the unit of work)
    TaskService svc = new TaskService(uow)
    // Return your Svc
    return svc;
});

Then, your controller will receive a fully configured TaskService, ready for use.
You can put each item in the DI container in turn, if you wish, but the UOW, Repository & Context do not need to be accessed outside of the TaskService, so its a bit of waste of time.
Just create the configured TaskService as above and that's all that needs to be injected by the DI container.

A: I also encountered the same error but the above solutions didn't help in my case. I was accidentally trying to inject the concrete class ReviewRepository instead of the interface IReviewRepository when I had the following registration:
services.AddScoped<IReviewRepository, ReviewRepository>();

And the following consuming code:
private IReviewRepository _reviewRepository;
private IPokemonRepository _pokemonRepository;
private readonly IReviewerRepository _reviewerRepository;
private IMapper _mapper;

public ReviewController(ReviewRepository reviewRepository,
    IMapper mapper,
    IPokemonRepository pokemonRepository,
    ReviewerRepository reviewerRepository)
{
    _reviewRepository = reviewRepository;
    _pokemonRepository = pokemonRepository;
    _reviewerRepository = reviewerRepository;
    _mapper = mapper;
}

Here, ReviewRepository needs to be replaced by IReviewRepository.
So as well as checking for missing dependency injection registrations, it's also worth checking that existing ones are correct!


text:
Q: multiprocessing python Нужно написать код мультипроцессинга для двух функций, в одной мы вводим значения старта и конца (например 0 5), и вводим имена (Паша Женя Ваня). Вторая функция (set) печатает результат. Аргументы написанные внутри функции, обязательны.
На выходе надо получить следующее:
Паша 0
Женя 1
Ваня 2
Паша 3
Женя 4
Ваня 5
Нужно использовать Process, Lock, Value. Ниже есть код, я смог только реализовать последовательный счетчик для одной функции. Как соединить его с именами и вывести, я не могу понять.
from multiprocessing import Process, Lock,Value

start = Value('I',0)

def set(name,item,iter_stop,lock):
    """
    Prints out the item that was passed in
    """
    with start.get_lock():
      start.value+=1
      print(start.value,name)
def start_g():
  start, game_stop = map(int, input().split())
  players = input().split()
  set

if __name__ == '__main__':
    lock = Lock()
    lst=['Паша', 'Женя','Ваня']
    for item in lst:
        p = Process(target=start_g, args=(item, lock))
        p.start()
        p.join()

Еще есть код функции без использования мультипроцессинга.
   def start_game():
        start, game_stop = map(int, input().split())
        players = input().split()
        a=start
        lst=[]
        while a!=game_stop+1:
            for i in players:
                lst.append(i)
                a=a+1
                if a==game_stop+1:
                    break
        for name,current_step in list(zip(lst,range(start,game_stop+1))):
          print(f'{name}: {current_step}')

A: Вот, держите работающий код. Если неправильно вас понял, допилите
Можете players положить в разделяемый Array
from multiprocessing import Process, Lock,Value

def set(players, value):
    """
    Prints out the item that was passed in
    """
    with value.get_lock():
      print(value.value, players[value.value % len(players)])
      value.value += 1

if __name__ == '__main__':

    # start, game_stop = map(int, input().split())
    start, game_stop = 0, 6
    # players = input().split()
    players = ['Паша', 'Женя','Ваня']
    value = Value('I', start)
    processes = [Process(target=set, args=(players,  value)) for i in range(start, game_stop+1)]
    for process in processes:
        process.start()
    for process in processes:
        process.join()
    for process in processes:
        process.close()


text:
Q: Questions about Free Space Map of PostgreSQL Let's create a temporary table (I choose temporary table because autovacuum don't run for this kind of tables):
CREATE TEMP TABLE test (
  id int PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
  value int
);
INSERT INTO test (value) SELECT 0 FROM generate_series(0, 250);
SELECT ctid, * FROM test;

We will see that the table consists of two pages:
(0,1)   1   0
(0,2)   2   0
...
(0,226) 226 0
(1,1)   227 0
...
(1,25)  251 0

Now if we update one row
UPDATE test SET value = -1 WHERE id = 1;
SELECT ctid, * FROM test WHERE value <> 0;

we will see that the new row version was inserted at the end of the table (in the second page, which has enough free space for this operation) and this is a standard PostgreSQL behavior (the old row verison from (0,1) was marked as dead)
(1,26)  1   -1

Let's check the free space of pages:
CREATE EXTENSION pg_freespacemap;
SELECT * FROM pg_freespace('test');

we get
0   0
1   0

i.e. no free space; documentations says that the Free Space Map (FSM) is updated after vacuum run.
Now if we update another row from the first page:
UPDATE test SET value = -1 WHERE id = 2;
SELECT ctid, * FROM test WHERE value <> 0;

we will see
(0,227) 2   -1
(1,26)  1   -1

The new row version was not added to the 2nd page but was added to the current page, because we made free space when we updated the record with id 1. But this approach does not correspond to my understanding of FSM. Here are my questions:

*

*How PostgreSQL knew at the second UPDATE that there was free space in the first page if pg_freespace('test') returned zero? I thought that this function gives you the FSM which in turn is used in case of UPDATEs in order to decide which page has enough free space to store the new row version.

*Generally I was thinking that even if first row was marked as dead it however occupies some space in the 1st page and this space will be freed only after vacuum. Thus I was expecting that the second UPDATE will also add the new row version to the 2nd page.

A: This will contain some PostgreSQL internals; sorry, you asked for it.
Autovacuum doesn't run on temporary tables (because they are invisible outside your session), and at any rate, one or two updates won't trigger autovacuum. Now it is VACUUM that creates and maintains the free space map, so there is no free space map in your case. pg_freespacemap does not error out, but reports that as 0.
Lacking a free space map, PostgreSQL has to look at the individual blocks to find a block with free space in it. That leaves the riddle why the second update could find space to create a tuple in block 0.
To answer the riddle, let's discuss your statements and their effect. You can verify all this using the pageinspect extension.

*

*the first UPDATE:
UPDATE test SET value = -1 WHERE id = 1;

That marks tuple (0,1) as updated (it sets xmax) and creates the new tuple (1,26), just as you expected.

*the following query:
SELECT ctid, * FROM test WHERE value <> 0;

This query can get a page lock on block 0 and performs heap pruning, that is a "micro-vacuum" that frees the space occupied by dead tuples. Note that it cannot remove (0,1), because it is still referenced in an index, but line pointer (0,1) becomes a "stub" marked LP_DEAD that does not occupy any space. The space occupied by that dead tuple is freed.
Note that if you don't run that SELECT, the following UPDATE will perform heap pruning on block 0, so the effect will be the same.

*the second UPDATE:
UPDATE test SET value = -1 WHERE id = 2;

Lacking a free space map, the statement looks a block 0 and notices that there is enough free space, so it performs a HOT update and puts the new tuple into block 0.


text:
Q: How can I disable GNU C compiler/GCC warnings without touching source code? There're tons of redundant explanations about how to disable GCC warnings being treated as errors as developer of the source code. Now, I'd like to know if there's a way to disable them without touching the source code (including build tool configuration files), i.e., let the compilation continue ignoring the warning. In my understand of the GCC documentation at Options to Request or Suppress Warnings, CXXFLAGS="-w" should be sufficient if specified for ./configure and make, e.g., CXXFLAGS="-w" ./configure && make.
Remark: I know that it is not a good idea to compile a program against the intentions of the developers and communicating an issue and fixing it together is always the better option if not the only.
Background (please read the whole question, especially the remark above and below, I'm not looking for a fix for the following issue!): I'm trying to compile QEMU Git tag v2.1.0 in a Debian 7.6 chroot on Synology DSM 5.0 with armv7 architecture and getting
  CC    migration-rdma.o

migration-rdma.c: In function 'ram_chunk_start':
migration-rdma.c:521:12: error: cast to pointer from integer of different size [-Werror=int-to-pointer-cast]
migration-rdma.c: In function '__qemu_rdma_add_block':
migration-rdma.c:553:49: error: cast to pointer from integer of different size [-Werror=int-to-pointer-cast]
migration-rdma.c:554:49: error: cast to pointer from integer of different size [-Werror=int-to-pointer-cast]
migration-rdma.c: In function '__qemu_rdma_delete_block':
migration-rdma.c:661:45: error: cast to pointer from integer of different size [-Werror=int-to-pointer-cast]
migration-rdma.c:696:49: error: cast to pointer from integer of different size [-Werror=int-to-pointer-cast]
migration-rdma.c: In function 'qemu_rdma_search_ram_block':
migration-rdma.c:1109:49: error: cast to pointer from integer of different size [-Werror=int-to-pointer-cast]
migration-rdma.c: In function 'qemu_rdma_register_and_get_keys':
migration-rdma.c:1172:50: error: cast from pointer to integer of different size [-Werror=pointer-to-int-cast]
migration-rdma.c:1173:29: error: cast from pointer to integer of different size [-Werror=pointer-to-int-cast]
migration-rdma.c:1173:51: error: cast from pointer to integer of different size [-Werror=pointer-to-int-cast]
migration-rdma.c:1174:29: error: cast from pointer to integer of different size [-Werror=pointer-to-int-cast]
migration-rdma.c: In function 'qemu_rdma_post_send_control':
migration-rdma.c:1558:36: error: cast from pointer to integer of different size [-Werror=pointer-to-int-cast]
migration-rdma.c: In function 'qemu_rdma_post_recv_control':
migration-rdma.c:1614:37: error: cast from pointer to integer of different size [-Werror=pointer-to-int-cast]
migration-rdma.c: In function 'qemu_rdma_write_one':
migration-rdma.c:1862:16: error: cast from pointer to integer of different size [-Werror=pointer-to-int-cast]
migration-rdma.c:1866:53: error: cast to pointer from integer of different size [-Werror=int-to-pointer-cast]
migration-rdma.c:1920:52: error: cast to pointer from integer of different size [-Werror=int-to-pointer-cast]
migration-rdma.c:1921:50: error: cast to pointer from integer of different size [-Werror=int-to-pointer-cast]
migration-rdma.c:1975:49: error: cast to pointer from integer of different size [-Werror=int-to-pointer-cast]
migration-rdma.c:1996:49: error: cast to pointer from integer of different size [-Werror=int-to-pointer-cast]
migration-rdma.c:2008:58: error: cast to pointer from integer of different size [-Werror=int-to-pointer-cast]
migration-rdma.c: In function 'qemu_rdma_registration_handle':
migration-rdma.c:3021:21: error: cast from pointer to integer of different size [-Werror=pointer-to-int-cast]
migration-rdma.c:3086:41: error: cast from pointer to integer of different size [-Werror=pointer-to-int-cast]
cc1: all warnings being treated as errors
make: *** [migration-rdma.o] Error 1

I played around with some options, and now I just want to know whether it's possible or not in order to achieve better inside in the GNU build tools. I'm very certain that the build result will be at least unreliable if not unusable.
BTW: If you found this through a search engine and are having same or similar trouble with QEMU, see Build of v2.1.0 fails on armv7l due to undeclared __NR_select.

A: You're right about the -w option, and the easiest way to make sure it propagates everywhere is to put it in the CC variable: CC="gcc -w" ./configure ...
However, if they turned on this warning as an error specifically, then I don't think you should try to disable it. In that case, the code was obviously intended for this warning not to be possible, and it's likely that something is horribly wrong in your toolchain (e.g. integer types are defined wrong, so that a type they expect to be the same size as pointers is not). You should try to track this issue down or you're just going to be wasting your time with a broken build that crashes when you run it. Why not look at some of the source lines the warning messages reference and see what's actually going on?


text:
Q: R for loop in a formula I need a for loop inside a formula in R. "Normal" loops are pretty straightforward in R (See for example here https://www.r-bloggers.com/how-to-write-the-first-for-loop-in-r/) However because there are " " in my formula it does not appear to work... Does anyone knows a way around this? In this formula I want ID1 to be a variable of which I have a list of 500 different IDs
testing <- formula(paste("STATUS ~ as.factor(data$TEMP) + C1 + ID1 * ID2 "))

A: y <- rnorm(10)
x1 <- rnorm(10)
x2 <- rnorm(10)
x3 <- rnorm(10)
d <- data.frame(y, x1, x2, x3)

# fit a model with all 2 way interactions
model1 <- lm(y ~ .*., d)
# remove one that you don't want
model2 <- update(model1, ~.-x2:x3)

A: use as.formula rather than just formula. That should work on paste. Although your version works for me..I'm getting class formula both ways. Set sep="" so it does not include any more spaces in the formula...
Regarding the second part I'm not sure what you're asking. You want it as factor as well?


text:
Q: Is it bad practice to define static globals at different locations throughout a file? When I first started programming I always followed the convention of defining global variables at the top of the file like:
static int a[10];
static int b[10];

void firstFn(void)
{
    a[0] = 1;
}

void secondFn(void)
{
    b[4] = 2;
}

void thirdFn(void)
{
    b[5] = 2;
}

But lately I was working on something where I wanted the definition of a global variable to be grouped with a few functions that operate on that variable defined further down in the file:
static int a[10];

void firstFn(void)
{
    a[0] = 1;
}

static int b[10];

void secondFn(void)
{
    b[4] = 2;
}

void thirdFn(void)
{
    b[5] = 2;
}

Another programmer was reviewing this code and said this was one of his pet peeves. Is there a good reason to stick to the top-defining convention?

A: Static variables are local to your compilation unit. Their placement makes absolutely no difference, as long as they are declared ahead of their first use in the program.
Although there are no purely technical reasons to keep static declarations at the top of the file, this is a rather widespread convention. I've seen it written out explicitly in the coding standards of several companies. When all programmers follow the same convention, the code looks more uniform, and uniformity is a great step toward code maintainability. When someone else opens your file and the code formatting looks familiar, that's a great plus. So if other colleagues on your team do follow this convention, you should follow it as well.


text:
Q: Is this an optimization done by C# compiler? I create a batch of anonymous functions by lambda expression. And I want to use TaskId to differ the anonymous functions from each other.
Here is the code:
int count = 3;
int i;
for (int j = 0; j < 10; j++)
{
    i = 0;
    Func<bool, Task<int>> func = async (b) =>
    {
        return j;
    };
    while (i++ < count)
    {
        var task = func(true);
        Console.WriteLine(String.Format("Task Result:{0} TaskId:{1}",
            task.Result, task.Id));
    }
}

Here is the output
Task Result:0 TaskId:1
Task Result:0 TaskId:1
Task Result:0 TaskId:1
Task Result:1 TaskId:2
Task Result:1 TaskId:2
Task Result:1 TaskId:2
Task Result:2 TaskId:3
Task Result:2 TaskId:3
Task Result:2 TaskId:3
Task Result:3 TaskId:4
Task Result:3 TaskId:4
Task Result:3 TaskId:4
Task Result:4 TaskId:5
Task Result:4 TaskId:5
Task Result:4 TaskId:5
Task Result:5 TaskId:6
Task Result:5 TaskId:6
Task Result:5 TaskId:6
Task Result:6 TaskId:7
Task Result:6 TaskId:7
Task Result:6 TaskId:7
Task Result:7 TaskId:8
Task Result:7 TaskId:8
Task Result:7 TaskId:8
Task Result:8 TaskId:9
Task Result:8 TaskId:9
Task Result:8 TaskId:9
Task Result:9 TaskId:10
Task Result:9 TaskId:11
Task Result:9 TaskId:12

As you can see, the TaskId changed since the result is greater than 8. I'm wondering to know the reason of this phenomenon. Thanks for your help:)

A: It's not the compiler, per se, but the .NET framework that is doing the caching. Look at the code for AsyncMethodBuilder which the compiler uses to manage the generated state machines for async methods. It looks like SetResult does some caching in GetTaskForResult. There is some very specific code for caching basic value types including this:
// For Int32, we cache a range of common values, e.g. [-1,4).
else if (typeof(TResult) == typeof(Int32))
{
    // Compare to constants to avoid static field access if outside of cached range.
    // We compare to the upper bound first, as we're more likely to cache miss on the upper side than on the
    // lower side, due to positive values being more common than negative as return values.
    Int32 value = (Int32)(object)result;
    if (value < AsyncTaskCache.EXCLUSIVE_INT32_MAX &&
        value >= AsyncTaskCache.INCLUSIVE_INT32_MIN)
    {
        Task<Int32> task = AsyncTaskCache.Int32Tasks[value - AsyncTaskCache.INCLUSIVE_INT32_MIN];
        return JitHelpers.UnsafeCast<Task<TResult>>(task); // UnsafeCast avoids a type check we know will succeed
    }
}

And we see that:
/// The minimum value, inclusive, for which we want a cached task.
internal const Int32 INCLUSIVE_INT32_MIN = -1;
/// The maximum value, exclusive, for which we want a cached task.
internal const Int32 EXCLUSIVE_INT32_MAX = 9;

Which is why 8 is the magic cutoff. Notably -1 should get cached too and from my tests it is.

A: The ambda expressions are storing variables and not values. Your expression is async so i think the threads are messing up the results. Try without the async magic, it will show the correct results.


text:
Q: Use of quotes for angularjs- directives I'm practicing writing AngularJS app using modules and embedded HTML. Does anyone know why the source of the ng-include directive below requires single quotes inside double quotes, while the source for the

A: ng-include expects an angular expression evaluating to the URL
For example, if you write ng-include="test.html", that would mean the html attribute of the test object of $scope.
When you say ng-include="'test.html'", that is an angular expression. In this case, the string that evaluates to the value test.html
Here is the official documentation
https://docs.angularjs.org/api/ng/directive/ngInclude

A: See the documentation here,ng-include, it says if string is a constant then you should use the single inverted commas, but for expressions like "getView()", "showViews()" etc, you don't need the single inverted commas


text:
Q: class getter rand variable #include <iostream>
#include <cstdlib>

using namespace std;

class Passenger {
private:
        int ticket ;
        int half ;
    public:
        Passenger(int ticket=rand() % 2, int half=rand() % 2) {                 //  Construct passenger
                cout << "passenger was constructed with " << ticket << " ticket and " << half << " half ticket" <<endl;
        }
        ~Passenger() {
                cout << "passenger was destructed" <<endl;
        }

        int getTicket()const{
            cout << ticket <<endl;
            return ticket;
        };

        int getHalf()const{
            return half;
        };
};

int main(){
    Passenger m;
    m.getTicket();
}

getTicket always prints 64 instead of the 0 or 1 that prints when the constructor is called.
I couldn't fix it with this and I don't know that many things for rand()

A: You are providing default values for the parameters of the constructor Passenger, but you are not initializing your class attributes ticket and half.
You may have initialized those parameters in Passenger::Passenger with a default value, but unless you assign those parameters to your function members, the attributes Passenger::ticket and Passenger::half will not be initialized with the values you seemingly want to assign to them.
In essence, you should update your constructor as follows:
Passenger::Passenger(int ticket=rand() % 2, int half=rand() % 2) {
    //  Construct passenger
    cout << "passenger was constructed with " << ticket << " ticket and " << half << " half ticket" <<endl;
    this->ticket = ticket;
    this->half = half;
}

You can also use an initialization list as given below.
class Passenger {
    Passenger(int ticket=rand() % 2, int half=rand() % 2) : ticket(ticket), half(half) {}
    ...  // Rest of the class definition
};


text:
Q: The Madelung equations are Euler equations for quantum mechanics. What is the Lagrangian description of quantum hydrodynamics? The Madelung equations of quantum mechanics suggest the hydrodynamic model of quantum mechanics (quantum mechanics is described as a fluid of universes in a multiverse, which, in the non-relativistic setting, is described by configuration space). However, the Madelung equations are Euler hydrodynamic equations, and Euler equations only describe bulk flow of a fluid. To get the full dynamics of a fluid, one can use a Lagrange description (among other solutions).
This suggests that the Madelung equations give an incomplete description of the hydrodynamic model of quantum mechanics, and a proper description of the hydrodynamic model would be (or be equivalent to) a Lagrange description.
Has anyone developed such a description?
(Note: I'm aware that the Bohmian mechanics an be derived from the Madelung equations by assuming that the universe fluid's particle velocity is equal to the bulk flow velocity. However, I've never seen any motivation for this assumption. I'd also be satisfied with a justification of why this works.)

A: In the original Madelung  paper, as far as I know, the quantum mechanical potential depended only on the position of a given particle in the fluid, and was independent of other particles that might also be guided by the fluid.  The Bohm quantum mechanical potential depends in general on all the coordinates of all the particles, ie. on the full configuration space.  This difference has been pointed out by Sheldon Goldstein in some of his papers, for example. I think that this can be remedied though, and Madelung's theory modified in the following way.  If the particles in the Madelung fluid are solitons in the fluid, then each particle creates a disturbance in the velocity field of the fluid that can be felt by the other particles.  In this way they interact, the quantum mechanical potential might then depend on the full configuration space.  I don't know of any fluid model which exists that illustrates this idea though.  The bouncing drop models of Yves Coudet might yield such a configuration space dependent fluidic interaction, but how close it is to quantum theory I don't know, and the bouncing drop Lagrangians are quite different from the Madelung Eulerian models.


text:
Q: Integrate Ads in Android Phonegap Build I am trying to integrate ads in Phonegap build android Application.
Integrating admob is not possible in html5 phonegap build.
I tried with MOBFOX (http://www.mobfox.com/) ad networks.
But ads not showing properly and I am not sure about their reliability compare to admob.
Please kindly suggest me the suitable ad networks for phonegap build android apps.

A: I have not been able to find any way at all to do this. I ended up having to work with the local CLI version of phonegap and this plugin for AdMob: https://github.com/floatinghotpot/cordova-plugin-admob

A: In this discussion they found other solutions:
http://community.phonegap.com/nitobi/topics/how_do_you_incorporate_advertising_or_banner_ads
but it seems to be not really possible to integrate ads in phonegap.
I look for more.


text:
Q: Delphi ADOConnection / ADOQuery (SELECT) to Access database file is freezing when another user is editing a record in the table Using: Delphi 10.2.3 Tokyo Enterprise / VCL forms application
I've written an application that connects via TADOConnection (JET 4.0 provider) to an existing Access back-end database (*.MDB) file that is located on a network shared drive (Z:). This Access back-end database is also connected to a front-end Access database by one or two users in the office to generate reports, and to input new data.
My program runs a SELECT..GROUP BY query on more than one tables in the database every 5 minutes to generate a report and display the result in a DBGrid (this report is displayed on a wall display). In order to minimize the time that the application spends in keeping the connection to the database open, I'm using a TClientDataSet/TDataSetProvider to cache the data and immediately disconnecting from the Access database (ie., closing the connection) as soon as the query is executed.
This is working well but there is a problem - when the application runs the query at the same time that a user has it open for editing via a form in the Access front-end database, my program will freeze. Windows Task Manager says for my program: "Not responding".
I think that this is because of table locks?
Is there any thing that I can do, any setting that I can change in the TADOConnection or TADOQuery component so that it does not freeze when the query is run?
If not, then is there any way to detect this lock condition, so that the scheduled query execution can be bypassed if the record is being edited at the time when the query is scheduled to run?
Thanks in advance for any tips or clues!


text:
Q: how to check if my website is being accessed using a crawler? how to check if a certain page is being accessed from a crawler or a script that fires contineous requests?
I need to make sure that the site is only being accessed from a web browser.
Thanks.

A: This question is a great place to start:
Detecting 'stealth' web-crawlers
Original post:
This would take a bit to engineer a solution.
I can think of three things to look for right off the bat:
One, the user agent. If the spider is google or bing or anything else it will identify it's self.
Two, if the spider is malicious, it will most likely emulate the headers of a normal browser. Finger print it, if it's IE. Use JavaScript to check for an active X object.
Three, take note of what it's accessing and how regularly. If the content takes the average human X amount of seconds to view, then you can use that as a place to start when trying to determine if it's humanly possible to consume the data that fast. This is tricky, you'll most likely have to rely on cookies. An IP can be shared by multiple users.

A: You can use the robots.txt file to block access to crawlers, or you can use javascript to detect the browser agent, and switch based on that. If I understood the first option is more appropriate, so:
User-agent: *
Disallow: /

Save that as robots.txt at the site root, and no automated system should check your site.

A: I had a similar issue in my web application because I created some bulky data in the database for each user that browsed into the site and the crawlers were provoking loads of useless data being created. However I didn't want to deny access to crawlers because I wanted my site indexed and found; I just wanted to avoid creating useless data and reduce the time taken to crawl.
I solved the problem the following ways:

*

*First, I used the HttpBrowserCapabilities.Crawler property from the .NET Framework (since 2.0) which indicates whether the browser is a search engine Web crawler.  You can access to it from anywhere in the code:

*

*ASP.NET C# code behind:
bool isCrawler = HttpContext.Current.Request.Browser.Crawler;

*ASP.NET HTML:
Is crawler? = <%=HttpContext.Current.Request.Browser.Crawler %>

*ASP.NET Javascript:
<script type="text/javascript">
var isCrawler = <%=HttpContext.Current.Request.Browser.Crawler.ToString().ToLower() %>
</script>
The problem of this approach is that it is not 100% reliable against unidentified or masked crawlers but maybe it is useful in your case.

*After that, I had to find a way to distinguish between automated robots (crawlers, screen scrapers, etc.) and humans and I realised that the solution required some kind of interactivity such as clicking on a button.  Well, some of the crawlers do process javascript and it is very obvious they would use the onclick event of a button element but not if it is a non interactive element such as a div.  The following is the HTML / Javascript code I used in my web application www.so-much-to-do.com to implement this feature:
<div
class="all rndCorner"
style="cursor:pointer;border:3;border-style:groove;text-align:center;font-size:medium;font-weight:bold"
onclick="$TodoApp.$AddSampleTree()">
Please click here to create your own set of sample tasks to do
</div>
This approach has been working impeccably until now, although crawlers could be changed to be even more clever, maybe after reading this article :D


text:
Q: My check all checkboxes not working I have this form that gets data from the database and displays checkboxes.I have a function to check and uncheck all boxes but its not working.can anyone please help?
      <form id="myform" method="POST" action="PHPMailer/examples/mail-exec.php">

  My Trailers :

  <input type="checkbox" name="Check_ctr" value="yes"     onClick="Check(document.myform.check_list)">Check Control

   <?php
   $qry="SELECT * from followers where vendorid =$vendorid";
  $stmt = $conn->prepare( $qry );
  $stmt->execute();
  while($row = $stmt->fetch(PDO::FETCH_ASSOC))
 {?>
 <input type="checkbox" name="check_list" value="<?php echo      $row['email'];?>"><?php echo $row['name'];?>

 <?php } ?>

 </form>

here is the js function:

A: There is an error like Uncaught TypeError: Cannot read property 'check_list' of undefined in your console
You need to assign the form's name to access it via document

function Check(chk, list) {
  var checked = document.myform.Check_ctr.checked
  for (i = 0; i < list.length; i++) {
    list[i].checked = checked;
  }
}
<form name="myform" method="POST" action="PHPMailer/examples/mail-exec.php">

My Trailers :

      <input type="checkbox" name="Check_ctr" value="yes" onClick="Check(this, document.myform.check_list)" /> Check Control

      <input type="checkbox" name="check_list" value="1">1
      <input type="checkbox" name="check_list" value="2">2
      <input type="checkbox" name="check_list" value="3">3
      <input type="checkbox" name="check_list" value="4">4

</form>


text:
Q: bash scripting: search Java STDOUT for a variable When I run myTest.jar, it outputs alot of information in STDOUT (not in a file) and I am trying to read/search that file for a specific string to put as a variable in my bash script.
java stdout:
line 1 info............

line 2 info...........

....

...

Successful    (either 'Successful' or 'Failed')

How do I search for, in bash, the last line in the stdout or for ('Successful' or 'Failed') without redirecting the stdout to a file?
Thanks in advance

A: This is not a good way of checking for success or failure.
You should instead rewrite myTest.jar to use System.exit(0) on success and System.exit(1) (or higher) on error. If the program is well written, it will already do this.
You can then check for success or failure in bash using e.g.
if java -jar mytest.jar
then
  echo "The command succeeded :D"
else
  echo "The command failed :("
fi

All UNIX programs work this way, and you should make sure that myTest.jar is no exception.

A: To make this work, you would need to redirect stdout to a file and then cat/vim/search that file. Bash doesn't save the output of commands on its own.
Alternatively, you could use a program like screen that allows you to save a transcript of your session to a file. You would get the output of everything and the command lines though.

A: for future users, I used "that other guys' " method with some minor adjustments:
1) the exit code and what your doing have to be right after the running jar, wouldn't work for me in other segments
2) I read the exit code I was receiving and made an if loop for my conditions (0-2) exit code was given in java
3) piece of my bash code
EXIT_CODE=$?
echo Exit code: $EXIT_CODE

if [ $EXIT_CODE = "0" ]
then
    ...............do something
elif [$EXIT_CODE = "1"]
then
    ...............do something
else
    ...............do something
fi


text: Q: No algpseudocode-package in TeXstudio I am using TeXstudio for writing my thesis. I am tying to use the algpseudocode-package, but it says that the package isn't found. Here is the screenshot of the error that I am getting:


text:
Q: Setting Up EmberJS I'm trying to set up EmberJS. This is my first website attempting this so please excuse my noobness. Currently nothing is outputting to the screen but the body's grey background color. I'm not sure where I went wrong in setting up my EmberJS page.
Here's the code and if you need to see it in action you can view it here http://andrewhnovak.com/newSite/index.html
HTML
  <!doctype html>

<meta charset="utf-8">
<title>Site Demo</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/header.css">
<link rel="stylesheet" type="text/css" href="css/mainPage.css">

CSS
var App = Ember.Application.create();

App.Router.map(function() {
  // put your routes here
});

App.IndexRoute = Ember.Route.extend({
  model: function() {
    return ['red', 'yellow', 'blue'];
  }
});

A: Looks like from checking the JavaScript console that you're missing jQuery.