问:
Unable to get HTML code when web scraping Instagram Error 429
I am trying to web scrape Instagram accounts to find out how many posts they have (visible on all public and private profiles). I am writing a script to do so.

I tried using the requests library to obtain the HTML code, but when running this below:

```<code>import requests

url = 'https://www.instagram.com/instagram/'
r = requests.get(url)
print(r)
print(r.text)
</code>```

I keep getting the 429 too many requests error even though I have sent less than 10 total (I am manually running the script). I also tried following https://stackoverflow.com/questions/22786068/how-to-avoid-http-error-429-too-many-requests-python#:~:text=Writing%20this%20piece,your%20bot%200.1'%7D) and using requests.get(link, headers = {'User-agent': 'your bot 0.1'}) but that also does not work.

Body:
I am trying to web scrape Instagram accounts to find out how many posts they have (visible on all public and private profiles). I am writing a script to do so.

I tried using the requests library to obtain the HTML code, but when running this below:

import requests

url = 'https://www.instagram.com/instagram/'
r = requests.get(url)
print(r)
print(r.text)

I keep getting the 429 too many requests error even though I have sent less than 10 total (I am manually running the script). I also tried following https://stackoverflow.com/questions/22786068/how-to-avoid-http-error-429-too-many-requests-python#:~:text=Writing%20this%20piece,your%20bot%200.1'%7D) and using requests.get(link, headers = {'User-agent': 'your bot 0.1'}) but that also does not work.


来源: stackexchange

问:
bad to have a DynamoDB schema design with 3 level nesting?
I'm new to DynamoDb and generally new to NoSql databases.
I'm currently playing arround with a simple webapplication which is written in asp.net core 6 an run on aws lambda.

I have posts which can be in different channels. Users can make comments on posts. Posts and Comments can be up/down voted.

When trying to implement voting on comments I started getting the feeling,
that my design is quite bad after reading for example the following question:
Update nested map dynamodb

The issue is that:

I can't update votes of a comment without knowing the array index

the array index is prone to race conditions when an older comment (with lower index therefore) is deleted

Current data structur (3 tables):

guids are saved as strings

```<code>post: {
    pk -> id
    sk -> id
    id : guid
    createdAt : date
    createdBy : guid // user.id
    comments: [
        {
            id : guid
            text : string
            createdAt : date
            createdBy : guid // user.id
            upvotedBy : guid[] // user ids
            downvotedBy : guid[] // user ids
            upvotes : int // aggregated count of above list
            downvotes : int
        },
        { ... },
        { ... },
        { ... },
    ]
    commentCount : int
    upvotedBy : guid[] // user ids
    downvotedBy : guid[] // user ids
    upvotes : int // aggregated count of above list
    downvotes : int
    channel : guid // channel.id
    hidden : bool
}

user: {
    pk -> id
    sk -> id
    id : guid
    username : string
    password : string
    createdAt : date
    subscribed_channels : guid[] // channel ids
}

channel: {
    pk -> id
    sk -> id
    id : guid / string
    channelname : string
}
</code>```

I have additional keys for:

```<code>    - posts
        - ChannelIndex   :   pk = channelname,  sk = createdAt
        - CreatedAtIndex :   pk = pk,           sk = createdAt
    - users
        - UsernameIndex :    pk = username,     sk = sk
    - channels
        - ChannelnameIndex : pk = channelname,  sk = sk
</code>```

Usecases (ordered by frequency):

Access all posts without comments

from multiple channels

from single channels

sorted by date

sorted by most comments

sorted by most likes

from all channels

Access single post with (all) comments

vote on comment

vote on post

create comment

create post

delete comment

delete post

Question:

How to improve this design from a performance but also from the ease of implementation side?

My ideas:
I thought about removing the nesting for comments making them a own table with a key beeing postId and createdAt
However this feels like the design for a relational database.

ContentLicense: CC BY-SA 4.0

Body:
I'm new to DynamoDb and generally new to NoSql databases.
I'm currently playing arround with a simple webapplication which is written in asp.net core 6 an run on aws lambda.

I have posts which can be in different channels. Users can make comments on posts. Posts and Comments can be up/down voted.

When trying to implement voting on comments I started getting the feeling,
that my design is quite bad after reading for example the following question:
Update nested map dynamodb

The issue is that:

I can't update votes of a comment without knowing the array index

the array index is prone to race conditions when an older comment (with lower index therefore) is deleted

Current data structur (3 tables):

guids are saved as strings

post: {
    pk -> id
    sk -> id
    id : guid
    createdAt : date
    createdBy : guid // user.id
    comments: [
        {
            id : guid
            text : string
            createdAt : date
            createdBy : guid // user.id
            upvotedBy : guid[] // user ids
            downvotedBy : guid[] // user ids
            upvotes : int // aggregated count of above list
            downvotes : int
        },
        { ... },
        { ... },
        { ... },
    ]
    commentCount : int
    upvotedBy : guid[] // user ids
    downvotedBy : guid[] // user ids
    upvotes : int // aggregated count of above list
    downvotes : int
    channel : guid // channel.id
    hidden : bool
}

user: {
    pk -> id
    sk -> id
    id : guid
    username : string
    password : string
    createdAt : date
    subscribed_channels : guid[] // channel ids
}

channel: {
    pk -> id
    sk -> id
    id : guid / string
    channelname : string
}

I have additional keys for:

    - posts
        - ChannelIndex   :   pk = channelname,  sk = createdAt
        - CreatedAtIndex :   pk = pk,           sk = createdAt
    - users
        - UsernameIndex :    pk = username,     sk = sk
    - channels
        - ChannelnameIndex : pk = channelname,  sk = sk

Usecases (ordered by frequency):

Access all posts without comments

from multiple channels

from single channels

sorted by date

sorted by most comments

sorted by most likes

from all channels

Access single post with (all) comments

vote on comment

vote on post

create comment

create post

delete comment

delete post

Question:

How to improve this design from a performance but also from the ease of implementation side?

My ideas:
I thought about removing the nesting for comments making them a own table with a key beeing postId and createdAt
However this feels like the design for a relational database.


问:
How to record audio while OpenCv has enabled camera
I want to record the audio and store the same while analyzing the emotion using Opencv. But unfortunately, the audio which is being recorded is of minimal length and the voice is also not clear. I want to analyze the voice emotion too for which I need to audio. Could somebody help me in resolving the same?</p>
```<code>def main():

  cap = cv2.VideoCapture(0)
  cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
  cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)

  p = pyaudio.PyAudio()
  stream = p.open(format=audio_format, channels=channels,rate=16000, input=True,frames_per_buffer=1024)

  start_time = time.time()
  aud = True

  while aud:

    ret, frame = cap.read()

    data = stream.read(chunk, exception_on_overflow = False)
    frames.append(data)

    if not ret:
        break

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors= 5, flags=cv2.CASCADE_SCALE_IMAGE)
    result = DeepFace.analyze(img_path = frame , actions = ["emotion"], enforce_detection=False,detector_backend='ssd')

    for (x,y,w,h) in faces:

        if w > 130: #trick: ignore small faces

            draw_border(frame, (x, y), (x + w, y + h), (255, 0, 105),4, 15, 10) ## draw rectangle around face.
            detected_face = frame[int(y):int(y+h), int(x):int(x+w)] #crop detected face
            detected_face = cv2.cvtColor(detected_face, cv2.COLOR_BGR2GRAY) #transform to gray scale
            detected_face = cv2.resize(detected_face, (48, 48)) #resize to 48x48
            img_pixels = img_to_array(detected_face)
            img_pixels = np.expand_dims(img_pixels, axis = 0)
            img_pixels /= 255 #pixels are in scale of [0, 255]. normalize all pixels in scale of [0, 1]

    emotion = result["dominant_emotion"]

    txt = str(emotion)

    cv2.putText(frame,txt,(50,50),cv2.FONT_HERSHEY_SIMPLEX,1,(0,0,255),3)

    cv2.imshow(file, frame)

    if cv2.waitKey(1) & 0xFF == ord("q"):
        aud=False
        break

stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open('/Users/xyz/Documents/Audio/wv.wav', 'wb')
wf.setnchannels(1)
wf.setsampwidth(p.get_sample_size(audio_format))

wf.setframerate(sample_rate)
wf.writeframes(b''.join(frames))
wf.close()

cap.release()
cv2.destroyAllWindows()
</code>```

Body:
I want to record the audio and store the same while analyzing the emotion using Opencv. But unfortunately, the audio which is being recorded is of minimal length and the voice is also not clear. I want to analyze the voice emotion too for which I need to audio. Could somebody help me in resolving the same?

