问:
Make a backup of an open file with the most recent changes
How can I make a backup of a file that's open and is actively written to, furthermore how can I make a backup of said file with the latest changes done to it?

For a long time, I thought that whenever I write to a file, the .swp file that's created is basically the up-to-date file that's still in swap memory, such that if I write to a file, then backup the .swp file, I will have that file with up to date content.

I tried this earlier and it doesn't seem to work. So it either doesn't work the way I thought it does, or there's a time interval between writing something in an open file, and that change making it's way to the swap file. Are any of these assumptions correct?

Are the changes that are actively written in a file present somewhere else in memory?

What I want to do is make a script that will make a new backup to a file I'm actively writing to while I write to it, with all the changes up to that point, in case my pc crashes or something.

EDIT: I tried opening the file, writing something to it and then waiting like 1 minute before trying the .swp file, and it does indeed have the changes.

答:
h undofile

From my vimrc:

```<code>" Backup
set nobackup
set noswapfile
set nowritebackup
set undolevels=10000
set history=10000

if has('persistent_undo')
  set undodir=$v/undo
  set undofile
endif
</code>```

And a script to map <leader>b to write file in ~/.vim/undo which is my undodir (I set $v -> ~/.vim on my .bashrc on unix)

```<code>" b -> Backup file
function! Backup(s)
  " Backup path
  let bck_file = expand('$v/undo/bck_') . strftime('%y-%m-%d-%H-%M-%S')
  " File path
  let bck_file .= '--' . substitute(expand('%:p:r'), '/', '_', 'g')
  " Extension
  let bck_file .= '-' . a:s . '.' . expand('%:e')
  silent execute a:s . 'write! ' . bck_file
  echom 'Backup lines ' . a:s . ' of file: $bck_file = ' . bck_file
endfunction
command! -range=% Backup call Backup('<line1>,<line2>')
" :BackView to feed backup path of the day in command line
command! -range=% BackupView call feedkeys(':e '
            \ . expand('$v/undo/bck_') . strftime('%y-%m-%d'))
nnoremap <leader>b :Backup<CR>
vnoremap <leader>b :Backup<CR>
</code>```

Body:
h undofile

From my vimrc:

" Backup
set nobackup
set noswapfile
set nowritebackup
set undolevels=10000
set history=10000

if has('persistent_undo')
  set undodir=$v/undo
  set undofile
endif

And a script to map <leader>b to write file in ~/.vim/undo which is my undodir (I set $v -> ~/.vim on my .bashrc on unix)

" b -> Backup file
function! Backup(s)
  " Backup path
  let bck_file = expand('$v/undo/bck_') . strftime('%y-%m-%d-%H-%M-%S')
  " File path
  let bck_file .= '--' . substitute(expand('%:p:r'), '/', '_', 'g')
  " Extension
  let bck_file .= '-' . a:s . '.' . expand('%:e')
  silent execute a:s . 'write! ' . bck_file
  echom 'Backup lines ' . a:s . ' of file: $bck_file = ' . bck_file
endfunction
command! -range=% Backup call Backup('<line1>,<line2>')
" :BackView to feed backup path of the day in command line
command! -range=% BackupView call feedkeys(':e '
            \ . expand('$v/undo/bck_') . strftime('%y-%m-%d'))
nnoremap <leader>b :Backup<CR>
vnoremap <leader>b :Backup<CR>


来源: stackexchange

问:
Laravel - Exception thrown at Guzzle function when running seeder
Running php artisan db:seed throws the following error: GuzzleHttp\Exception\InvalidArgumentException  : IDN conversion failed (errors: IDNA_ERROR_EMPTY_LABEL) at vendor/guzzlehttp/guzzle/src/functions.php:384

Never seen this error before and it doesn't appear to be an issue with my seeder syntax.

The partial exception trace is:

```<code>1   GuzzleHttp\_idn_uri_convert()
      /home/vagrant/code/companion-2.0/vendor/guzzlehttp/guzzle/src/Client.php:220

2   GuzzleHttp\Client::buildUri()
      /home/vagrant/code/companion-2.0/vendor/guzzlehttp/guzzle/src/Client.php:113
</code>```

