问:
How can i access my dockerised flask application from a separate device on the host network
I've created a API on a flask application that i'm trying to access from my phone on the same network as the windows host machine but i'm having no luck.

I'm running docker desktop on windows 10 with a WSL 2 (ubuntu) backend which is enabled. I can access the API if run the script outside of the docker container from my phone but not when it is running in the container. I can also access the API from the windows device by going to localhost:port/endpoint or hostip:port:endoint but i cannot access it using the windows host ip from a device on the same ip range.

I'm aware they is a different network for the docker container and WSL backend:

home network - 192.168.0.X

WSL 2  -  172.27.145.194

Flask container - 172.18.0.2

This is my docker-compose:

```<code>tfmodelserving:
  build: ./tfserving/docker-image
  container_name: tfserving
  ports:
    - "5001:5001"
  volumes:
    - ./tfserving/drive/src:/src

</code>```

and the dockerfile for it:

```<code>FROM tensorflow/tensorflow:2.10.0-gpu

COPY ./packages/ /packages
COPY ./requirements.txt requirements.txt
RUN apt-get update
RUN apt-get install libjack-dev -y
RUN apt-get install libasound-dev libportaudio2 libportaudiocpp0 portaudio19-dev libsndfile1 -y \
    && pip install --no-cache-dir --user -r /requirements.txt
CMD python3 packages/speech_to_text/stt_api.py
EXPOSE 5001
</code>```

It doesnt seem to be very clear what further configuration i need to do here. From what i've read they seems to be alot of suggestion that just publishing the ports should do the trick. I've also read about macvlan being a option but seems to be only supported on a linux host.

My networking knowledge is fairly limited but it seems quite complicated to configure this docker container to be accessible from my home network. I feel like i need to find a way to link the docker network to the home network but i am unsure on the best approach to doing this.

This is my first post so i apologise if things are not explained very clearly.If someone could nudge me in the direction of how this could be done it would be great!

Body:
I've created a API on a flask application that i'm trying to access from my phone on the same network as the windows host machine but i'm having no luck.

I'm running docker desktop on windows 10 with a WSL 2 (ubuntu) backend which is enabled. I can access the API if run the script outside of the docker container from my phone but not when it is running in the container. I can also access the API from the windows device by going to localhost:port/endpoint or hostip:port:endoint but i cannot access it using the windows host ip from a device on the same ip range.

I'm aware they is a different network for the docker container and WSL backend:

home network - 192.168.0.X

WSL 2  -  172.27.145.194

Flask container - 172.18.0.2

This is my docker-compose:

tfmodelserving:
  build: ./tfserving/docker-image
  container_name: tfserving
  ports:
    - "5001:5001"
  volumes:
    - ./tfserving/drive/src:/src

and the dockerfile for it:

FROM tensorflow/tensorflow:2.10.0-gpu

COPY ./packages/ /packages
COPY ./requirements.txt requirements.txt
RUN apt-get update
RUN apt-get install libjack-dev -y
RUN apt-get install libasound-dev libportaudio2 libportaudiocpp0 portaudio19-dev libsndfile1 -y \
    && pip install --no-cache-dir --user -r /requirements.txt
CMD python3 packages/speech_to_text/stt_api.py
EXPOSE 5001

It doesnt seem to be very clear what further configuration i need to do here. From what i've read they seems to be alot of suggestion that just publishing the ports should do the trick. I've also read about macvlan being a option but seems to be only supported on a linux host.

My networking knowledge is fairly limited but it seems quite complicated to configure this docker container to be accessible from my home network. I feel like i need to find a way to link the docker network to the home network but i am unsure on the best approach to doing this.

This is my first post so i apologise if things are not explained very clearly.If someone could nudge me in the direction of how this could be done it would be great!


来源: stackexchange

问:
getchar and buffer, EOF
```<code>/* getchar.c */

#include <stdio.h>

int main(void)
{
    int c;
    while ((c = getchar()) != EOF) {
        putchar(c);
        putchar(c);
    }
    return 0;
}
</code>```

This is an example code of getchar() and putchar() in 'a book on C'. Then I heard simply from my professor that how getchar() works.

standatd input is stored in buffer.

getchar() read a character from buffer at once.

if there is no more character, then buffer return -1.

There is < called 'redirection' which can be substitution(poor english...) of standard input.

$ gcc getchar.c -o getchar

echo "abc" > input

It worked when I use < redirection as an input.

$ ./getchar < input,

 But when I just typed, it didn't terminated.

 $ ./getchar
 abc

Then I thought that maybe I misunderstood and this process will be correct:

when I use <, a contents input 'file' is stored in buffer with EOF (= -1) like a NULL of string.

So getchar() read -1 when it read all contents of input file in buffer, and loop terminates.

when I just typed(standard input), then what I typed is stored in buffer with '\n' (End Of Line).

So getchar() read \n when it read all contents of standard input in buffer, and loop doesn't terminate.

Is it correct? or is there anything that I don't know? (e.g. buffer really returns -1 but conditionally, ...)

ContentLicense: CC BY-SA 4.0

Title: getchar and buffer, EOF

Body:
/* getchar.c */

#include <stdio.h>

int main(void)
{
    int c;
    while ((c = getchar()) != EOF) {
        putchar(c);
        putchar(c);
    }
    return 0;
}

This is an example code of getchar() and putchar() in 'a book on C'. Then I heard simply from my professor that how getchar() works.

standatd input is stored in buffer.

getchar() read a character from buffer at once.

if there is no more character, then buffer return -1.

There is < called 'redirection' which can be substitution(poor english...) of standard input.

$ gcc getchar.c -o getchar

echo "abc" > input

It worked when I use < redirection as an input.

$ ./getchar < input,

 But when I just typed, it didn't terminated.

 $ ./getchar
 abc

Then I thought that maybe I misunderstood and this process will be correct:

when I use <, a contents input 'file' is stored in buffer with EOF (= -1) like a NULL of string.

So getchar() read -1 when it read all contents of input file in buffer, and loop terminates.

when I just typed(standard input), then what I typed is stored in buffer with '\n' (End Of Line).

So getchar() read \n when it read all contents of standard input in buffer, and loop doesn't terminate.

Is it correct? or is there anything that I don't know? (e.g. buffer really returns -1 but conditionally, ...)


问:
Getting 401 error from Post request in R with Bearer token
Im trying to update a body on a postman POST which ask for Bearer Token (that I have) but still getting 401 error..

I first request the Token

```<code>login <- list(
                  "corporateEmail" = " xxx@xxx.com",
                          "password" = "xxx"
             )

test <- httr::POST("https://xxxx", body = login, encode = "json")
</code>```

and succesfully the the access token in the response.

then trying to do the post to change the body

```<code>test2 <-  httr::POST(url = urls,

                     add_headers(Authorization = token),
                     body = bodys,
                     encode = "json",
                     verbose())

</code>```

and i get 401...

the body is correct and I have tryed with Authorization = paste("Bearer",token)... the Postman configuration of the request is that Bearer is add in Auth tab and not directly in the Header tab.

Post request, expecting 200 answer

Body:
Im trying to update a body on a postman POST which ask for Bearer Token (that I have) but still getting 401 error..

I first request the Token

login <- list(
                  "corporateEmail" = " xxx@xxx.com",
                          "password" = "xxx"
             )

test <- httr::POST("https://xxxx", body = login, encode = "json")

and succesfully the the access token in the response.

then trying to do the post to change the body

test2 <-  httr::POST(url = urls,

                     add_headers(Authorization = token),
                     body = bodys,
                     encode = "json",
                     verbose())

and i get 401...

the body is correct and I have tryed with Authorization = paste("Bearer",token)... the Postman configuration of the request is that Bearer is add in Auth tab and not directly in the Header tab.

Post request, expecting 200 answer


问:
How to show different keyboards to different users in pyTelegramBotAPI using SQLAlchemy
I'm building telegram bot with SQLAlchemy and have the issue. I have class User (table users), that have relationship with class Role (table roles), accordingly, user can have different roles.

```<code>from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.orm import declarative_base, relationship, sessionmaker

Base = declarative_base()
class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True, index=True)
    telegram_id = Column(String)
    role_id = Column(Integer, ForeignKey("roles.id"))
    role = relationship("Role", back_populates="users")

class Role(Base):
    __tablename__ = 'roles'
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String)
    users = relationship("User", back_populates="role")
</code>```

I want, to User with role "user" and with role "admin" have different keyboards when you call certain method. If there is the way, to do it with inheritance - it would be more prefeable

Body:
I'm building telegram bot with SQLAlchemy and have the issue. I have class User (table users), that have relationship with class Role (table roles), accordingly, user can have different roles.

from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.orm import declarative_base, relationship, sessionmaker

Base = declarative_base()
class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True, index=True)
    telegram_id = Column(String)
    role_id = Column(Integer, ForeignKey("roles.id"))
    role = relationship("Role", back_populates="users")

class Role(Base):
    __tablename__ = 'roles'
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String)
    users = relationship("User", back_populates="role")

I want, to User with role "user" and with role "admin" have different keyboards when you call certain method. If there is the way, to do it with inheritance - it would be more prefeable


问:
Picking element in iframe using Selenium Java / not able to accept GDPR consent window via automation
I am trying to accept the GDPR Consent window via Selenium (Java), which is placed in an iframe. I understood from the lecture and forums that I have to first switch to that frame (which I did) and then click on the button. However, nothing happens.
Can anyone please help?Thanks

```<code>import java.time.Duration;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class GDPRiframe {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        System.setProperty("webdriver.chrome.driver", "/Users/DDD/WebDrivers/chromedriver");

        WebDriver driver = new ChromeDriver();

        driver.get("http://demo.guru99.com/test/");

        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));

        WebElement frameelement = driver.findElement(By.xpath("//iframe[@id='gdpr-consent-notice']"));

        driver.switchTo().frame(frameelement);

        driver.findElement(By.xpath("//button[@id='save']")).click();

    }

}
</code>```

Verified the css of the object via console, if there is no issue with that - appears to be ok. Also, I tried to click on a link within the frame, also not working. Seems as if I was not switched to the frame.

Thanks

Body:
I am trying to accept the GDPR Consent window via Selenium (Java), which is placed in an iframe. I understood from the lecture and forums that I have to first switch to that frame (which I did) and then click on the button. However, nothing happens.
Can anyone please help?Thanks

import java.time.Duration;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class GDPRiframe {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        System.setProperty("webdriver.chrome.driver", "/Users/DDD/WebDrivers/chromedriver");

        WebDriver driver = new ChromeDriver();

        driver.get("http://demo.guru99.com/test/");

        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));

        WebElement frameelement = driver.findElement(By.xpath("//iframe[@id='gdpr-consent-notice']"));

        driver.switchTo().frame(frameelement);

        driver.findElement(By.xpath("//button[@id='save']")).click();

    }

}

Verified the css of the object via console, if there is no issue with that - appears to be ok. Also, I tried to click on a link within the frame, also not working. Seems as if I was not switched to the frame.

Thanks


问:
withCredentials: true is set but session variable is still missing in express
I am building cross domain web application with React and express
They run at port 3000 and 3001 respectively
I am trying to send a post request to create and record to database  base on the user id that set in the req.session
My problem is that session variable become undefined after the set up of CORS()
I have search through similar post and try to follow their instruction and solution
none of them works for me so I decide to come up here