def main():

  cap = cv2.VideoCapture(0)
  cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
  cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)

  p = pyaudio.PyAudio()
  stream = p.open(format=audio_format, channels=channels,rate=16000, input=True,frames_per_buffer=1024)

  start_time = time.time()
  aud = True

  while aud:

    ret, frame = cap.read()

    data = stream.read(chunk, exception_on_overflow = False)
    frames.append(data)

    if not ret:
        break

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors= 5, flags=cv2.CASCADE_SCALE_IMAGE)
    result = DeepFace.analyze(img_path = frame , actions = ["emotion"], enforce_detection=False,detector_backend='ssd')

    for (x,y,w,h) in faces:

        if w > 130: #trick: ignore small faces

            draw_border(frame, (x, y), (x + w, y + h), (255, 0, 105),4, 15, 10) ## draw rectangle around face.
            detected_face = frame[int(y):int(y+h), int(x):int(x+w)] #crop detected face
            detected_face = cv2.cvtColor(detected_face, cv2.COLOR_BGR2GRAY) #transform to gray scale
            detected_face = cv2.resize(detected_face, (48, 48)) #resize to 48x48
            img_pixels = img_to_array(detected_face)
            img_pixels = np.expand_dims(img_pixels, axis = 0)
            img_pixels /= 255 #pixels are in scale of [0, 255]. normalize all pixels in scale of [0, 1]

    emotion = result["dominant_emotion"]

    txt = str(emotion)

    cv2.putText(frame,txt,(50,50),cv2.FONT_HERSHEY_SIMPLEX,1,(0,0,255),3)

    cv2.imshow(file, frame)

    if cv2.waitKey(1) & 0xFF == ord("q"):
        aud=False
        break

stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open('/Users/xyz/Documents/Audio/wv.wav', 'wb')
wf.setnchannels(1)
wf.setsampwidth(p.get_sample_size(audio_format))

wf.setframerate(sample_rate)
wf.writeframes(b''.join(frames))
wf.close()

cap.release()
cv2.destroyAllWindows()


问:
Print list view from Array Adapter in Android Studio
I'm trying to print a return statement (exercises) to a list view so that I can see it on the screen.

When I use the     listView.setAdapter(adapter) code, there is an error that Cannot resolve symbol 'setAdapter' and also Unknown class: 'adapter'. However, I had defined the array adaptor in line     ArrayAdapter adapter = new ArrayAdapter(this, R.layout.exercise_item, exercises).

I have the correct import statements I believe

Pasting the full code below

```<code>package com.example.fit_world;

import static java.security.AccessController.getContext;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.ListView;

import android.content.Intent;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import com.example.fit_world.Exercise;

public class GenerateWorkout extends AppCompatActivity {
    private static final String DATABASE_NAME = "Exercises.db";
    private SQLiteDatabase database;
    String equipmentType = "None";
    String difficultyType = "Easy";
    String weightGoalType = "Weight Loss";

    private void copyDatabaseToInternalStorage() {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            // Open the database file in the assets folder
            AssetManager assetManager = getAssets();
            inputStream = assetManager.open(DATABASE_NAME);
            if (inputStream == null) {
                throw new IOException("Failed to open file: " + DATABASE_NAME);
            }

            // Generate a unique file name for the database in the internal storage
            File outputFile = new File(getFilesDir(), "Exercises_" + System.currentTimeMillis() + ".db");

            // Check if the file already exists in the internal storage
            if (outputFile.exists()) {
                // Delete the file if it already exists
                outputFile.delete();
            }

            outputStream = new FileOutputStream(outputFile);

            // Copy the database file from the assets folder to the internal storage
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // Close the streams
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

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

        List<Exercise> exercises = getExercisesFromDatabase(equipmentType, difficultyType, weightGoalType);
        for (Exercise exercise : exercises) {
            Log.d("LOL", exercise.toString());
        }
    }

    private List<Exercise> exercises;

    private List<Exercise> getExercisesFromDatabase(String equipmentType, String difficultyType, String weightGoalType) {
        // Check if the database file exists in the internal storage
        File databaseFile = new File(getFilesDir(), DATABASE_NAME);
        if (!databaseFile.exists()) {
            // If the database file does not exist, copy it from the assets folder
            copyDatabaseToInternalStorage();
        }

        // Open the database file in the internal storage
        SQLiteDatabase database = null;
        Cursor cursor = null;
        try {
            // Open the database file in the internal storage
            database = openOrCreateDatabase("Exercises.db", MODE_PRIVATE, null);

            // Execute the query to retrieve the list of exercises
            String query = "SELECT * FROM Exercises WHERE required_equipment = ? AND difficulty = ? AND weight_goal = ?";
            String[] selectionArgs = new String[]{equipmentType, difficultyType, weightGoalType};
            cursor = database.rawQuery(query, selectionArgs);
            DatabaseUtils.dumpCursor(cursor);
            int rowCount = cursor.getCount();
            System.out.print(rowCount);
            Log.d("TAG", "Row count: " + rowCount);
            Log.d("MMM", "Row count: " + database.rawQuery("SELECT * FROM exercises", null).getCount());

            // Iterate through the result set and create a list of exercises
            while (cursor.moveToNext()) {
                int idColumnIndex = cursor.getColumnIndex("id");
                int nameColumnIndex = cursor.getColumnIndex("name");
                int descriptionColumnIndex = cursor.getColumnIndex("description");
                int difficultyColumnIndex = cursor.getColumnIndex("difficulty");
                int exercisetypeIndex = cursor.getColumnIndex("exercise_type");
                int weightGoalColumnIndex = cursor.getColumnIndex("weight_goal");
                int requiredEquipmentColumnIndex = cursor.getColumnIndex("required_equipment");
                int numberOfRepsColumnIndex = cursor.getColumnIndex("number_of_reps");
                if (idColumnIndex != -1 && nameColumnIndex != -1 && descriptionColumnIndex != -1 && exercisetypeIndex != -1 &&
                        difficultyColumnIndex != -1 && weightGoalColumnIndex != -1 && requiredEquipmentColumnIndex != -1 &&
                        numberOfRepsColumnIndex != -1) {
                    int id = cursor.getInt(idColumnIndex);
                    String name = cursor.getString(nameColumnIndex);
                    String description = cursor.getString(descriptionColumnIndex);
                    String exercisetype = cursor.getString(exercisetypeIndex);
                    String difficulty = cursor.getString(difficultyColumnIndex);
                    String weightGoal = cursor.getString(weightGoalColumnIndex);
                    String requiredEquipment = cursor.getString(requiredEquipmentColumnIndex);
                    String numberOfReps = cursor.getString(numberOfRepsColumnIndex);
                    Exercise exercise = new Exercise(id, name, description, difficulty, weightGoal, requiredEquipment, exercisetype, numberOfReps);
                    exercises.add(exercise);

                    Log.d("TAG", "Exercise name: " + name);
                    Log.d("TAG", "Exercise description: " + description);
                    Log.d("TAG", "Number of exercises retrieved: " + exercises.size());

                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            Log.e("TAG", "Error accessing database: " + e.getMessage());
        } finally {
            // Close the cursor and database
            if (cursor != null) {
                cursor.close();
            }
            if (database != null) {
                database.close();
            }
        }
        return exercises;

    }

    // Get the ListView
    ListView listView = findViewById(R.id.list_view);

    // Create an ArrayAdapter
    ArrayAdapter<Exercise> adapter = new ArrayAdapter<Exercise>(this, R.layout.exercise_item, exercises) {
        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            // Get the exercise at the current position
            Exercise exercise = getItem(position);
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.exercise_item, parent, false);
            }

            // Get the views from the exercise_item.xml layout file
            TextView textViewName = convertView.findViewById(R.id.text_view_name);
            TextView textViewDescription = convertView.findViewById(R.id.text_view_description);

            // Set the text of the views
            textViewName.setText(exercise.getName());

            return convertView;
        }
    };

    // Set the adapter for the ListView
    listView.setAdapter(adapter);

}

</code>```

Also, I'm adding the dump of the logcat when trying to run the program without setting the adaptor for the listview

```<code>                                                                                Process: com.example.fit_world, PID: 10927
                                                                                java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.fit_world/com.example.fit_world.GenerateWorkout}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3194)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
                                                                                at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
                                                                                at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
                                                                                at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:107)
                                                                                at android.os.Looper.loop(Looper.java:214)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:7356)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
                                                                                Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
                                                                                at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:163)
                                                                                at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:174)
                                                                                at android.content.Context.obtainStyledAttributes(Context.java:738)
                                                                                at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:852)
                                                                                at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:819)
                                                                                at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:640)
                                                                                at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:261)
                                                                                at com.example.fit_world.GenerateWorkout.<init>(GenerateWorkout.java:181)
                                                                                at java.lang.Class.newInstance(Native Method)
                                                                                at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
                                                                                at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
                                                                                at android.app.Instrumentation.newActivity(Instrumentation.java:1243)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3182)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
                                                                                at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
                                                                                at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
                                                                                at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:107)
                                                                                at android.os.Looper.loop(Looper.java:214)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:7356)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
2023-01-07 11:22:44.721 10927-10927 Process                 com.example.fit_world                I  Sending signal. PID: 10927 SIG: 9
2023-01-07 11:22:44.846  2064-2167  InputDispatcher         system_process                       E  channel '8ad08ab com.example.fit_world/com.example.fit_world.LoginActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
2023-01-07 11:22:44.846  2064-2167  InputDispatcher         system_process                       E  channel 'afa41ba com.example.fit_world/com.example.fit_world.HomeActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
---------------------------- PROCESS ENDED (10927) for package com.example.fit_world ----------------------------
2023-01-07 11:22:44.846  2064-2167  InputDispatcher         system_process                       E  channel 'd2ba6a7 com.example.fit_world/com.example.fit_world.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
---------------------------- PROCESS STARTED (11005) for package com.example.fit_world ----------------------------```