I'm running commands within a vagrant/homestead environment. Could this be a version incompatibility?

答:
This is an issue with guzzle 6.5.0. See more info here: https://github.com/guzzle/guzzle/issues/2448

Solution: downgrade to version 6.4.1.

ContentLicense: CC BY-SA 4.0

Body:
Running php artisan db:seed throws the following error: GuzzleHttp\Exception\InvalidArgumentException  : IDN conversion failed (errors: IDNA_ERROR_EMPTY_LABEL) at vendor/guzzlehttp/guzzle/src/functions.php:384

Never seen this error before and it doesn't appear to be an issue with my seeder syntax.

The partial exception trace is:

1   GuzzleHttp\_idn_uri_convert()
      /home/vagrant/code/companion-2.0/vendor/guzzlehttp/guzzle/src/Client.php:220

2   GuzzleHttp\Client::buildUri()
      /home/vagrant/code/companion-2.0/vendor/guzzlehttp/guzzle/src/Client.php:113

I'm running commands within a vagrant/homestead environment. Could this be a version incompatibility?


问:
How can I suppress the output image generation in detectObjectsFromImage()?
I am using ImageAI's detectObjectsFromImage function to run a pre-trained keras model on certain images. It works fine but it generates an output image with enclosed boxes against objects. Ideally, I dont want the output image to be generated as I just need to detect in code and perform action on it. I tried not to give output argument but it still created a jpg file.

Any ideas how to suppress the output image?

code:

```<code>detections = detector.detectObjectsFromImage(input_image=os.path.join("pics",filename))
for eachObject in detections:
    if(eachObject["name"]=="person"):
        print("yes")
    else:
        print("no")
</code>```

答:
Set the output_type to "array":

```<code>detected_image_array, detections = detector.detectObjectsFromImage(output_type="array", input_image="image.jpg" ) # For numpy array output type
</code>```

Described in the docs: https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/Detection/README.md

Note: You can also set the input_type to "array".

Body:
I am using ImageAI's detectObjectsFromImage function to run a pre-trained keras model on certain images. It works fine but it generates an output image with enclosed boxes against objects. Ideally, I dont want the output image to be generated as I just need to detect in code and perform action on it. I tried not to give output argument but it still created a jpg file.

Any ideas how to suppress the output image?

code:

detections = detector.detectObjectsFromImage(input_image=os.path.join("pics",filename))
for eachObject in detections:
    if(eachObject["name"]=="person"):
        print("yes")
    else:
        print("no")

Body:
Set the output_type to "array":

detected_image_array, detections = detector.detectObjectsFromImage(output_type="array", input_image="image.jpg" ) # For numpy array output type

Described in the docs: https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/Detection/README.md

Note: You can also set the input_type to "array".


问:
What browser features/plugins for opera, IE, firefox, chrome, safari, etc. do you use for browser compatibility testing?
I use the Nightly Tester Tools for Firefox and Fiddler for IE. What do you use?</p>

答: Web Developer toolbar for Firefox, Visual Studio JIT debugger for IE, and Chrome's Resource Inspector.  We don't use Opera for debugging due to the aforementioned tools, but we do take a look at our stuff to make sure it looks correct in Opera to be on the safe side.</p>

OwnerDisplayName: not-bob

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: moocha

OwnerDisplayName: Sukasa


问:
Populating several values in an empty column in a row, based on a value from another column
I already have an idea as to how I'm going to do this - I'm just curious about whether my method is the most efficient.

So for instance, let's say that for whatever reason, I have the following table:

The first 4 columns in the table are all repeated - they just say info about the employee. The reason these rows repeat is because that employee handles multiple clients.

In some cases, I am missing info on the Age and Employee duration of an employee. Another colleague gave me this information in an excel sheet.

So now, I have info on Brian's and Dennis' age and employment duration, and I need to fill all rows with their employee IDs based on the information. My plan for doing that is this:

```<code>data = {"14": # Brian's Employee ID
{"Age":31,
:"Employment Duration":3},
"21": # Dennis' Employee ID
{"Age":45,
"Employment Duratiaon":12}
}
</code>```

After making the above dictionary of dictionaries with the necessary values, my plan is to iterate over each row in the above dataframe, and fill in the 'Age' and 'Employment Duration' columns based on the value in 'Employee ID':

```<code>for index, row in df.iterrows:
if row["Employee ID"] in data:
    row["Age"] = data["Employee ID"]["Age"]
    row["Employment Duration"] = data["Employee ID"]["Employement Duration"]
</code>```

That's my plan for populating the missing values!

I'm curious about whether there's a simpler way that's just not presenting itself to me, because this was the first thing that sprang to mind!

答:
Ensure missing values are represented as null values (np.NaN). The second set of information should be stored in another DataFrame with the same column labels.

Then by setting the Index to the 'Employee ID' update will align on the indices and fill the missing values.

Sample Data

```<code>import pandas as pd
import numpy as np

df = pd.DataFrame({'Employee ID': ["11", "11", "14", "21"],
                   'Name': ['Alan', 'Alan', 'Brian', 'Dennis'],
                   'Age': [14,14, np.NaN, np.NaN],
                   'Employment Duration': [3,3, np.NaN, np.NaN],
                   'Clients Handled': ['A', 'B', 'C', 'G']})
data = {"14": {"Age": 31, "Employment Duration": 3},
        "21": {"Age": 45, "Employment Duration": 12}}

df2 = pd.DataFrame.from_dict(data, orient='index')
</code>```

Code

```<code>#df = df.replace('', np.NaN) # If not null in your dataset
df = df.set_index('Employee ID')

df.update(df2, overwrite=False)
print(df)

               Name   Age  Employment Duration Clients Handled
Employee ID
11             Alan  14.0                  3.0                A
11             Alan  14.0                  3.0                B
14            Brian  31.0                  3.0                C
21           Dennis  45.0                 12.0                G
</code>```

Body:
I already have an idea as to how I'm going to do this - I'm just curious about whether my method is the most efficient.

So for instance, let's say that for whatever reason, I have the following table:

The first 4 columns in the table are all repeated - they just say info about the employee. The reason these rows repeat is because that employee handles multiple clients.

In some cases, I am missing info on the Age and Employee duration of an employee. Another colleague gave me this information in an excel sheet.

So now, I have info on Brian's and Dennis' age and employment duration, and I need to fill all rows with their employee IDs based on the information. My plan for doing that is this:

data = {"14": # Brian's Employee ID
{"Age":31,
:"Employment Duration":3},
"21": # Dennis' Employee ID
{"Age":45,
"Employment Duratiaon":12}
}

After making the above dictionary of dictionaries with the necessary values, my plan is to iterate over each row in the above dataframe, and fill in the 'Age' and 'Employment Duration' columns based on the value in 'Employee ID':

for index, row in df.iterrows:
if row["Employee ID"] in data:
    row["Age"] = data["Employee ID"]["Age"]
    row["Employment Duration"] = data["Employee ID"]["Employement Duration"]

That's my plan for populating the missing values!

I'm curious about whether there's a simpler way that's just not presenting itself to me, because this was the first thing that sprang to mind!

Body:
Ensure missing values are represented as null values (np.NaN). The second set of information should be stored in another DataFrame with the same column labels.

Then by setting the Index to the 'Employee ID' update will align on the indices and fill the missing values.

Sample Data

import pandas as pd
import numpy as np

df = pd.DataFrame({'Employee ID': ["11", "11", "14", "21"],
                   'Name': ['Alan', 'Alan', 'Brian', 'Dennis'],
                   'Age': [14,14, np.NaN, np.NaN],
                   'Employment Duration': [3,3, np.NaN, np.NaN],
                   'Clients Handled': ['A', 'B', 'C', 'G']})
