When before the open page show "Null check operator used on a null value" and after fetch from data base and show in flutter

Question: In my code fetch data and show nicely but before open the that page show this error and after show those details.In my code fetch data from firebase array type data and string type data.
error

after that error page opening and fetch data prefect

model code
class Details {
  String? id;
  String? email;
  String? age;
  String? familyChildren;
  List<String>? drinkstalkSE;
  List<String>? drinksUnderstandSE;
  List<String>? drinksUnderstandSE2;

  Details(
      {this.id,
      this.email,
      this.age,
      this.familyChildren,
      this.drinkstalkSE,
      this.drinksUnderstandSE,
      this.drinksUnderstandSE2});

  Details.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    email = json['email'];
    age = json['age'];
    familyChildren = json['familyChildren'];
    drinksUnderstandSE = json['drinksUnderstandSE'].cast<String>();
    drinkstalkSE = json['drinkstalkSE'].cast<String>();
    drinksUnderstandSE2 = json['drinksUnderstandSE2'].cast<String>();
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['email'] = this.email;
    data['age'] = this.age;
    data['familyChildren'] = this.familyChildren;

    data['drinksUnderstandSE'] = this.drinksUnderstandSE;
    data['drinkstalkSE'] = this.drinkstalkSE;
    data['drinksUnderstandSE2'] = this.drinksUnderstandSE2;
    return data;
  }
}