I tried to print out the return statement using an ArrayAdaptor however there is an error on the   Set the adapter for the ListView.

```

Body:
I'm trying to print a return statement (exercises) to a list view so that I can see it on the screen.

When I use the     listView.setAdapter(adapter) code, there is an error that Cannot resolve symbol 'setAdapter' and also Unknown class: 'adapter'. However, I had defined the array adaptor in line     ArrayAdapter adapter = new ArrayAdapter(this, R.layout.exercise_item, exercises).

I have the correct import statements I believe

Pasting the full code below

package com.example.fit_world;

import static java.security.AccessController.getContext;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.ListView;

import android.content.Intent;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import com.example.fit_world.Exercise;

public class GenerateWorkout extends AppCompatActivity {
    private static final String DATABASE_NAME = "Exercises.db";
    private SQLiteDatabase database;
    String equipmentType = "None";
    String difficultyType = "Easy";
    String weightGoalType = "Weight Loss";

    private void copyDatabaseToInternalStorage() {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            // Open the database file in the assets folder
            AssetManager assetManager = getAssets();
            inputStream = assetManager.open(DATABASE_NAME);
            if (inputStream == null) {
                throw new IOException("Failed to open file: " + DATABASE_NAME);
            }

            // Generate a unique file name for the database in the internal storage
            File outputFile = new File(getFilesDir(), "Exercises_" + System.currentTimeMillis() + ".db");

            // Check if the file already exists in the internal storage
            if (outputFile.exists()) {
                // Delete the file if it already exists
                outputFile.delete();
            }

            outputStream = new FileOutputStream(outputFile);

            // Copy the database file from the assets folder to the internal storage
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // Close the streams
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

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

        List<Exercise> exercises = getExercisesFromDatabase(equipmentType, difficultyType, weightGoalType);
        for (Exercise exercise : exercises) {
            Log.d("LOL", exercise.toString());
        }
    }

    private List<Exercise> exercises;

    private List<Exercise> getExercisesFromDatabase(String equipmentType, String difficultyType, String weightGoalType) {
        // Check if the database file exists in the internal storage
        File databaseFile = new File(getFilesDir(), DATABASE_NAME);
        if (!databaseFile.exists()) {
            // If the database file does not exist, copy it from the assets folder
            copyDatabaseToInternalStorage();
        }

        // Open the database file in the internal storage
        SQLiteDatabase database = null;
        Cursor cursor = null;
        try {
            // Open the database file in the internal storage
            database = openOrCreateDatabase("Exercises.db", MODE_PRIVATE, null);

            // Execute the query to retrieve the list of exercises
            String query = "SELECT * FROM Exercises WHERE required_equipment = ? AND difficulty = ? AND weight_goal = ?";
            String[] selectionArgs = new String[]{equipmentType, difficultyType, weightGoalType};
            cursor = database.rawQuery(query, selectionArgs);
            DatabaseUtils.dumpCursor(cursor);
            int rowCount = cursor.getCount();
            System.out.print(rowCount);
            Log.d("TAG", "Row count: " + rowCount);
            Log.d("MMM", "Row count: " + database.rawQuery("SELECT * FROM exercises", null).getCount());

            // Iterate through the result set and create a list of exercises
            while (cursor.moveToNext()) {
                int idColumnIndex = cursor.getColumnIndex("id");
                int nameColumnIndex = cursor.getColumnIndex("name");
                int descriptionColumnIndex = cursor.getColumnIndex("description");
                int difficultyColumnIndex = cursor.getColumnIndex("difficulty");
                int exercisetypeIndex = cursor.getColumnIndex("exercise_type");
                int weightGoalColumnIndex = cursor.getColumnIndex("weight_goal");
                int requiredEquipmentColumnIndex = cursor.getColumnIndex("required_equipment");
                int numberOfRepsColumnIndex = cursor.getColumnIndex("number_of_reps");
                if (idColumnIndex != -1 && nameColumnIndex != -1 && descriptionColumnIndex != -1 && exercisetypeIndex != -1 &&
                        difficultyColumnIndex != -1 && weightGoalColumnIndex != -1 && requiredEquipmentColumnIndex != -1 &&
                        numberOfRepsColumnIndex != -1) {
                    int id = cursor.getInt(idColumnIndex);
                    String name = cursor.getString(nameColumnIndex);
                    String description = cursor.getString(descriptionColumnIndex);
                    String exercisetype = cursor.getString(exercisetypeIndex);
                    String difficulty = cursor.getString(difficultyColumnIndex);
                    String weightGoal = cursor.getString(weightGoalColumnIndex);
                    String requiredEquipment = cursor.getString(requiredEquipmentColumnIndex);
                    String numberOfReps = cursor.getString(numberOfRepsColumnIndex);
                    Exercise exercise = new Exercise(id, name, description, difficulty, weightGoal, requiredEquipment, exercisetype, numberOfReps);
                    exercises.add(exercise);

                    Log.d("TAG", "Exercise name: " + name);
                    Log.d("TAG", "Exercise description: " + description);
                    Log.d("TAG", "Number of exercises retrieved: " + exercises.size());

                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            Log.e("TAG", "Error accessing database: " + e.getMessage());
        } finally {
            // Close the cursor and database
            if (cursor != null) {
                cursor.close();
            }
            if (database != null) {
                database.close();
            }
        }
        return exercises;

    }

    // Get the ListView
    ListView listView = findViewById(R.id.list_view);

    // Create an ArrayAdapter
    ArrayAdapter<Exercise> adapter = new ArrayAdapter<Exercise>(this, R.layout.exercise_item, exercises) {
        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            // Get the exercise at the current position
            Exercise exercise = getItem(position);
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.exercise_item, parent, false);
            }

            // Get the views from the exercise_item.xml layout file
            TextView textViewName = convertView.findViewById(R.id.text_view_name);
            TextView textViewDescription = convertView.findViewById(R.id.text_view_description);

            // Set the text of the views
            textViewName.setText(exercise.getName());

            return convertView;
        }
    };

    // Set the adapter for the ListView
    listView.setAdapter(adapter);

}

Also, I'm adding the dump of the logcat when trying to run the program without setting the adaptor for the listview

                                                                                Process: com.example.fit_world, PID: 10927
                                                                                java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.fit_world/com.example.fit_world.GenerateWorkout}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3194)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
                                                                                at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
                                                                                at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
                                                                                at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:107)
                                                                                at android.os.Looper.loop(Looper.java:214)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:7356)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
                                                                                Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
                                                                                at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:163)
                                                                                at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:174)
                                                                                at android.content.Context.obtainStyledAttributes(Context.java:738)
                                                                                at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:852)
                                                                                at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:819)
                                                                                at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:640)
                                                                                at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:261)
                                                                                at com.example.fit_world.GenerateWorkout.<init>(GenerateWorkout.java:181)
                                                                                at java.lang.Class.newInstance(Native Method)
                                                                                at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
                                                                                at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
                                                                                at android.app.Instrumentation.newActivity(Instrumentation.java:1243)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3182)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
                                                                                at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
                                                                                at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
                                                                                at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:107)
                                                                                at android.os.Looper.loop(Looper.java:214)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:7356)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
2023-01-07 11:22:44.721 10927-10927 Process                 com.example.fit_world                I  Sending signal. PID: 10927 SIG: 9
2023-01-07 11:22:44.846  2064-2167  InputDispatcher         system_process                       E  channel '8ad08ab com.example.fit_world/com.example.fit_world.LoginActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
2023-01-07 11:22:44.846  2064-2167  InputDispatcher         system_process                       E  channel 'afa41ba com.example.fit_world/com.example.fit_world.HomeActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
---------------------------- PROCESS ENDED (10927) for package com.example.fit_world ----------------------------
2023-01-07 11:22:44.846  2064-2167  InputDispatcher         system_process                       E  channel 'd2ba6a7 com.example.fit_world/com.example.fit_world.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
---------------------------- PROCESS STARTED (11005) for package com.example.fit_world ----------------------------```

I tried to print out the return statement using an ArrayAdaptor however there is an error on the   Set the adapter for the ListView.


问:
Cropping the Mediabox does not work for some pdfs
I wrote a little script which shall blank out the lower half of a PDF document. The document itself shall remain the same size, but the lower half shall be just white.
(This is to remove the "instructions" part from parcel labels of German parcel comanies like DHL and Hermes.)

To do this, I take the PDF page, adjust the Mediabox, and then merge this page onto a new, blank page.

Fortunately, this works as intended with the PDFs I need it for. However, I also tried a few other PDFs and for some, it just does not work. It copies over the complete PDF. This happens for example, when my code is given this file: https://www.veeam.com/veeam_backup_product_overview_ds.pdf

Here is the code:

import pypdf   # PyPDF2, 3 and 4 are deprecated. PyPDF is currently in active development