data = {"14": {"Age": 31, "Employment Duration": 3},
        "21": {"Age": 45, "Employment Duration": 12}}

df2 = pd.DataFrame.from_dict(data, orient='index')

Code

#df = df.replace('', np.NaN) # If not null in your dataset
df = df.set_index('Employee ID')

df.update(df2, overwrite=False)
print(df)

               Name   Age  Employment Duration Clients Handled
Employee ID
11             Alan  14.0                  3.0                A
11             Alan  14.0                  3.0                B
14            Brian  31.0                  3.0                C
21           Dennis  45.0                 12.0                G


问:
How to make drop shadow for shape in Android?
I'm trying to design a shape so that it has a drop shadow like on the picture below(that login shape).

答:
Try using this github project by including dependency </p>

```<code>compile 'com.h6ah4i.android.materialshadowninepatch:materialshadowninepatch:1.0.0'
</code>```

Body:
Try using this github project by including dependency

compile 'com.h6ah4i.android.materialshadowninepatch:materialshadowninepatch:1.0.0'


问:
LINQ- filer as required model and add a list to the select statement
I need to access to the following list.
Mainlist - contains equipmentlist and it will display with the following model.

```<code>public class BTypeModel
{
    public string Image { get; set; }
    public int? id { get; set; }
    public string bName { get; set; }
    public string alterName { get; set; }
    public string number { get; set; }
    public List<MainEquipment> equipment { get; set; }
    public string displayName { get; set; }

}

public class MainEquipment
{
    public int id { get; set; }
    public string name { get; set; }

}
</code>```

My issue is that I can not access the equipemnt list

see as follow

```<code>var available = MainList
     .Where(o => o.bType?.id == placeid)
     .Select(s => new BTypeModel {
      displayName = s.Type.name,
      id = s.id,
      number = s.number,
      Image = s.files.FirstOrDefault()?.Image,
      alterName = s.alternateName,
      equipment=s.mainequipmentlist.Select(a=>a.id), *
</code>```

//The select is what gives the error. no matter if I select the int or the string the error is the same just change

'System.Collections.Generic.IEnumerable' Cannot implicitly
  convert type 'System.Collections.Generic.IEnumerable' to to
  'System.Collections.Generic.List'. An
  explicit conversion exists (are you missing a cast?)

```<code>equipment=s.mainequipmentlist.Select(a=>a.id)
</code>```

I can't get it to display this list -** error is can convert int to a generic list- **

答:
I used this as reference

convert ienumerable linq list to typed list

instead of this

equipment=s.mainequipmentlist.Select(a=>a.id),

do this - convert to a model

```<code>equipment = s.mainequipmentlist.Select(p => new BTypeModel {name= p.name ,id=p.id }).ToList()
</code>```

Body:
I need to access to the following list.
Mainlist - contains equipmentlist and it will display with the following model.

public class BTypeModel
{
    public string Image { get; set; }
    public int? id { get; set; }
    public string bName { get; set; }
    public string alterName { get; set; }
    public string number { get; set; }
    public List<MainEquipment> equipment { get; set; }
    public string displayName { get; set; }

}

public class MainEquipment
{
    public int id { get; set; }
    public string name { get; set; }

}

My issue is that I can not access the equipemnt list

see as follow