Here is my ajax request:

```<code>$.ajax({
  type: 'POST',
  url: apiEndPoint + 'create',
  data: data,
  xhrFields: {withCredentials: true},
  success: results=>{
    //do something
  }
})
</code>```

Here is my app.js setup for cors

```<code>var express = require('express');
var app = express();
var cors = require('cors')
var session = require('express-session');

...

var usersRouter = require('./routes/users');

var corsOptions = {
    origin: ['http://localhost:3000'],
    credentials: true
}
app.use(cors(corsOptions));

app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));

app.use(session({
    secret: 'randomstringhere',
    resave: true,
    saveUninitialized: true
}));

app.options('*', cors(corsOptions));
app.use('/', notesRouter);

...

app.listen(3001);
</code>```

value inside req.session

```<code>Session {
  cookie: { path: '/', _expires: null, originalMaxAge: null, httpOnly: true }
}
</code>```

Body:
I am building cross domain web application with React and express
They run at port 3000 and 3001 respectively
I am trying to send a post request to create and record to database  base on the user id that set in the req.session
My problem is that session variable become undefined after the set up of CORS()
I have search through similar post and try to follow their instruction and solution
none of them works for me so I decide to come up here

Here is my ajax request:

$.ajax({
  type: 'POST',
  url: apiEndPoint + 'create',
  data: data,
  xhrFields: {withCredentials: true},
  success: results=>{
    //do something
  }
})

Here is my app.js setup for cors

var express = require('express');
var app = express();
var cors = require('cors')
var session = require('express-session');

...

var usersRouter = require('./routes/users');

var corsOptions = {
    origin: ['http://localhost:3000'],
    credentials: true
}
app.use(cors(corsOptions));

app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));

app.use(session({
    secret: 'randomstringhere',
    resave: true,
    saveUninitialized: true
}));

app.options('*', cors(corsOptions));
app.use('/', notesRouter);

...

app.listen(3001);

value inside req.session

Session {
  cookie: { path: '/', _expires: null, originalMaxAge: null, httpOnly: true }
}


问:
I'm using modal and I just want to use dropdown select method in laravel 7
This is my code in my Controller but I already try this method without using modal and it works.

```<code>public function create()
    {
        $department = Department::pluck('department', 'id');
        return view('positions.create',compact('department'));
    }

public function store()
    {
        $validator = Validator::make(Request::all(), [
            'dep_id'           => 'required',
            'position'         => 'required',
        ],
        [
            'dep_id.required'           =>  'Department Required',
            'position.required'       =>  'Position Required',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        Position::create(Request::all());
        Session::flash('message', 'Position Created Successfully');
        return redirect()->back();
    }
</code>```

This is my Model:

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Position extends Model
{
    protected $guarded = [];

    public function department(){
        return $this->belongsTo('App\Department','dep_id','id');
    }
}

</code>```

This is my code in my create modal form, but I get this error:

Undefined variable: department

I want to use the modal form for my project.

```<code><div class="modal-body">
    @include('alert')
    {!! Form::open(['method'=>'POST','action'=>'PositionController@store']) !!}

        <div class="form-group">
            <label>Department</label>
            {!! Form::select('dep_id',$department,null,['class'=>'form-control','placeholder'=>'PLEASE SELECT']) !!}
        </div>

        <div class="form-group">
            <label>Position</label>
            {!! Form::text('position',null,['class'=>'form-control']) !!}
        </div>

        <div class="text-end">
            <button type="submit" class="btn btn-primary">Submit</button>
        </div>

    {!! Form::close() !!}
</div>
</code>```

Body:
This is my code in my Controller but I already try this method without using modal and it works.

public function create()
    {
        $department = Department::pluck('department', 'id');
        return view('positions.create',compact('department'));
    }

public function store()
    {
        $validator = Validator::make(Request::all(), [
            'dep_id'           => 'required',
            'position'         => 'required',
        ],
        [
            'dep_id.required'           =>  'Department Required',
            'position.required'       =>  'Position Required',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        Position::create(Request::all());
        Session::flash('message', 'Position Created Successfully');
        return redirect()->back();
    }

This is my Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Position extends Model
{
    protected $guarded = [];

    public function department(){
        return $this->belongsTo('App\Department','dep_id','id');
    }
}

This is my code in my create modal form, but I get this error:

Undefined variable: department

I want to use the modal form for my project.

    @include('alert')
    {!! Form::open(['method'=>'POST','action'=>'PositionController@store']) !!}

            Department
            {!! Form::select('dep_id',$department,null,['class'=>'form-control','placeholder'=>'PLEASE SELECT']) !!}

            Position
            {!! Form::text('position',null,['class'=>'form-control']) !!}

            <button type="submit" class="btn btn-primary">Submit</button>

    {!! Form::close() !!}


问:
Javascript Proxy Object in React Custom Hook
I have 2 custom hooks useFormInput and other useFormInputWithoutProxies which is using Javascript proxy

My Question what benefit does Javascript proxy provides over creating normal custom hooks ?

Can Somebody give real world use case or example as to when one would be using the proxy pattern to create custom hooks ? And is this a good pattern or an anti-pattern.

```<code>import { useState } from 'react';

// version using Proxies
function useFormInput(initialValue) {
  const [value, setValue] = useState(initialValue);

  const handler = {
    get: (target, property) => {
      if (property === 'value') {
        return value;
      } else {
        return target[property];
      }
    },
    set: (target, property, newValue) => {
      if (property === 'value') {
        setValue(newValue);
      }
      return true;
    }
  };

  const input = new Proxy({ value }, handler);

  return input;
}