reader = pypdf.PdfReader(source_filename)
writer = pypdf.PdfWriter()

# get first page
page = reader.pages[0]
# create new page
new_page = pypdf.PageObject.create_blank_page( None, width = page.mediabox.width, height = page.mediabox.height )
# crop original
page.mediabox.bottom = ( page.mediabox.top - page.mediabox.bottom ) / 2 + page.mediabox.bottom
# merge original into empty new page
new_page.merge_page( page )

writer.add_page(new_page)
with open(output_file, "wb") as fp:
    writer.write(fp)
```

Can anyone explain why it does not work sometimes?

Body:
I wrote a little script which shall blank out the lower half of a PDF document. The document itself shall remain the same size, but the lower half shall be just white.
(This is to remove the "instructions" part from parcel labels of German parcel comanies like DHL and Hermes.)

To do this, I take the PDF page, adjust the Mediabox, and then merge this page onto a new, blank page.

Fortunately, this works as intended with the PDFs I need it for. However, I also tried a few other PDFs and for some, it just does not work. It copies over the complete PDF. This happens for example, when my code is given this file: https://www.veeam.com/veeam_backup_product_overview_ds.pdf

Here is the code:

import pypdf   # PyPDF2, 3 and 4 are deprecated. PyPDF is currently in active development

reader = pypdf.PdfReader(source_filename)
writer = pypdf.PdfWriter()

# get first page
page = reader.pages[0]
# create new page
new_page = pypdf.PageObject.create_blank_page( None, width = page.mediabox.width, height = page.mediabox.height )
# crop original
page.mediabox.bottom = ( page.mediabox.top - page.mediabox.bottom ) / 2 + page.mediabox.bottom
# merge original into empty new page
new_page.merge_page( page )

writer.add_page(new_page)
with open(output_file, "wb") as fp:
    writer.write(fp)

Can anyone explain why it does not work sometimes?


问:
SwiftUI WebView: This method should not be called on the main thread as it may lead to UI unresponsiveness
I'm trying to have a list of NavigationLinks that show a website in full screen. But when I tap on the NavigationLink I get the warning: "This method should not be called on the main thread as it may lead to UI unresponsiveness."

Here is a small example to reproduce the error:

struct ContentView: View {
    var body: some View {
        NavigationView {
            List {
                NavigationLink("Apple") {
                    WebViewScreen(url: URL(string: "https://www.apple.com")!)
                }
            }
        }
    }
}

struct WebViewScreen: View {
    let url: URL
    @State private var isWebViewLoading = true
    var body: some View {
        ZStack {
            WebViewRepresentable(
                isLoading: $isWebViewLoading,
                url: url
            )
            if isWebViewLoading {
                ProgressView()
                    .scaleEffect(1.5)
                    .tint(.accentColor)
            }
        }
    }
}

struct WebViewRepresentable: UIViewRepresentable {
    @Binding var isLoading: Bool
    let url: URL
    func makeUIView(context: Context) -> WKWebView {
        let webView = WKWebView(frame: .zero)
        webView.navigationDelegate = context.coordinator
        let request = URLRequest(url: url)
        webView.load(request)
        return webView
    }

    func updateUIView(_ webView: WKWebView, context: Context) {}

    func makeCoordinator() -> WebViewCoordinator {
        WebViewCoordinator(isLoading: $isLoading)
    }
}

class WebViewCoordinator: NSObject, WKNavigationDelegate {

    @Binding var isLoading: Bool

    init(isLoading: Binding<Bool>) {
        _isLoading = isLoading
    }

    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        isLoading = true
    }

    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
        isLoading = false
    }
}
```

The warning does not appear without if I only show the WebViewScreen.

Body:
I'm trying to have a list of NavigationLinks that show a website in full screen. But when I tap on the NavigationLink I get the warning: "This method should not be called on the main thread as it may lead to UI unresponsiveness."

Here is a small example to reproduce the error:

struct ContentView: View {
    var body: some View {
        NavigationView {
            List {
                NavigationLink("Apple") {
                    WebViewScreen(url: URL(string: "https://www.apple.com")!)
                }
            }
        }
    }
}

struct WebViewScreen: View {
    let url: URL
    @State private var isWebViewLoading = true
    var body: some View {
        ZStack {
            WebViewRepresentable(
                isLoading: $isWebViewLoading,
                url: url
            )
            if isWebViewLoading {
                ProgressView()
                    .scaleEffect(1.5)
                    .tint(.accentColor)
            }
        }
    }
}

struct WebViewRepresentable: UIViewRepresentable {
    @Binding var isLoading: Bool
    let url: URL
    func makeUIView(context: Context) -> WKWebView {
        let webView = WKWebView(frame: .zero)
        webView.navigationDelegate = context.coordinator
        let request = URLRequest(url: url)
        webView.load(request)
        return webView
    }

    func updateUIView(_ webView: WKWebView, context: Context) {}

    func makeCoordinator() -> WebViewCoordinator {
        WebViewCoordinator(isLoading: $isLoading)
    }
}

class WebViewCoordinator: NSObject, WKNavigationDelegate {

    @Binding var isLoading: Bool

    init(isLoading: Binding<Bool>) {
        _isLoading = isLoading
    }

    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        isLoading = true
    }

    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
        isLoading = false
    }
}

The warning does not appear without if I only show the WebViewScreen.


问:
My Bukkit plugins has a plugin.yml but it gives this error
```<code>[11:20:12 ERROR]: Could not load 'plugins/selamla.jar' in folder 'plugins'
org.bukkit.plugin.InvalidDescriptionException: Invalid plugin.yml
        at org.bukkit.plugin.java.JavaPluginLoader.getPluginDescription(JavaPluginLoader.java:178) ~[purpur-api-1.19-R0.1-SNAPSHOT.jar:?]
        at org.bukkit.plugin.SimplePluginManager.loadPlugins(SimplePluginManager.java:154) ~[purpur-api-1.19-R0.1-SNAPSHOT.jar:?]
        at org.bukkit.craftbukkit.v1_19_R1.CraftServer.loadPlugins(CraftServer.java:419) ~[purpur-1.19.jar:git-Purpur-1670]
        at net.minecraft.server.dedicated.DedicatedServer.initServer(DedicatedServer.java:313) ~[purpur-1.19.jar:git-Purpur-1670]
        at net.minecraft.server.MinecraftServer.runServer(MinecraftServer.java:1137) ~[purpur-1.19.jar:git-Purpur-1670]
        at net.minecraft.server.MinecraftServer.lambda$spin$1(MinecraftServer.java:307) ~[purpur-1.19.jar:git-Purpur-1670]
        at java.lang.Thread.run(Thread.java:833) ~[?:?]
Caused by: java.io.FileNotFoundException: Jar does not contain plugin.yml
        ... 7 more
</code>```

I'm learning to write Bukkit plugin but it gives this error code
How can i solve this problem ?

Body:
[11:20:12 ERROR]: Could not load 'plugins/selamla.jar' in folder 'plugins'
org.bukkit.plugin.InvalidDescriptionException: Invalid plugin.yml
        at org.bukkit.plugin.java.JavaPluginLoader.getPluginDescription(JavaPluginLoader.java:178) ~[purpur-api-1.19-R0.1-SNAPSHOT.jar:?]
        at org.bukkit.plugin.SimplePluginManager.loadPlugins(SimplePluginManager.java:154) ~[purpur-api-1.19-R0.1-SNAPSHOT.jar:?]
        at org.bukkit.craftbukkit.v1_19_R1.CraftServer.loadPlugins(CraftServer.java:419) ~[purpur-1.19.jar:git-Purpur-1670]
        at net.minecraft.server.dedicated.DedicatedServer.initServer(DedicatedServer.java:313) ~[purpur-1.19.jar:git-Purpur-1670]
        at net.minecraft.server.MinecraftServer.runServer(MinecraftServer.java:1137) ~[purpur-1.19.jar:git-Purpur-1670]
        at net.minecraft.server.MinecraftServer.lambda$spin$1(MinecraftServer.java:307) ~[purpur-1.19.jar:git-Purpur-1670]
        at java.lang.Thread.run(Thread.java:833) ~[?:?]
Caused by: java.io.FileNotFoundException: Jar does not contain plugin.yml
        ... 7 more

I'm learning to write Bukkit plugin but it gives this error code
How can i solve this problem ?


问:
Dynamically replace IL code of method body at runtime
Please note that I have no advanced knowledge of code injection nor IL code treatment. In fact I have less than basic knowledge for this and I needed to research much time to write the code at the end of this post.

I'm under .NET 4.8, I've found this answer which I think it suggests that I could modify at runtime the IL code (of the method body) of a compiled method. That is what I would like to do.

In the body of a compiled method I would like to inject a Call OpCode, in this example at the very begining (as first instruction of the method body) to call another method, but I would like to be have flexibility to choose the position where to inject these new IL instructions.

The problem is that when I try to put all this in practice, and due my lack of experience in this matter, I end up getting an AccessViolationException with this error message:

Attempted to read or write protected memory. This is often an
indication that other memory is corrupt.