var available = MainList
     .Where(o => o.bType?.id == placeid)
     .Select(s => new BTypeModel {
      displayName = s.Type.name,
      id = s.id,
      number = s.number,
      Image = s.files.FirstOrDefault()?.Image,
      alterName = s.alternateName,
      equipment=s.mainequipmentlist.Select(a=>a.id), *

//The select is what gives the error. no matter if I select the int or the string the error is the same just change

'System.Collections.Generic.IEnumerable' Cannot implicitly
  convert type 'System.Collections.Generic.IEnumerable' to to
  'System.Collections.Generic.List'. An
  explicit conversion exists (are you missing a cast?)

equipment=s.mainequipmentlist.Select(a=>a.id)

I can't get it to display this list -** error is can convert int to a generic list- **

Body:
I used this as reference

convert ienumerable linq list to typed list

instead of this

equipment=s.mainequipmentlist.Select(a=>a.id),

do this - convert to a model

equipment = s.mainequipmentlist.Select(p => new BTypeModel {name= p.name ,id=p.id }).ToList()


问:
COUNT the active user and in active user in database
I have a problem with the number of active and inactive users in the database by C# and ASP.net. We have two value in statues "active" and "inactive". I want label "none" to show the count of active users and label "inone" label to show the inactive.</p>

```<code>  private void countactivelUser()
    {
        //string queryString = "SELECT COUNT(*) AS [status]   from users ";
        string queryString = "select  COUNT(*) AS [status]   from users ";

        try
        {
            using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ToString()))
            {
                con.Open();
                //var da = new SqlDataAdapter("SELECT COUNT(*)  From users Order By Id desc", con);
                SqlCommand cmd = new SqlCommand(queryString, con);
                SqlDataReader dr = cmd.ExecuteReader();

                //cmd.Parameters["@status"].Value = "active";

                int a = Convert.ToInt32(cmd.ExecuteScalar());
                none.Text = a.ToString();// this show activeuser
                inone.Text = a.ToString(); // this show inactive user

                con.Close();
            }
        }
    }
</code>```

答:
I'll guess the column is called status.
You're counting all of the statuses. So your query needs to count based on status type:

```<code>SELECT status,COUNT(status) FROM users GROUP BY status
</code>```

You should then get multiple rows with counts based on whatever statuses you have.

For the reset you probably want to use ExecuteReader (example there)

Body:
I have a problem with the number of active and inactive users in the database by C# and ASP.net. We have two value in statues "active" and "inactive". I want label "none" to show the count of active users and label "inone" label to show the inactive.

  private void countactivelUser()
    {
        //string queryString = "SELECT COUNT(*) AS [status]   from users ";
        string queryString = "select  COUNT(*) AS [status]   from users ";

        try
        {
            using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ToString()))
            {
                con.Open();
                //var da = new SqlDataAdapter("SELECT COUNT(*)  From users Order By Id desc", con);
                SqlCommand cmd = new SqlCommand(queryString, con);
                SqlDataReader dr = cmd.ExecuteReader();

                //cmd.Parameters["@status"].Value = "active";

                int a = Convert.ToInt32(cmd.ExecuteScalar());
                none.Text = a.ToString();// this show activeuser
                inone.Text = a.ToString(); // this show inactive user

                con.Close();
            }
        }
    }

Body:
I'll guess the column is called status.
You're counting all of the statuses. So your query needs to count based on status type:

SELECT status,COUNT(status) FROM users GROUP BY status

You should then get multiple rows with counts based on whatever statuses you have.

For the reset you probably want to use ExecuteReader (example there)


问:
How to shrink an array in C?
Having this snippet

```<code>int main() {

  char *obstacles[3*3]

  char map[3][3] = {'D','*',' ',' ',' ',' ','*',' ',' '};

  int k = 0;

  for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
      if (map[i][j] == '*')
        obstacles[k++] = &map[i][j];
    }
  }
  return 0;
}
</code>```

Leads to me to this situation:

How do I shrink this array to a k-cells array?

答:
If your array is declared with a fixed size, there's nothing you can do about it. Its size is chosen at compile time and you have no way of modifying that when the program runs. What you can do however is to use malloc() and realloc(), if you really wish to do so. I don't really see a good reason to do that though: it's only 9 pointers, you're not going to have any advantage in reducing that.

You can initialize the array as char *obstacles[3*3] = {NULL} (all cells set to NULL) and then later stop at the first NULL cell when scanning it. This is a common way to avoid passing around the size of the array.

Title: How to shrink an array in C?

Body:
Having this snippet

int main() {

  char *obstacles[3*3]

  char map[3][3] = {'D','*',' ',' ',' ',' ','*',' ',' '};

  int k = 0;

  for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
      if (map[i][j] == '*')
        obstacles[k++] = &map[i][j];
    }
  }
  return 0;
}