// version without Proxies
function useFormInputWithoutProxies(initialValue) {
  const [value, setValue] = useState(initialValue);

  const input = {
    value,
    onChange: event => {
      setValue(event.target.value);
    }
  };

  return input;
}
</code>```

Body:
I have 2 custom hooks useFormInput and other useFormInputWithoutProxies which is using Javascript proxy

My Question what benefit does Javascript proxy provides over creating normal custom hooks ?

Can Somebody give real world use case or example as to when one would be using the proxy pattern to create custom hooks ? And is this a good pattern or an anti-pattern.

import { useState } from 'react';

// version using Proxies
function useFormInput(initialValue) {
  const [value, setValue] = useState(initialValue);

  const handler = {
    get: (target, property) => {
      if (property === 'value') {
        return value;
      } else {
        return target[property];
      }
    },
    set: (target, property, newValue) => {
      if (property === 'value') {
        setValue(newValue);
      }
      return true;
    }
  };

  const input = new Proxy({ value }, handler);

  return input;
}

// version without Proxies
function useFormInputWithoutProxies(initialValue) {
  const [value, setValue] = useState(initialValue);

  const input = {
    value,
    onChange: event => {
      setValue(event.target.value);
    }
  };

  return input;
}


问:
Changing cells in sheet using Java and Smartsheet API
I have a not big, but unsolvable for me problem. My Java code connects with smartsheet, and reads a list of sheets at folder (by folder id), next, it copies from folder ony sheets (leaving reports and dashboards), changing name of sheets and paste them at another folder. I'm using Correto 17.

How can I change a value of cell at any sheet by code. I need change only 1 cell for each running code, so it not should be a genius loop. I want to understand the basics of this.

Below I added 2 classes at part after copying and renaming. Everything is working perfect before I trying to change cell. If it will help: cell is unlocked, valueType text_number, not a formula, just text, but in sheet are other cells with values, they are with formulas / they are locked).

I can read a value at cell but can't set it.

```<code>public void projectFolderCreate(String projectID_Value) throws SmartsheetException {

 Smartsheet smartsheet = SmartsheetFactory.createDefaultClient(API);
 System.out.println("Folder working. Loading folder: " + getFolderID());

 Folder workFolder = smartsheet.folderResources().getFolder(getFolderID(), null);

for (var element : workFolder.getSheets()) {

System.out.println(element.getId());
ContainerDestination containerDestination = new ContainerDestination().setDestinationType(DestinationType.FOLDER).setDestinationId(8775808614459268L).setNewName(element.getName().replace("Project_Name", projectID_Value));
Sheet sheet = smartsheet.sheetResources().copySheet(element.getId(),containerDestination,EnumSet.of(SheetCopyInclusion.DATA,SheetCopyInclusion.CELLLINKS));
if (sheet.getName().endsWith("Metadata")) {
Sheet newSheet = smartsheet.sheetResources().getSheet(sheet.getId(),null,null,null,null,null,null,null);
long newSheetId = newSheet.getId();
System.out.println("ID of the New Sheet : " + newSheetId);
Column projIDcolumn = newSheet.getColumns().get(1);
System.out.println(projIDcolumn.getTitle());
Row firstRow = newSheet.getRows().get(2);
firstRow.getCells().get(2).setValue(new CellDataItem().setObjectValue(projectID_Value));
firstRow.getColumnByIndex(projIDcolumn.getIndex());
Cell s = newSheet.getRows().get(2).getCells().get(1).setDisplayValue(projectID_Value);
}System.out.println(sheet.getName() + " was created");
}
}
</code>```
```<code>ProjectFolderWorking(String projectID) throws SQLException, SmartsheetException {
String folderID;
LikeAWall law = new LikeAWall(1);
DataBase db = new DataBase(law.getPickDB());
db.setApi();
SmartIM smartIM = new SmartIM(db.getApi());
folderID = String.valueOf(SmartIM.getFolderID());
System.out.println("FolderID: " + folderID);
setProjectID(projectID);
smartIM.projectFolderCreate(getProjectID());
}
</code>```

I'm sure that linking to variable was good, because I tried getters, but setters of this aren't working but compiling without any exceptions / errors / bugs / problems and of coarse result.

Below are the methods I tried.

```<code>smartsheet.sheetResources().getSheet(sheet.getId(),null,null,null,null,null,null,null).getRows().get(2).getCells().set(1,null);
smartsheet.sheetResources().getSheet(sheet.getId(),null,null,null,null,null,null,null).getRows().get(2).getCells().get(1).setDisplayValue(projectID_Value)
smartsheet.sheetResources().getSheet(sheet.getId(),null,null,null,null,null,null,null).getRows().get(2).getCells().get(1).setValue(projectID_Value.toString) / and getBytes()
smartsheet.sheetResources().getSheet(sheet.getId(),null,null,null,null,null,null,null).getRows().get(2).getCells().get(1).setObjectValue()
</code>```

This is didn't make sense, but I just broke. I tried do every above with parts as:

```<code>Sheet sh = lallalalla;
Column s = sh.lalallalala;
Rows w = sh.lalallala;
Cell = w.getCells().get(lalallaa);
</code>```

Body:
I have a not big, but unsolvable for me problem. My Java code connects with smartsheet, and reads a list of sheets at folder (by folder id), next, it copies from folder ony sheets (leaving reports and dashboards), changing name of sheets and paste them at another folder. I'm using Correto 17.

How can I change a value of cell at any sheet by code. I need change only 1 cell for each running code, so it not should be a genius loop. I want to understand the basics of this.

Below I added 2 classes at part after copying and renaming. Everything is working perfect before I trying to change cell. If it will help: cell is unlocked, valueType text_number, not a formula, just text, but in sheet are other cells with values, they are with formulas / they are locked).

I can read a value at cell but can't set it.

public void projectFolderCreate(String projectID_Value) throws SmartsheetException {

 Smartsheet smartsheet = SmartsheetFactory.createDefaultClient(API);
 System.out.println("Folder working. Loading folder: " + getFolderID());

 Folder workFolder = smartsheet.folderResources().getFolder(getFolderID(), null);

for (var element : workFolder.getSheets()) {

System.out.println(element.getId());
ContainerDestination containerDestination = new ContainerDestination().setDestinationType(DestinationType.FOLDER).setDestinationId(8775808614459268L).setNewName(element.getName().replace("Project_Name", projectID_Value));
Sheet sheet = smartsheet.sheetResources().copySheet(element.getId(),containerDestination,EnumSet.of(SheetCopyInclusion.DATA,SheetCopyInclusion.CELLLINKS));
if (sheet.getName().endsWith("Metadata")) {
Sheet newSheet = smartsheet.sheetResources().getSheet(sheet.getId(),null,null,null,null,null,null,null);
long newSheetId = newSheet.getId();
System.out.println("ID of the New Sheet : " + newSheetId);
Column projIDcolumn = newSheet.getColumns().get(1);
System.out.println(projIDcolumn.getTitle());
Row firstRow = newSheet.getRows().get(2);
firstRow.getCells().get(2).setValue(new CellDataItem().setObjectValue(projectID_Value));
firstRow.getColumnByIndex(projIDcolumn.getIndex());
Cell s = newSheet.getRows().get(2).getCells().get(1).setDisplayValue(projectID_Value);
}System.out.println(sheet.getName() + " was created");
}
}

ProjectFolderWorking(String projectID) throws SQLException, SmartsheetException {
String folderID;
LikeAWall law = new LikeAWall(1);
DataBase db = new DataBase(law.getPickDB());
db.setApi();
SmartIM smartIM = new SmartIM(db.getApi());
folderID = String.valueOf(SmartIM.getFolderID());
System.out.println("FolderID: " + folderID);
setProjectID(projectID);
smartIM.projectFolderCreate(getProjectID());
}

I'm sure that linking to variable was good, because I tried getters, but setters of this aren't working but compiling without any exceptions / errors / bugs / problems and of coarse result.

Below are the methods I tried.

smartsheet.sheetResources().getSheet(sheet.getId(),null,null,null,null,null,null,null).getRows().get(2).getCells().set(1,null);
smartsheet.sheetResources().getSheet(sheet.getId(),null,null,null,null,null,null,null).getRows().get(2).getCells().get(1).setDisplayValue(projectID_Value)
smartsheet.sheetResources().getSheet(sheet.getId(),null,null,null,null,null,null,null).getRows().get(2).getCells().get(1).setValue(projectID_Value.toString) / and getBytes()
smartsheet.sheetResources().getSheet(sheet.getId(),null,null,null,null,null,null,null).getRows().get(2).getCells().get(1).setObjectValue()

This is didn't make sense, but I just broke. I tried do every above with parts as:

Sheet sh = lallalalla;
Column s = sh.lalallalala;
Rows w = sh.lalallala;
Cell = w.getCells().get(lalallaa);


问:
Can't move validation from view to serializer
I need to move validation from views.py to serializators.py.
How can I do it?

Validation must check:

user can't follow himself

user can't follow author that his already follow

I have a ViewSet with @action:

my view.py:

```<code>@action(

        detail=True,

        methods=['post', 'delete'],

        permission_classes=(permissions.IsAuthenticated,)

    )

    def subscribe(self, request, id=None):

        """Following"""

        author_id = id

        if request.method == 'POST':

            author = get_object_or_404(CustomUser, id=author_id)

            if author == request.user:

                raise serializers.ValidationError(

                    {'errors': 'You can't follow yourself.'}

                )

            if self.request.user.follower.filter(author=author).exists():

                raise serializers.ValidationError(

                    {'errors': 'You already follow this author.'}

                )

            author = get_object_or_404(CustomUser, id=author_id)

            Follow.objects.create(

                user=request.user, author=author

            )

            serializer = FollowSerializer(author, context={'request': request})

            return Response(serializer.data, status=status.HTTP_201_CREATED)

        if request.method == 'DELETE':

            user_id = request.user.id

            subscribe = get_object_or_404(

                Follow, user__id=user_id, author__id=author_id

            )

            subscribe.delete()

            return Response(status=status.HTTP_204_NO_CONTENT)
</code>```

and I have a FollowSerializer in serializers.py

my serializers.py

```<code>class FollowSerializer(serializers.ModelSerializer):

    class Meta:

        model = CustomUser

        fields = ('email', 'id', 'username', 'first_name',

                  'last_name', 'is_subscribed', 'recipes', 'recipes_count')
</code>```

I try to add a validate method like def validate(self, data): but it doesn't work.

Body:
I need to move validation from views.py to serializators.py.
How can I do it?

Validation must check:

user can't follow himself

user can't follow author that his already follow

I have a ViewSet with @action:

my view.py:

@action(

        detail=True,

        methods=['post', 'delete'],

        permission_classes=(permissions.IsAuthenticated,)

    )

    def subscribe(self, request, id=None):

        """Following"""

        author_id = id

        if request.method == 'POST':

            author = get_object_or_404(CustomUser, id=author_id)

            if author == request.user:

                raise serializers.ValidationError(

                    {'errors': 'You can't follow yourself.'}

                )

            if self.request.user.follower.filter(author=author).exists():

                raise serializers.ValidationError(

                    {'errors': 'You already follow this author.'}

                )

            author = get_object_or_404(CustomUser, id=author_id)

            Follow.objects.create(

                user=request.user, author=author

            )

            serializer = FollowSerializer(author, context={'request': request})

            return Response(serializer.data, status=status.HTTP_201_CREATED)

        if request.method == 'DELETE':

            user_id = request.user.id

            subscribe = get_object_or_404(

                Follow, user__id=user_id, author__id=author_id

            )

            subscribe.delete()

            return Response(status=status.HTTP_204_NO_CONTENT)

and I have a FollowSerializer in serializers.py

my serializers.py

class FollowSerializer(serializers.ModelSerializer):

    class Meta:

        model = CustomUser

        fields = ('email', 'id', 'username', 'first_name',

                  'last_name', 'is_subscribed', 'recipes', 'recipes_count')

I try to add a validate method like def validate(self, data): but it doesn't work.


问:
How to implement uploading a snapshot taken in firebase?
I don't understand honestly. why the picture is compressed to quality 7 -10.61 KB

when it should upload about 3mb

```<code>else if (requestCode == CAMERA_PICTURE_REQUEST_CODE && resultCode == Activity.RESULT_OK) {

        Bundle extras = data.getExtras();
        Bitmap bitmap = (Bitmap) extras.get("data");
        imagePreview.setImageBitmap(bitmap);
        filePath = getImageUri(getApplicationContext(), bitmap);
    }
}

private Uri getImageUri(Context context, Bitmap bitmap) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
1. bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "title", null);
    return Uri.parse(path);
}
</code>```

what's wrong here? why does it compress to a very small format

Body:
I don't understand honestly. why the picture is compressed to quality 7 -10.61 KB

when it should upload about 3mb

else if (requestCode == CAMERA_PICTURE_REQUEST_CODE && resultCode == Activity.RESULT_OK) {

        Bundle extras = data.getExtras();
        Bitmap bitmap = (Bitmap) extras.get("data");
        imagePreview.setImageBitmap(bitmap);
        filePath = getImageUri(getApplicationContext(), bitmap);
    }
}

private Uri getImageUri(Context context, Bitmap bitmap) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
1. bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "title", null);
    return Uri.parse(path);
}

what's wrong here? why does it compress to a very small format


问:
Can't deploy random forest model
emphasized textHalo I'm new to shinny and R, but can't deploy random forest model because the dataframe that I made didn't exist and error "**

Error in $<-.data.frame: replacement has 0 rows, data has 1`

Anyone with same problem ? thank you

Title: Can't deploy random forest model


问:
'NoneType' object has no attribute 'text' - Beautifulsoup
I managed to retrieve the HTML of the page, but when I tried to iterate through each review div to get the text, it returned this error:

AttributeError: 'NoneType' object has no attribute 'text'

I have tried changing html.parser to lxml or html5lib but it still returns the same error.

Here is the code:

```<code>import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait as Wait
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.chrome.options import Options
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from bs4 import BeautifulSoup as bs
</code>```

Retrieve HTML from the page using selenium

```<code>options = Options()

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.get('https://www.imdb.com/title/tt0241527/reviews?ref_=tt_sa_3')

while True:
    try:
        time.sleep(1)
        driver.execute_script("arguments[0].click();", WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, 'load-more-trigger'))))
    except NoSuchElementException:
        break
</code>```

Iterate through divs to extract the texts

```<code>doc = driver.page_source
html = doc
soup = bs(html, 'html.parser')

reviews = []

review_divs = soup.find_all('div', class_='lister-item-content')

# Iterate through each review div
for review_div in review_divs:
    # Get review title
    title = review_div.find('a', class_='title').text

    # Get review score
    score = review_div.find('span', class_='rating-other-user-rating').text

    # Get review content
    content = review_div.find('div', class_='text show-more__control').text

    # Create dictionary for review data
    review = {
            'title': title,
            'score': score,
            'content': content
        }

    # Append review data to reviews list
    reviews.append(review)
</code>```

Body:
I managed to retrieve the HTML of the page, but when I tried to iterate through each review div to get the text, it returned this error:

AttributeError: 'NoneType' object has no attribute 'text'

I have tried changing html.parser to lxml or html5lib but it still returns the same error.

Here is the code:

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait as Wait
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.chrome.options import Options
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from bs4 import BeautifulSoup as bs

Retrieve HTML from the page using selenium

options = Options()

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.get('https://www.imdb.com/title/tt0241527/reviews?ref_=tt_sa_3')

while True:
    try:
        time.sleep(1)
        driver.execute_script("arguments[0].click();", WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, 'load-more-trigger'))))
    except NoSuchElementException:
        break

Iterate through divs to extract the texts

doc = driver.page_source
html = doc
soup = bs(html, 'html.parser')

reviews = []

review_divs = soup.find_all('div', class_='lister-item-content')

# Iterate through each review div
for review_div in review_divs:
    # Get review title
    title = review_div.find('a', class_='title').text

    # Get review score
    score = review_div.find('span', class_='rating-other-user-rating').text

    # Get review content
    content = review_div.find('div', class_='text show-more__control').text

    # Create dictionary for review data
    review = {
            'title': title,
            'score': score,
            'content': content
        }

    # Append review data to reviews list
    reviews.append(review)


问:
Installing tfjs in Mac M1pro
I'm installing tfjs on my Mac, however, i've spent a lot of time struggling.

My Mac version is: Monterey 12.6, M1 silicon

My node version:18.8.0(in fact, i falied using other versions as well,16.18.0 e.g.)

npm version: 8.18.0

i've tried a lot of methods, including change the version of python, change the version of npm and node, none of them worked.

The error is as follows:

```<code>npm ERR! code 1
npm ERR! path /Users/zhanghan/R_projects/site/helloworld/node_modules/@tensorflow/tfjs-node
npm ERR! command failed
npm ERR! command sh -c -- node scripts/install.js
npm ERR! CPU-darwin-4.1.0.tar.gz
npm ERR! https://storage.googleapis.com/tf-builds/libtensorflow_r2_7_darwin_arm64_cpu.tar.gz
npm ERR! node-pre-gyp install failed with error: Error: Command failed: node-pre-gyp install --fallback-to-build
npm ERR! node-pre-gyp info it worked if it ends with ok
npm ERR! node-pre-gyp info using node-pre-gyp@1.0.9
npm ERR! node-pre-gyp info using node@18.8.0 | darwin | arm64
npm ERR! node-pre-gyp info check checked for "/Users/zhanghan/R_projects/site/helloworld/node_modules/@tensorflow/tfjs-node/lib/napi-v8/tfjs_binding.node" (not found)
npm ERR! node-pre-gyp http GET https://storage.googleapis.com/tf-builds/pre-built-binary/napi-v8/4.1.0/CPU-darwin-4.1.0.tar.gz
npm ERR! node-pre-gyp ERR! install response status 404 Not Found on https://storage.googleapis.com/tf-builds/pre-built-binary/napi-v8/4.1.0/CPU-darwin-4.1.0.tar.gz
npm ERR! node-pre-gyp WARN Pre-built binaries not installable for @tensorflow/tfjs-node@4.1.0 and node@18.8.0 (node-v108 ABI, unknown) (falling back to source compile with node-gyp)
npm ERR! node-pre-gyp WARN Hit error response status 404 Not Found on https://storage.googleapis.com/tf-builds/pre-built-binary/napi-v8/4.1.0/CPU-darwin-4.1.0.tar.gz
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp info using node-gyp@9.1.0
npm ERR! gyp info using node@18.8.0 | darwin | arm64
npm ERR! gyp info ok
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp info using node-gyp@9.1.0
npm ERR! gyp info using node@18.8.0 | darwin | arm64
npm ERR! gyp info find Python using Python version 3.9.12 found at "/opt/anaconda3/envs/mujoco/bin/python3"
npm ERR! gyp WARN EACCES current user ("zhanghan") does not have permission to access the dev dir "/Users/zhanghan/Library/Caches/node-gyp/18.8.0"
npm ERR! gyp WARN EACCES attempting to reinstall using temporary dev dir "/var/folders/nd/sbq4px9x4bqd0yrtkrp2y3zh0000gn/T/.node-gyp"
npm ERR! gyp http GET https://nodejs.org/download/release/v18.8.0/node-v18.8.0-headers.tar.gz
npm ERR! gyp http 200 https://nodejs.org/download/release/v18.8.0/node-v18.8.0-headers.tar.gz
npm ERR! gyp http GET https://nodejs.org/download/release/v18.8.0/SHASUMS256.txt
npm ERR! gyp http 200 https://nodejs.org/download/release/v18.8.0/SHASUMS256.txt
npm ERR! gyp info spawn /opt/anaconda3/envs/mujoco/bin/python3
npm ERR! gyp info spawn args [
npm ERR! gyp info spawn args   '/Users/zhanghan/.nvm/versions/node/v18.8.0/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py',
npm ERR! gyp info spawn args   'binding.gyp',
npm ERR! gyp info spawn args   '-f',
npm ERR! gyp info spawn args   'make',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/Users/zhanghan/R_projects/site/helloworld/node_modules/@tensorflow/tfjs-node/build/config.gypi',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/Users/zhanghan/.nvm/versions/node/v18.8.0/lib/node_modules/npm/node_modules/node-gyp/addon.gypi',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/var/folders/nd/sbq4px9x4bqd0yrtkrp2y3zh0000gn/T/.node-gyp/18.8.0/include/node/common.gypi',
npm ERR! gyp info spawn args   '-Dlibrary=shared_library',
npm ERR! gyp info spawn args   '-Dvisibility=default',
npm ERR! gyp info spawn args   '-Dnode_root_dir=/var/folders/nd/sbq4px9x4bqd0yrtkrp2y3zh0000gn/T/.node-gyp/18.8.0',
npm ERR! gyp info spawn args   '-Dnode_gyp_dir=/Users/zhanghan/.nvm/versions/node/v18.8.0/lib/node_modules/npm/node_modules/node-gyp',
npm ERR! gyp info spawn args   '-Dnode_lib_file=/var/folders/nd/sbq4px9x4bqd0yrtkrp2y3zh0000gn/T/.node-gyp/18.8.0/<(target_arch)/node.lib',
npm ERR! gyp info spawn args   '-Dmodule_root_dir=/Users/zhanghan/R_projects/site/helloworld/node_modules/@tensorflow/tfjs-node',
npm ERR! gyp info spawn args   '-Dnode_engine=v8',
npm ERR! gyp info spawn args   '--depth=.',
npm ERR! gyp info spawn args   '--no-parallel',
npm ERR! gyp info spawn args   '--generator-output',
npm ERR! gyp info spawn args   'build',
npm ERR! gyp info spawn args   '-Goutput_dir=.'
npm ERR! gyp info spawn args ]
npm ERR! gyp info ok
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp info using node-gyp@9.1.0
npm ERR! gyp info using node@18.8.0 | darwin | arm64
npm ERR! gyp info spawn make
npm ERR! gyp info spawn args [ 'BUILDTYPE=Release', '-C', 'build' ]
npm ERR! make: /usr/local/opt/llvm/bin/clang++: No such file or directory
npm ERR! make: *** [Release/obj.target/tfjs_binding/binding/tfjs_backend.o] Error 1
npm ERR! gyp ERR! build error
npm ERR! gyp ERR! stack Error: `make` failed with exit code: 2
npm ERR! gyp ERR! stack     at ChildProcess.onExit (/Users/zhanghan/.nvm/versions/node/v18.8.0/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:201:23)
npm ERR! gyp ERR! stack     at ChildProcess.emit (node:events:513:28)
npm ERR! gyp ERR! stack     at ChildProcess._handle.onexit (node:internal/child_process:291:12)
npm ERR! gyp ERR! System Darwin 21.6.0
npm ERR! gyp ERR! command "/Users/zhanghan/.nvm/versions/node/v18.8.0/bin/node" "/Users/zhanghan/.nvm/versions/node/v18.8.0/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "build" "--fallback-to-build" "--module=/Users/zhanghan/R_projects/site/helloworld/node_modules/@tensorflow/tfjs-node/lib/napi-v8/tfjs_binding.node" "--module_name=tfjs_binding" "--module_path=/Users/zhanghan/R_projects/site/helloworld/node_modules/@tensorflow/tfjs-node/lib/napi-v8" "--napi_version=8" "--node_abi_napi=napi" "--napi_build_version=8" "--node_napi_label=napi-v8"
npm ERR! gyp ERR! cwd /Users/zhanghan/R_projects/site/helloworld/node_modules/@tensorflow/tfjs-node
npm ERR! gyp ERR! node -v v18.8.0
npm ERR! gyp ERR! node-gyp -v v9.1.0
npm ERR! gyp ERR! not ok
npm ERR! node-pre-gyp ERR! build error
npm ERR! node-pre-gyp ERR! stack Error: Failed to execute

</code>```

Hope someone can help with me!

Title: Installing tfjs in Mac M1pro

Body:
I'm installing tfjs on my Mac, however, i've spent a lot of time struggling.

My Mac version is: Monterey 12.6, M1 silicon

My node version:18.8.0(in fact, i falied using other versions as well,16.18.0 e.g.)

npm version: 8.18.0

i've tried a lot of methods, including change the version of python, change the version of npm and node, none of them worked.

The error is as follows:

npm ERR! code 1
npm ERR! path /Users/zhanghan/R_projects/site/helloworld/node_modules/@tensorflow/tfjs-node
npm ERR! command failed
npm ERR! command sh -c -- node scripts/install.js
npm ERR! CPU-darwin-4.1.0.tar.gz
npm ERR! https://storage.googleapis.com/tf-builds/libtensorflow_r2_7_darwin_arm64_cpu.tar.gz
npm ERR! node-pre-gyp install failed with error: Error: Command failed: node-pre-gyp install --fallback-to-build
npm ERR! node-pre-gyp info it worked if it ends with ok
npm ERR! node-pre-gyp info using node-pre-gyp@1.0.9
npm ERR! node-pre-gyp info using node@18.8.0 | darwin | arm64
npm ERR! node-pre-gyp info check checked for "/Users/zhanghan/R_projects/site/helloworld/node_modules/@tensorflow/tfjs-node/lib/napi-v8/tfjs_binding.node" (not found)
npm ERR! node-pre-gyp http GET https://storage.googleapis.com/tf-builds/pre-built-binary/napi-v8/4.1.0/CPU-darwin-4.1.0.tar.gz
npm ERR! node-pre-gyp ERR! install response status 404 Not Found on https://storage.googleapis.com/tf-builds/pre-built-binary/napi-v8/4.1.0/CPU-darwin-4.1.0.tar.gz
npm ERR! node-pre-gyp WARN Pre-built binaries not installable for @tensorflow/tfjs-node@4.1.0 and node@18.8.0 (node-v108 ABI, unknown) (falling back to source compile with node-gyp)
npm ERR! node-pre-gyp WARN Hit error response status 404 Not Found on https://storage.googleapis.com/tf-builds/pre-built-binary/napi-v8/4.1.0/CPU-darwin-4.1.0.tar.gz
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp info using node-gyp@9.1.0
npm ERR! gyp info using node@18.8.0 | darwin | arm64
npm ERR! gyp info ok
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp info using node-gyp@9.1.0
npm ERR! gyp info using node@18.8.0 | darwin | arm64
npm ERR! gyp info find Python using Python version 3.9.12 found at "/opt/anaconda3/envs/mujoco/bin/python3"
npm ERR! gyp WARN EACCES current user ("zhanghan") does not have permission to access the dev dir "/Users/zhanghan/Library/Caches/node-gyp/18.8.0"
npm ERR! gyp WARN EACCES attempting to reinstall using temporary dev dir "/var/folders/nd/sbq4px9x4bqd0yrtkrp2y3zh0000gn/T/.node-gyp"
npm ERR! gyp http GET https://nodejs.org/download/release/v18.8.0/node-v18.8.0-headers.tar.gz
npm ERR! gyp http 200 https://nodejs.org/download/release/v18.8.0/node-v18.8.0-headers.tar.gz
npm ERR! gyp http GET https://nodejs.org/download/release/v18.8.0/SHASUMS256.txt
npm ERR! gyp http 200 https://nodejs.org/download/release/v18.8.0/SHASUMS256.txt
npm ERR! gyp info spawn /opt/anaconda3/envs/mujoco/bin/python3
npm ERR! gyp info spawn args [
npm ERR! gyp info spawn args   '/Users/zhanghan/.nvm/versions/node/v18.8.0/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py',
npm ERR! gyp info spawn args   'binding.gyp',
npm ERR! gyp info spawn args   '-f',
npm ERR! gyp info spawn args   'make',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/Users/zhanghan/R_projects/site/helloworld/node_modules/@tensorflow/tfjs-node/build/config.gypi',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/Users/zhanghan/.nvm/versions/node/v18.8.0/lib/node_modules/npm/node_modules/node-gyp/addon.gypi',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/var/folders/nd/sbq4px9x4bqd0yrtkrp2y3zh0000gn/T/.node-gyp/18.8.0/include/node/common.gypi',
npm ERR! gyp info spawn args   '-Dlibrary=shared_library',
npm ERR! gyp info spawn args   '-Dvisibility=default',
npm ERR! gyp info spawn args   '-Dnode_root_dir=/var/folders/nd/sbq4px9x4bqd0yrtkrp2y3zh0000gn/T/.node-gyp/18.8.0',
npm ERR! gyp info spawn args   '-Dnode_gyp_dir=/Users/zhanghan/.nvm/versions/node/v18.8.0/lib/node_modules/npm/node_modules/node-gyp',
npm ERR! gyp info spawn args   '-Dnode_lib_file=/var/folders/nd/sbq4px9x4bqd0yrtkrp2y3zh0000gn/T/.node-gyp/18.8.0/<(target_arch)/node.lib',
npm ERR! gyp info spawn args   '-Dmodule_root_dir=/Users/zhanghan/R_projects/site/helloworld/node_modules/@tensorflow/tfjs-node',
npm ERR! gyp info spawn args   '-Dnode_engine=v8',
npm ERR! gyp info spawn args   '--depth=.',
npm ERR! gyp info spawn args   '--no-parallel',
npm ERR! gyp info spawn args   '--generator-output',
npm ERR! gyp info spawn args   'build',
npm ERR! gyp info spawn args   '-Goutput_dir=.'
npm ERR! gyp info spawn args ]
npm ERR! gyp info ok
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp info using node-gyp@9.1.0
npm ERR! gyp info using node@18.8.0 | darwin | arm64
npm ERR! gyp info spawn make
npm ERR! gyp info spawn args [ 'BUILDTYPE=Release', '-C', 'build' ]
npm ERR! make: /usr/local/opt/llvm/bin/clang++: No such file or directory
npm ERR! make: *** [Release/obj.target/tfjs_binding/binding/tfjs_backend.o] Error 1
npm ERR! gyp ERR! build error
npm ERR! gyp ERR! stack Error: `make` failed with exit code: 2
npm ERR! gyp ERR! stack     at ChildProcess.onExit (/Users/zhanghan/.nvm/versions/node/v18.8.0/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:201:23)
npm ERR! gyp ERR! stack     at ChildProcess.emit (node:events:513:28)
npm ERR! gyp ERR! stack     at ChildProcess._handle.onexit (node:internal/child_process:291:12)
npm ERR! gyp ERR! System Darwin 21.6.0
npm ERR! gyp ERR! command "/Users/zhanghan/.nvm/versions/node/v18.8.0/bin/node" "/Users/zhanghan/.nvm/versions/node/v18.8.0/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "build" "--fallback-to-build" "--module=/Users/zhanghan/R_projects/site/helloworld/node_modules/@tensorflow/tfjs-node/lib/napi-v8/tfjs_binding.node" "--module_name=tfjs_binding" "--module_path=/Users/zhanghan/R_projects/site/helloworld/node_modules/@tensorflow/tfjs-node/lib/napi-v8" "--napi_version=8" "--node_abi_napi=napi" "--napi_build_version=8" "--node_napi_label=napi-v8"
npm ERR! gyp ERR! cwd /Users/zhanghan/R_projects/site/helloworld/node_modules/@tensorflow/tfjs-node
npm ERR! gyp ERR! node -v v18.8.0
npm ERR! gyp ERR! node-gyp -v v9.1.0
npm ERR! gyp ERR! not ok
npm ERR! node-pre-gyp ERR! build error
npm ERR! node-pre-gyp ERR! stack Error: Failed to execute