backend code
 Details oneUserDetails = Details();
  Future<void> getDetails() async {
    final sp = context.read<SignInProvider>();

    print(sp.uid);
    final snapshot =
        FirebaseFirestore.instance.collection('users').doc('${sp.uid}').get();

    final result = await snapshot.then(
        (snap) => snap.data() == null ? null : Details.fromJson(snap.data()!));
    print('result is ====> $result');
    setState(() {
      oneUserDetails = result!;
      loading = false;
    });

How to remove that error showing before the page open?
Answer: Details? oneUserDetails;
Change this to:
  Details oneUserDetails = Details();

Comment: initially your oneUserDetails is null unit it get data from server which takes some time . now when you are calling Details oneUserDetails = Details(); is Empty Object not null
Comment: Thank you That's worked .. can you explain reason for that
Answer: oneUserDetails is defines as nullable variable and its may be null but you use ! in Text widget when try to access drinksUnderstandSE or other property which is wrong because by using ! you said I'm pretty sure it is not null which it is, so change ! to ?:
Text( 'drink understand : ${oneUserDetails?.drinksUnderstandSE}'), // this will show like this => drink understand : null

or you can set default value to avoid showing null, like this:
Text( 'drink understand : ${oneUserDetails?.drinksUnderstandSE ?? 'default variable'}'), // this will show like this => drink understand : default variable

Comment: Thank you bro.  but I tried to pass uid to firebase query but that's not passing I will edit the question
Comment: @DasunDola glad to help.  I think that is an other issue, try ask new question and use firebase tag so other guys who are expert in it could help you.


Php display content after login

Question: I don't know how to get to the main page index.php and show some div's with javascript function after i check if the login data is correct. I run login.php scrip after the user clicks on submit button, and than if user data is correct i want to show some div's with javascript and stay on index.php page. I tried this using javascript function and than the header(location: ./index.php) in php but it didn't work.
My code:
if($name == $username && $pass == $password){
    echo '';
    header("Location: ./index.php");
}

Answer: The way you are using seems weird. A better approach would be to use SESSION variables to store login info(when user logs in) and display content after checking the SESSION variable like this:-
if(isset($_SESSION['somevalue']))
{
echo 'whatever you want';
}

Answer: In your login.php write this.
session_start();

if($name == $username && $pass == $password){
    $_SESSION['somevalue'] = $username;
    header("Location: ./index.php");
}

In index.php You need to check whether your session is set or not? If set show youw div with javascript code.
session_start();
if(isset($_SESSION['somevalue']))
{
    //show your div code here.
}

Comment: I got the error: Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent.
Answer: if($name == $username && $pass == $password)
    $_SESSION['login'] = true;

Now anyhwhere in code first start session and check for login name session variable.
session_start();
if (isset($_SESSION['login'] ) && $_SESSION['login'] === true)
{
   //do what logged in user require
}
else
{
  // redirect them to login page with proper error.
}

Answer: Put session_start(); at the top of your login.php and index.php files, then put this in your login.php file:
if ($name == $username && $pass == $password) {
    $_SESSION['authenticated'] = true;
    header("Location: ./index.php");
}

Then, on your index.php file, do this to see if the user is logged in:
if (isset($_SESSION['authenticated']) && $_SESSION['authenticated']) {
    echo ''; # If you want your div to show on your index.php
}

Answer: You have to write session_start(); in first line of your login.php file. Because some time it has problem.
session_start(); // line 1 in login.php

if($name == $username && $pass == $password)
{
  $_SESSION['mydata'] = $username;
  header("Location: ./index.php");
}

Answer: Actually you need to use some Jquery and an Ajax call in order to not refresh the page once the user clicked the submit button.
The code you need is something like this:
$.ajax({
   'url': 'http://yourdomain.com/authentication_script.php',
   'beforeSend': function(xhr) {
    xhr.setRequestHeader("Authentication", "Basic " + encodeBase64(username + ":" + password)
  },
  sucess: function(result) {
   alert('authenticated'); // here you can add some other functions to execute once authenticated
}
});

The idea is that you should take care that in the authentication script you should also include session variables and keep track of the user data as long as you / he want/s.

Php display content after login


Something like `top` for vhosts

Question: Is there any way of establishing what vhosts are keeping Apache processes busy, in real time?
Ideally I'd like a tool like top (or htop) that shows me which sites are busiest, or most costly, right now.
Could a tool like this be built on mod_log_forensic, which writes a strict log of when each request starts and ends? It wouldn't give you process IDs or CPU time, only the elapsed time from start to finish, but it might help track down leaky or long-running requests.
Answer: Feed your access logs to apachetop and see if that's any good for you. At least apachetop fills in your "See the most busiest site/URL in real time" wish.
Something like tail -f /var/log/apache2/*access_log | apachetop should work.
Of course, then there's logstalgia ... :-)
Comment: Ooh, logstalia is pretty :)
Comment: `apachetop` looks useful, but suffers from the same weakness as any software that relies just on the log files, which is that the standard log format doesn't actually include the vhost name, just the path. I could change the log format, but then it wouldn't be the standard. On my system `mod_log_forensic` includes the `Host:` header, but that's probably because NginX is forwarding it to Apache.
Answer: Anything that is dependent on log files has the disadvantage that log entries are only generated once a request is complete.
Apache's mod_status shows the current requests, as they're being processed.
Comment: It's not pretty, but it does tell me what each process ID is processing. Accepting.
Comment: It **is ugly** yes!

Something like `top` for vhosts


IPC bottleneck?

Question: I have two processes, a producer and a consumer. IPC is done with OpenFileMapping/MapViewOfFile on Win32.
The producer receives video from another source, which it then passes over to the consumer and synchronization is done through two events.
For the producer:
Receive frame
Copy to shared memory using CopyMemory
Trigger DataProduced event
Wait for DataConsumed event

For the consumer
Indefinitely wait for DataProducedEvent
Copy frame to own memory and send for processing
Signal DataConsumed event

Without any of this, the video averages at 5fps.
If I add the events on both sides, but without the CopyMemory, it's still around 5fps though a tiny bit slower.
When I add the CopyMemory operation, it goes down to 2.5-2.8fps. Memcpy is even slower.
I find hard to believe that a simple memory copy can cause this kind of slowdown.
Any ideas on a remedy?
Here's my code to create the shared mem:
HANDLE fileMap = CreateFileMapping(INVALID_HANDLE_VALUE, 0, PAGE_READWRITE, 0, fileMapSize, L"foomap");
void* mapView = MapViewOfFile(fileMap, FILE_MAP_WRITE | FILE_MAP_READ, 0, 0, fileMapSize);

The size is 1024 * 1024 * 3
Edit - added the actual code:
On the producer:
void OnFrameReceived(...)
{
    // get buffer
    BYTE *buffer = 0;
...

    // copy data to shared memory
    CopyMemory(((BYTE*)mapView) + 1, buffer, length);

    // signal data event
SetEvent(dataProducedEvent);

    // wait for it to be signaled back!
    WaitForSingleObject(dataConsumedEvent, INFINITE);
}

On the consumer:
while(WAIT_OBJECT_0 == WaitForSingleObject(dataProducedEvent, INFINITE))
    {
        SetEvent(dataConsumedEvent);
    }

Well, it seems that copying from the DirectShow buffer onto shared memory was the bottleneck after all. I tried using a Named Pipe to transfer the data over and guess what - the performance is restored.
Does anyone know of any reasons why this may be?
To add a detail that I didn't think was relevant before: the producer is injected and hooks onto a DirectShow graph to retrieve the frames.
Comment: Can't debug pseudo-code.  Post your event signaling/waiting code.
Answer: Copying of memory involves certain operations under the hood, and for video this can be significant.
I'd try another route: create a shared block for each frame or several of frames. Name them consequently, i.e. block1, block2, block3 etc, so that the recipient knows what block to read next. Now receive the frame directly to the allocated blockX, notify the consumer about availability of the new block and allocate and start using another block immediately. Consumer maps the block and doesn't copy it - the block belongs to consumer now and consumer can use the original buffer in further processing. Once the consumer closes mapping of the block, this mapping is destroyed. So you get a stream of blocks and avoid blocking.
If frame processing doesn't take much time and creation of shared block does, you can create a pool of shared blocks, large enough to ensure that producer and consumer never attempt to use the same block (you can complicate scheme by using a semaphore or mutx to guard each block).
Hope my idea is clear - avoid copying by using the block in producer, than in consumer
Comment: What do yo mean by "Copying of memory involves certain operations under the hood"?
Comment: I really don't have details to tell you, but my observations show that extra copying of memory blocks significantly slows down many operations, especially in processes that are mainly number crunching or network-involving processes. Call it empirical knowledge.
Comment: Well, at the moment I don't do any processing on the frame, while I'm trying to figure out how to fix this - do you still think it'll help? I mean, the copy operation will stay there - I just won't have to wait for data consumed event, I guess?
Comment: No, there should be no data copy operation involved at all. You will collect the data right to the shared memory block in producer, then signal to consumer and release the block. Consumer will take the address of the block and will pass it to further processing without copying.
Comment: Like I said in my comment in the other answer, I can't collect the data straight to the shared memory without any considerable work since the buffer is handled internally by DirectShow.

However, I did what you suggested with using blocks rather a single buffer. Strangely enough, only one block ends up ever being used but the performance is still lacking. I'm starting to think the bottleneck is actually at CopyMemory itself - is there any reason why it would be slower when triggered in a process I've injected myself in?
Comment: Well, as I mentioned above, I noticed that copymemory slows down processing, but this is empirical knowledge without theoretical background. In other words, I don't know why :)
Answer: The time it takes to copy 3MB of memory really shouldn't be at all noticeable. A quick test on my old (and busted) laptop was able to complete 10,000 memcpy(buf1, buf2, 1024 * 1024 * 3) operations in around 10 seconds. At 1/1000th of a second it shouldn't be slowing down your frame rate by a noticeable amount.
Regardless, it would seem that there is probably some optimisation that could occur to speed things up. Currently you seem to be either double or tripple handling the data. Double handling because you "recieve the frame" then "copy to shared memory". Triple handling if "Copy frame to own memory and send for processing" means that you truly copy to a local buffer and then process instead of just processing from the buffer.
The alternative is to receive the frame into the shared buffer directly and process it directly out of the buffer. If, as I suspect, you want to be able to receive one frame while processing another you just increase the size of the memory mapping to accomodate more than one frame and use it as a circular array. On the consumer side it would look something like this.
char *sharedMemory;
int frameNumber = 0;
...
WaitForSingleObject(...)  // Consume data produced event
frame = &sharedMemory[FRAME_SIZE * (frameNumber % FRAMES_IN_ARRAY_COUNT)
processFrame(frame);
ReleaseSemaphore(...)     // Generate data consumed event

And the producer
char *sharedMemory;
int frameNumber = 0;
...
WaitForSingleObject(...)  // Consume data consumed event
frame = &sharedMemory[FRAME_SIZE * (frameNumber % FRAMES_IN_ARRAY_COUNT)
recieveFrame(frame);
ReleaseSemaphore(...)     // Generate data produced event

Just make sure that the semaphore the data consumed semaphore is initialised to FRAME_IN_ARRAY_COUNT and the data produced semaphore is initialised to 0.
Comment: Yes, I did think of that also - the problem with the first part is that the original image buffer is managed by DirectShow and I don't want to delve into its memory management APIs just yet. The processing is done after the event has been signaled to send more data when available so it shouldn't interfere like that. Makes sense?
Comment: Yes and no. You could still ommit the last copy by processing it directly from the shared buffer.

IPC bottleneck?


How to exposed custom profile fields in views

Question: The custom fields were created using a custom form in a module, not user entities or Profile2.
How can I expose these fields to views? My goal is to allow an admin to filter users by exposing those custom fields.
Here's the function that creates the custom profile form:
function mymodule_profile_form($form, &$form_state, $account) {
[...]
//
// Basic Info
//
$form['fs_basic'] = array(
  '#title' => 'Basic Info',
  '#type' => 'fieldset',
  '#prefix' => '
',
);

$form['fs_basic'][SOME_SF_CONTACT_FIRSTNAME] = array(
  '#title' => 'First Name',
  '#type' => 'textfield',
  '#default_value' => $contact[SOME_SF_CONTACT_FIRSTNAME],
 );
$form['fs_basic'][SOME_SF_CONTACT_LASTNAME] = array(
  '#title' => 'Last Name',
  '#type' => 'textfield',
  '#default_value' => $contact[SOME_SF_CONTACT_LASTNAME],
);
$form['fs_basic'][SOME_SF_CONTACT_MIDDLENAME] = array(
  '#title' => 'Middle Name',
  '#type' => 'textfield',
  '#default_value' => $contact[SOME_SF_CONTACT_MIDDLENAME],
);
$form['fs_basic'][SOME_SF_CONTACT_SUFFIX] = array(
  '#title' => 'Suffix',
  '#type' => 'textfield',
  '#default_value' => $contact[SOME_SF_CONTACT_SUFFIX],
);
//
// Profile Info
//
$form['fs_profile'] = array(
  '#title' => 'Profile',
  '#type' => 'fieldset',
  '#prefix' => '
',
);
$form['fs_profile']['name'] = array(
  '#title' => 'Username',
  '#type' => 'textfield',
  '#default_value' => $account->name,
  '#maxlength' => 20,
);
[...]
$form['submit'] = array(
  '#value' => 'Submit',
  '#type' => 'submit',
  '#attributes' => array('class' => array('btn btn-primary align-left push-
down')),
);

$form['#validate'][] = 'user_account_form_validate';
$form['#validate'][] = 'user_validate_picture';
$form['#validate'][] = 'user_profile_form_validate';
$form['#validate'][] = 'mymoduler_profile_form_validate';
$form['#submit'][] = 'mymodule_profile_form_submit';
// Add the final user profile form submit handler.
$form['#submit'][] = 'user_profile_form_submit';

  return $form;
}

I want to be able to expose the Last Name in Views to I can allow an admin to search.
Comment: What is `mymodule_profile_form_submit` doing?
Comment: It's used to populate the form fields into Salesforce.
Answer: In order to use it with Views, one of the following have to be true:

You are using Profile2
You are using core User profile
You are using actual fields from Field API
The profile storage is an entity
None of the above, and you are using a custom table

One of these should let you add a relationship in Views from 'User' to 'Profile2' associated to that user, if not, the core profile fields should be available.
However, if you used a custom table, you will have to do some legwork describing your data to Views in order for it to be an option.
Here are some resources that will help you in that direction:

How to add relationship in view for custom entity
hook_views_data
https://groups.drupal.org/node/400598
http://www.zyxware.com/articles/3280/drupal-how-to-add-view-relationships-programmatically-with-custom-database-tables-in-drupal-7

Do know that just because they are 'fields' in a custom form does not mean that it is represented in Drupal the same way. As far as Drupal knows (and from what I see in the provided code) it is your standard form made with FormAPI. They are not really "custom fields" so much as form items abstracting the input to store data.
Comment: Thanks, I was able to describe the data to views using hook_views_data.
Comment: Glad it helped.
Comment: @Kevin How to expose the username, password and email field forms in panels or maybe in the manage fields? I want to use field_group module to create a vertically tabbed "Edit Profile Page". Each tab will only have relevant field form. For example: General Tab will have username, password and email fields forms. And similarly other tabs will have other fields. How to do that?


How to test for differences with multiple observations per subject under the same (level-2) condition?

Question: I'm trying test for the difference in a numeric outcome (WearTime) that was measured 7 times (7 consecutive days) for each subject under the same condition (Season) that was measured at the participant level. The question I want to test is: "Does Season affect daily WearTime?" This is not a primary outcome, but more of a check for going forward to determine if Seasonality needs to be accounted for in future analyses.
Data structure: 700obs, 5 variables

SubjectID: 100 individuals
ObservationDay: 1 to 7; Day 1 refers to
1st dat etc. Every subject has 7 days with values
Date: Date of ObservationDay; 7 days in sequence spread throughout a
year
Season: Fall/Winter/Spring/Summer; Season when observation period
began based on Date from ObservationDay 1 for that subject
WearTime: 0-1440 minutes; How long an electronic device was worn by a
participants on each ObservationDay

My instinct for testing this is a mixed model ANOVA approach with Season as an independent fixed-effects factor, and subject ID as a random effects factor.
e.g. code from R (as this is the notation I am familiar with)
library(lme4)
library(car)
Anova(lmer(formula = WearTime ~ Season + (1 | Subject), data = df)

But if WearTime is measured at level-1 (per day, per subject), should Season be classified as a level-2 (per subject) variable?
Something more along the lines of:
WearTime ~ (1 | Season)

So my questions to you is which interpretation of the Season variable is correct? As a level-1 or 2 variable? And if the latter how would I go about testing for a difference by Season (as when I try to apply car::Anova to the above model I get an error, so I assume this is not a valid approach)? Just want to make sure I'm using the appropriate statistical approach before wrestling with code.
Thanks in advance!
Answer: It does not matter what level a variable belongs to. The software doesn't care. At least, all the mixed effects software that I am aware of does not care, and you are using equation formats commonly used in mixed effects software.
So, the heart of your question seems to be how to specify the random effects. You have repeated measures within subjects, so ... + (1 | Subject) is appropriate. If you don't specify random intercepts for subjects then you won't be controlling for the non-independence of observations within each subject.
So, the question is between:
WearTime ~ Season + (1 | Subject)

or
WearTime ~ 1 + (1 | Season) + (1 | Subject)

Since your research question is specifically about the "affect" of Season, and since you can't really consider the sample of seasons in your dataset as being taken from a larger population of seasons, I would favour the first case where you treat Season as a fixed effect and your interest centres on the estimated regression coefficients for it.
In the second case you treat season as random (crossed random effects) and your interest centres on the estimated variance for it - but that makes much less sense to me.
You may also also want to include the date of each observation, perhaps as the number of days from baseline and see if it interacts with season. So you could have:
WearTime ~ Season * Days + (1 | Subject)

or even
WearTime ~ Season * Days + (Season * Days | Subject)

provided that the data supports such a random structure.
It's also common to consider nonlinearities for time, which you could introduce with higher order terms, or even better, splines.
Comment: Great. if this answers your question, please can you mark it as an accepted answer.
Comment: Thanks for the response. I had felt that the first option (i.e. WearTime ~ Season + (1 | Subject)) would answer my question, but am relatively new to multilevel approaches outside of your standard pre/post design relying on RM-ANOVA as opposed to the flexibility offered by linear modeling. And yes I have plans for various additional tests & interactions between various factors (Day of week, Weekend vs Weekday, Day of observation within the 7 day cycle etc), but wanted to confirm my interpretation first. Thank you!


Calling controller with ajax in mvc

Question: I'm trying to fetch data from a controller and update my view using ajax.
This is my controller:
public class PatientController
{
    DatabaseContext db = new DatabaseContext();
    public JsonResult GetPatientFromCpr()
    {
        var patient = db.Patients.FirstOrDefault(p => p.Cpr == "2410911615");
        return new JsonResult() { Data = patient, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }
}

And this is my ajax call:
    function getPatient() {
    cpr2 = $("#cpr-first").val() + $("#cpr-last").val();
    $.ajax(
    {
        url: '/Patient/GetPatientFromCpr',
        dataType: 'json',
        success: function () {
            alert("success");
        },
        error: function () {
            alert("error");
        },
    });
}

When i call the function i always get the error alert.
GET http://localhost:51140/Patient/GetPatientFromCpr 404 (Not Found)

Can someone point out what's wrong?
(EDIT)
I now get a new error after adding ": Controller"
GET http://localhost:51140/Patient/GetPatientFromCpr 500 (Internal Server Error)
Comment: The url looks correct. What happens when you enter it in the address bar and navigate to it? Are your using areas?
Comment: where is the type , add type:"Get" after url call
Comment: @SrinivasR, The default is 'GET'
Comment: Can u please share the routes
Comment: @StephenMuecke I get 404 when entering it. Areas?
Comment: @Shu Routes?
I'm really new to this, so I apologize if I have missend something simple.
Comment: Remove dataType: 'json' and try again, working fine in my code with removal of dataType
Comment: add the request Type in tha AJAX request like type:"POST"
Answer: Your 'PatientController' is not a Controller (it does not inherit from Controller)
public class PatientController : Controller
{
   ....
}

Comment: @Smit. NO! OP is sending back a `JsonResult` so it needs to be `dataType: 'json'` and its a GET method so it needs to be `type: 'get'` but that is the default so it can be omitted.
Comment: Wow i'm stupid. Thanks, but it didn't fix my error (Well it must have fixed something)
Comment: Are you saying your still getting a `404 Not Found`?
Comment: Ahh no you are right..

    GET http://localhost:51140/Patient/GetPatientFromCpr 500 (Internal Server Error)
Comment: Then that means your server code is throwing an exception - you need to debug your code (and you can use your browser tools to inspect the response and the error details (Network Tab). And please undo your edit to the question - or I will - you cant just change the question based on a correct answer (in makes my answer pointless)
Comment: I already did it :). This answers you question and if your getting a different error, then that needs to be a new question. But debugging your code should solve it.
Comment: add the request Type in tha AJAX request like type:"POST", and also Remove dataType: 'json' and try again, working fine in my code with removal of dataType
Comment: @Smit, Read OP's comments. My answer solved the problem (none of your changes are necessary)
Answer: Try using this, may be this works..!!
View:
function getPatient() {
    cpr2 = $("#cpr-first").val() + $("#cpr-last").val();
    $.ajax(
    {
        url: '/Patient/GetPatientFromCpr',
        //dataType: 'json',
        type:"POST", // GET or POST
        success: function () {
            alert("success");
        },
        error: function () {
            alert("error");
        },
    });
}

Controller:
public class PatientController : Controller
{
   ....
}

Answer: Inherit you PatientController with Base Controller Class
public class PatientController : Controller

In controller
 public JsonResult GetPatientFromCpr()
    {
        var patient = db.Patients.where(p => p.Cpr == "2410911615").FirstOrDefault();
        return new JsonResult() { Data = patient, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }

And Specify the type of ajax calling
type: "POST" or type: "GET" ....

This will help you to fix error
Comment: Thanks for your response, but it has already been replied. I now get a new error (500).

Calling controller with ajax in mvc


in laravel 8 for API controller , how show the ID not found message as json?

Question: i'm working with laravel 8 and building an API.
I have a CategoryController and doing CRUD. in my  store method ,  When i enter an ID that does not exist , i want to show a message that says : category not found
and i don't know how to put it in the method.
this is my categorycontroller and my update method :
public function update(Request $request, Category $category)
    {
        $data = $request->all();

        $validator = Validator::make($data, [
            'title' => 'required|max:100|unique:categories',
            'description' => 'required|max:500',
        ]);

        if ($validator->fails()) {
            return response(['error' => $validator->errors(), 'Validation Error']);
        }

        $category->title = $data['title'];
        $category->description = $data['description'];
        $category->save();

        return response()->json([
        "success" => true,
        "message" => "با موفقیت ویرایش گردید",
        "data" => $category
        ]);
    }

Comment: What is your appropriate route for update ?
Comment: in postman i enter this route : `http://localhost:8000/api/subcategories/100?parent_id=104&title=examplr&description=example`
Comment: and in my api.php i have resource : `Route::apiResource('categories' , CategoryController::class);
`
Comment: I wanted to know about category field. Anyway if it's "category_id" (the field name in the POST/PUT request (actually in REST apps you need to run PUT request in the postman for updates)), then you can replace "Category $category" to "int $category_id" in your method's 2-nd argument. After that you also will need to find the category by yourself in your method, after validation. Like this: "$category = Category::find($category_id); if (empty($category_id)) { return response()->json(['success' => false, 'message' => "Category not found!"], 404); }"
Comment: Where do you enter the ID?
Comment: sorry for deleting my comment  , i though it solved but it didn't. my question is when i remove `Category $category` from update() parameters , then laravel doesn't know $category in $category->title=$data['title']
Comment: I don't get what you mean? in postman?
Answer: i fixed it

public function update(Request $request, $id)
    {

        $category_faild = Category::find($id);
        if(is_null($category_faild)){
            return response()->json('دسته بندی مورد نظر یافت نشد' , 404);
        }

        $data = $request->all();

        $validator = Validator::make($data, [
            'title' => 'required|max:100|unique:categories',
            'description' => 'required|max:500',
        ]);

        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors(), 'Validation Error']);
        }

        $category = Category::find($id);
        $category->title = $data['title'];
        $category->description = $data['description'];
        $category->save();

        return response()->json([
            "success" => true,
            "message" => "با موفقیت ویرایش گردید",
            "data" => $category
            ]);

    }


c++ overwrite [] operator with std::string

Question: I'm basically trying to create a thread-safe wrapper class for std::map.
As I'm coming from C, I have quite a hard time figuring out all the nuances of C++.
I'm trying to overwrite the [] operator to take std::string arguments to just pass it to my std::map member.
By the reference of std::map::operator[] this should work fine:
T& operator[]( const Key& key );

Here is my class:
thread_map.hpp
#ifndef THREAD_MAP_H
#define THREAD_MAP_H

#include <map>
#include <functional>
#include <mutex>

template <class T>class Thread_map
{
private:
    std::map<std::string, T> map;
    std::mutex map_mutex;

public:

    ~Thread_map();

    T& at(size_t pos);
    T& operator[](std::string &key);

    size_t size() const;
    bool empty() const;

    void clear();
    void insert(std::pair<std::string, T> pair);
    T& erase(const std::string &key);

    bool for_each(std::function<bool (Thread_map, std::string&, T&)> fun);
};

template<class T> Thread_map<T>::~Thread_map()
{
    this->map.clear();
}

template<class T> T& Thread_map<T>::at(size_t pos)
{
    T *value;
    this->map_mutex.lock();
    value = this->map.at(pos);
    this->map_mutex.unlock();
    return value;
}

template<class T> T& Thread_map<T>::operator[](std::string &key)
{
    this->map_mutex.lock();
    T &value = this->map[key];
    this->map_mutex.unlock();
    return value;
}

template<class T> size_t Thread_map<T>::size() const
{
    size_t size;
    this->map_mutex.lock();
    size = this->map.size();
    this->map_mutex.unlock();
    return size;
}

template<class T> bool Thread_map<T>::empty() const
{
    bool empty;
    this->map_mutex.lock();
    empty = this->map.empty();
    this->map_mutex.unlock();
    return empty;
}

template<class T> void Thread_map<T>::clear()
{
    this->map_mutex.lock();
    this->map.clear();
    this->map_mutex.unlock();
}

template<class T> void Thread_map<T>::insert(std::pair<std::string, T> pair)
{
    this->map_mutex.lock();
    this->map.insert(pair);
    this->map_mutex.unlock();
}

template<class T> T& Thread_map<T>::erase(const std::string &key)
{
    T *value;
    this->map_mutex.lock();
    value = this->map.erase(key);
    this->map_mutex.unlock();
    return value;
}

template<class T> bool Thread_map<T>::for_each(std::function<bool
(Thread_map, std::string&, T&)> fun)
{

}

#endif

I put the implementation into the header file, because I heard you do that with template classes. Am I right on that?
My Problem is, that when I try to call the operator
Thread_map<std::string> map;
map["mkey"] = "value";

g++ throws an invalid initialization error on map["mkey"].
As far as my understanding goes the problem is that mkey gets compiled to std::string("mkey") which is just the value, not a reference.
But why or how does the following work then?
std::map<std::string, std::string> map;
map["mkey"] = "value";

I mean I could just pass the string by value but that seems inefficient.
Comment: Compare and contrast `T& operator[]( const Key& key )` with `T& Thread_map::operator[](std::string &key)`. There's one keyword that's present in the former and missing in the latter. Hint: it begins with `c` and ends with `t`.
Comment: Your code seems to be riddled with errors.
Comment: @pear Try to `erase` a key from your dictionary, use `empty` function, use `size` function (An hint- `empty` and `size` problems are the same kind), and use `at` function.
Comment: Well thanks overlooked that :D
Comment: Can you tell me what the errors are or not Kkid. Im kinda new to C++? Well ill refere you to that link Fei Xiang: https://stackoverflow.com/questions/8752837/undefined-reference-to-template-class-constructor
Comment: @pear Ignore what I previously said. I made a mistake, my bad.
Answer: Reference requires a variable's address that cans be modified. For lvalue string ("some string") there is no address that can be value modified.
There are some ways that I know to solve this issue:
Remove Reference (Not recommended)
One way is to remove the '&' from the parameter. like this:
T& operator[](std::string key);

In this way you don't request lvalue, but rvalue. The problem is that when ever you'll send a value, you won't send 4 bytes of memory address, but sizeof("Your string") bytes. Heavy method..
Make a const lvalue (Recommended way)
The most beautiful way to solve this issue, is to make the parameter const lvalue (what that called rvalue reference), to make a promise to the compiler that you won't try to change the given address's value inside this function. It's looks like this:
T& operator[](const std::string &key);

Now you can send a lvalue string and rvalue string.
Give up
This way is not bad as the first one, but absolutely not good as the second. You can easily use your declaration:
T& operator[](std::string &key);

And when you pass a value, use another string variable to store the value, and use this variable at call time:
Thread_map<std::string> map;
string key = "mkey";
map[key] = "value";

(Don't do that.. Just as extension for the knowledge).
Comment: Nice attempt at one tiny problem, but the whole code seems to be FUBAR ))
Comment: @KillzoneKid thanks! BTW, it isn't problem to solve them for him, but I don't want to interrupt his fun :)
Comment: Thanks for the answer much appreciated :)
Comment: "make the parameter const rvalue" and yet, you have an lvalue reference.


Como pegar valor de um button sem um formulário

Question: Opa, e aí galera, eu queria saber como faria para passar uma função ao button sem um formulário em php...
Ex: Clico no botão Seguir, e começo a segui a pessoa.
E sem passar via get também, pois ficaria bem feio se meu site ficasse cheio de '?key=3937''
Tentei de várias maneira mas não consegui, e a maioria dos tópicos que li precisava de ajax.
Comment: https://api.jquery.com/jquery.ajax/ Aqui ensina como fazer.
Comment: Exatamente, Ajax!
Comment: `?key=3937` é um método get,você tem que usar um método ajax que é post.
Answer: Eis um exemplo de uma chamada AJAX, mas a sua pergunta está muito incompleta, sugiro que nas próximas perguntas, estude mais sobre o assunto tente desenvolver sozinho e venha com dúvida mais específicas que nos poupe de desenvolver algo pra vc.
Fora isso o código é simples e no Javascript, ele possue alguns comentários,para facilitação do entendimento.
Além do HTML, CSS, e JS(Javascript), foram utilizados o framework bootstrap, e a biblioteca JS, Jquery.
<!DOCTYPE html>

  <title></title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

        <button class="btn btn-info btn-seguir" meu-id="1" id-pessoa="2">Seguir</button>

Comment: Esse é o problema kkk... vim aqui pra ver se havia um jeito de fazer só com php pois ainda não aprendi ajax, js, jquery kkkk
Comment: Quem cuida de fazer uma requisição é o cliente(Navegador), pra ter acesso ao script do servidor(PHP), vc precisa enviar uma requisição, seja ela por um formulário, ou por um ajax
Comment: PHP(servidor). Jquery(cliente).
Comment: Mas obrigado,, vou estudar essas linguagens


Proof of consistency of Maximum Likelihood Estimator

Question: I would appreciate some help comprehending a logical step in the proof below about the consistency of MLE. It comes directly from Hogg, McKean, Craig, Introduction to Mathematical Statistics, 6th edition, Chapter 6, page 317.
So here goes:
Assume that $\hat{\theta_n}$ solves the estimating equation $\frac{\partial l(\theta)}{\partial \theta}=0$.
Also assume the following regularity conditions:

the parameters identify the pdfs
the pdfs  have common support for all $\theta$
The point $\theta_0$ is the true parameter and is an interior point in $\Omega$

Then $\hat{\theta_n} \xrightarrow{P} \theta_0$
Proof
Let $\mathbf{X}=(x_1,x_2, \ldots, {x_n})$, the vector of observations.
Since $\theta_0$ is an interior point in $\Omega$ , $(\theta_0 -a, \theta_0 +a) \subset \Omega $ for some $a >0$. Define $S_n$ to be the event
$$S_n= \{ \mathbf {X} : l(\theta_0 ; \mathbf{X}) > l(\theta_0 -a ; \mathbf{X}) \}
 \cap \{ \mathbf{X}: l(\theta_0; \mathbf{X}) > l( \theta_0 +a  ;\mathbf{X}) \} $$
And this is where i have a problem. How can we evaluate the log-likelihood function at $\theta=\theta_0\pm a $ ? we only know that $(\theta_0 -a, \theta_0 +a) \subset \Omega $, we have not assumed that $\theta_0 -a\in\Omega$ or that $\theta_0 +a\in\Omega$. What if $\Omega=(\theta_0 -a, \theta_0 +a)$? Then the set $S_n$ is always empty(because $l(\theta_0 -a ; \mathbf{X})$ and $l(\theta_0 +a ; \mathbf{X})$ are undefined. ) and the proof breaks down for trivial reasons.
So that is my question. How is it justified to assume that $l(\theta_0 +a ; \mathbf{X})$ and $l(\theta_0 -a ; \mathbf{X})$ are defined?
Of course, the proof is not complete at this point but if I have this clarified, I can take it from there. Thank you in advance.
edit:
until now, I have seen this same proof in two books, namely Lehman Casella(2nd edition) page 447 and Hogg and Craig(6th edition) page 317. and in both books, the authors did not assume that $\theta-a$ and $\theta+a$ are inside the parameter space. And so, I am of the opinion that assuming $\theta-a\in\Omega$ and $\theta+a\in\Omega$ is unnecessary. What I do not understand is why these assumptions are unnecessary.
Answer: It looks like the author intends for the set $(\theta_0-a, \theta_0+a)$ to be on the interior of $\Omega$.  Strictly speaking, what the proof should have done is to choose a value $a>0$ such that:
$$(\theta_0-a, \theta_0+a) \subseteq \text{int }\Omega,$$
which then implies $\theta \pm a \in \Omega$.  Bear in mind here that we only need to have the relevant equations hold for some $a>0$, and this can be guaranteed by taking $a$ to be sufficiently small to ensure that $(\theta_0-a, \theta_0+a)$ lies in the interior of the parameter space.  I think the author of the proof was just a bit sloppy here in stating that particular step.
Comment: your (Ben) answer is better (more technical) than mine, but it was pretty much exactly what I was thinking
Answer: I am not sure that I understand your concern, but sounds like it is that possibly $\theta-a$ or $\theta+a$ might be on the boundary of the parameter space, with one being either the maximum or the minimum of $\Omega$.
I agree that you need to assume both $\theta-a$ and $\theta+a$ are interior points in the parameter space. It is just a fact that even when you get a proof from a textbook sometimes small details (and sometimes large ones) are left out. Usually when a proof says for 'some $a$' it means there is at least one $a>0$ that works, and for $a$ to work you also need it to have $\theta-a$ and $\theta+a$ in the parameter space. In fact the above proof doesn't even say that $\theta+a$ or $\theta-a$ has to be anywhere inside or even close to being inside the parameter space. Also, although I am not sure how the rest of the proof proceeds, but I am guessing at some point it takes a limit as $a$ goes to $0$? That means it does not really matter how close the original value of $a$ is to 0.
Comment: you are right, the possibility that $θ_0−a$ or $θ_0+a$ might be on the boundary of the parameter space is exactly what concerns me. because the parameter space can be an open interval, in which case we have $\theta_0-a\notin\Omega$ due to which $l(\theta_0 -a ; \mathbf{X})$ is undefined, and because of this, $S_n$ is empty and as a result, the whole proof breaks down.
Comment: there is no step in the proof where $a$ tends to zero. see edit.
Answer: I am just a student but here an other prove that works if you all ready know by hypothesis that the MLE estimator is unbiased at least when the size sample goes to infinity.

$\theta_n $ is the MLE estimator of an i.i.d sample $\left \{ X_1=x_1, X_2=x_2,\ldots,X_n=x_n \right \}$ of size $n$ and $\theta_0$ the parameter to estimate.
First let note that the sequence $(\theta_n)_n$ is a sequence of r.v. while $\theta_0$ is a parameter (a "constant").
So it is asking to us to prove: $$\forall \epsilon>0 \Rightarrow \lim_{n \to \infty }\mathbb{P}(|\theta_n - \theta_0| \geq \epsilon)=0$$

In order to do that we will use the Markov Inequality with $r=2$ (the condition are verify by question hypothesis):
$$\forall \epsilon>0 \Rightarrow \mathbb{P}(|\theta_n - \theta_0| \geq \epsilon) \leq \frac{E(|\theta_n-\theta_0|^2)}{\epsilon^2}=\frac{E((\theta_n-\theta_0)^2)}{\epsilon^2}=\frac{E(\theta_n^2+\theta_0^2-2\theta_n \theta_0)}{\epsilon^2}=\frac{E(\theta_n^2)+\theta_0^2-2\theta_0E(\theta_n)}{\epsilon^2}$$

As we know that $\theta_n$ is unbiased when $n$ goes to infinity it means that: $$\lim_{n \to \infty }E(\theta_n)-\theta_0=0 \Rightarrow \lim_{n \to \infty }E(\theta_n) = \theta_0 = E(\theta_0)$$

Hence $E(\theta_n)$ converges in law to $E(\theta_0)=\theta_0$. So because $f(x)=x^2$ is a continuous function:$$\lim_{n \to \infty }E(\theta_n^2)=E(\theta_0^2) = \theta_0^2$$
Q.E.D.
I hope this is correct.


Como mudar a versão do PHP em que o Composer é executado no Windows?

Question: Tenho o PHP 8 instalado e rodando no Xampp. Alterei as configurações para rodar a versão do php 7.1 em outra porta. Tudo certo até aí.
Mas na hora de rodar o composer no terminal diz que a versão do PHP é a 8 e não é compatível com meu sistema feito em PHP 7.1.
Como faço pra alterar a versão do PHP no terminal?
Quando executo > php -v, aparece a versão 8.0 eu preciso alterar para 7.1.
Já tem uma resposta aqui no fórum sobre isso, mas é para Linux, não encontrei nada para Windows.
Comment: Já tentou usando os paths completos? `C:\path_para_php7.1\php7.1.exe C:\path_para_composer\composer -v`
Answer: Eu resolvi o problema da seguinte forma:

Renomeei as pastas c:\xampp\apache e c:\xampp\php para c:\xampp\apache8 e c:\xampp\php8, respectivamente.
Baixei o xampp com php 7.1, que eu precisava
Copiei as pastas apache e php da versão baixada pro lugar das anteriores c:\xampp\apache e c:\xampp\php
Reiniciei os serviços do xamp.

E pronto!
Foi a forma mais simples que encontrei.
Agora, quando preciso mudar de versão, renomeio a pasta que está sendo usada e substituo pelas pastas da versão que preciso.
Answer: Reinstale o composer, e na hora de selecionar a versão coloque a versão que deseja e marque a opção de adicionar ao PATH do Windows, logo após abra novamente o projeto.
Comment: Eu preciso alterar a versão do PHP no terminal do Windows, desculpe, mas não entendi como isso vai ajudar.
Comment: Isso vai fazer o que você precisa, quando eu preciso mudar a versão faço isso.


Secure / Encrypted QR Codes

Question: Is there an application where  you can generate encrypted  QR Codes?
I havent a lot of literature on  encrypting QR codes out there. We are looking to implement    something that clients can send us encrypted information and we scanning them on our site.
Has any of you been involved in a project such as this?
Comment: QR code is an encoding, not encryption.  The key difference between the two is that anyone can decode an encoded message, but to decrypt an encrypted message you also need to know a secret key.  As far as I know, QR codes do not use a key, so it is only an encoding.  Andreas is (presumably) asking for encryption, then encoding in a QR code.
Comment: @Tadmas that is correct. i've heard of SQR  (secure QR)codes anyone heard about this?
Comment: Adding a little more detail for those readers who may want it -- the distinction here is that encryption involves a secret key of some kind, while encoding is just a representation of data and doesn't add a layer of secrecy.  The word "code" embedded in the word "encoding" might suggest some secrecy or protection -- nope.
Comment: A QR code by nature is encrypted, and can only be decrypted by a QR Code decrypter. So I'm not 100% sure what you mean, could you rephrase your question?
Comment: This app consumes encrypted data stored in a QR code: http://itunes.apple.com/us/app/scanpass-pro/id455022825?mt=8. This app generates QR codes containing encrypted data: http://www.redhoundsoftware.com/apps/smime/barcodegenerator.html.
Comment: U can use https://satyasnehith.github.io/QRes/
Answer: Other answers suggest you could use the QR code to encode a URL, and then ensure the service at that URL provides the authentication / security you need.  If the channel you're using to communicate with your client is digital and internet-connected, maybe that makes sense ... and if it does make sense, you don't need a QR code at all, just send the URL.  As Tadmas pointed out, QR is just an encoding.
However, I'll infer from your original question that the channel you're using is analog (paper??), or digital but not internet-connected (digital photos of a paper original or screen shot, or ??).  That's not the most usual use case -- not what most of the respondents on this forum would naturally consider -- but I can imagine some realistic use cases e.g. for bills or payment data where that could be happening.
If that's true -- if for some reason you have to transmit the actual data through a non-internet channel, and the actual data has to be wrapped in a QR code format, then there's a different way to do this.
The obvious approach (hi-level) looks like this
<code>message
   --> (compress) --> compressed message
      --> (encrypt) --> encrypted compressed message
         --> (QR encode) --> QR of encrypted compressed message
            ... send over channel ...
      encrypted compressed message <-- (QR decode) <--
   compressed message <-- (decrypt) <--
message <-- (decompress) <--
</code>
In which your primary challenge is to choose compression & crypto algorithms that suit your purposes.
Note well, crypto is non-obvious, approach with respect & caution, don't just slam something together ...
Compressing before encrypting is a best practice.  It isn't always needed as a separate step, because some crypto algorithms perform compression for you -- for example, PGP compresses data before encrypting.  Others don't.  If you're not sure or the approach needs to be general (work for different choices of crypto algorithm) you can always compress; it's safe, just sometimes pointless.
Choice of crypto algorithm has many implications (key management etc. -- huge topic).  However one of the implications is especially relevant to QR codes -- how much the crypto step bloats your message.  QR code blocks have a limited capacity of 2953 bytes of 8-bits each.  If the message you're transmitting is close to this limit, you'll want to choose a crypto algorithm that has output size equal to input size (AES is one example).  If the message is much smaller than this limit, then you won't care about this (could use the highly-bloating PGP for example).
If you can find compression and encryption algorithms that work for both you & your client (and a safe way to distribute keys and so on), then I don't think it's particularly hard to satisfy your original request.  Don't try to encrypt the QR code itself (not sure that terminology actually makes any sense) but instead, compress and encrypt your data, then QR-encode the resulting encrypted data.  Nothing to it.
Answer: A QR code, at heart, just encodes bytes. Those bytes could be anything you want. They could be the encryption of some data. The question is whether a reader application will know that is the nature of the bytes and know what to do with it.
And the problem is, no it won't. There is no such scheme as "Secure QR codes" defined in the QR code spec or otherwise. So, no reader out there will do anything but show a string of garbage text.
You can write your own custom reader that knows what to do, but I imagine this is completely infeasible.
So, @Dan is right. The right way to do this is encode a link to a web server which challenges for authentication.
If you want clients to encrypt their communication to you, why is it necessary to wrap it in a QR code? just encrypt and send it via HTTPS. Sending a QR code is conceivable, but like sending a picture of data instead of data. It doesn't really make sense.
Comment: Yes there is: http://www.qrcode.com/en/codes/sqrc.html, since 2008
Comment: Nope, because: "SQRC can be read only by specific types of scanners." Of course you can make any kind of scheme if it's non-standard, but that wasn't the question.
Comment: His question was: "Is there an application where you can generate encrypted QR Codes?" Yes there is and is made by DensoWave itself.
Answer: There is! (despite all the above complicated ways of misunderstanding the question and saying "no there isn't").
The answer is an Android app called QR Droid. It's a general QR code reader and generator.
QR Droid can create a QR code (including from plain keyboard text) and optionally create a variation with the content encrypted using a requested key word.  Because this is a feature of this particular app and not QR, this app is needed to read and decrypt the encrypted QR code (it'll ask for a key to decrypt after scanning).
This is handy way of creating username/passwords to leave in plain sight to decipher (only via QR Droid) when needed.
So, yes. There is an application that can generate QR codes with encrypted content.  It is the Android App: QR Droid.
Comment: +1 for pointing out that the "impossible" has already been done :-). As far as I can tell, that app and others ( [a](http://www.milliontech.com/home/content/view/254/139/), [b](http://www.beetagg.com/en/learning-center/Encrypted-Codes/44), [c](http://www.2dtg.com/learning_center/protective-suite), [d](http://uvsar.blogspot.com/2009/05/secure-qr-and-qm-codes.html) ) internally use more-or-less the approach suggested by Chris Johnson. I hear that "SQRC" has plaintext readable with any scanner and also encrypted data, both in the same 2D barcode.
Comment: This is correct. qr droid 4 encrypts messages in DES encryption before encoding the encrypted information as a qr code
Comment: Fair point, but this is not a standard QR code and can't be read by any other QR code scanner. It's not really a "QR code".
Comment: Another app that does the same is "QuickMark", QR codes can be created with encryption on the website and then read with the iOS/Android app.
Comment: Though it is a bit old post, just to make thing clear for other people. SQRC Code contains two portions of data. One for public and the other one for private. For public data, any device (as long as it can decode QR Code) can read and get it. However, for private data, it is hidden with a 16 digits hex value encryption key in the same QR Code. Only DensoWave brand devices with correct encryption key can retrieve it. It is more like information hidden in QR Code with password protected.
Answer: You don't really need an "encrypted" QR Code- you just need to make sure that wherever the information is hosted on the web, that is encrypted.
Comment: Dan the issue is on the client side, we would like our customers to send us their payment information  encrypted in some way for extra security
Comment: The OP didn't ask whether anyone _thought encrypted QR codes were needed_, the question is about identifying an app that makes them.

Secure / Encrypted QR Codes


Using Webform as an Application for membership/user roles

Question: I'd like to implement the following on a Drupal site:

Anonymous site visitor (Joe) submits a membership application with various custom fields
Admin (Jane) reviews membership application
Jane approves Joe's application and creates new user account
Joe gets notice of approval and login information

Possible solutions:

A Webform (But how can the data from the webform be easily transferred into a user account?)
Profile2 with Admin approval necessary. (The problem with this one is we don't want it to feel to the user like they are creating an account on the site, but applying for the membership.)
Create a Membership content type that an anonymous user can fill out (?)

I feel like I'm overlooking something obvious.
I can't use the core user registration with additional fields because there are 3 different types of memberships. And users should be able to change from 1 membership to another (upon approval).
Answer: Based on some other questions you've asked on this site I wonder if you are using CiviCRM for tracking the memberships? If so I might suggest this workflow:

Setup a webform with CiviCRM integration. Add your membership and other custom fields to the form.
Set the membership status to be "Approval Needed" (you can create that status in CiviCRM if it isn't there already).
Have it send an email to your staff whenever that form is filled out.
You can optionally restrict access to that form so that only non-members can use it.  This would require you to enable the module 'CiviMember Roles Sync' which is bundled with CiviCRM and enabled syncing between Drupal roles and Civi memberships.
Comment: Well, I am no longer approaching this using CiviCRM. I did try CiviCRM but found a lot of overhead and complexity in the base installation that is specifically what the client is trying to avoid. Their current system is too complex and my task is to simplify.

So at this point I'm looking for non-CiviCRM ideas about how to do this.


Missing Vite Manifest File after deployment

Question: I have deployed my laravel project using hostinger. I've encounter a problem where there is Missing Vite Manifest File deploy at line
@vite(['resources/css/app.css', 'resources/js/app.js'])

How do i solve this?
I saw answers recommending on stack
npm run dev/npm install/ npm run build

I tried running them before uploading the files to the server, but they did not work. Is there ant other way to solve it?
Answer: If you are running it locally, you need to remove /public/build from .gitignore otherwise it will never upload if you add it on .gitignore.
Another way, you could add npm run build, on your deploy script
Comment: I tried that too, but it does not work. This is the link https://eurofinsmy.net/register
Comment: How do i run npm run build on a deploy script? I couldnt find any terminal on the hosting website hostinger
Comment: @ggcode could you confirm if there is `build` folder on server, if not, could be git cache issue.
Comment: Yes, there is a ```build``` folder under ```public_html```
Comment: and still there isn't manifest.json inside build folder?
Comment: there is a manifest,json inside, this is the code of the file
```{
  "resources/js/app.js": {
    "file": "assets/app.7cafe3db.js",
    "src": "resources/js/app.js",
    "isEntry": true
  },
  "resources/css/app.css": {
    "file": "assets/app.0e1d3a96.css",
    "src": "resources/css/app.css",
    "isEntry": true
  }
}
```
Comment: what is the exact error you are receiving?
Comment: Vite manifest not found at: /home/u765133174/domains/eurofinsmy.net/eurotracks/public/build/manifest.json. It didnt appear on that website just now because i deleted the line but forget to put it back when asking.
Comment: I also dont know hwo to run a npm run build on the deploy script, is it through manifest.json?
Answer: when you are pushing to production remove /public/build from .gitignore of course after running npm run build locally.


Intuition behind Correlated Terms in Mixed Effect Models

Question: In mixed effect models, one can specify a varying intercept term and a varying slope term that covary with each other. The second to last row in this vignette by Douglas Bates shows how to specify such an interaction.

I do not have an intuitive understanding for what allowing this interaction means.
1) What does it intuitively mean to allow these particular coefficients to covary?
2) If I introduced another varying slope $s_2$ term into the model, in addition to $s_1$, what would it intuitively mean for $s_1$ and $s_2$ to vary?
3) Finally, what resources can I use to better understand how to perform inference on such correlations (in a manner similar to say Inference in linear mixed model
)?

What do I know:
I have an imprecise mathematical understanding of what correlations between coefficients mean. In particular, I recognize that a varying slope term and varying intercept term are random variables, and so the usual definition of covariance $E[(X - \mu_{X})(Y - \mu_{Y})]$ applies to them. I also understand that the goal of fitting a mixed effect model can be articulated as trying to find a covariance matrix, among other parameters, which is the covariance of a vector of model coefficients. Off diagonal terms in the covariance matrix represent correlations between model coefficients; thus, allowing (or prohibiting) correlation is tantamount to letting the off-diagonal terms be non-zero (or $0$).
Answer: Suppose, for concreteness, that we have a model
y ~ 1 + x1 + x2 + (1|g)

where x1 and x2 are (for simplicity) continuous predictor variables (g is a categorical grouping variable). This model states that the expected value of y changes linearly with changes in x1 and x2 and that there are differences in the intercept between groups (i.e. $\hat y = (\beta_0+b_{0,i}) + \beta_1 x_1 + \beta_2 x_2$), with $b_{0,i} \sim \textrm{Normal}(0,\sigma^2_0)$); that's what the 1 in (1|g) means.
If we change the random effect to (1|g) + (0+x1|g) + (0+x2|g) (separate terms), or equivalently (1+x1+x2||g), that specifies that the intercept, slope with respect to x1, and slope with respect to x2 all vary across groups, but this variation is independent: we could write this model out as
$$
\begin{split}
\hat y_{ij} & = (\beta_0 + b_{0,i}) + (\beta_1 + b_{1,i}) x_1 + (\beta_2 + b_{2,i}) x_2 \\
b_{0,i} & \sim \textrm{Normal}(0,\sigma^2_0) \\
b_{1,i} & \sim \textrm{Normal}(0,\sigma^2_1) \\
b_{2,i} & \sim \textrm{Normal}(0,\sigma^2_2) \quad .
\end{split}
$$
So a particular group might have a higher-than-average intercept, a lower-than-average response to $x_1$, and an average response to $x_2$, but all of these term-specific effects are independent of each other.
If we instead write (1+x1+x2|g), we can no longer specify models for $b_{k,i}$ separately: instead we have to write
$$
\boldsymbol b_i = \{b_{0,i}, b_{1,i}, b_{2,i} \} \sim \textrm{MVN}(\boldsymbol 0, \Sigma)
$$
(where MVN is "multivariate normal"). Now in addition to the separate variances for each varying term ($\sigma^2_0$, $\sigma^2_1$, $\sigma^2_2$) we also have to specify the covariances or correlations ($\rho_{01}$, $\rho_{02}$, $\rho_{12}$). For example, suppose that $\rho_{12}$, the correlation between the $x_1$ and the $x_2$ slopes, is negative. That means that groups that respond strongly (positively) to changes in $x_1$ are likely to respond weakly, or even in the opposite direction, to changes in $x_2$ -- similar logic applies to $\rho_{01}$ and $\rho_{02}$ (correlations between among-group variation in the intercept and the two slopes).
You can compare the likelihood of a model with the full ("unstructured" or "general positive-definite") variance-covariance matrix to one with the diagonal (independent) variance-covariance matrix using likelihood ratio tests (or AIC): the independent-terms model is properly nested within the full model (i.e. starting with the full model and constraining $\rho_{01}=\rho_{02}=\rho_{12}$ gets you the reduced/nested model). Alternatively, you can find confidence intervals for individual $\rho_{ij}$ parameters. (nlme::lme does this by computing Wald intervals on a constrained (hyperbolic-tangent) scale and back-transforming; lme4::lmer does it by computing likelihood profiles).


Transformar um vetor de char em um vetor de int em C

Question: char ch[] = {'7', '3', '0', '8'};
int [] nums[2];

void transformInt(char [] c1) {
    int n1[2];
    int j = 0;
    for (j = 0; j < 10; j++ ) {
        if (c1[j] != '0') {
            n1[j] = c1[j];
        } else break;
        return n1;
    }
}

Pessoal, preciso transformar um vetor de char em um vetor de int, mas não consigo. No caso,o '0' separaria os dois valores. Assim, n1[0] precisaria ser igual à 73 e n1[1] igual a 8. Tentei criar um método, mas ele não funciona nem para alocar o primeiro valor, não sei o que está errado.
Também não sei como faço para o método retornar um vetor.
Comment: seu código tem erros de sintaxe, nem compila...tire pelo menos os erros de sintaxe e tente executar o programa
Comment: O que vem a ser este array tam? Não seria o caso de você ir construindo um novo array até encontrar um caractere '0' e daí utilizar a função strtol de  para converter a string em um inteiro?
Comment: No caso, a minha dificuldade é conseguir construir o novo array até encontrar o zero.
Comment: O array tam estava errado, era para ser o c1
Comment: editei a pergunta colocando espacços...use espaços para separar operadores (+, =, -, etc) e chaves ({}), senão fica muito difícil entender quando fica tudo grudado
Comment: int [] nums[2];   isso não é válido C
Answer: Você pode utilizar o sscanf é um método de fácil utilização e presente no stdio.h.
char myarray[5] = {'-', '1', '2', '3', '\0'};
int i;
sscanf(myarray, "%d", &i);

Também existem outras opções como o atoi e o strtol.
Referências:
link 1
link 2
Answer: Para passar uma array como parâmetro de uma função, teria que utilizar ponteiro, e pela complexidade do programa, acredito não ser o caso.
Ao invés de utilizar alguma função externa, eu faria a subtração do carácter por - '0'.
Quando se utiliza o '0' no seu código, é feita uma conversão para o valor representativo da tabela ASCII.
EX: '7' - '0' //Segundo a tabela ASCII seria igual a 55 - 48
E o resultado de 55-48 = 7
Como exemplo
int main()
{
    char ch[] = {'7', '3', '0', '8'};
    int nums[]={0,0}, i = 0;

    for (i = 0; i<4;i++){
        nums[i/2]= (nums[i/2]* 10) + (ch[i]-'0');
        //printf("nums[%i]= %i\n",(i/2),nums[i/2]); descomente para ver como a variavel é preenchida
    }
    printf("nums[0]= %i\n nums[1]= %i\n",nums[0],nums[1]);
    return 0;
}

Essa é uma tatica muito útil, principalmente para programas que serão enviados para o URI


Dynamic Database function for getting and setting data

Question: I have created a class to handle all database operations for my application. So far I have gathered and displayed the data in foreach statements within my view. What I wish to be able to do is get and set individual elements from a function from my database class.
Here is my database function for displaying data within a foreach:
   public function test($sql, $type, $param)
   {
       $variables = array();
       $results = array();

       // Mysqli
       if($stmt = $this->AC->Mysqli->prepare($sql))
       {
        $params = array_merge($type, $param);
           call_user_func_array(array($stmt, 'bind_param'), $this->make_values_referenced($params));
        $stmt->execute();
        $stmt->store_result();
        // Existance
        if($stmt->num_rows > 0)
        {

        $meta = $stmt->result_metadata();

        while($field = $meta->fetch_field())
        {
            $parameters[] = &$row[$field->name];
        }

        call_user_func_array(array($stmt, 'bind_result'), $parameters);

        while($stmt->fetch())
        {

            $elemet = array();

            foreach($row as $key => $val)
            {
                $element[$key] = $val;
            }

            $results[] = $element;

        }

        return $results;

        }
        else
        {
            $results = FALSE;
            return $results;
        }
        }
        else
        {
        die("ERROR: We could not connect.");
        }
    }

The function below is called from my model:
    public function profile_information($account_name)
    {
    // Mysqli Variables
    $sql = "SELECT $this->account_details.bio
            FROM account_details
            WHERE $this->account_details.account_name = ? LIMIT 10";

            $type = array("s");
            $param = array($account_name);

            $results = $this->AC->Database->prepared_select_loop($sql, $type, $param);

            $this->AC->Template->set_data('profile_information', $results, FALSE);
    }

Once set within my model, I call the function within my controller and access it within my view with a foreach for displaying data:
    $profile_information = $this->get_data('profile_information');
    foreach ($profile_information as $row) :
        //Displaying data here
    endforeach;

The above works fine for displaying a large amount of data, but what I'm wanting to do is call the a database function that will allow me set individual data elements. Therefore not having to use a foreach if im only getting a limited amount of data (i.e. one row of Name, age, address)
A non dynamic way I have tackled this problem is to write the database for every function that only desires one row from the database:
    function name($variable)
    {
            $sql = 'statement here';
            $stmt = $this->AC->Mysqli->prepare($sql);
                $stmt->bind_param("i", $id);
                $stmt->execute();
                $stmt->store_result();
                $stmt->bind_result(bind results);
                $stmt->fetch();

            $this->AC->Template->set_data('id', $id);
            $this->AC->Template->set_data('account_name', $account_name);
    }

So in basically I want to make the above statement refactored into my database class and thus making it more dynamic.
I dont know how I would be able to tackle this problem, I don't want to use PDO, as I wish to find a solution within Mysqli. Any help would be appreciated.
Comment: your idea of combining database api with template calls in one function looks err... unusual to me. However, I wish you luck. Mysqli especially evil with dynamic prepared statements. If you don't like PDO one-liners, several screens of mysqli code is the best choice.
Comment: Would you recommend just switching over to PDO?
Answer:
Would you recommend just switching over to PDO?

Definitely.
Whole your function test() could be rewritten into three lines (assuming $param contains an array with parameters for the prepared statement):
public function test($sql, $param)
{
    $stmt = $this->AC->pdo->prepare($sql);
    $stmt->execute($param);
    return $stmt->fetchAll();
}


A question about ordered vector spaces

Question: Relevant Definitions:
Definition:
Let $X$ be a set. A partial order $\leq$ on $X$ is a relation that is reflexive, anti-symmetric, and transitive.
Definition:
Let $\leq$ be partial order on a real vector space $E.$ The pair $(E, \leq)$ is said to be an ordered vector space (OVS) if:\

For all $f,g,h \in E$ one has, $f \leq g \implies f+h \leq g+h$
For all $f,g \in E$ with $f \leq g$ and for all $\alpha \in \mathbb{R}, \alpha \geq 0$ one has $f \leq g \implies \alpha f \leq \alpha g.$

Definition
Let $E$ be a real vector space. $C \subset E, C \neq \emptyset$ is said to be a convex cone with vertex at the origin if

For all $x,y \in C$ we have $x+y \in C$
For all $x \in C, \lambda \geq 0$ we have $\lambda x \in C.$

Definition:
Let $E$ be a real vector space. Let $C \subset E$ be a convex cone with its vertex at the origin. $C$ is said to be a strict cone if:
$$\forall \;\; x \in C \setminus \{0\} \;\;\text{one has} -x \notin C.$$
Definition:
Let $(E,\leq)$ be a real ordered vector space. Define
$$E_+=\{x \in E: 0 \leq x\}$$
The set $E_+$ is called the cone of positive elements.
Proposition:
$E_+$ is a strict cone.
Proof:
First let $x,y \in E_+$. Then $0 \leq x$ and $0 \leq y$ so that
$$0\leq y = 0+y \leq x+y$$
by the first property of an OVS applied to the inequality $0 \leq x$ (adding $y$ to both sides).  Now let $x$ be in $C$ and let $\lambda$ be a non-negative real number. Then by the second property of an OVS we have
$$0 \leq x \implies 0=\lambda 0 \leq \lambda x,$$
which proves that $E_+$ is a cone with its vertex at the origin. To see that $E_+$ is strict, let $x \in C \setminus \{0\}.$ Then $x \geq 0 \implies -x \leq 0$ by property 1) of OVS.
My Question: What I want to argue here is that since $-x \neq 0$ we must have that $-x <0$ which completes the proof. However, I do not see why this is evident from the definition of a partial order. My understanding is that there are relationships between what I think are termed strict vs non-strict partial orders, and it may be that one inducing the other is required here. Is there a way to establish the desired result using only the definitions above or am I perhaps misunderstanding what the text I am working with means by partial order. For reference, the text I am working with calls $\leq$ an order and then makes statements of the form, if $\leq$ is total then... so I assumed they meant partial order. The text I am working makes no distinction between $\leq$ and $<$ or $=$. Thank you in advanced.
Answer: You must use antisymmetry of the order $\leq$. Namely, you're assuming that $x\in C\smallsetminus \{0\}$, and you want to show that $-x\in C$. Assume by contradiction that $-x\in C$, so that $-x \geq 0$. By adding $x$ to both sides, it follows that $x \leq 0$. But $x\in C$ means that $x\geq 0$. Both conditions $x\geq 0$ and $x\leq 0$ together imply that $x=0$ (this is antisymmetry of $\leq$), which is a contradiction.
Comment: Awesome! Thank you so much for the help!
Comment: I'm not sure I agree that they need to use anti-symmetry, $ -x \leq 0$ was derived from the properties of an ordered vector space, and $-x\neq 0$ can be concluded since $x\neq 0$ and the properties of vector spaces, but I might be missing something, or it could be that you simply meant this can be easily done by employing anti-symmetry
Comment: Sorry, I see that they don't need anti-symmetry to conclude $-x<0$ but this doesn't complete the proof as they stated, and anti-symmetry is needed to complete the proof
Answer: Your answer lies in the definition of $<$, which is not a new relation really, but a conjunction of the $\neq$ and $\leq$ relations.
So by definition, if $v\leq w$ and $v\neq w$ then $v<w$.
You might think that its not sufficient to define it this way, but for partial orders this definition satisfies an important property:
$$\forall_x,y[x<y \land x\geq y \implies \perp]$$
The proof for this is simple:
Assume $x<y \land x\geq y$ then
$$\implies x\neq y \land x\leq y \land x\geq y$$
$$\implies x\neq y \land x=y $$
$$\implies \perp $$
Where the second to last step was thanks to the anti-symmetry of a partial order.

A question about ordered vector spaces


Where does drupal store all its files?

Question: I would like to use FTP to copy my current site to a new server. I obviously know that the bulk of my files will be stored in /var/www/ and the folders inside. I also exported my databases from phpMyAdmin to a localhost.sql file.
Is there any other place I need to pull files from? Is that it for the database?
Answer: You should be able to transfer the site wholesale, without too much fuss. After transferring, you may need to alter some paths (eg admin/config/media/file-system in D7) if the sites directory has changed paths relative to your Drupal codebase. Odds are you won't need to, though.
For a simple site, the layout will be something like this -
/var/www/index.php
         modules/                  } don't install modules here
         themes/                   } nor themes here
         includes/
         [many other Drupal core files]
         sites/
               default/            } all installed code
                       files/      } lives in the
                       modules/    } site directory
                       themes/     } and its children

For more complex setups you may need to understand multisite layouts, but for now hopefully this answers your question.
Answer: Thankfully, Drupal installations are typically very self-contained. If there were any changes made to your old server's httpd.conf (or comparable server configuration file if you're not running Apache), you may want to migrate those to the new server as well, assuming you aren't on a shared host where all of that is taken care of for you. Though other than copying everything in the root of your Drupal install (the folder containing index.php and all subdirectories) to your new DocumentRoot and importing your database dump, you should be all set.
Comment: Now, I hope there will be no problems bringing it from a 32b Ubuntu to a 64b Ubuntu?
Comment: I've migrated Drupal to and from 32-bit and 64-bit operating systems numerous times without issue. You just want to make sure that all of your PHP/MySQL/Apache packages are set up for the appropriate architecture on each server (assuming of course that this isn't managed for you).
Answer: It depends on your setup really. For example if you use the private file system (properly) and use a folder outside of the web root then you'll need to copy those files too and put them in a folder in the same location on the new site.
Similarly if you use Ubercart (and perhaps Commerce, I'm not sure) and take credit card payments on the site then the encryption keys for those will also be stored outside of the site root, for security purposes; those would also need to be copied.
There are probably other modules that store files outside of the web root but I don't know any off the top of my head. In the majority of cases (except for those above) you should be ok though, just copying the entire web root across will probably work.

Where does drupal store all its files?


Kill FINished sockets (using libpcap - tcpdump/tcpkill)

Question: I'm trying to create a small service that monitors and kills sockets which have the FIN flag. I can get them with tcpdump (I also tried tcp[13] & 1):
tcpdump "tcp[tcpflags] & tcp-fin != 0"

tcpkill is suppose to use the same interface as tcpdump, but it isn't working the same. I've tried a bunch of commands, but it should just be (-i eth0 optional):
tcpkill -9 "tcp[tcpflags] & tcp-fin != 0"

Which says (but nothing else, successful tcpkill outputs data):

tcpkill: listening on eth0 [tcp[tcpflags] & tcp-fin != 0]

Looking at the source, it should be passing the correct filter to pcap (between the [ ] brackets). Using a perl script with Net::Pcap I can determine the filter works fine. I don't know what I'm doing wrong, or if it's an older version of tcpkill/pcap that's an issue. Any help with tcpkill or help using perl's Net::Pcap to kill sockets would be appreciated. Thanks!
#!/usr/bin/perl

use strict;
use warnings;

use Net::Pcap;

my $err = '';
my $dev = 'eth0';

my ($address, $netmask);
Net::Pcap::lookupnet($dev, \$address, \$netmask, \$err);

my $pcap = Net::Pcap::open_live($dev, 1500, 1, 0, \$err);

my $filter;
Net::Pcap::compile($pcap, \$filter, "tcp[tcpflags] & tcp-fin != 0", 0, $netmask);
Net::Pcap::setfilter($pcap, $filter);

while(1)
{
 Net::Pcap::loop($pcap, 1, \&process_packet, "packet found");
}

Net::Pcap::close($pcap);

sub process_packet
{
 my($user_data, $header, $packet) = @_;
 print "$user_data\n";
}

exit 0;

Comment: Just out of curiosity, what is the purpose or goal behind this?  If it's just "because I can" or "because I want to", that's cool.  But I'm wondering what the actual problem you're trying to solve is.  If you're just concerned with connections that you've FIN'ed and that haven't closed yet, changing OS TCP/IP paramters (like 'tcp_fin_timeout' on Linux) may be a better solution.
Answer: Looking at the source code for tcpkill, it uses libnet to generate a RST packet(s) to kill a given TCP connection.  I'm not sure why it's not working (though verifying the PCAP version it was built against is a great place to start).  You can also use tcpdump to look for the RST packets it should be sending out.
Regarding implementing the equivalent in Perl, I once had to do something sort of similar.  Below is (untested!) code which might point you in the right direction.
use NetPacket::Ethernet;
use NetPacket::IP;
use NetPacket::TCP;
use Net::RawIP;

... (the rest of your script) ...

sub process_packet {
    my ($user_data,$header,$packet) = @_;

    my $ethernet_frame = NetPacket::Ethernet::strip($packet);
    my $ip_packet = NetPacket::IP->decode($ethernet_frame);
    my $tcp = NetPacket::TCP->decode($ip_packet->{data});

    my $reset_packet = new Net::RawIP;

    $reset_packet->set({
        ip => {
            saddr => $ip_packet->{dest_ip},
            daddr => $ip_packet->{src_ip}
        },
        tcp => {
            source => $tcp->{dest_port},
            dest => $tcp->{src_port}
        },
        rst => 1,
        seq => $ip->{acknum},
        data => 'access denied'
    });

    $reset_packet->send();
}

tcpkill is more refined in terms of attempting to figure out the correct sequence number, which is what the -1..9 flags are for.  Have you tried using different values for that flag?
Comment: Good to know, thanks. I started using pycap, which seemed to be working at least half the time, but I wasn't sure. I'm going to give these suggestions a try (perl and figuring out sequence).

Something I was wondering is if I should ONLY be sending the RST packet to the OTHER servers, or just my server, or both my server and the others? tcpkill seems to just reverse the destination and source? Would that be circular?
Comment: When you say you want to "kill FINished sockets", what is your goal?  What OS are you using?

With tcpkill, you're only initiating a tear down of the TCP session.  After the RST is sent, you're waiting on the TCP/IP stack timers to clear out the resources on the local end.

Alternatively, BSD systems have a utility called 'tcpdrop', which instruct the kernel to drop the connection.  It too initiates a RST packet, but alleviates the need to figure out the correct TCP sequence number in user space (i.e. the TCP/IP stack knows).  It also seems to be quicker about clearing out the local resources.


Can I do a t-test Power Analysis for Unequal Size Groups which Produces 2 Different Minimum n's?

Question: It's usually straightforward to do a Power Analysis to compute the minimum sample size, especially in R which is my preferred statistical computing environment.
However, I am being asked to conduct a Power Analysis that's a little different than anything I've done or which I can find reference to online. I'm wondering if what I'm being asked for is even possible/valid.
The project basically has two unequal groups of states and the hypothesis is that these two groups are significantly different in terms of an outcome variable (which is the duration of phone calls to customers). The "control" group consists of 40 states and produced about 2,500 observations. The "test" group has about 10 states and 500 observations.
Initially, I found group means + pooled standard deviation, which I used to calculate an Effect Size. Then I used a package called pwr in R and found that I needed a minimum sample size of about 135 observations per group, given .05 significance and .8 power.
However, they rejected my answer because they want one group to be much bigger than the other like it is now, and they are expecting either two different minimum numbers of observations per group or a minimum % of the population in terms of numbers of states or observations that have to go into their "test" group.
I see Power Analyses for two sample t-tests (i.e. the R function pwr.t2n.test), but I'd have to specify at least one of the sample sizes whereas they want me to tell them the minimal sample size for both groups (either as numbers or percentages) and this function doesn't reflect the differences in standard deviations for the two groups.
Is this possible or do I just tell them that's not how it works (i.e. the best I can do is tell them that given one of the sample sizes and a pooled standard deviation the second group has to be at least a certain size)?
Answer: You can do sample size calculations for unequal sample sizes.
For example, you can decide the n's are in some ratio (such as in proportion to the populations perhaps).
It's then possible to do power calculations (at the least you can simulate to obtain the power under any particular set of circumstances, whether or not you are able to do the algebra).
The problem is that it's relatively inefficient at finding differences compared to the same total number of observations at equal sample sizes.
Imagine you had a total sample of $n=n_1 + n_2$, with equal variance in the population and close to equal sample variance, and that your choice was between a 50-50 split and a 90-10 split ($n_1 = 0.5n$ vs $n_1=0.9n$).
The two-sample t-statistic is:
$t = \frac{\bar {X}_1 - \bar{X}_2}{s_{\text{pooled}} \cdot \sqrt{\frac{1}{n_1}+\frac{1}{n_2}}}$
The impact of the sample size is in the term $1/{\sqrt{\frac{1}{n_1}+\frac{1}{n_2}}}$.
If you have the 50-50 split it's like having a 40% smaller standard deviation; at a given $n_1+n_2$ you can pick up a substantially smaller effect with the even split.
If the combined sample size is not an effective constraint, this calculation may pointless however. It matters in cases where every observation carries the same marginal cost, which is not always relevant.
Comment: @Glen: That is why I tried to quickly remove my comment about the (un)usefulness of a t test in duration analysis. But you were even faster. Another concern is the grouped structure of the data. But your answer exactly fits to the question.
Comment: Thanks! So, to actually carry this out is my best bet to simply use something like pwr.t2n.test() in R for basically every possible combination given a combined sample size, or is there a better way you'd recommend to compute this? If you use another language/package then I can figure out how to translate your answer into R. In either case, thanks for your solution.
Comment: I don't understand what you're getting at here. As far as I can tell you don't have the ability to split in any ratio you like; my example was to illustrate the effect of uneven splits. If you do have a fixed total sample size, then split it as near to 50-50 as would be accepted. If you don't have a fixed total sample size, then you optimize based on however your costs and constraints actually do go.
Comment: The extent of my information is that they currently have those two really unequal groups which total to 3,000 observations across 50 US states. They ask for the minimum number of observations per group and/or the % which should go into each group, based on the means and standard deviations I get from the data. I have no idea if they could split the data 50-50 or any way they like, but I was going to show them the minimum n in group 2 for every value of group 1's n and also show them the cost of splits other than 50-50, probably in terms of power. I thought that was roughly what you suggested?
Comment: I see. You could certainly calculate something like that, but you wouldn't necessarily need to do it at every $n$; these things progress quite smoothly.
Comment: @MichaelMayer Yes, I made no attempt to deal with that issue at all, but the sample size issue will be similar across analyses.
Comment: Don't use $s_{\textrm{Pooled}}$.  If the sample sizes and variances are substantially unequal your confidence intervals will be either optimistic or conservative.  Use $$s^2_{\bar{x}_1-\bar{x}_2} = \frac{s^2_1}{n_1} + \frac{s^2_2}{n_2}$$.  Because you are using sample estimates, figure Satterthwaite's approximation to the DF and use that for your non-central $T$.
Comment: @Dennis My discussion specifically assumed equality to make the *illustration of the point simple*. The same underlying issue applies to other analyses, but saves having to consider a variety of cases that don't serve to make the basic issue any clearer. I was not advocating any particular analysis - as Michael Mayer already suggests, t-tests aren't likely to be suitable in the first place, so arguing for a better t-test neither helps the basic explanation of the issue with sample size, nor arrives at a suitable analysis for the problem. To what end, then?
Comment: @Glen_b: there is such a thing as oversimplification.  Users don't need any more encouragement to use pooled $T$ than is already out there on their bookshelves.  In the case of equal or nearly equal sample sizes, I don't worry too much.  In the case of very disparate sample sizes, I do worry.  The situation here is to determine sample sizes intended to be disparate.  Assuming $\sigma$ known also simplifies the situation tremendously.  That would have made the same point, but be nearly impossible to mistake as a suggestion.
Answer: First off, why are you assuming equal variances in the two groups?  Please don't say, "Because it's convenient."  I seriously doubt that the group variances are equal, although in the case of equal sample sizes that isn't crucial.  Your degrees of freedom will be off, but you know you have at least 130, so who cares?  There are much bigger questions to address.
If you are going to permit (or require) unequal group sample sizes, the problem will not have a unique solution.  There are two unknowns ($n_1$ and $n_2$ and only one constraint (the power must be at least $\phi$.)  I don't think the problem can be solved without an additional constraint.  There are two obvious possibilities.  The first is to fix one of the sample sizes (e.g., the sponsors want at least 300 observations from Group I).  The other is to fix the ratio (e.g., because Group I is ten times the count of Group II, we want $n_1 = 10\, n_2$).  Now proceed with your power analysis.
Comment: How did I assume that there were equal variances? I know there's not... that's why I was asking about the possibility of using the different standard deviations for each group to do a calculation, though the normal way of doing a Power Analysis is to use pooled standard deviations when you have more than 1 group.
Comment: @NerdLife: Pooled variance, which you said you used, amounts to assuming equal variances.  The "normal" way of doing it is to assume that $n_1 = n_2$, and in that case pooling doesn't matter to the value of the test statistic.  The OSL is affected because the degrees of freedom shift between$\n_1-1$ and $2\,(n_1 - 1)$.  But those shifts are pretty minor above 30 or so df.


Determine the mean value and standard deviation with which the elevator operates per load.

Question: The number of people $N$ entering an elevator is approximately distributed as a Poisson of
mean $\lambda = 2.3$. On the other hand, the weight $W$ of a person is modeled by
a Gamma distribution with shape and scale parameters, $\alpha = 53$ and $\beta = 1.25$, respectively.
Determine the mean value and standard deviation with which the elevator operates per load.
I'm not sure if the function is defined like $$f(n,w)=\frac{\lambda^ne^{-\lambda n}}{n!}\frac{w^{\alpha -1}e^{\frac{-w}{\beta}}}{\beta^\alpha \Gamma(\alpha)}I_{\{0,1,...\}}(n)I_{\{0<w<\infty\}}(w)$$
Any suggestions would be great!
Comment: Is $\beta$ the scale parameter or *inverse* scale parameter? E.g is the mean of $W$ equal to $\alpha \beta$ or $\alpha / \beta$ for you?
Comment: Thanks for the answer @paulinho ! The mean is defined by $E[W]=\alpha \beta$
Answer: You're going to want to condition on the number of people who enter the elevator. Let $T$ be the total load of the elevator. Then the mean can be calculated using the tower law of expectation as follows:
$$\mathbb{E}[T] = \sum_{n = 0}^\infty \mathbb{E}[T ~|~ N = n] \cdot \mathbb{P}[N = n] = \sum_{i = 0}^\infty n \cdot \frac \alpha \beta \cdot \mathbb{P}[N = n] = \frac \alpha \beta \sum_{i = 0}^\infty n \cdot \mathbb{P}[N = n] = \frac \alpha \beta \cdot \mathbb{E}[N]$$
Note that $\mathbb{E}[T]$ conditioned on $N = n$ is simply the expected weight per person times $n$, by linearity of expectation. Hence, the expected load is conveniently the product of expectations: $\mathbb{E}[T] = \boxed{\frac \alpha \beta \cdot \lambda}$.
To calculate the variance of $T$, apply the same strategy to calculate $E[T^2]$:
$$\mathbb{E}[T^2] = \sum_{n = 0}^\infty \mathbb{E}[T^2 ~|~ N = n] \cdot \mathbb{P}[N = n]$$
To calculate the conditioned expectation $\mathbb{E}[T^2 ~|~ N = n]$, note that if we have $n$ passengers, then $T \sim T_n$, where
$$T_n \sim W_1 + W_2 + \cdots + W_n$$
where all the $W_i \sim \text{Gamma}(\alpha, \beta)$ are independent and identically distributed. Note that
$$\mathbb{E}[T_n] = n \cdot \mathbb{E}[W_1] = n \cdot \frac{\alpha}{\beta}, ~~ \text{Var}(T_n) = n \cdot \text{Var}(W_1) = n \cdot \frac{\alpha}{\beta^2}$$
And finally we can conclude that
$$\mathbb{E}[T^2_n] = \text{Var}(T_n) + \mathbb{E}[T_n]^2 = \frac{n \alpha (1 + n \alpha)}{\beta^2}$$
Plugging this expression back into the formula for $\mathbb{E}[T^2]$, we have
$$\mathbb{E}[T^2] = \sum_{n = 0}^\infty \frac{n \alpha (1 + n \alpha)}{\beta^2} \cdot \mathbb{P}[N = n] = \frac{\alpha}{\beta^2} \left[\mathbb{E}[N] + \alpha \mathbb{E}[N^2]\right] = \frac{\alpha}{\beta^2} \left[\lambda + \alpha (\lambda^2 + \lambda)\right]
 $$
Hence, the standard deviation is given by
$$\sigma(T) = \sqrt{\mathbb{E}[T^2] - \mathbb{E}[T]^2} = \boxed{\frac{\sqrt{\lambda \alpha(1 + \alpha)}}{\beta}}$$
Comment: Nice derivation overall (+1). But $\beta$ is _scale_ parameter of gamma dist'n and so belongs in numerators of  $E(T)$ and $\sigma(T).$
Comment: @BruceET Thanks! I got the formulas for mean and variance of a gamma distribution from Wikipedia - since OP used $\alpha$ and $\beta$, I assumed that the convention was like Wikipedia's convention with $\alpha$ and $\beta$ where $\beta$ is an inverse scale parameter. I'll ask OP to clarify.
Comment: OP seems clear enough: ""modeled by a Gamma distribution with shape and scale parameters," Additionally, taking $\beta$ as rate parameter would lead to absurd weights. Sadly, there is no standard notation for gamma rate and scale parameters.
Answer: This is sometimes called 'a random sum of random variables'.
A conditioning argument similar to that of @paulinho's
Answer gives
$$E(T) = E(N)E(W) = \lambda\alpha\beta = 152.38$$ and
$$Var(T) = E(N)V(T) + [E(W)]^2V(N)
= \lambda\alpha\beta^2 + \lambda\alpha^2\beta^2
= \lambda\alpha\beta^2(1+\alpha).$$
Thus, $SD(T) = \beta\sqrt{\lambda\alpha(1+\alpha)} =101.42.$
lam = 2.3;  a = 53;  b = 5/4
mu = lam*a*b;  mu
[1] 152.375

sd = b*sqrt(lam*a*(1+a));  sd
[1] 101.4165

A simulation in R (where rgamma uses the rate, rather than
the scale parameter) approximates the numerical values above
and illustrates that the distribution of $T$ inherits
'lumpiness' from the discreteness of $N.$ With a million
simulated elevator trips, one can expect about three significant
digits of accuracy from the simulation, in good agreement
with the exact values above. In addition, simulation
provides $P(T \le 350) = 0.9609\pm 0.0004.$
set.seed(712)       # for reproducibility
t = replicate(10^6, sum(rgamma(rpois(1,2.3),53,4/5)))
mean(t);  sd(t)
[1] 152.5289        # aprx E(T) = 152.4
[1] 101.3677        # aprx SD(T) = 101.4
mean(t <= 350)
[1] 0.960886        # aprx P(T <= 350) = .9609 +/- 0.0004
2*sd(t <= 350)/1000
[1] 0.0003877326    # aprx 95% margin of simulation err

hist(t, prob=T, br=25, col="skyblue2")
  abline(v = 350, col="red", lty="dotted")


Check when a Program is Done Running using a .BAT

Question: How would I go about checking to see if a specific program is done running?
I'm attempting to make a script that runs a series of .exe's (specifically and setup program and a number of patches) in order automatically.
So far I've been able to get them to run at the same time, but that's obviously not what I need.
How can I get them to run each after the other is completed?
I've looked at a few already posted, but I wasn't able to modify them to what I need.
Comment: post an example of what you're doing.  A BAT file shouldn't default to launching an executable in a new thread.
Answer: Run your exe from the bat using this syntax
<code>start /wait foo.exe
</code>
to wait for the executable to return before continuing on in the bat file.
Answer: Could you specify what method are you using for running the programs?
There are more than one.
For instance, if you are using "START", there's a "/WAIT" switch which takes care of the waiting.
Comment: I'm currently using run, or just the filename on the line. I tried start, but it basically brought up command prompt with the directory where the .bat was run from.
Comment: Are you sure you are passing the right parameters to START?

It should be used like this:

    START "Window Title" /WAIT "Path\to\my.exe" "my exe parameter" "or parameters"

with an optional /Dpath to set the starting directory for you exe.
Comment: Eww, that was my first comment. Didn't realise I wouldn't get formatting, sorry. Important part: from START "Window Title" to \my.exe".
Comment: Ah, ok. I was unaware that I needed a window title.

I'm also using Vista if that matters.
Comment: You do not need to specify a window title to use the start command.  You should edit your original question and give more details about what you're trying to accomplish.
Comment: The wierd thing is though, it works fine when I have an extra parameter with a window title. When I take it away it stops working.
Comment: Which brings us back to my first comment: use the window title parameter and you're good. :)


Calculating variance for total data

Question: If I know the variance of column A, column B and Column C. But I want to know what is the variance of Column D which is equal to D = A+B+C. How do I calculate that variance?
Comment: @dfife for sample variances ("variance of column" implies taking variance of sample data) that's not going to work as-is. If you use R try: `x=rnorm(10);y=rnorm(10);var(x)+var(y);var(x+y)` a few times
Comment: @dfife : Your comment seems hasty and ill-considered. See my answer below.
Comment: Are A, B, and C independent?
Comment: yes, A, B, C are independent and D is just the Sum of A,B,C
Comment: Then it's just the sum of the variances (var(A) + var(B) + var(C)).
Comment: In a nutshell: are your "columns" vector-valued random variables (as suggested by your assertion they are "independent"), for which you want to compute variances, or are they just columns of data for which you want to compute *empirical variances* or *variance estimates*?
Answer: I am suspicious about the meaning of the question.  Suppose you have two columns: $$ \left[ \begin{array}{c} 1 \\ 2 \\ 3 \\ 4 \\ 5 \end{array} \right], \left[ \begin{array}{c} 10 \\ 9 \\ 8 \\ 7 \\ 6 \end{array} \right] $$ Someone might observe that the average of the entries in the first column is $3$ and then find
$$
\left. \left(\begin{array}{r} (1-3)^2 \\ {} + (2-3)^2 \\ {} + (3-3)^2 \\ {} + (4-3)^2 \\ {} + (5-3)^2 \end{array} \right) \right/ 5, \text{ which comes to } 2.
$$
and call that the "variance" of the first column. Try that with both columns and and with their sum and you will find, in this particular case, that the variance of the sum is $0$ and the sum of the variances is $2+2=4 \ne0.$ The variance of the sum is not the sum of the variances, contrary to an assertion in a comment under the question. But, I imagine it will be said, these are not independent. Here's one thing that "independence" might mean in this case:
$$
\begin{array}{c|ccccc}
& 10 & 9 & 8 & 7 & 6 \\
\hline
1 \\
2 \\
3 \\
4 \\
5
\end{array}
$$
Fill in the addition table and get $25$ numbers. Then the variance of the "sum", e.g. the list of $25$ sums, is the sum of the two variances. But then would one call this a "sum of two columns" without explaining the meaning and expect it to be understood?
Another possibility is that the two columns are random variables and what is seen above is merely one realization of each of the two, and then the variance depends on their two separate probability distributions. Then one can speak of "independence". But in that case, what does "variance" mean? These are vector-valued random variables; what is their variance? The $5\times 5$ matrix of covariances of the entries? That's the standard thing, but I would expect the question to make clear that that is what is meant.
Another problem is that some people will say they were taught to divide by $5-1=4$ instead of $5$ where I divided by $5$ above. At best, that should be done only when estimating a population variance when what you have is a sample rather than the whole population. But if that is done, then the sum of the variances is not the variance of the sum.
So the question as it now stands is not very clear.

Calculating variance for total data