Leads to me to this situation:

How do I shrink this array to a k-cells array?


问:
How to make SVD recommendations
I'm trying to use SVD to make book recommendations based on purchases. I'm using a matrix where the columns are the books, the rows are the usernames and the content if he/she purchased the book in question (1 if the user did or 0 if he didn't [I don't know if this is the best option]).
I've also created a cosine_similarity matrix where I can see the similarity between users based on their purchases.

```<code># Matrix with users as rows, products as columns and count as content
df_matrix = pd.pivot_table(order_df, values='count', index='username', columns='product')
# Replace all NaN contents with 0
df_matrix_dummy = df_matrix.copy().fillna(0)
#Compute the cosine similarity matrix using the dummy matrix
cosine_sim = cosine_similarity(df_matrix_dummy, df_matrix_dummy)
#Convert into pandas dataframe
cosine_sim = pd.DataFrame(cosine_sim, index=df_matrix.index, columns=df_matrix.index)

reader = Reader()
# Famous SVD algorithm
algo = SVDpp()
data = Dataset.load_from_df(order_df[['username', 'product', 'count']], reader)
# Divide the data into train and test (80-20)
trainset, testset = train_test_split(data, test_size=0.2)
algo.train(trainset)
</code>```

As I'm new with this kind of technology my question here is how to get a list of recommendations after training the SVD.

答:
You can follow this example and integrate it with your code.

```<code>from surprise import SVD
from surprise import Dataset
from surprise import accuracy
from surprise.model_selection import train_test_split

# Load the movielens-100k dataset (download it if needed),
data = Dataset.load_builtin('ml-100k')

trainset, testset = train_test_split(data, test_size=.25)

algo = SVD()
algo.fit(trainset)
predictions = algo.test(testset)
test = pd.DataFrame(predictions)
test = test.rename(columns={'uid':'userId', 'iid': 'movieId',
                            'r_ui':'actual', 'est':'prediction'})
cf_model = test.pivot_table(index='userId',
                            columns='movieId', values='prediction').fillna(0)

def get_users_predictions(user_id, n, model):
    recommended_items = pd.DataFrame(model.loc[user_id])
    recommended_items.columns = ["predicted_rating"]
    recommended_items = recommended_items.sort_values('predicted_rating', ascending=False)
    recommended_items = recommended_items.head(n)
    return recommended_items.index.tolist()

def get_recs(model, k):
    recs = []
    for user in model.index:
        cf_predictions = get_users_predictions(user, k, model)
        recs.append(cf_predictions)
    return recs

# Top-10 recommendations for each user
k = 10
recs = get_recs(cf_model, k)
preds = pd.DataFrame(index=cf_model.index)
preds[f'Top-{k} Recommendation'] = recs
preds.head()
</code>```

Output:

```<code>|   userId | Top-10 Recommendation                                                     |
|---------:|:--------------------------------------------------------------------------|
|        1 | ['50', '174', '173', '268', '183', '89', '64', '251', '100', '136']       |
|       10 | ['174', '178', '98', '530', '474', '511', '478', '132', '493', '709']     |
|      100 | ['887', '292', '1235', '268', '1238', '348', '1234', '271', '326', '886'] |
|      101 | ['181', '742', '237', '596', '405', '118', '255', '1028', '717', '928']   |
|      102 | ['50', '98', '96', '187', '168', '79', '530', '435', '228', '185']        |
</code>```

Title: How to make SVD recommendations

Body:
I'm trying to use SVD to make book recommendations based on purchases. I'm using a matrix where the columns are the books, the rows are the usernames and the content if he/she purchased the book in question (1 if the user did or 0 if he didn't [I don't know if this is the best option]).
I've also created a cosine_similarity matrix where I can see the similarity between users based on their purchases.