Hope someone can help with me!


问:
Use tensorboard with already trained models
Want to see mine model like in Netron but maybe get more infomation.

I tried "Get started with TensorBoard" in Colab but it load the log dir. But
i have to in some way load the log with mine model without training.


问:
How do I change the font list in my browser using selenium?
I'm doing a fingerprint swap (selenium + chromedriver), basically overriding objects with javascript. Got as far as changing the font list, can't find how to do it.
For example, I have an array of font names: ["Arial", "Arial Black", "Calibri", "Cambria"], how can I replace the font list with this one so that sites collecting the browser fingerprint get it?

Tried to find the chrome argument to load a list of custom fonts, but couldn't find it.


问:
Get the error "All intermediate steps should be transformers and implement fit and transform or be the string passthrough" and I can't resolve it
I'm trying to create a training and predicting pipeline that allows me to train models using various sizes of training data and perform predictions on the testing data, I wrote a function:

```<code>def train_predict(learner, sample_size, X_train, y_train, X_test, y_test):
    results = {}
    learner = Pipeline(steps=[('tree', DecisionTreeClassifier()),
                                     ('logistic', LogisticRegression()),
                                     ('naive', MultinomialNB())])
    learner.fit(X_train, y_train)
    predictions_test = learner.predict(X_test)
    predictions_train = learner.predict(X_train[:300])
    results['acc_train'] = accuracy_score(y_train[:300], predictions_train)
    results['acc_test'] = accuracy_score(y_test, predictions_test)
    results['f_train'] = fbeta_score(y_train[:300], predictions_train, beta=0.5)
    results['f_test'] = fbeta_score(y_test, predictions_test, beta=0.5)
    print("{} trained on {} samples.".format(learner.__class__.__name__, sample_size))
    return results
</code>```

and then wrote that code:

```<code>clf_A = DecisionTreeClassifier()
clf_B = LogisticRegression()
clf_C = MultinomialNB()
samples_100 = len(y_train)
samples_10 = int(len(y_train) * 0.1)
samples_1 = int(len(y_train) * 0.01)
results = {}
for clf in [clf_A, clf_B, clf_C]:
    clf_name = clf.__class__.__name__
    results[clf_name] = {}
    for i, samples in enumerate([samples_1, samples_10, samples_100]):
        results[clf_name][i] = \
        train_predict(clf, samples, X_train, y_train, X_test, y_test)
vs.evaluate(results, accuracy, fscore)
</code>```

but got the error:

```<code>TypeError: All intermediate steps should be transformers and implement fit and transform or be the string 'passthrough' 'DecisionTreeClassifier()' (type <class 'sklearn.tree._classes.DecisionTreeClassifier'>) doesn't
</code>```

I tried a lot and did not find a solution, can you help me?

Body:
I'm trying to create a training and predicting pipeline that allows me to train models using various sizes of training data and perform predictions on the testing data, I wrote a function:

def train_predict(learner, sample_size, X_train, y_train, X_test, y_test):
    results = {}
    learner = Pipeline(steps=[('tree', DecisionTreeClassifier()),
                                     ('logistic', LogisticRegression()),
                                     ('naive', MultinomialNB())])
    learner.fit(X_train, y_train)
    predictions_test = learner.predict(X_test)
    predictions_train = learner.predict(X_train[:300])
    results['acc_train'] = accuracy_score(y_train[:300], predictions_train)
    results['acc_test'] = accuracy_score(y_test, predictions_test)
    results['f_train'] = fbeta_score(y_train[:300], predictions_train, beta=0.5)
    results['f_test'] = fbeta_score(y_test, predictions_test, beta=0.5)
    print("{} trained on {} samples.".format(learner.__class__.__name__, sample_size))
    return results

and then wrote that code:

clf_A = DecisionTreeClassifier()
clf_B = LogisticRegression()
clf_C = MultinomialNB()
samples_100 = len(y_train)
samples_10 = int(len(y_train) * 0.1)
samples_1 = int(len(y_train) * 0.01)
results = {}
for clf in [clf_A, clf_B, clf_C]:
    clf_name = clf.__class__.__name__
    results[clf_name] = {}
    for i, samples in enumerate([samples_1, samples_10, samples_100]):
        results[clf_name][i] = \
        train_predict(clf, samples, X_train, y_train, X_test, y_test)
vs.evaluate(results, accuracy, fscore)

but got the error:

TypeError: All intermediate steps should be transformers and implement fit and transform or be the string 'passthrough' 'DecisionTreeClassifier()' (type <class 'sklearn.tree._classes.DecisionTreeClassifier'>) doesn't

I tried a lot and did not find a solution, can you help me?


问:
Matching a csv file and output in Shiny
I would like Shiny (RStudio) to load a csv file and have it report a result. Very similar to the code I attached, but instead of a textInput I would like the input to be a csv file, which will be a column with a title and multiple rows with characters.

Do you have any idea how I can do this?

Thank you very much for the support.

```<code>library(shiny)
library(tidyverse)

df = tibble(id=as.character(c("A", "B", "C")),stock=as.double(c(210.57,94.42,412.31)))

ui <- fluidPage(
  textInput(inputId = "stock", "Stock", placeholder = "i.e. 210.57"),
  actionButton(inputId = "click", "Click"),
  tableOutput(outputId = "table")
)

server <- function(input, output) {

  result = eventReactive(input$click, {
    df %>% filter(stock %in% input$stock) %>%
      distinct(id, stock) %>%
      group_by(id) %>%
      slice(first(which(stock >= input$stock)))
  })

  output$table = renderTable({
    result()
  })
}
# Run the application
shinyApp(ui = ui, server = server)
</code>```

I haven't tried anything yet, because I have no idea how to do it.

Title: Matching a csv file and output in Shiny

Body:
I would like Shiny (RStudio) to load a csv file and have it report a result. Very similar to the code I attached, but instead of a textInput I would like the input to be a csv file, which will be a column with a title and multiple rows with characters.

Do you have any idea how I can do this?

Thank you very much for the support.

library(shiny)
library(tidyverse)

df = tibble(id=as.character(c("A", "B", "C")),stock=as.double(c(210.57,94.42,412.31)))

ui <- fluidPage(
  textInput(inputId = "stock", "Stock", placeholder = "i.e. 210.57"),
  actionButton(inputId = "click", "Click"),
  tableOutput(outputId = "table")
)

server <- function(input, output) {

  result = eventReactive(input$click, {
    df %>% filter(stock %in% input$stock) %>%
      distinct(id, stock) %>%
      group_by(id) %>%
      slice(first(which(stock >= input$stock)))
  })

  output$table = renderTable({
    result()
  })
}
# Run the application
shinyApp(ui = ui, server = server)

I haven't tried anything yet, because I have no idea how to do it.


问:
Why is my github desktop fetching origin goes infinitely hang on?
enter image description here
My github desktop gets stuck and infinitely load(actually takes like 10minutes) and goes to refreshing repository(also takes 10minutes). Whats happening? i need to back up my unity project, but I'm stucked on this problem. Could somebody help me?

I need to make my github desktop faster. Its too slow to use. push and pull in empty project takes 20minutes. Wish someone answer this problem.


问:
Theme.json Wordpress - Bold Font Weight of Google Font Doesn't Show in Chrome, only in Safari
I'm building my own WordPress Block Theme and have the following issue.

I'm trying to enrol the Google Font "PT Serif" via my theme.json. It works like a charm with Chrome and Safari, however, just for the regular 400 font-weight.

The bold 700 font-weight is reflected in Safari, but not in Chrome. Has anyone a solution for me? I've been sitting on this for hours.

Here's the full theme.json