I think probably I'm breaking the IL Code and that is corrupting the memory and maybe it's just a matter of fixing the order of the OpCodes, or maybe it could be a memory issue in caso of that I'm not properly writing into the unmanaged memory when patching the original IL Code.

How can I fix this problem?.

Here is the code that I'm using. In this example I'm tying to modify the method with name "TestMethod" to insert an instruction in its body to call the other method with name "LoggerMethod":

Imports System.Reflection
Imports System.Reflection.Emit

Public NotInheritable Class Form1 : Inherits Form

    Public Sub TestMethod()
        Console.WriteLine("Test Method Call.")
    End Sub

    Public Sub LoggerMethod(<CallerMemberName> Optional memberName As String = "")
        Console.WriteLine($"Logger method call by '{memberName}'.")
    End Sub

    Private Sub Form1_Shown(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Shown

        Dim testMethodInfo As MethodInfo =
            GetType(Form1).GetMethod("TestMethod", BindingFlags.Instance Or BindingFlags.Public)

        Dim loggerMethodInfo As MethodInfo =
            GetType(Form1).GetMethod("LoggerMethod", BindingFlags.Instance Or BindingFlags.Public)

        ' Using a DynamicMethod is just the way I found
        ' for using ILGenerator to generate the wanted IL code to inject.
        Dim dynMethod As New DynamicMethod("qwerty_dyn", Nothing, Type.EmptyTypes, restrictedSkipVisibility:=True)
        Dim ilGen As ILGenerator = dynMethod.GetILGenerator(streamSize:=16)
        ilGen.Emit(OpCodes.Call, loggerMethodInfo)
        ' ilGen.EmitCall(OpCodes.Call, loggerMethodInfo, Nothing)

        ILHelper.InjectILCode(testMethodInfo, GetIlAsByteArray2(dynMethod), position:=0)
        Me.TestMethod()

        ' testMethodInfo.Invoke(Me, BindingFlags.Default, Type.DefaultBinder, Type.EmptyTypes, Thread.CurrentThread.CurrentCulture)

    End Sub

End Class
```
<pre class="lang-vb prettyprint-override"><code>Public NotInheritable Class ILHelper

    Private Sub New()
    End Sub

    Public Shared Sub InjectILCode(method As MethodInfo, newIlCode As Byte(), position As Integer)

        Dim body As MethodBody = method.GetMethodBody()
        Dim ilOpCodes As Byte() = body.GetILAsByteArray()

        If position < 0 Then
            Throw New ArgumentException($"Position must be equals or greater than zero.")
        End If

        If position > ilOpCodes.Length Then
            Throw New IndexOutOfRangeException($"Position {position} is greater than the IL byte array length ({ilOpCodes.Length}).")
        End If

        Dim newIlOpCodes((newIlCode.Length + ilOpCodes.Length) - 1) As Byte

        ' Add new IL instructions first.
        For i As Integer = 0 To newIlCode.Length - 1
            newIlOpCodes(i) = newIlCode(i)
        Next

        ' Continue with adding the original IL instructions.
        For i As Integer = 0 To ilOpCodes.Length - 1
            newIlOpCodes(position + newIlCode.Length + i) = ilOpCodes(i)
        Next

        ' This helps to visualize the byte array differences:
        Console.WriteLine($"Old IL Bytes: {String.Join(", ", ilOpCodes)}")
        Console.WriteLine($"NeW Il Bytes: {String.Join(", ", newIlOpCodes)}")

        Dim methodHandle As RuntimeMethodHandle = method.MethodHandle

        ' Makes sure the target method gets compiled.
        ' https://reverseengineering.stackexchange.com/a/21014
        RuntimeHelpers.PrepareMethod(methodHandle)

        Dim hGlobal As IntPtr = Marshal.AllocHGlobal(newIlOpCodes.Length)
        Marshal.Copy(newIlOpCodes, 0, hGlobal, newIlOpCodes.Length)

        Dim methodPointer As IntPtr = methodHandle.GetFunctionPointer()
        Marshal.WriteIntPtr(methodPointer, hGlobal)

        Marshal.FreeHGlobal(hGlobal)

    End Sub

End Class
</code>```

Public Module DynamicMethodExtensions

    <Extension>
    Public Function GetIlAsByteArray2(dynMethod As DynamicMethod) As Byte()

        Dim ilGen As ILGenerator = dynMethod.GetILGenerator()
        Dim fiIlStream As FieldInfo

        ' https://stackoverflow.com/a/4147132/1248295
        ' Conditional for .NET 4.x because DynamicILGenerator class derived from ILGenerator.
        If Environment.Version.Major >= 4 Then
            fiIlStream = ilGen.GetType().BaseType.GetField("m_ILStream", BindingFlags.Instance Or BindingFlags.NonPublic)
        Else ' This worked on .NET 3.5
            fiIlStream = ilGen.GetType().GetField("m_ILStream", BindingFlags.Instance Or BindingFlags.NonPublic)
        End If

        Return TryCast(fiIlStream.GetValue(ilGen), Byte())

    End Function

    ' THIS IS NOT WORKING FOR ME, ArgumentException IS THROWN.
    ' --------------------------------------------------------
    '<Extension>
    'Public Function GetIlAsByteArray(dynMethod As DynamicMethod) As Byte()
    '
    '    Dim resolver As Object = GetType(DynamicMethod).GetField("m_resolver", BindingFlags.Instance Or BindingFlags.NonPublic).GetValue(dynMethod)
    '    If resolver Is Nothing Then
    '        Throw New ArgumentException("The dynamic method's IL has not been finalized.")
    '    End If
    '    Return DirectCast(resolver.GetType().GetField("m_code", BindingFlags.Instance Or BindingFlags.NonPublic).GetValue(resolver), Byte())
    '
    'End Function

End Module
```

Body:
Please note that I have no advanced knowledge of code injection nor IL code treatment. In fact I have less than basic knowledge for this and I needed to research much time to write the code at the end of this post.

I'm under .NET 4.8, I've found this answer which I think it suggests that I could modify at runtime the IL code (of the method body) of a compiled method. That is what I would like to do.

In the body of a compiled method I would like to inject a Call OpCode, in this example at the very begining (as first instruction of the method body) to call another method, but I would like to be have flexibility to choose the position where to inject these new IL instructions.

The problem is that when I try to put all this in practice, and due my lack of experience in this matter, I end up getting an AccessViolationException with this error message:

Attempted to read or write protected memory. This is often an
indication that other memory is corrupt.

I think probably I'm breaking the IL Code and that is corrupting the memory and maybe it's just a matter of fixing the order of the OpCodes, or maybe it could be a memory issue in caso of that I'm not properly writing into the unmanaged memory when patching the original IL Code.

How can I fix this problem?.

Here is the code that I'm using. In this example I'm tying to modify the method with name "TestMethod" to insert an instruction in its body to call the other method with name "LoggerMethod":

Imports System.Reflection
Imports System.Reflection.Emit

Public NotInheritable Class Form1 : Inherits Form

    Public Sub TestMethod()
        Console.WriteLine("Test Method Call.")
    End Sub

    Public Sub LoggerMethod(<CallerMemberName> Optional memberName As String = "")
        Console.WriteLine($"Logger method call by '{memberName}'.")
    End Sub

    Private Sub Form1_Shown(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Shown

        Dim testMethodInfo As MethodInfo =
            GetType(Form1).GetMethod("TestMethod", BindingFlags.Instance Or BindingFlags.Public)

        Dim loggerMethodInfo As MethodInfo =
            GetType(Form1).GetMethod("LoggerMethod", BindingFlags.Instance Or BindingFlags.Public)

        ' Using a DynamicMethod is just the way I found
        ' for using ILGenerator to generate the wanted IL code to inject.
        Dim dynMethod As New DynamicMethod("qwerty_dyn", Nothing, Type.EmptyTypes, restrictedSkipVisibility:=True)
        Dim ilGen As ILGenerator = dynMethod.GetILGenerator(streamSize:=16)
        ilGen.Emit(OpCodes.Call, loggerMethodInfo)
        ' ilGen.EmitCall(OpCodes.Call, loggerMethodInfo, Nothing)

        ILHelper.InjectILCode(testMethodInfo, GetIlAsByteArray2(dynMethod), position:=0)
        Me.TestMethod()

        ' testMethodInfo.Invoke(Me, BindingFlags.Default, Type.DefaultBinder, Type.EmptyTypes, Thread.CurrentThread.CurrentCulture)

    End Sub

End Class

Public NotInheritable Class ILHelper

    Private Sub New()
    End Sub

    Public Shared Sub InjectILCode(method As MethodInfo, newIlCode As Byte(), position As Integer)

        Dim body As MethodBody = method.GetMethodBody()
        Dim ilOpCodes As Byte() = body.GetILAsByteArray()

        If position < 0 Then
            Throw New ArgumentException($"Position must be equals or greater than zero.")
        End If

        If position > ilOpCodes.Length Then
            Throw New IndexOutOfRangeException($"Position {position} is greater than the IL byte array length ({ilOpCodes.Length}).")
        End If

        Dim newIlOpCodes((newIlCode.Length + ilOpCodes.Length) - 1) As Byte

        ' Add new IL instructions first.
        For i As Integer = 0 To newIlCode.Length - 1
            newIlOpCodes(i) = newIlCode(i)
        Next

        ' Continue with adding the original IL instructions.
        For i As Integer = 0 To ilOpCodes.Length - 1
            newIlOpCodes(position + newIlCode.Length + i) = ilOpCodes(i)
        Next

        ' This helps to visualize the byte array differences:
        Console.WriteLine($"Old IL Bytes: {String.Join(", ", ilOpCodes)}")
        Console.WriteLine($"NeW Il Bytes: {String.Join(", ", newIlOpCodes)}")

        Dim methodHandle As RuntimeMethodHandle = method.MethodHandle

        ' Makes sure the target method gets compiled.
        ' https://reverseengineering.stackexchange.com/a/21014
        RuntimeHelpers.PrepareMethod(methodHandle)

        Dim hGlobal As IntPtr = Marshal.AllocHGlobal(newIlOpCodes.Length)
        Marshal.Copy(newIlOpCodes, 0, hGlobal, newIlOpCodes.Length)

        Dim methodPointer As IntPtr = methodHandle.GetFunctionPointer()
        Marshal.WriteIntPtr(methodPointer, hGlobal)

        Marshal.FreeHGlobal(hGlobal)

    End Sub

End Class

Public Module DynamicMethodExtensions

    <Extension>
    Public Function GetIlAsByteArray2(dynMethod As DynamicMethod) As Byte()

        Dim ilGen As ILGenerator = dynMethod.GetILGenerator()
        Dim fiIlStream As FieldInfo

        ' https://stackoverflow.com/a/4147132/1248295
        ' Conditional for .NET 4.x because DynamicILGenerator class derived from ILGenerator.
        If Environment.Version.Major >= 4 Then
            fiIlStream = ilGen.GetType().BaseType.GetField("m_ILStream", BindingFlags.Instance Or BindingFlags.NonPublic)
        Else ' This worked on .NET 3.5
            fiIlStream = ilGen.GetType().GetField("m_ILStream", BindingFlags.Instance Or BindingFlags.NonPublic)
        End If

        Return TryCast(fiIlStream.GetValue(ilGen), Byte())

    End Function

    ' THIS IS NOT WORKING FOR ME, ArgumentException IS THROWN.
    ' --------------------------------------------------------
    '<Extension>
    'Public Function GetIlAsByteArray(dynMethod As DynamicMethod) As Byte()
    '
    '    Dim resolver As Object = GetType(DynamicMethod).GetField("m_resolver", BindingFlags.Instance Or BindingFlags.NonPublic).GetValue(dynMethod)
    '    If resolver Is Nothing Then
    '        Throw New ArgumentException("The dynamic method's IL has not been finalized.")
    '    End If
    '    Return DirectCast(resolver.GetType().GetField("m_code", BindingFlags.Instance Or BindingFlags.NonPublic).GetValue(resolver), Byte())
    '
    'End Function

End Module


问:
why google colab cannot identify image file using while using tesseract?
```<code>!apt install tesseract-ocr
!pip install pytesserac
import pytesseract
from PIL import Image

# Open image file
image = Image.open("/content/book.PNG")

# Recognize text
text = pytesseract.image_to_string(image)

print(text)
</code>```

I wrote this code in google colab and getting an error "cannot identify image file '/content/book.PNG'"

I am expecting the code to run.

Body:
!apt install tesseract-ocr
!pip install pytesserac
import pytesseract
from PIL import Image

# Open image file
image = Image.open("/content/book.PNG")

# Recognize text
text = pytesseract.image_to_string(image)

print(text)

I wrote this code in google colab and getting an error "cannot identify image file '/content/book.PNG'"

I am expecting the code to run.


问:
Draw a canvas on top of every image in a browser extension
I'm trying to develop a browser extension that detect faces in all images of a web page and draw a bounding box around these faces.

For this purpose I first need to draw a canvas on top of every image.
There is a well-know approach for this task when one is creating their own web page from scratch (I mean not modifying an already existing web page).

I've tried to apply that approach and it seems to work on some websites but for some reason on some websites it adds some padding.

Below a very simplified version of my code, which only includes the canvas overlay part.

Manifest.json (v3):

```<code>{
    "manifest_version": 3,
    "name": "Canvas Overlay",
    "version": "1.0",
    "description": "Draw Canvas on Top of Every Image",
    "content_scripts": [
        {
          "js": ["scripts/content.js"],
          "matches": ["<all_urls>"]
        }
      ]
}
</code>```

scripts/content.js:

```<code>for (let image of document.images) {

    let parent = image.parentNode

    let wrapper = document.createElement('div')

    wrapper.width = image.width
    wrapper.height = image.height
    wrapper.style.margin = image.margin
    wrapper.style.padding = image.padding
    parent.replaceChild(wrapper, image)
    wrapper.appendChild(image)

    let canvas = document.createElement('canvas')
    wrapper.appendChild(canvas)

    wrapper.style.cssText = 'display:inline-block;position:relative;'
    image.style.cssText = 'position:absolute;z-index:0;'
    canvas.style.cssText = 'position:relative;z-index:1;'

    canvas.width = wrapper.width
    canvas.height = wrapper.height
    canvas.style.outline = 'thick solid #0000FF'
    canvas.style.margin = image.margin
    canvas.style.padding = image.padding

    console.log('width and height:')
    console.log('wrapper', wrapper.width, wrapper.height)
    console.log('image', image.width, image.height)
    console.log('canvas', canvas.width, canvas.height)

    console.log('margin and padding:')
    console.log('wrapper', wrapper.style.margin, wrapper.style.padding)
    console.log('image', image.margin, image.padding)
    console.log('canvas', canvas.style.margin, canvas.style.padding)
}
</code>```

You'll understand that one of the biggest challenges is to add a canvas for every image while limiting the change of the page style as much as possible.

There is also the challenge of the image dimensions changing dynamically.

Anyone can try this code on any web page. Just giving two websites:

https://www.bbc.co.uk/ the canvas overlay works as expected

https://news.sky.com/ the canvas overlay solution creates some additional padding

Any help would be appreciated.

Body:
I'm trying to develop a browser extension that detect faces in all images of a web page and draw a bounding box around these faces.

For this purpose I first need to draw a canvas on top of every image.
There is a well-know approach for this task when one is creating their own web page from scratch (I mean not modifying an already existing web page).

I've tried to apply that approach and it seems to work on some websites but for some reason on some websites it adds some padding.

Below a very simplified version of my code, which only includes the canvas overlay part.

Manifest.json (v3):

{
    "manifest_version": 3,
    "name": "Canvas Overlay",
    "version": "1.0",
    "description": "Draw Canvas on Top of Every Image",
    "content_scripts": [
        {
          "js": ["scripts/content.js"],
          "matches": ["<all_urls>"]
        }
      ]
}

scripts/content.js:

for (let image of document.images) {

    let parent = image.parentNode

    let wrapper = document.createElement('div')

    wrapper.width = image.width
    wrapper.height = image.height
    wrapper.style.margin = image.margin
    wrapper.style.padding = image.padding
    parent.replaceChild(wrapper, image)
    wrapper.appendChild(image)

    let canvas = document.createElement('canvas')
    wrapper.appendChild(canvas)

    wrapper.style.cssText = 'display:inline-block;position:relative;'
    image.style.cssText = 'position:absolute;z-index:0;'
    canvas.style.cssText = 'position:relative;z-index:1;'

    canvas.width = wrapper.width
    canvas.height = wrapper.height
    canvas.style.outline = 'thick solid #0000FF'
    canvas.style.margin = image.margin
    canvas.style.padding = image.padding

    console.log('width and height:')
    console.log('wrapper', wrapper.width, wrapper.height)
    console.log('image', image.width, image.height)
    console.log('canvas', canvas.width, canvas.height)

    console.log('margin and padding:')
    console.log('wrapper', wrapper.style.margin, wrapper.style.padding)
    console.log('image', image.margin, image.padding)
    console.log('canvas', canvas.style.margin, canvas.style.padding)
}

You'll understand that one of the biggest challenges is to add a canvas for every image while limiting the change of the page style as much as possible.

There is also the challenge of the image dimensions changing dynamically.

Anyone can try this code on any web page. Just giving two websites:

https://www.bbc.co.uk/ the canvas overlay works as expected

https://news.sky.com/ the canvas overlay solution creates some additional padding

Any help would be appreciated.


问:
Draw a graph of a PyTorch model which takes a packed tensor as input
I defined my neural network to take a packed sequence as input, and then pads it a

```<code>def forward(self, x):
        y, _ = self.rnn(x)
        output ,lengths = torch.nn.utils.rnn.pad_packed_sequence(y, batch_first = True)
        out = [output[e, i-1,:].unsqueeze(0) for e, i in enumerate(lengths)]
        out = torch.cat(out, dim = 0)
        return out
</code>```

And tried to make a graph of the network.

```<code>tb = torch.utils.tensorboard.SummaryWriter()
tb.add_graph(model, input) # input is a packed sequence tensor
</code>```

This results in the following error:

```<code>TypeError: MyRNN.forward() takes 2 positional arguments but 5 were given
</code>```

Any ideas? I'm not sure if it's possible to use the packed sequence here.

Body:
I defined my neural network to take a packed sequence as input, and then pads it a

def forward(self, x):
        y, _ = self.rnn(x)
        output ,lengths = torch.nn.utils.rnn.pad_packed_sequence(y, batch_first = True)
        out = [output[e, i-1,:].unsqueeze(0) for e, i in enumerate(lengths)]
        out = torch.cat(out, dim = 0)
        return out

And tried to make a graph of the network.

tb = torch.utils.tensorboard.SummaryWriter()
tb.add_graph(model, input) # input is a packed sequence tensor

This results in the following error:

TypeError: MyRNN.forward() takes 2 positional arguments but 5 were given

Any ideas? I'm not sure if it's possible to use the packed sequence here.


问:
Splitforlder without shuffling data - How to split dataset among train, test and validation on disk without shuffling the information (python)?
I am working on a deep learning model that uses a large amount of time series related data. As the data is too big to be loaded in RAM at once, I will use keras train_on_batch to train the model reading data from disk.
I am looking for a simple and fast process to split the data among train, validation and test folders.

I´ve tried "splitfolder" function, but could not deactivate the data shuffling (what is inapropriate for time series related data). Arguments on this function documentation does not inclued an option to turn shuffle on/off.

Code I´ve tried:

```<code>import splitfolders
input_folder = r"E:\Doutorado\apagar"

splitfolders.ratio(input_folder, output = r'E:\Doutorado\apagardivididos', ratio=(0.7, 0.2, 0.1),
              group_prefix=None)
</code>```

Resulting split data is shuffled, but this shuffle is a problem for my time series analysis...

source: https://pypi.org/project/split-folders/

splitfolders.ratio("input_folder", output="output",
seed=1337, ratio=(.8, .1, .1), group_prefix=None, move=False) # default values

Usage:
splitfolders [--output] [--ratio] [--fixed] [--seed] [--oversample] [--group_prefix] [--move] folder_with_images
Options:
--output        path to the output folder. defaults to output. Get created if non-existent.
--ratio         the ratio to split. e.g. for train/val/test .8 .1 .1 -- or for train/val .8 .2 --.
--fixed         set the absolute number of items per validation/test set. The remaining items constitute
the training set. e.g. for train/val/test 100 100 or for train/val 100.
Set 3 values, e.g. 300 100 100, to limit the number of training values.
--seed          set seed value for shuffling the items. defaults to 1337.
--oversample    enable oversampling of imbalanced datasets, works only with --fixed.
--group_prefix  split files into equally-sized groups based on their prefix
--move          move the files instead of copying

Body:
I am working on a deep learning model that uses a large amount of time series related data. As the data is too big to be loaded in RAM at once, I will use keras train_on_batch to train the model reading data from disk.
I am looking for a simple and fast process to split the data among train, validation and test folders.

I´ve tried "splitfolder" function, but could not deactivate the data shuffling (what is inapropriate for time series related data). Arguments on this function documentation does not inclued an option to turn shuffle on/off.

Code I´ve tried:

import splitfolders
input_folder = r"E:\Doutorado\apagar"

splitfolders.ratio(input_folder, output = r'E:\Doutorado\apagardivididos', ratio=(0.7, 0.2, 0.1),
              group_prefix=None)

Resulting split data is shuffled, but this shuffle is a problem for my time series analysis...

source: https://pypi.org/project/split-folders/

splitfolders.ratio("input_folder", output="output",
seed=1337, ratio=(.8, .1, .1), group_prefix=None, move=False) # default values

Usage:
splitfolders [--output] [--ratio] [--fixed] [--seed] [--oversample] [--group_prefix] [--move] folder_with_images
Options:
--output        path to the output folder. defaults to output. Get created if non-existent.
--ratio         the ratio to split. e.g. for train/val/test .8 .1 .1 -- or for train/val .8 .2 --.
--fixed         set the absolute number of items per validation/test set. The remaining items constitute
the training set. e.g. for train/val/test 100 100 or for train/val 100.
Set 3 values, e.g. 300 100 100, to limit the number of training values.
--seed          set seed value for shuffling the items. defaults to 1337.
--oversample    enable oversampling of imbalanced datasets, works only with --fixed.
--group_prefix  split files into equally-sized groups based on their prefix
--move          move the files instead of copying


问:
Can anyone help me with the playerctl output?
There is program called "playerctl" in linux which is used get metadata and status of the playing music.

```<code>#!/bin/bash

if [ $(echo -n $(playerctl status)) == "Playing" ]; then
    echo " play "
elif [ $(echo -n $(playerctl status)) == "Paused" ]; then
    echo " pause "
elif [ $(echo -n $(playerctl status 2>/dev/null)) == "No players found" ]; then
    echo " not found "
else
    echo "other"
fi

</code>```

The output should either of the four echo statements.
But I am getting "No players found"

Body:
There is program called "playerctl" in linux which is used get metadata and status of the playing music.

#!/bin/bash

if [ $(echo -n $(playerctl status)) == "Playing" ]; then
    echo " play "
elif [ $(echo -n $(playerctl status)) == "Paused" ]; then
    echo " pause "
elif [ $(echo -n $(playerctl status 2>/dev/null)) == "No players found" ]; then
    echo " not found "
else
    echo "other"
fi

The output should either of the four echo statements.
But I am getting "No players found"


问:
yolov7 pose estimation RuntimeError: Sizes of tensors must match except in dimension 2. Got 24 and 23
I used the code to test yolov7 pose estimation.

```<code>import matplotlib.pyplot as plt
import torch
import cv2
from torchvision import transforms
import numpy as np
from utils.datasets import letterbox
from utils.general import non_max_suppression_kpt
from utils.plots import output_to_keypoint, plot_skeleton_kpts
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
weigths = torch.load('yolov7-w6-pose.pt', map_location=device)
model = weigths['model']
_ = model.float().eval()

if torch.cuda.is_available():
    model.half().to(device)
image = cv2.imread('./person.jpg')
image = letterbox(image, 960, stride=32, auto=True)[0] #original is stride=64
image_ = image.copy()
image = transforms.ToTensor()(image)
image = torch.tensor(np.array([image.numpy()]))

if torch.cuda.is_available():
    image = image.half().to(device)
output, _ = model(image)
output = non_max_suppression_kpt(output, 0.25, 0.65, nc=model.yaml['nc'], nkpt=model.yaml['nkpt'], kpt_label=True)
with torch.no_grad():
    output = output_to_keypoint(output)
nimg = image[0].permute(1, 2, 0) * 255
nimg = nimg.cpu().numpy().astype(np.uint8)
nimg = cv2.cvtColor(nimg, cv2.COLOR_RGB2BGR)
for idx in range(output.shape[0]):
    plot_skeleton_kpts(nimg, output[idx, 7:].T, 3)
%matplotlib inline
plt.figure(figsize=(8,8))
plt.axis('off')
plt.imshow(nimg)
plt.show()
</code>```

When I change stride to 32:

image = letterbox(image, 960, stride=64, auto=True)[0]  to

image = letterbox(image, 960, stride=32, auto=True)[0]

The error message is:RuntimeError: Sizes of tensors must match except in dimension 2. Got 24 and 23 (The offending index is 0)

Why can't I use stride=32?

Body:
I used the code to test yolov7 pose estimation.

import matplotlib.pyplot as plt
import torch
import cv2
from torchvision import transforms
import numpy as np
from utils.datasets import letterbox
from utils.general import non_max_suppression_kpt
from utils.plots import output_to_keypoint, plot_skeleton_kpts
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
weigths = torch.load('yolov7-w6-pose.pt', map_location=device)
model = weigths['model']
_ = model.float().eval()

if torch.cuda.is_available():
    model.half().to(device)
image = cv2.imread('./person.jpg')
image = letterbox(image, 960, stride=32, auto=True)[0] #original is stride=64
image_ = image.copy()
image = transforms.ToTensor()(image)
image = torch.tensor(np.array([image.numpy()]))

if torch.cuda.is_available():
    image = image.half().to(device)
output, _ = model(image)
output = non_max_suppression_kpt(output, 0.25, 0.65, nc=model.yaml['nc'], nkpt=model.yaml['nkpt'], kpt_label=True)
with torch.no_grad():
    output = output_to_keypoint(output)
nimg = image[0].permute(1, 2, 0) * 255
nimg = nimg.cpu().numpy().astype(np.uint8)
nimg = cv2.cvtColor(nimg, cv2.COLOR_RGB2BGR)
for idx in range(output.shape[0]):
    plot_skeleton_kpts(nimg, output[idx, 7:].T, 3)
%matplotlib inline
plt.figure(figsize=(8,8))
plt.axis('off')
plt.imshow(nimg)
plt.show()

When I change stride to 32:

image = letterbox(image, 960, stride=64, auto=True)[0]  to

image = letterbox(image, 960, stride=32, auto=True)[0]

The error message is:RuntimeError: Sizes of tensors must match except in dimension 2. Got 24 and 23 (The offending index is 0)

Why can't I use stride=32?


问:
Dividing my website into three columns of unequal length
I have been trying to divide my website into three columns, two of 15% and one of 70% which would be the middle one and would contain the content of the website. But I wasnt able to make the three columns take 100% of the website.
I am using the following code:

 this is column 1
tting, remairem

 this is column 2
Lorem Ip Lorem

 this is column 1
Lorem Ipsum ing Lorem

```
<p>And styled it with this CSS</p>
<pre class="lang-css prettyprint-override"><code>div.content{
    width:100%;
}
div.column1{
    float: left;
    width: 15%;
    background-color:aqua;

}
div.column2{
    float:left;
    width:70%;
    background-color:green;
}
</code>```

After running it I get the following result.

As you can see the three columns are not taking 100% width of the website, I have checked and I don't have any padding or margin that would avoid the columns to take 100% of the space.

Does anyone know what I am doing wrong?

I would like to add that if I only add one column the max space it takes is this:
enter image description here

Might then this be a problem of the nav bar?

Body:
I have been trying to divide my website into three columns, two of 15% and one of 70% which would be the middle one and would contain the content of the website. But I wasnt able to make the three columns take 100% of the website.
I am using the following code:

 this is column 1
tting, remairem

 this is column 2
Lorem Ip Lorem

 this is column 1
Lorem Ipsum ing Lorem

And styled it with this CSS

div.content{
    width:100%;
}
div.column1{
    float: left;
    width: 15%;
    background-color:aqua;

}
div.column2{
    float:left;
    width:70%;
    background-color:green;
}

After running it I get the following result.

As you can see the three columns are not taking 100% width of the website, I have checked and I don't have any padding or margin that would avoid the columns to take 100% of the space.

Does anyone know what I am doing wrong?

I would like to add that if I only add one column the max space it takes is this:
enter image description here

Might then this be a problem of the nav bar?


问:
React Native Expo is stuck between specific lines of code
I'm writing an app using React Native and Expo, which integrates with Firebase.

In my app, I have the following function, which uploads an image to the Storage service, and some data regarding that image to Firestore:

/**
 * Upload image and data.
 * @param {string} uri Image URI. (file://)
 * @param {{x: number, y: number}} ratings Number ratings (1-5)
 * @param {string} review Text review.
 * @param {LocationObject} location Location object.
 * @return {Promise<string|boolean>} A string containing the image id if is successful, otherwise `false`.
 */
async function uploadReview(uri, ratings, review, location) {
  let updatedStorage = false;
  let imageId;
  try {
    imageId = Date.now() + uri.substring(uri.lastIndexOf('.'));
    let sTime = Date.now();
    const storageRef = storage()
        .ref()
        .child('images/' + auth().currentUser.uid + '/' + imageId);

    const response = await fetch(uri);
    const blob = await response.blob();
    await storageRef.put(blob);
    console.log('Uploaded image in ' + (Date.now() - sTime) + 'ms');
    updatedStorage = true;

    sTime = Date.now();
    await firestore().collection('users').doc(auth().currentUser.uid).collection('reviews')
        .doc(imageId.toString()).set({
          x: ratings.x,
          y: ratings.y,
          review: review,
          imageId: imageId,
          location: new firestore.GeoPoint(location.coords.latitude, location.coords.longitude),
        });
    console.log('Uploaded review in ' + (Date.now() - sTime) + 'ms'); // --- 1 ---

    console.log('Review uploaded successfully'); // --- 2 ---

    return imageId;
  } catch (e) {
    console.log(e);

    try {
      if (updatedStorage) {
        const storageRef = storage()
            .ref()
            .child('images/' + auth().currentUser.uid + '/' + imageId);
        await storageRef.delete();
      }
    } catch (e) {
      console.log('ERROR DELETING FAILED UPLOAD: ' + imageId);
      console.log(e);
    }

    return false;
  }
}
```

The problem I have is that when this function is called, it gets to the line marked with ---1---, but for some reason it (usually) hangs there, and does not continue to the line marked with

---2--- (without any errors or whatever, it's just stuck).

If I remove line ---1--- (which I placed there only for some testing), and only keep line ---2---, then it simply stops after that one, and does not get to the line where I return imageId.

Also, when this happens the app is half irresponsive. When I tap the back button, it does the usual animation, and does not seem to be frozen or anything, but in reality it is, and does nothing.

Another issue is that sometimes the app takes an insane amount of time to upload to Firestore - can reach up to a few minutes, for just 2 numbers, 2 short strings, and one GeoPoint, so it's not like I'm uploading some 10 TB data. (And uploading the Storage is always fine, no problem with that one)

I have tried cleaning gradle with gradlew clean, and then rebuilding, but it didn't help. I've restarted my phone a few times, the PC, but the problem persists.

I'm really clueless on what can be the cause of this, I've never encountered a code which simply does not continue to run to the next line.

Does anyone have any idea on what's happening it, how can I fix it?

(I'm running on a physical Android device, and am using some native libraries, so this is an Expo Development Build)

Body:
I'm writing an app using React Native and Expo, which integrates with Firebase.

In my app, I have the following function, which uploads an image to the Storage service, and some data regarding that image to Firestore:

/**
 * Upload image and data.
 * @param {string} uri Image URI. (file://)
 * @param {{x: number, y: number}} ratings Number ratings (1-5)
 * @param {string} review Text review.
 * @param {LocationObject} location Location object.
 * @return {Promise<string|boolean>} A string containing the image id if is successful, otherwise `false`.
 */
async function uploadReview(uri, ratings, review, location) {
  let updatedStorage = false;
  let imageId;
  try {
    imageId = Date.now() + uri.substring(uri.lastIndexOf('.'));
    let sTime = Date.now();
    const storageRef = storage()
        .ref()
        .child('images/' + auth().currentUser.uid + '/' + imageId);

    const response = await fetch(uri);
    const blob = await response.blob();
    await storageRef.put(blob);
    console.log('Uploaded image in ' + (Date.now() - sTime) + 'ms');
    updatedStorage = true;

    sTime = Date.now();
    await firestore().collection('users').doc(auth().currentUser.uid).collection('reviews')
        .doc(imageId.toString()).set({
          x: ratings.x,
          y: ratings.y,
          review: review,
          imageId: imageId,
          location: new firestore.GeoPoint(location.coords.latitude, location.coords.longitude),
        });
    console.log('Uploaded review in ' + (Date.now() - sTime) + 'ms'); // --- 1 ---

    console.log('Review uploaded successfully'); // --- 2 ---

    return imageId;
  } catch (e) {
    console.log(e);

    try {
      if (updatedStorage) {
        const storageRef = storage()
            .ref()
            .child('images/' + auth().currentUser.uid + '/' + imageId);
        await storageRef.delete();
      }
    } catch (e) {
      console.log('ERROR DELETING FAILED UPLOAD: ' + imageId);
      console.log(e);
    }

    return false;
  }
}

The problem I have is that when this function is called, it gets to the line marked with ---1---, but for some reason it (usually) hangs there, and does not continue to the line marked with

---2--- (without any errors or whatever, it's just stuck).

If I remove line ---1--- (which I placed there only for some testing), and only keep line ---2---, then it simply stops after that one, and does not get to the line where I return imageId.

Also, when this happens the app is half irresponsive. When I tap the back button, it does the usual animation, and does not seem to be frozen or anything, but in reality it is, and does nothing.

Another issue is that sometimes the app takes an insane amount of time to upload to Firestore - can reach up to a few minutes, for just 2 numbers, 2 short strings, and one GeoPoint, so it's not like I'm uploading some 10 TB data. (And uploading the Storage is always fine, no problem with that one)

I have tried cleaning gradle with gradlew clean, and then rebuilding, but it didn't help. I've restarted my phone a few times, the PC, but the problem persists.

I'm really clueless on what can be the cause of this, I've never encountered a code which simply does not continue to run to the next line.

Does anyone have any idea on what's happening it, how can I fix it?

(I'm running on a physical Android device, and am using some native libraries, so this is an Expo Development Build)


问:
Access table showing incorrect data from a linked table
I have an issue with my access table which is linked from postgres. The table in postgres has a time column with a 'time without time zone' data type and it looks fine. However when i linked the table to Access, the same fields show the same data but have a date in front of them. It looks like this, '07/01/2023 11:33:00 AM'. I just want it to display time.

I have tried chaning the data type in postgres and relinking the table but that didnt help. I've deleted the table and created a new one and that didnt help. Whenever I try to delete the dates directly from the table in access I get an error 'Another user edited this record and saved the changes before you attempted to save your changes' and it goes back to how it was.


问:
how can I turn off debug bar in Laravel on production
I installed Laravel "barryvdh/laravel-debugbar" for debug and after uploaded on live server i turn off debugger but now the logs is still appear to pages .</p>
```<code>APP_DEBUG=false
</code>```

Body:
I installed Laravel "barryvdh/laravel-debugbar" for debug and after uploaded on live server i turn off debugger but now the logs is still appear to pages .

APP_DEBUG=false