# Matrix with users as rows, products as columns and count as content
df_matrix = pd.pivot_table(order_df, values='count', index='username', columns='product')
# Replace all NaN contents with 0
df_matrix_dummy = df_matrix.copy().fillna(0)
#Compute the cosine similarity matrix using the dummy matrix
cosine_sim = cosine_similarity(df_matrix_dummy, df_matrix_dummy)
#Convert into pandas dataframe
cosine_sim = pd.DataFrame(cosine_sim, index=df_matrix.index, columns=df_matrix.index)

reader = Reader()
# Famous SVD algorithm
algo = SVDpp()
data = Dataset.load_from_df(order_df[['username', 'product', 'count']], reader)
# Divide the data into train and test (80-20)
trainset, testset = train_test_split(data, test_size=0.2)
algo.train(trainset)

As I'm new with this kind of technology my question here is how to get a list of recommendations after training the SVD.

Body:
You can follow this example and integrate it with your code.

from surprise import SVD
from surprise import Dataset
from surprise import accuracy
from surprise.model_selection import train_test_split

# Load the movielens-100k dataset (download it if needed),
data = Dataset.load_builtin('ml-100k')

trainset, testset = train_test_split(data, test_size=.25)

algo = SVD()
algo.fit(trainset)
predictions = algo.test(testset)
test = pd.DataFrame(predictions)
test = test.rename(columns={'uid':'userId', 'iid': 'movieId',
                            'r_ui':'actual', 'est':'prediction'})
cf_model = test.pivot_table(index='userId',
                            columns='movieId', values='prediction').fillna(0)

def get_users_predictions(user_id, n, model):
    recommended_items = pd.DataFrame(model.loc[user_id])
    recommended_items.columns = ["predicted_rating"]
    recommended_items = recommended_items.sort_values('predicted_rating', ascending=False)
    recommended_items = recommended_items.head(n)
    return recommended_items.index.tolist()

def get_recs(model, k):
    recs = []
    for user in model.index:
        cf_predictions = get_users_predictions(user, k, model)
        recs.append(cf_predictions)
    return recs

# Top-10 recommendations for each user
k = 10
recs = get_recs(cf_model, k)
preds = pd.DataFrame(index=cf_model.index)
preds[f'Top-{k} Recommendation'] = recs
preds.head()

Output:

|   userId | Top-10 Recommendation                                                     |
|---------:|:--------------------------------------------------------------------------|
|        1 | ['50', '174', '173', '268', '183', '89', '64', '251', '100', '136']       |
|       10 | ['174', '178', '98', '530', '474', '511', '478', '132', '493', '709']     |
|      100 | ['887', '292', '1235', '268', '1238', '348', '1234', '271', '326', '886'] |
|      101 | ['181', '742', '237', '596', '405', '118', '255', '1028', '717', '928']   |
|      102 | ['50', '98', '96', '187', '168', '79', '530', '435', '228', '185']        |


问:
read indefinite amount of integers until one is negative and then print them
I am new to pointers so I tried inventing this simple problem. why is it not working? other than saying what mistake I made I'd greatly appreciate if you guys could tell me an alternative to this method    </p>

```<code>#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    int *p;
    int i, j;
    i = 0;
    p = (int *)malloc(sizeof(int) * (i + 1));
    scanf("%d", p);
    do {
        i++;
        p = realloc(p, sizeof(int) * i);
        scanf("%d", (p + i));
    } while (*(p + i) > 0);

    for (j = 0; j < i; j++) {
        printf("%d\n", *(p + j));
    }
    free(p);
    return 0;
}
</code>```

答:
This statement

```<code>p=(int *)malloc(sizeof(int) * (i+1));
</code>```

is redundant. It is better to write

```<code>p = NULL;
</code>```

And in a call of scanf use an object of the type int not the pointer.

There can be redundant memory allocation if for example the first entered value will be negative

In this call

```<code>    scanf("%d", (p+i));
</code>```

there is an access beyond the allocated memory. You should at least write

```<code>    scanf("%d", (p + i -1));
</code>```

It is better to specify an intermediate pointer in this statement

```<code>    p=realloc(p,sizeof(int)*i);
</code>```