```<code>{
    "version": 2,
    "settings": {
        "appearanceTools": true,
        "color": {
            "palette": [
                {
                    "slug": "background",
                    "color": "#ffffff",
                    "name": "Background"
                },
                {
                    "slug": "foreground",
                    "color": "#2e2e2e",
                    "name": "Foreground"
                },
                {
                    "slug": "primary",
                    "color": "#1c569e",
                    "name": "Primary"
                },
                {
                    "slug": "secondary",
                    "color": "#ffc860",
                    "name": "Secondary"
                },
                {
                    "slug": "consulterce-blue",
                    "color": "#15212a",
                    "name": "Consulterce Blue"
                }
            ]
        },
        "layout": {
            "contentSize": "700px",
            "wideSize": "1100px"
        },
        "spacing": {
            "units": [ "px", "em", "rem", "vh", "vw", "%" ]
        },
        "typography": {
            "fontFamilies": [
              {
                "fontFamily": "\"PT Serif\", serif",
                "name": "PT Serif",
                "slug": "pt-serif",
                "fontFace": [
                  {
                    "fontFamily": "PT Serif",
                    "fontWeight": "400",
                    "fontStyle": "normal",
                    "fontStretch": "normal",
                    "src": [ "file:./fonts/pt-serif-v17-latin-regular.woff2" ]
                  },
                  {
                    "fontFamily": "PT Serif",
                    "fontWeight": "700",
                    "fontStyle": "bold",
                    "fontStretch": "normal",
                    "src": [ "file:./fonts/pt-serif-v17-latin-700.woff2" ]
                  },
                  {
                    "fontFamily": "PT Serif",
                    "fontWeight": "400",
                    "fontStyle": "italic",
                    "fontStretch": "normal",
                    "src": [ "file:./fonts/pt-serif-v17-latin-italic.woff2" ]
                  }
                ]
              }
            ]
        }
    },
    "styles": {
        "typography": {
            "fontFamily": "var(--wp--preset--font-family--pt-serif)"
        },
        "color": {
            "background": "var(--wp--preset--color--background)",
            "text": "var(--wp--preset--color--foreground)"
        }
    }
}
</code>```

Body:
I'm building my own WordPress Block Theme and have the following issue.

I'm trying to enrol the Google Font "PT Serif" via my theme.json. It works like a charm with Chrome and Safari, however, just for the regular 400 font-weight.

The bold 700 font-weight is reflected in Safari, but not in Chrome. Has anyone a solution for me? I've been sitting on this for hours.

Here's the full theme.json

{
    "version": 2,
    "settings": {
        "appearanceTools": true,
        "color": {
            "palette": [
                {
                    "slug": "background",
                    "color": "#ffffff",
                    "name": "Background"
                },
                {
                    "slug": "foreground",
                    "color": "#2e2e2e",
                    "name": "Foreground"
                },
                {
                    "slug": "primary",
                    "color": "#1c569e",
                    "name": "Primary"
                },
                {
                    "slug": "secondary",
                    "color": "#ffc860",
                    "name": "Secondary"
                },
                {
                    "slug": "consulterce-blue",
                    "color": "#15212a",
                    "name": "Consulterce Blue"
                }
            ]
        },
        "layout": {
            "contentSize": "700px",
            "wideSize": "1100px"
        },
        "spacing": {
            "units": [ "px", "em", "rem", "vh", "vw", "%" ]
        },
        "typography": {
            "fontFamilies": [
              {
                "fontFamily": "\"PT Serif\", serif",
                "name": "PT Serif",
                "slug": "pt-serif",
                "fontFace": [
                  {
                    "fontFamily": "PT Serif",
                    "fontWeight": "400",
                    "fontStyle": "normal",
                    "fontStretch": "normal",
                    "src": [ "file:./fonts/pt-serif-v17-latin-regular.woff2" ]
                  },
                  {
                    "fontFamily": "PT Serif",
                    "fontWeight": "700",
                    "fontStyle": "bold",
                    "fontStretch": "normal",
                    "src": [ "file:./fonts/pt-serif-v17-latin-700.woff2" ]
                  },
                  {
                    "fontFamily": "PT Serif",
                    "fontWeight": "400",
                    "fontStyle": "italic",
                    "fontStretch": "normal",
                    "src": [ "file:./fonts/pt-serif-v17-latin-italic.woff2" ]
                  }
                ]
              }
            ]
        }
    },
    "styles": {
        "typography": {
            "fontFamily": "var(--wp--preset--font-family--pt-serif)"
        },
        "color": {
            "background": "var(--wp--preset--color--background)",
            "text": "var(--wp--preset--color--foreground)"
        }
    }
}


问:
Eclipse 's "Run as" does not auto add "Run on Server" even to I added the Tomcat server to the Project?
I am coding java with eclipse and here is my problem.

I added Tomcat v10.0 to my Project successfully and as you can see in this picture

But my problem is, I do not see the "Run on Server" when I clicked to the "Run As" ? As you can see in this picture ?

I think that when I added the Tomcat successfully, the Tomcat must appeared at "Run As" ?

Could you please give me some advice ? Thank you in advance.


问:
EMV transaction apple/google pay
I need to write a program for making contactless transactions that will support both payment with a physical EMV credit card chip, and payment with Google Pay or Apple Pay,

I have to treat each transaction differently and currently I have no way to differentiate between these types of transactions because they are both cataloged under "Contactless"

What is the earliest possible indication that I have from the moment the card is recognized until I can tell what type of transaction it is?

Is there a unique AIP for Google or Apple Pay transactions?
I saw that there is an option through tag 82 to see if a certain bit is on, but I didn't understand how I could check....

What other ways do I have to get the indication?

I tried to look for a unique parameter that differentiates between the types of transactions, I tried to look for whether there are unique tags but I saw that it varies between each brand and it was not so clear to me,
I saw that it was possible through tag 82, but I didn't understand exactly how

Title: EMV transaction apple/google pay


问:
I am having trouble removing the .html extension from my URLs. I'm getting "Bad Flag Delimiter" in my .htaccess rewrite?
Per the recommendation in this thread, I am trying to rewrite my .htaccess file to remove the .html suffix from my site's urls. For example, I want "my-website.ca/ecology.html" to be shortened to "my-website.ca/ecology". However, I am getting some errors (see below).

I appended the following code to my .htaccess file. (Note: I already had RewriteEngine On from previous tinkering.)

```<code>RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)\.html$ /$1 [L,R=301]
</code>```

The results have been... weird. Sometimes it doesn't work, and I'm given a "bad flag delimiter" error. Other times, it works for all but one webpage: ecology.html. When I try to access that, I get a weird page asking me to contact the site's webmaster and the log has a "no matching directoryindex"

I worked out that "ecology.html" had a common name with a folder called "ecology" which I have since renamed to "science". But that didn't fix it.

I'd appreciate any advice.

Body:
Per the recommendation in this thread, I am trying to rewrite my .htaccess file to remove the .html suffix from my site's urls. For example, I want "my-website.ca/ecology.html" to be shortened to "my-website.ca/ecology". However, I am getting some errors (see below).

I appended the following code to my .htaccess file. (Note: I already had RewriteEngine On from previous tinkering.)

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)\.html$ /$1 [L,R=301]

The results have been... weird. Sometimes it doesn't work, and I'm given a "bad flag delimiter" error. Other times, it works for all but one webpage: ecology.html. When I try to access that, I get a weird page asking me to contact the site's webmaster and the log has a "no matching directoryindex"

I worked out that "ecology.html" had a common name with a folder called "ecology" which I have since renamed to "science". But that didn't fix it.

I'd appreciate any advice.


问:
Unknown Syntax error:"keyword argument repeated". Just Why?
```<code>import random, requests

from datetime import datetime

from sys import getsizeof

#FileHanlder & DataHandler is a some other supporting class

class Requester:

    """A class for making HTTP requests."""

    def __init__(self, agent=None, header=None, proxy=None, ref=None, ref_file=None, proxy_file=None, agent_file=None, set_agent=False, set_header=False, set_ref=False, set_proxy=False, break_pt=None):

        self.agent = 0
        self.ref = 0
        self.proxy = 0
        self.header = 0
        self.break_pt = break_pt

        if agent_file is not None:
            self.agent = FileHandler.read(agent_file)
        elif set_agent:
            self.agent = agent
        else:
            self.agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'

        if ref_file is not None:
            self.ref = FileHandler.read(ref_file).split('\n')
        elif set_ref:
            self.ref = ref

        if proxy_file is not None:
            self.proxy = FileHandler.read(proxy_file).split('\n')
        elif set_proxy:
            self.proxy = proxy

        if set_header:
            self.header = header

    def request(self, url, method='get', params=None, data=None, json=None, headers=None, cookies=None, timeout=5, redirect=True, verify=True, proxy=None, ref=None, agent=None, break_pt=None):

        if break_pt is None:
            break_pt = self.break_pt

        if break_pt is not None:
            time.sleep(random.uniform(break_pt[0], break_pt[1]))

        if agent is None:
            agent = self.agent

        if ref is None:
            ref = self.ref

        if proxy is None:
            proxy = self.proxy

        if headers is None:
            headers = self.header

        if method.lower() == 'get':
            ret = requests.get(url, params=params, headers=headers, cookies=cookies, timeout=timeout, allow_redirects=redirect, verify=verify, proxies=proxy, headers={'User-Agent': agent, 'Referer': ref})
        elif method.lower() == 'post':
            ret = requests.post(url, params=params, data=data, json=json, headers=headers, cookies=cookies, timeout=timeout, allow_redirects=redirect, verify=verify, proxies=proxy, headers={'User-Agent': agent, 'Referer': ref})
        elif method.lower() == 'put':
            ret = requests.put(url, params=params, data=data, json=json, headers=headers, cookies=cookies, timeout=timeout, allow_redirects=redirect, verify=verify, proxies=proxy, headers={'User-Agent': agent, 'Referer': ref})
        elif method.lower() == 'patch':
            ret = requests.patch(url, params=params, data=data, json=json, headers=headers, cookies=cookies, timeout=timeout, allow_redirects=redirect, verify=verify, proxies=proxy, headers={'User-Agent': agent,'Referer': ref})
        elif method.lower() == 'delete':
            ret = requests.delete(url,params=params,data=data, json=json, headers=headers, cookies=cookies, timeout=timeout, allow_redirects=redirect, verify=verify, proxies=proxy, headers={'User-Agent': agent,'Referer': ref})

        return ret

if '__main__'==__name__:

    t = Requester.request('https://www.google.com/').status_cod
    print( 'ok' if (t==200) else 'failed')

</code>```

This code when ever I run, it shows the syntax error of "keyword argument repeated" at line no:-59

```<code>ret = requests.delete(...)
</code>```

I don't know how to fix it.

I was trying to make a method that automatically does http/https request to the url that i need and automatic provide with headers and all the other stuff.

Body:
import random, requests

from datetime import datetime

from sys import getsizeof

#FileHanlder & DataHandler is a some other supporting class