because the function can return NULL. In this case the address of the previously allocated memory will be lost.

And the condition in the loop

```<code>}while(*(p+i)>0);
</code>```

does not check that the value is not negative.

The program can look the following way

```<code>#include <stdio.h>
#include <stdlib.h>

int main( void )
{
    int *p = NULL;
    size_t n = 0;
    int value;

    for ( int *tmp;
          scanf( "%d", &value ) == 1 &&
          !( value < 0 ) &&
          ( tmp = realloc( p, ( n + 1 ) * sizeof( int ) ) ) != NULL;
          ++n )
    {
        p = tmp;
        *( p + n ) = value;
    }

    for ( size_t i = 0; i < n; i++ )
    {
        printf( "%d ", *( p + i ) );
    }

    putchar( '\n' );

    free( p );

    return 0;
}
</code>```

If to enter

```<code>0 1 2 3 4 5 6 7 8 9 -1
</code>```

the program output will be

```<code>0 1 2 3 4 5 6 7 8 9
</code>```

Body:
I am new to pointers so I tried inventing this simple problem. why is it not working? other than saying what mistake I made I'd greatly appreciate if you guys could tell me an alternative to this method

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    int *p;
    int i, j;
    i = 0;
    p = (int *)malloc(sizeof(int) * (i + 1));
    scanf("%d", p);
    do {
        i++;
        p = realloc(p, sizeof(int) * i);
        scanf("%d", (p + i));
    } while (*(p + i) > 0);

    for (j = 0; j < i; j++) {
        printf("%d\n", *(p + j));
    }
    free(p);
    return 0;
}

Body:
This statement

p=(int *)malloc(sizeof(int) * (i+1));

is redundant. It is better to write

p = NULL;

And in a call of scanf use an object of the type int not the pointer.

There can be redundant memory allocation if for example the first entered value will be negative

In this call

    scanf("%d", (p+i));

there is an access beyond the allocated memory. You should at least write

    scanf("%d", (p + i -1));

It is better to specify an intermediate pointer in this statement

    p=realloc(p,sizeof(int)*i);

because the function can return NULL. In this case the address of the previously allocated memory will be lost.

And the condition in the loop

}while(*(p+i)>0);

does not check that the value is not negative.

The program can look the following way

#include <stdio.h>
#include <stdlib.h>

int main( void )
{
    int *p = NULL;
    size_t n = 0;
    int value;

    for ( int *tmp;
          scanf( "%d", &value ) == 1 &&
          !( value < 0 ) &&
          ( tmp = realloc( p, ( n + 1 ) * sizeof( int ) ) ) != NULL;
          ++n )
    {
        p = tmp;
        *( p + n ) = value;
    }

    for ( size_t i = 0; i < n; i++ )
    {
        printf( "%d ", *( p + i ) );
    }

    putchar( '\n' );

    free( p );

    return 0;
}

If to enter

0 1 2 3 4 5 6 7 8 9 -1

the program output will be

0 1 2 3 4 5 6 7 8 9


问:
laravel: grabbing query param value in controller?
I have am adding the query param ?order=921 to my request and when I check log_info($request), I see this:

```<code>Pragma:          no-cache
Referer:         https://local/admin/inquire?order=219
Sec-Fetch-Mode:  cors
Sec-Fetch-Site:  same-origin
</code>```

I know $request->getQueryString() will grab me order=219 but is there anyway to just grab the value of order without having to get $request->getQueryString() and parsing that?

I have tried to log log_info($request->order) but nothing shows up for it.

答: you can use $request->order to do that.

Body:
I have am adding the query param ?order=921 to my request and when I check log_info($request), I see this:

Pragma:          no-cache
Referer:         https://local/admin/inquire?order=219
Sec-Fetch-Mode:  cors
Sec-Fetch-Site:  same-origin

I know $request->getQueryString() will grab me order=219 but is there anyway to just grab the value of order without having to get $request->getQueryString() and parsing that?

I have tried to log log_info($request->order) but nothing shows up for it.

Body: you can use $request->order to do that.