class Requester:

    """A class for making HTTP requests."""

    def __init__(self, agent=None, header=None, proxy=None, ref=None, ref_file=None, proxy_file=None, agent_file=None, set_agent=False, set_header=False, set_ref=False, set_proxy=False, break_pt=None):

        self.agent = 0
        self.ref = 0
        self.proxy = 0
        self.header = 0
        self.break_pt = break_pt

        if agent_file is not None:
            self.agent = FileHandler.read(agent_file)
        elif set_agent:
            self.agent = agent
        else:
            self.agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'

        if ref_file is not None:
            self.ref = FileHandler.read(ref_file).split('\n')
        elif set_ref:
            self.ref = ref

        if proxy_file is not None:
            self.proxy = FileHandler.read(proxy_file).split('\n')
        elif set_proxy:
            self.proxy = proxy

        if set_header:
            self.header = header

    def request(self, url, method='get', params=None, data=None, json=None, headers=None, cookies=None, timeout=5, redirect=True, verify=True, proxy=None, ref=None, agent=None, break_pt=None):

        if break_pt is None:
            break_pt = self.break_pt

        if break_pt is not None:
            time.sleep(random.uniform(break_pt[0], break_pt[1]))

        if agent is None:
            agent = self.agent

        if ref is None:
            ref = self.ref

        if proxy is None:
            proxy = self.proxy

        if headers is None:
            headers = self.header

        if method.lower() == 'get':
            ret = requests.get(url, params=params, headers=headers, cookies=cookies, timeout=timeout, allow_redirects=redirect, verify=verify, proxies=proxy, headers={'User-Agent': agent, 'Referer': ref})
        elif method.lower() == 'post':
            ret = requests.post(url, params=params, data=data, json=json, headers=headers, cookies=cookies, timeout=timeout, allow_redirects=redirect, verify=verify, proxies=proxy, headers={'User-Agent': agent, 'Referer': ref})
        elif method.lower() == 'put':
            ret = requests.put(url, params=params, data=data, json=json, headers=headers, cookies=cookies, timeout=timeout, allow_redirects=redirect, verify=verify, proxies=proxy, headers={'User-Agent': agent, 'Referer': ref})
        elif method.lower() == 'patch':
            ret = requests.patch(url, params=params, data=data, json=json, headers=headers, cookies=cookies, timeout=timeout, allow_redirects=redirect, verify=verify, proxies=proxy, headers={'User-Agent': agent,'Referer': ref})
        elif method.lower() == 'delete':
            ret = requests.delete(url,params=params,data=data, json=json, headers=headers, cookies=cookies, timeout=timeout, allow_redirects=redirect, verify=verify, proxies=proxy, headers={'User-Agent': agent,'Referer': ref})

        return ret

if '__main__'==__name__:

    t = Requester.request('https://www.google.com/').status_cod
    print( 'ok' if (t==200) else 'failed')

This code when ever I run, it shows the syntax error of "keyword argument repeated" at line no:-59

ret = requests.delete(...)

I don't know how to fix it.

I was trying to make a method that automatically does http/https request to the url that i need and automatic provide with headers and all the other stuff.


问:
Mockito response is null after adding ZonedDateTime module by registerModule
Mockito response is null after adding ZonedDateTime module by registerModule..
This is the test I am writing...

```<code>@PostMapping("/bankStatement")
fun getBankStatementList(@Valid @RequestBody request: GenericRequest<BankStatementRequestDTO>): ResponseEntity<ResponseDTO> {
    return createSuccessResponse(bankStatementService.getBankStatementList(request.data))
}
</code>```
```<code>
fun getBankStatementListSuccess() {
    val DEFAULT_DATE:ZonedDateTime  = ZonedDateTime.ofInstant(Instant.ofEpochMilli(0L), ZoneOffset.UTC);
    val request = GenericRequest(
        BankStatementRequestDTO(
            10,
            1,
            "",
            emptyList(),
            DEFAULT_DATE,
            DEFAULT_DATE,
            "03b3238c-66bb-4a4a-b205-4a9e8231b420"
        )
    )
    val response =
        BankStatementListResponseDTO(
            listOf(
                BankStatementResponseDTO(
                    "XXX123",
                    "CREDIT",
                    "upi-123213",
                    "03b3238c-66bb-4a4a-b205-4a9e8231b420",
                    "UPI",
                    BigDecimal(1234),
                    "remarks",
                    DEFAULT_DATE,
                    DEFAULT_DATE,
                    "CLAIMED",
                    "COIN12345678900"
                )
            ),
            1
        )

    Mockito.`when`(bankStatementService.getBankStatementList(request.data)).thenReturn(response)
    val objectMapper = jacksonObjectMapper()
    objectMapper.registerModule(JavaTimeModule())
    mvc.perform(
        MockMvcRequestBuilders
            .post("/api/v1/bankStatement")
            .accept(MediaType.APPLICATION_JSON)
            .contentType(MediaType.APPLICATION_JSON)
            .content(objectMapper.writeValueAsString(request))
    ).andExpect(MockMvcResultMatchers.status().isOk)
        .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON))
}
</code>```

The Error

```<code>Request processing failed; nested exception is java.lang.NullPointerException: Parameter specified as non-null is null: method com.coinomerelaunch.brokeradminbackend.shared.dto.ResponseAdapterKt.createSuccessResponse, parameter dto
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException: Parameter specified as non-null is null: method com.coinomerelaunch.brokeradminbackend.shared.dto.ResponseAdapterKt.createSuccessResponse, parameter dto
    at app//org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014)
</code>```

When I am using Date instead of ZonedDateTime test works..
after adding ZonedDate ..I have to add library

```<code>implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.9.5")

</code>```

also added these lines

```<code>val objectMapper = jacksonObjectMapper()
    objectMapper.registerModule(JavaTimeModule())
</code>```
```<code>content(objectMapper.writeValueAsString(request))
</code>```

but not works

Someone please help me why the mockito response is not getting mocked when I add the jackson library ..or Im missing something

Body:
Mockito response is null after adding ZonedDateTime module by registerModule..
This is the test I am writing...

@PostMapping("/bankStatement")
fun getBankStatementList(@Valid @RequestBody request: GenericRequest<BankStatementRequestDTO>): ResponseEntity<ResponseDTO> {
    return createSuccessResponse(bankStatementService.getBankStatementList(request.data))
}

fun getBankStatementListSuccess() {
    val DEFAULT_DATE:ZonedDateTime  = ZonedDateTime.ofInstant(Instant.ofEpochMilli(0L), ZoneOffset.UTC);
    val request = GenericRequest(
        BankStatementRequestDTO(
            10,
            1,
            "",
            emptyList(),
            DEFAULT_DATE,
            DEFAULT_DATE,
            "03b3238c-66bb-4a4a-b205-4a9e8231b420"
        )
    )
    val response =
        BankStatementListResponseDTO(
            listOf(
                BankStatementResponseDTO(
                    "XXX123",
                    "CREDIT",
                    "upi-123213",
                    "03b3238c-66bb-4a4a-b205-4a9e8231b420",
                    "UPI",
                    BigDecimal(1234),
                    "remarks",
                    DEFAULT_DATE,
                    DEFAULT_DATE,
                    "CLAIMED",
                    "COIN12345678900"
                )
            ),
            1
        )

    Mockito.`when`(bankStatementService.getBankStatementList(request.data)).thenReturn(response)
    val objectMapper = jacksonObjectMapper()
    objectMapper.registerModule(JavaTimeModule())
    mvc.perform(
        MockMvcRequestBuilders
            .post("/api/v1/bankStatement")
            .accept(MediaType.APPLICATION_JSON)
            .contentType(MediaType.APPLICATION_JSON)
            .content(objectMapper.writeValueAsString(request))
    ).andExpect(MockMvcResultMatchers.status().isOk)
        .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON))
}

The Error

Request processing failed; nested exception is java.lang.NullPointerException: Parameter specified as non-null is null: method com.coinomerelaunch.brokeradminbackend.shared.dto.ResponseAdapterKt.createSuccessResponse, parameter dto
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException: Parameter specified as non-null is null: method com.coinomerelaunch.brokeradminbackend.shared.dto.ResponseAdapterKt.createSuccessResponse, parameter dto
    at app//org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014)

When I am using Date instead of ZonedDateTime test works..
after adding ZonedDate ..I have to add library

implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.9.5")

also added these lines

val objectMapper = jacksonObjectMapper()
    objectMapper.registerModule(JavaTimeModule())

content(objectMapper.writeValueAsString(request))

but not works

Someone please help me why the mockito response is not getting mocked when I add the jackson library ..or Im missing something


问:
Why am I unable to decrypt this AES encrypted string even though I have the key and IV?
I am trying to figure out how a mobile app requests work so I can parse some data in my account.

It looks like they are encrypting their request payload and their response as well but they do send in the key and iv at every request.

I tried using an online decrypt tool like this by decoding the IV and key from base64, however it complains that the key is longer than 32 characters. What am I doing wrong?

Example:

```<code>{
    "RequestKey": "zDmNGDRrzNxWEeWX1NThsehsYW3MD/VA7DIcLQ61RuRe7K6sZFUyhaL8+trTzDYoTcTsRtFBbGUawizDJHnm7GfO086sfC/Y0JZ1iViduw1Clw24vAEwlOtRRph9/BF/zwhpHBk2bokKqNNc9K4G62Z5OrRLqyAxfMec7OWK5pOe9pc4ekj+noFBUfF34KsJ9TP/w3qvTlyemrE/qKPEecqttsGoFmFeh5eyPI9AK9sy7zqzd0TVWywwVu7i2niLoOQdb+2awIvFL9Suedep4mwnoUeboepLqnvxR8dyPEk+jT0JyQoma97Qz0+ZKGNaArL6LTOW0Y2A0lXAgWkBcw==",
    "RequestData": "G5/RGRc7XY1GSfU9FTBzgW0p5bVqzfshHZ5/UQQlea82iVRyWbsLPRgbs4zmfLZYbJn6TpmhSnYpw8EIjuVchv6VvmYwoDiZP9zK9Sqifv/TN/m8rQ4BLMQ4h2HvmFXxAolxHNLf2J4No2nZ/SWpYmoAaYOTaawe7nm/z5WVF9BGX1nNTzezeGCIf5RpmoH89dPkK1eBNbM4Ud582IWwggFCKtCEdJ4CJs2Qajt4x4D/o4j5lskAV/LGoStZ7PXpPTj2lX14fF1ADZ4fczAYAWPVQQQZl5A3pKI8s9iDJ9AZQgCz89zd8W1H0R0TVQt91Z5C7CDCJ1zd63/wAmGSG7Wlr43X0CnKH4UBytf/6jjoGUKxf+1VY1FVT7rmz/lT",
    "RequestIv": "Sml4MGc0MjZ2VkFlUDlHOA=="
}
</code>```

And the response looks like this:

```<code>{
"ResponseData":     "....<truncated>...",
"ResponseIv": "2oeVI+asIWm6ECu4CfpU0A\u003d\u003d"
}
</code>```

Body:
I am trying to figure out how a mobile app requests work so I can parse some data in my account.

It looks like they are encrypting their request payload and their response as well but they do send in the key and iv at every request.

I tried using an online decrypt tool like this by decoding the IV and key from base64, however it complains that the key is longer than 32 characters. What am I doing wrong?

Example:

{
    "RequestKey": "zDmNGDRrzNxWEeWX1NThsehsYW3MD/VA7DIcLQ61RuRe7K6sZFUyhaL8+trTzDYoTcTsRtFBbGUawizDJHnm7GfO086sfC/Y0JZ1iViduw1Clw24vAEwlOtRRph9/BF/zwhpHBk2bokKqNNc9K4G62Z5OrRLqyAxfMec7OWK5pOe9pc4ekj+noFBUfF34KsJ9TP/w3qvTlyemrE/qKPEecqttsGoFmFeh5eyPI9AK9sy7zqzd0TVWywwVu7i2niLoOQdb+2awIvFL9Suedep4mwnoUeboepLqnvxR8dyPEk+jT0JyQoma97Qz0+ZKGNaArL6LTOW0Y2A0lXAgWkBcw==",
    "RequestData": "G5/RGRc7XY1GSfU9FTBzgW0p5bVqzfshHZ5/UQQlea82iVRyWbsLPRgbs4zmfLZYbJn6TpmhSnYpw8EIjuVchv6VvmYwoDiZP9zK9Sqifv/TN/m8rQ4BLMQ4h2HvmFXxAolxHNLf2J4No2nZ/SWpYmoAaYOTaawe7nm/z5WVF9BGX1nNTzezeGCIf5RpmoH89dPkK1eBNbM4Ud582IWwggFCKtCEdJ4CJs2Qajt4x4D/o4j5lskAV/LGoStZ7PXpPTj2lX14fF1ADZ4fczAYAWPVQQQZl5A3pKI8s9iDJ9AZQgCz89zd8W1H0R0TVQt91Z5C7CDCJ1zd63/wAmGSG7Wlr43X0CnKH4UBytf/6jjoGUKxf+1VY1FVT7rmz/lT",
    "RequestIv": "Sml4MGc0MjZ2VkFlUDlHOA=="
}

And the response looks like this:

{
"ResponseData":     "....<truncated>...",
"ResponseIv": "2oeVI+asIWm6ECu4CfpU0A\u003d\u003d"
}


问:
Error: remote-exec provisioner error with aws instance.jenkins
[Error: remote-exec provisioner error

with aws instance.jenkins,

on ec2.tf line 113, in resource "aws_instance"

113: provisioner "remote-exec" i

error executing "/tmp/terraform_182135562.sh: Process exited with status 1](https://i.stack.imgur.com/zUPFD.jpg)

How to resolve this error? and the code used by me is
enter image description here

[[enter image description here](https://i.stack.imgur.com/8avLI.jpg)](https://i.stack.imgur.com/oIEs3.jpg)

Automating Infrastructure using Terraform.

```<code>Considering the Organizational requirement you are asked to automate the infrastructure using Terraform first and install other required automation tools in it.

Tools required: Terraform, AWS account with security credentials, Keypair

Expected Deliverables:

Launch an EC2 instance using Terraform

Connect to the instance

Install Jenkins, Java, and Python in the instance
</code>```

So that's why I used terraform script to create ec2 instance, and install jenkins, java and python.
But error occurred here after using terraform apply i.e., "remote exec provisioner error."  { Error: remote-exec provisioner error  with aws instance.jenkins,  on ec2.tf line 113, in resource "aws_instance" 113: provisioner "remote-exec" i  error executing "/tmp/terraform_182135562.sh: Process exited with status}

How can I solve this error, pls guide me?

Body:
[Error: remote-exec provisioner error

with aws instance.jenkins,

on ec2.tf line 113, in resource "aws_instance"

113: provisioner "remote-exec" i

error executing "/tmp/terraform_182135562.sh: Process exited with status 1](https://i.stack.imgur.com/zUPFD.jpg)

How to resolve this error? and the code used by me is
enter image description here

[[enter image description here](https://i.stack.imgur.com/8avLI.jpg)](https://i.stack.imgur.com/oIEs3.jpg)

Automating Infrastructure using Terraform.

Considering the Organizational requirement you are asked to automate the infrastructure using Terraform first and install other required automation tools in it.

Tools required: Terraform, AWS account with security credentials, Keypair

Expected Deliverables:

Launch an EC2 instance using Terraform

Connect to the instance

Install Jenkins, Java, and Python in the instance

So that's why I used terraform script to create ec2 instance, and install jenkins, java and python.
But error occurred here after using terraform apply i.e., "remote exec provisioner error."  { Error: remote-exec provisioner error  with aws instance.jenkins,  on ec2.tf line 113, in resource "aws_instance" 113: provisioner "remote-exec" i  error executing "/tmp/terraform_182135562.sh: Process exited with status}

How can I solve this error, pls guide me?


问:
How many dimens files I have to create to support all the devices according to the screen width?
I have tried to see all the possible dp values of all the different android devices widths, but I have seen that there are a huge amount of different dp values as there is a huge amount of different screen sizes with different screen densities.

I have seen in the Android official docs that the typical dp values are the following: 320dp, 480dp, 600dp, 720dp

I have created a different dimens.xml for the above different dp values:

dimens.xml (w320dp) (will manage 320 to 479 dp)

dimens.xml (w480dp) (will manage 480 to 599 dp)

dimens.xml (w600dp) (will manage 600 to 699 dp)

dimens.xml (w700dp) (will manage up or equal to 700 dp)

Now my question is, how many more dimens files are needed to support like 95% of all devices? I'm going off my head because I think I'll have to add more than 1000 dimens.xml(???dp) if I want to support all the different Android devices.


问:
Reset Password Using Sent OTP Via Mobile, Feature Request Flow in Web API?
I'm currently working on feature 'reset password with otp send via sms' we have 3 screens on mob app (forget password, verify otp, reset password)

I'm asking about:

the request secured flow and contract between mobile app and api?

the endpoints as i think, will be 3 as following:
a- forgetPassword -- receive the phonenumber or username
b- verifyOTP -- validate otp, generic api used in some other places (in registration for example)
c- ResetPassword -- receive the new password + something for validating the user

so,
1- what are the parameters should be sent and received from each api to avoid any vulnerability?
2- should verify OTP be generic or custom per feature?


问:
Error occurred prerendering page "/". Vercel Deployment
Heyyyo everyone, I'm encountering an error about pre-renderer in nextjs. I did some searching on google but cant really figure out what the error is about. I'm new to nextjs and this is my first project that is deployed on vercel. Please help me with this.

vercel deployment log

if more info is needed please let me know.

I've tried deleting the node_modules & .next but didnt work (both files are already in the gitignore). I followed this Vercel Next.js build error while prerendering pages but didnt work.

code: /pages/index.tsx

```<code>import { Suspense } from "react";
import type { GetStaticProps } from "next";
import Image from 'next/image'
import Head from "next/head";
import Link from "next/link";
import About from "../components/about";
import Contact from "../components/contact";
import Experience from "../components/experience";
import Header from "../components/header";
import Hero from "../components/hero";
import Projects from "../components/projects";
import Skills from "../components/skills";
import * as fetchInterface from "../typings";
import {
    fetchExperience,
    fetchPageInfo,
    fetchProject,
    fetchSkills,
    fetchSocial,
} from "../utils/fetchApi";

interface Props {
    pageInfo: fetchInterface.PageInfo;
    experience: fetchInterface.Experience[];
    skills: fetchInterface.Skill[];
    socials: fetchInterface.Social[];
    project: fetchInterface.Project[];
}

const Home = ({ pageInfo, experience, skills, socials, project }: Props) => {
    return (

        <div className="bg-[rgb(36,36,36)] text-white h-screen snap-y snap-mandatory overflow-y-scroll overflow-x-hidden z-0 scrollbar scrollbar-none">
            <Suspense fallback={<div>loading....</div>}>
                <Head>
                    <title>Kush Bhalodi Portfolio</title>
                </Head>

                <Header socials={socials} />

                <section id="hero" className="snap-start">
                    <Hero pageInfo={pageInfo} />
                </section>

                <section id="about" className="snap-center">
                    <About pageInfo={pageInfo} />
                </section>

                <section id="experience" className="snap-center">
                    <Experience experiences={experience} />
                </section>

                <section id="skills" className="snap-start">
                    <Skills skills={skills} />
                </section>

                <section id="projects" className="snap-start">
                    <Projects projects={project} />
                </section>

                <section id="contact" className="snap-start">
                    <Contact />
                </section>

                <Link href="#hero">
                    <footer className="sticky bottom-5 w-full cursor-pointer">
                        <div className="flex items-center justify-center">
                            <Image src={`https://kush-web.web.app/images/profilepic.jpg`} alt='my-img' width={30} height={30} />
                        </div>
                    </footer>
                </Link>
            </Suspense>
        </div>
    );
};

export default Home;

export const getStaticProps: GetStaticProps<Props> = async () => {

    const pageInfo: fetchInterface.PageInfo = await fetchPageInfo();
    const socials: fetchInterface.Social[] = await fetchSocial();
    const skills: fetchInterface.Skill[] = await fetchSkills();
    const project: fetchInterface.Project[] = await fetchProject();
    const experience: fetchInterface.Experience[] = await fetchExperience();

    return {
        props: {
            pageInfo,
            socials,
            skills,
            project,
            experience,
        },
        revalidate: 10000
    };
};
</code>```

Body:
Heyyyo everyone, I'm encountering an error about pre-renderer in nextjs. I did some searching on google but cant really figure out what the error is about. I'm new to nextjs and this is my first project that is deployed on vercel. Please help me with this.

vercel deployment log

if more info is needed please let me know.

I've tried deleting the node_modules & .next but didnt work (both files are already in the gitignore). I followed this Vercel Next.js build error while prerendering pages but didnt work.

code: /pages/index.tsx

import { Suspense } from "react";
import type { GetStaticProps } from "next";
import Image from 'next/image'
import Head from "next/head";
import Link from "next/link";
import About from "../components/about";
import Contact from "../components/contact";
import Experience from "../components/experience";
import Header from "../components/header";
import Hero from "../components/hero";
import Projects from "../components/projects";
import Skills from "../components/skills";
import * as fetchInterface from "../typings";
import {
    fetchExperience,
    fetchPageInfo,
    fetchProject,
    fetchSkills,
    fetchSocial,
} from "../utils/fetchApi";

interface Props {
    pageInfo: fetchInterface.PageInfo;
    experience: fetchInterface.Experience[];
    skills: fetchInterface.Skill[];
    socials: fetchInterface.Social[];
    project: fetchInterface.Project[];
}

const Home = ({ pageInfo, experience, skills, socials, project }: Props) => {
    return (

            <Suspense fallback={
loading....
}>

                    <title>Kush Bhalodi Portfolio</title>

                    <Hero pageInfo={pageInfo} />

                    <About pageInfo={pageInfo} />

                    <Experience experiences={experience} />

                    <Skills skills={skills} />

                    <Projects projects={project} />

                    <Contact />

                <Link href="#hero">

                            <Image src={`https://kush-web.web.app/images/profilepic.jpg`} alt='my-img' width={30} height={30} />

                </Link>
            </Suspense>

    );
};

export default Home;

export const getStaticProps: GetStaticProps<Props> = async () => {

    const pageInfo: fetchInterface.PageInfo = await fetchPageInfo();
    const socials: fetchInterface.Social[] = await fetchSocial();
    const skills: fetchInterface.Skill[] = await fetchSkills();
    const project: fetchInterface.Project[] = await fetchProject();
    const experience: fetchInterface.Experience[] = await fetchExperience();

    return {
        props: {
            pageInfo,
            socials,
            skills,
            project,
            experience,
        },
        revalidate: 10000
    };
};