问:
Uncaught (in promise) TypeError: Failed to fetch . i can not connect to api from front end
I have 3 file in my source code. problem is that, I fill the .env file correctly but still failed to fetch and gives 4 error in chrome console . I search a lot for this issue.

This is my client side .env file:

```<code>REACT_APP_BASE_URL=http://loaclhost:5000/api
REACT_APP_SOCKET_IO_URL=http://localhost:5000
REACT_APP_GOOGLE_CLIENT_ID=<GOOGLE_CLIENT_ID>
REACT_APP_GITHUB_CLIENT_ID=<GITHUB_CLIENT_ID>
REACT_APP_FB_APP_ID=<FACEBOOK_CLIENT_ID>
</code>```

This is my server side .env file:

```<code>DB_USER = //user name for db
DB_PASSWORD = //password for db
DB_NAME = // name for db
JWT_KEY = ssssssssssssssssssssadacxvdsvs34242341dfssdfsdfs;
COOKIE_KEY = sfamvaljgteojgodaelmgsdadasafoiwehornhuehqq22;
NODE_ENV = 'development';
CLIENT_URL = http://localhost:3000

//cloundiary will provide you with the following credentials
CLOUDINARY_CLOUD_NAME =
CLOUDINARY_API_KEY =
CLOUDINARY_API_SECRET =

//Google will provide you with the following credentials
GOOGLE_API_KEY = //API key

//Github will provide you with the following credentials
GH_CLIENT_ID = //Github's Client ID
GH_CLIENT_SECRET = //Github's Client Secret

// Twitter will provide you with the following credentials
TWITTER_CONSUMER_KEY = //Twitter's Consumer key
TWITTER_CONSUMER_SECRET = //Twitter's Consumer Secret
</code>```

And this is my app.js file:

```<code>const express = require('express');
const app = express();
const cors = require('cors');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const passport = require('passport');
const cookieSession = require('cookie-session');
const path = require('path');
const { createServer } = require('http');
const { Server } = require('socket.io');
require('dotenv').config();

const postsRoutes = require('./routes/posts');
const usersRoutes = require('./routes/users');
const commentsRoutes = require('./routes/comments');
const tagsRoutes = require('./routes/tags');
const HttpError = require('./models/http-error');
const { socketHandlers } = require('./utils/socket');

const {
  DB_USER,
  DB_PASSWORD,
  DB_NAME,
  COOKIE_KEY,
  PORT,
  NODE_ENV,
  CLIENT_URL,
} = process.env;

const httpServer = createServer(app);

app.set('trust proxy', 1);

app.use(
  cookieSession({
    name: 'session',
    keys: [COOKIE_KEY],
    maxAge: 24 * 60 * 60 * 1000, // session will expire after 24 hours
    secure: NODE_ENV === 'development' ? false : true,
    sameSite: NODE_ENV === 'development' ? false : 'none',
  })
);

app.use(bodyParser.json());

app.use(passport.initialize());
app.use(passport.session());
require('./config/passport-twitter');

const io = new Server(httpServer, {
  cors: {
    origin: `*`,

    methods: ['GET', 'POST'],
  },
});
socketHandlers(io);

app.use(
  cors({
    origin: CLIENT_URL, // allow to server to accept request from different origin
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
    credentials: true, // allow session cookie from browser to pass through
  })
);

app.use('/api/posts', postsRoutes);

app.use('/api/users', usersRoutes);

app.use('/api/comments', commentsRoutes);

app.use('/api/tags', tagsRoutes);

app.get('/', (req, res) => {
  res.send('DEV.to is running');
});

// app.use((req, res, next) => {
//   throw new HttpError('Could not find the route', 404);
// });

app.use((error, req, res, next) => {
  if (res.headerSent) {
    //res already sent ? => don't send res, just forward the error
    return next(error);
  }
  //else, send a res
  res.status(error.code || 500);
  res.json({
    message: error.message || 'An unknown error occurred',
  });
});

mongoose
  .connect(
    'mongodb://localhost:27017/DevtoClone11',
    {
      useUnifiedTopology: true,
      useNewUrlParser: true,
      useCreateIndex: true,
      useFindAndModify: false,
    }
  )
  .then(() => {
    httpServer.listen(PORT || 5000, () => {
      console.log('Starting server');
    });
  })
  .catch((err) => {
    console.log(err);
  });

  //edit
// mongoose
//   .connect(
//     `mongodb+srv://${DB_USER}:${DB_PASSWORD}@cluster0.ynmnh.mongodb.net/${DB_NAME}?retryWrites=true&w=majority`,
//     {
//       useUnifiedTopology: true,
//       useNewUrlParser: true,
//       useCreateIndex: true,
//       useFindAndModify: false,
//     }
//   )
//   .then(() => {
//     httpServer.listen(PORT || 5000, () => {
//       console.log('Starting server');
//     });
//   })
//   .catch((err) => {
//     console.log(err);
//   });

</code>```

This is my google chrome console error. problem is no matter what changes I do into the code, But still can not sign up to website because of this errors.

console

I just want sign up in to source code but i can not. if any one need more information to answer me. please ask in comment section i will answer instantly.

I tried to fix google chrome console errors 1 by one, but i can not fix the source code at all.

Body:
I have 3 file in my source code. problem is that, I fill the .env file correctly but still failed to fetch and gives 4 error in chrome console . I search a lot for this issue.

This is my client side .env file:

REACT_APP_BASE_URL=http://loaclhost:5000/api
REACT_APP_SOCKET_IO_URL=http://localhost:5000
REACT_APP_GOOGLE_CLIENT_ID=<GOOGLE_CLIENT_ID>
REACT_APP_GITHUB_CLIENT_ID=<GITHUB_CLIENT_ID>
REACT_APP_FB_APP_ID=<FACEBOOK_CLIENT_ID>

This is my server side .env file:

DB_USER = //user name for db
DB_PASSWORD = //password for db
DB_NAME = // name for db
JWT_KEY = ssssssssssssssssssssadacxvdsvs34242341dfssdfsdfs;
COOKIE_KEY = sfamvaljgteojgodaelmgsdadasafoiwehornhuehqq22;
NODE_ENV = 'development';
CLIENT_URL = http://localhost:3000

//cloundiary will provide you with the following credentials
CLOUDINARY_CLOUD_NAME =
CLOUDINARY_API_KEY =
CLOUDINARY_API_SECRET =

//Google will provide you with the following credentials
GOOGLE_API_KEY = //API key

//Github will provide you with the following credentials
GH_CLIENT_ID = //Github's Client ID
GH_CLIENT_SECRET = //Github's Client Secret

// Twitter will provide you with the following credentials
TWITTER_CONSUMER_KEY = //Twitter's Consumer key
TWITTER_CONSUMER_SECRET = //Twitter's Consumer Secret

And this is my app.js file:

const express = require('express');
const app = express();
const cors = require('cors');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const passport = require('passport');
const cookieSession = require('cookie-session');
const path = require('path');
const { createServer } = require('http');
const { Server } = require('socket.io');
require('dotenv').config();

const postsRoutes = require('./routes/posts');
const usersRoutes = require('./routes/users');
const commentsRoutes = require('./routes/comments');
const tagsRoutes = require('./routes/tags');
const HttpError = require('./models/http-error');
const { socketHandlers } = require('./utils/socket');

const {
  DB_USER,
  DB_PASSWORD,
  DB_NAME,
  COOKIE_KEY,
  PORT,
  NODE_ENV,
  CLIENT_URL,
} = process.env;

const httpServer = createServer(app);

app.set('trust proxy', 1);

app.use(
  cookieSession({
    name: 'session',
    keys: [COOKIE_KEY],
    maxAge: 24 * 60 * 60 * 1000, // session will expire after 24 hours
    secure: NODE_ENV === 'development' ? false : true,
    sameSite: NODE_ENV === 'development' ? false : 'none',
  })
);

app.use(bodyParser.json());

app.use(passport.initialize());
app.use(passport.session());
require('./config/passport-twitter');

const io = new Server(httpServer, {
  cors: {
    origin: `*`,

    methods: ['GET', 'POST'],
  },
});
socketHandlers(io);

app.use(
  cors({
    origin: CLIENT_URL, // allow to server to accept request from different origin
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
    credentials: true, // allow session cookie from browser to pass through
  })
);

app.use('/api/posts', postsRoutes);

app.use('/api/users', usersRoutes);

app.use('/api/comments', commentsRoutes);

app.use('/api/tags', tagsRoutes);

app.get('/', (req, res) => {
  res.send('DEV.to is running');
});

// app.use((req, res, next) => {
//   throw new HttpError('Could not find the route', 404);
// });

app.use((error, req, res, next) => {
  if (res.headerSent) {
    //res already sent ? => don't send res, just forward the error
    return next(error);
  }
  //else, send a res
  res.status(error.code || 500);
  res.json({
    message: error.message || 'An unknown error occurred',
  });
});

mongoose
  .connect(
    'mongodb://localhost:27017/DevtoClone11',
    {
      useUnifiedTopology: true,
      useNewUrlParser: true,
      useCreateIndex: true,
      useFindAndModify: false,
    }
  )
  .then(() => {
    httpServer.listen(PORT || 5000, () => {
      console.log('Starting server');
    });
  })
  .catch((err) => {
    console.log(err);
  });

  //edit
// mongoose
//   .connect(
//     `mongodb+srv://${DB_USER}:${DB_PASSWORD}@cluster0.ynmnh.mongodb.net/${DB_NAME}?retryWrites=true&w=majority`,
//     {
//       useUnifiedTopology: true,
//       useNewUrlParser: true,
//       useCreateIndex: true,
//       useFindAndModify: false,
//     }
//   )
//   .then(() => {
//     httpServer.listen(PORT || 5000, () => {
//       console.log('Starting server');
//     });
//   })
//   .catch((err) => {
//     console.log(err);
//   });

This is my google chrome console error. problem is no matter what changes I do into the code, But still can not sign up to website because of this errors.

console

I just want sign up in to source code but i can not. if any one need more information to answer me. please ask in comment section i will answer instantly.

I tried to fix google chrome console errors 1 by one, but i can not fix the source code at all.


来源: stackexchange

问:
No ec2 instances are being created when using philips labs terraform aws self hosted module
I have been trying to test and implement self hosted runners but the issue is that instances are turning on even after everything is connected. I have followed every step github apps and everything but still the instances are not turning up. Cloudwatch registers the request but for somereason the request to create instances are not working. I have attached the main.tf file clould anyone please help in sorting this issue out.

```<code>terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "4.44.0"
    }
  }
}

provider "aws" {
  region     = var.aws_region
  access_key = "Akey"
  secret_key = "skey"
}

data "aws_caller_identity" "current" {}

resource "random_id" "random" {
  byte_length = 20
}
resource "aws_iam_service_linked_role" "spot" {
  aws_service_name = "spot.amazonaws.com"
}
module "github-runner" {
  create_service_linked_role_spot = true
  source  = "philips-labs/github-runner/aws"
  version = "2.0.0-next.1"

  aws_region = var.aws_region
  vpc_id     = module.vpc.vpc_id
  subnet_ids = module.vpc.private_subnets

  prefix = var.prefix

  github_app = {
    key_base64     = "key"
    id = "id"
    webhook_secret = random_id.random.hex
  }

  webhook_lambda_zip                = "lambdas-download/webhook.zip"
  runner_binaries_syncer_lambda_zip = "lambdas-download/runner-binaries-syncer.zip"
  runners_lambda_zip                = "lambdas-download/runners.zip"
  enable_organization_runners = true
  runner_extra_labels         = "default,example"

  # enable access to the runners via SSM
  enable_ssm_on_runners = true

  instance_types = ["m5.large", "c5.large"]
  # Uncomment to enable ephemeral runners
  runner_run_as = "ubuntu"
  enable_ephemeral_runners = false
  # enabled_userdata         = true
  delay_webhook_event      = 0
  runners_maximum_count = 20

  idle_config = [{
    cron      = "* * o-23 * * *"
    timeZone  = "Europe/Amsterdam"
    idleCount = 3
  }]

  # fifo_build_queue = true
  enable_job_queued_check = true
  # override scaling down
  scale_down_schedule_expression = "cron(* * * * ? *)"
}
</code>```

I have tried with ephemeral and isle configs enabling and disabling fifo queue and most other toggles but nothing seems to work.

ContentLicense: CC BY-SA 4.0

Body:
I have been trying to test and implement self hosted runners but the issue is that instances are turning on even after everything is connected. I have followed every step github apps and everything but still the instances are not turning up. Cloudwatch registers the request but for somereason the request to create instances are not working. I have attached the main.tf file clould anyone please help in sorting this issue out.

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "4.44.0"
    }
  }
}

provider "aws" {
  region     = var.aws_region
  access_key = "Akey"
  secret_key = "skey"
}

data "aws_caller_identity" "current" {}

resource "random_id" "random" {
  byte_length = 20
}
resource "aws_iam_service_linked_role" "spot" {
  aws_service_name = "spot.amazonaws.com"
}
module "github-runner" {
  create_service_linked_role_spot = true
  source  = "philips-labs/github-runner/aws"
  version = "2.0.0-next.1"

  aws_region = var.aws_region
  vpc_id     = module.vpc.vpc_id
  subnet_ids = module.vpc.private_subnets

  prefix = var.prefix

  github_app = {
    key_base64     = "key"
    id = "id"
    webhook_secret = random_id.random.hex
  }

  webhook_lambda_zip                = "lambdas-download/webhook.zip"
  runner_binaries_syncer_lambda_zip = "lambdas-download/runner-binaries-syncer.zip"
  runners_lambda_zip                = "lambdas-download/runners.zip"
  enable_organization_runners = true
  runner_extra_labels         = "default,example"

  # enable access to the runners via SSM
  enable_ssm_on_runners = true

  instance_types = ["m5.large", "c5.large"]
  # Uncomment to enable ephemeral runners
  runner_run_as = "ubuntu"
  enable_ephemeral_runners = false
  # enabled_userdata         = true
  delay_webhook_event      = 0
  runners_maximum_count = 20

  idle_config = [{
    cron      = "* * o-23 * * *"
    timeZone  = "Europe/Amsterdam"
    idleCount = 3
  }]

  # fifo_build_queue = true
  enable_job_queued_check = true
  # override scaling down
  scale_down_schedule_expression = "cron(* * * * ? *)"
}

I have tried with ephemeral and isle configs enabling and disabling fifo queue and most other toggles but nothing seems to work.


问:
Use an Excel Cell as a Input Data for filtration to a SQL Server View
I have a basic view in SQL Server which includes these columns,

"Lot Number" , "Time" , "Code" , "Name" , "Barcode"

Now I need a Excel file which will have EXACTLY the same columns and the same information.

What I want to do is, in the Excel file when I write a number to "lot number" section, the other columns will fill itself automatically based on the SQL Server view. Basically I'll be using "lot number" cell as a filtering.

The problem is that, this is a ERP system database. I don't want to extract all the information to Excel file, there are millions of rows. Excel should be blank, I will write the lot number first, then refresh the Excel file and the other columns should be filled in automatically. I will refresh the Excel every 1 min automatically and only 1 row is enough.

So I need a procedure in SQL Server (or in Excel) to receive data from the Excel cell, then use that data for filtration in a view and return the data to the same Excel.

Now I'll show you my set up, waiting for your ideas.

This Screen shot is the SQL Server view in "192.168.2.100" server. My SQL knowledge is pretty basic, I create views by schematics not by codes.

And this is the Excel file that I connected. As you can see I can extract all the data. (I deleted code-name-barcode cells. they are not empty, because these are official information).

Obviously this is not I want. When I put the lot number I want other data to came automatically. At least when I refresh the Excel file. Excel is in "192.168.2.116\\barkod\\Tyvek_Mdr.xls" . It is in a shared network.

So I have been researching but still I couldn't find the best solution. If someone can help me I'd really appreciate it.


问:
Keep track record of AttendaceTime put values in ModifiedTime
I have created a python face recognition attendance system using open-cv, which recognizes our face and take system date-time as IN-TIME, which is connected to SQL database (inserting all data from csv).

In below pic I want AttendanceTime as first IN-TIME (constant for that day) and ModifiedTime should be keep track record of AttendanceTime changes value every time face recognized.

CSV writeline code python:

```<code>with open('Attendance.csv', 'r+') as f:
    myDataList = f.readlines()
    nameList = []
    for line in myDataList:
        entry = line.split(',')
        nameList.append(entry[0])
    if (name and date) not in nameList:
        now = datetime.now()
        dtString = now.strftime('%H:%M:%S')
        modifiedTime = /***/    # logic
        f.writelines(f'\n{name},{date},{dtString},{modifiedTime}')
</code>```

Coming Output:

EmployeeName
AttendanceDate
AttendanceTime
ModifiedTime

CHIRANJIT
2022-08-12
10:55:32.0000000
NULL

CHIRANJIT
2022-08-12
10:55:32.0000000
NULL

CHIRANJIT
2022-08-12
10:55:44.0000000
NULL

CHIRANJIT
2022-08-12
11:04:11.0000000
NULL

Expected Output:

EmployeeName
AttendanceDate
AttendanceTime
ModifiedTime

CHIRANJIT
2022-08-12
10:55:32
11:04:11

Thanks.

Appreciate your help!

Body:
I have created a python face recognition attendance system using open-cv, which recognizes our face and take system date-time as IN-TIME, which is connected to SQL database (inserting all data from csv).

In below pic I want AttendanceTime as first IN-TIME (constant for that day) and ModifiedTime should be keep track record of AttendanceTime changes value every time face recognized.

CSV writeline code python:

with open('Attendance.csv', 'r+') as f:
    myDataList = f.readlines()
    nameList = []
    for line in myDataList:
        entry = line.split(',')
        nameList.append(entry[0])
    if (name and date) not in nameList:
        now = datetime.now()
        dtString = now.strftime('%H:%M:%S')
        modifiedTime = /***/    # logic
        f.writelines(f'\n{name},{date},{dtString},{modifiedTime}')

Coming Output:

EmployeeName
AttendanceDate
AttendanceTime
ModifiedTime

CHIRANJIT
2022-08-12
10:55:32.0000000
NULL

CHIRANJIT
2022-08-12
10:55:32.0000000
NULL

CHIRANJIT
2022-08-12
10:55:44.0000000
NULL

CHIRANJIT
2022-08-12
11:04:11.0000000
NULL

Expected Output:

EmployeeName
AttendanceDate
AttendanceTime
ModifiedTime

CHIRANJIT
2022-08-12
10:55:32
11:04:11

Thanks.

Appreciate your help!


问:
errorCode": "6000" - azure synapse running the pipeline
I have error when running a pipeline in azure synapse. If I execute the synapse notebook manually it works good (readind and writing). But when I call the name notebook from the ForEach activity inside the pipeline it fails to run. I have the following error. Previously, I had no porblem.

```<code>Error
{
    "errorCode": "6000",
    "message": "{\n  \"code\": 400,\n  \"message\": \"Failed to run notebook due to invalid request. [Error: Not supported language in Synapse: ]\",\n  \"result\": {\n    \"errorMessage\": null,\n    \"details\": null\n  }\n}",
    "failureType": "UserError",
    "target": "1 - Full load Parquet",
    "details": []
}
</code>```

Maybe worth to mention that, If I run first cmd i notebook manually and then trigger the pipeline, it run perfectly. So I dont know why but I requires the manuall start of engine?

Body:
I have error when running a pipeline in azure synapse. If I execute the synapse notebook manually it works good (readind and writing). But when I call the name notebook from the ForEach activity inside the pipeline it fails to run. I have the following error. Previously, I had no porblem.

Error
{
    "errorCode": "6000",
    "message": "{\n  \"code\": 400,\n  \"message\": \"Failed to run notebook due to invalid request. [Error: Not supported language in Synapse: ]\",\n  \"result\": {\n    \"errorMessage\": null,\n    \"details\": null\n  }\n}",
    "failureType": "UserError",
    "target": "1 - Full load Parquet",
    "details": []
}

Maybe worth to mention that, If I run first cmd i notebook manually and then trigger the pipeline, it run perfectly. So I dont know why but I requires the manuall start of engine?


问:
I'm trying to make this code in vanilla javascript work in reactjs, but it's falling into the infinite loop
This is the code i got from codepen, it generates special characters and changes to the phrase i put, I'm wanting to compile this vanilla javascript code to react, because you can't use the DOM
there.

My real doubt is where do I put the useState so that it stops looping and shows character by character, this passing for example the state 'title' in a .

vanilla javascript code:

```<code>function setCharAt(str,index,chr) {
    if(index > str.length-1) return str;
    return str.substr(0,index) + chr + str.substr(index+1);
}

var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-=+<>,./?[{()}]!@#$%^&*~`\|'.split('');

var progress404 = 0;
var total404 = $('.text__error').data('text').length;

var progressLink = 0;
var totalLink = $('.text__link a').data('text').length;

var scrambleInterval = setInterval(function() {
    var string404 = $('.text__error').data('text');
    var stringLink = $('.text__link a').data('text');

    for(var i = 0; i < total404; i++) {
        if(i >= progress404) {
            string404 = setCharAt(string404, i, characters[Math.round(Math.random() * (characters.length - 1))]);
        }
    }

    for(var i = 0; i < totalLink; i++) {
        if(i >= progressLink) {
            stringLink = setCharAt(stringLink, i, characters[Math.round(Math.random() * (characters.length - 1))]);
        }
    }

    $('.text__error').text(string404);
    $('.text__link a').text(stringLink);
}, 1000 / 60);

setTimeout(function() {
    var revealInterval = setInterval(function() {
        if(progress404 < total404) {
            progress404++;
        }else if(progressLink < totalLink) {
            progressLink++;
        }else{
            clearInterval(revealInterval);
            clearInterval(scrambleInterval);
        }
    }, 50);
}, 1000);
</code>```

This is the code I developed to try to work:

```<code>const [ title, setTitle ] = useState('404 page not found')
    const [ link, setLink ] = useState('click here to go home')

    function setCharAt(str: string,index: number,chr: any) {
        if(index > str.length-1) return str;
        return str.substr(0,index) + chr + str.substr(index+1);
    }

    var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-=+<>,./?[{()}]!@#$%^&*~`\|'.split('');

    var progress404 = 0;
    var total404 = title.length

    var progressLink = 0;
    var totalLink = link.length

    var scrambleInterval = setInterval(function() {

        for(var i = 0; i < total404; i++) {
            if(i >= progress404) {
                setTitle( setCharAt(title, i, characters[Math.round(Math.random() * (characters.length - 1))]));
            }
        }

        for(var i = 0; i < totalLink; i++) {
            if(i >= progressLink) {
                setLink( setCharAt(link, i, characters[Math.round(Math.random() * (characters.length - 1))]));
            }
        }

    }, 1000 / 60);

    setTimeout(function() {
        var revealInterval = setInterval(function() {
            if(progress404 < total404) {
                progress404++;
            }else if(progressLink < totalLink) {
                progressLink++;
            }else{
                clearInterval(revealInterval);
                clearInterval(scrambleInterval);
            }
        }, 50);
    }, 1000);
</code>```

Body:
This is the code i got from codepen, it generates special characters and changes to the phrase i put, I'm wanting to compile this vanilla javascript code to react, because you can't use the DOM
there.

My real doubt is where do I put the useState so that it stops looping and shows character by character, this passing for example the state 'title' in a .

vanilla javascript code:

function setCharAt(str,index,chr) {
    if(index > str.length-1) return str;
    return str.substr(0,index) + chr + str.substr(index+1);
}

var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-=+<>,./?[{()}]!@#$%^&*~`\|'.split('');

var progress404 = 0;
var total404 = $('.text__error').data('text').length;

var progressLink = 0;
var totalLink = $('.text__link a').data('text').length;

var scrambleInterval = setInterval(function() {
    var string404 = $('.text__error').data('text');
    var stringLink = $('.text__link a').data('text');

    for(var i = 0; i < total404; i++) {
        if(i >= progress404) {
            string404 = setCharAt(string404, i, characters[Math.round(Math.random() * (characters.length - 1))]);
        }
    }

    for(var i = 0; i < totalLink; i++) {
        if(i >= progressLink) {
            stringLink = setCharAt(stringLink, i, characters[Math.round(Math.random() * (characters.length - 1))]);
        }
    }

    $('.text__error').text(string404);
    $('.text__link a').text(stringLink);
}, 1000 / 60);

setTimeout(function() {
    var revealInterval = setInterval(function() {
        if(progress404 < total404) {
            progress404++;
        }else if(progressLink < totalLink) {
            progressLink++;
        }else{
            clearInterval(revealInterval);
            clearInterval(scrambleInterval);
        }
    }, 50);
}, 1000);

This is the code I developed to try to work:

const [ title, setTitle ] = useState('404 page not found')
    const [ link, setLink ] = useState('click here to go home')

    function setCharAt(str: string,index: number,chr: any) {
        if(index > str.length-1) return str;
        return str.substr(0,index) + chr + str.substr(index+1);
    }

    var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-=+<>,./?[{()}]!@#$%^&*~`\|'.split('');

    var progress404 = 0;
    var total404 = title.length

    var progressLink = 0;
    var totalLink = link.length

    var scrambleInterval = setInterval(function() {

        for(var i = 0; i < total404; i++) {
            if(i >= progress404) {
                setTitle( setCharAt(title, i, characters[Math.round(Math.random() * (characters.length - 1))]));
            }
        }

        for(var i = 0; i < totalLink; i++) {
            if(i >= progressLink) {
                setLink( setCharAt(link, i, characters[Math.round(Math.random() * (characters.length - 1))]));
            }
        }

    }, 1000 / 60);

    setTimeout(function() {
        var revealInterval = setInterval(function() {
            if(progress404 < total404) {
                progress404++;
            }else if(progressLink < totalLink) {
                progressLink++;
            }else{
                clearInterval(revealInterval);
                clearInterval(scrambleInterval);
            }
        }, 50);
    }, 1000);


问:
How can I implement notification sound with the sound file present in my device in react native?
I am unable to play the sound which I have downloaded on my device push notification sound. The file has been downloaded in my device to my app directory but I am unable to play it. I wrote the code in MainActivity.java and get the function through import native modules in react native.</p>
```<code> notificationChannelWatch.setSound(parse(ContentResolver.SCHEME_ANDROID_RESOURCE + ".//" + getPackageName() + "/files/Sound/" + soundName), att);
                Log.d("check11",ContentResolver.SCHEME_ANDROID_RESOURCE + ".//" + getPackageName() + "/files/Sound/" + soundName );
</code>```

Body:
I am unable to play the sound which I have downloaded on my device push notification sound. The file has been downloaded in my device to my app directory but I am unable to play it. I wrote the code in MainActivity.java and get the function through import native modules in react native.

 notificationChannelWatch.setSound(parse(ContentResolver.SCHEME_ANDROID_RESOURCE + ".//" + getPackageName() + "/files/Sound/" + soundName), att);
                Log.d("check11",ContentResolver.SCHEME_ANDROID_RESOURCE + ".//" + getPackageName() + "/files/Sound/" + soundName );


问:
NET MAUI iOS, the background color is always gray when the CollectionView is selected
I am trying to create a UI like the image below.

As you can see, it works fine on Android, but when I run this on iOS, it shows a gray rectangle.

How can I make this gray rectangle transparent?
Here is the actual code.

```<code><CollectionView SelectionMode="Single"
                HeightRequest="50"
                WidthRequest="250"
                ItemsLayout="HorizontalList"
                BackgroundColor="White">
    <CollectionView.ItemTemplate>
        <DataTemplate>
            <Border StrokeThickness="0"
                    WidthRequest="50"
                    HeightRequest="50"
                    StrokeShape="RoundRectangle 25">
                <Border StrokeThickness="0" BackgroundColor="Transparent">
                    <Label Text="{Binding}" HorizontalOptions="Center" VerticalOptions="Center"/>
                </Border>
                <VisualStateManager.VisualStateGroups>
                    <VisualStateGroup Name="CommonStates">
                        <VisualState Name="Normal"/>
                        <VisualState Name="Selected">
                            <VisualState.Setters>
                                <Setter Property="BackgroundColor" Value="yellow"/>
                            </VisualState.Setters>
                        </VisualState>
                    </VisualStateGroup>
                </VisualStateManager.VisualStateGroups>
            </Border>
        </DataTemplate>
    </CollectionView.ItemTemplate>

    <CollectionView.ItemsSource>
        <x:Array Type="{x:Type x:String}">
            <x:String>1</x:String>
            <x:String>2</x:String>
            <x:String>3</x:String>
            <x:String>4</x:String>
            <x:String>5</x:String>
        </x:Array>
    </CollectionView.ItemsSource>
</CollectionView>

</code>```

Body:
I am trying to create a UI like the image below.

As you can see, it works fine on Android, but when I run this on iOS, it shows a gray rectangle.

How can I make this gray rectangle transparent?
Here is the actual code.

<CollectionView SelectionMode="Single"
                HeightRequest="50"
                WidthRequest="250"
                ItemsLayout="HorizontalList"
                BackgroundColor="White">
    <CollectionView.ItemTemplate>
        <DataTemplate>
            <Border StrokeThickness="0"
                    WidthRequest="50"
                    HeightRequest="50"
                    StrokeShape="RoundRectangle 25">
                <Border StrokeThickness="0" BackgroundColor="Transparent">

                </Border>
                <VisualStateManager.VisualStateGroups>
                    <VisualStateGroup Name="CommonStates">
                        <VisualState Name="Normal"/>
                        <VisualState Name="Selected">
                            <VisualState.Setters>
                                <Setter Property="BackgroundColor" Value="yellow"/>
                            </VisualState.Setters>
                        </VisualState>
                    </VisualStateGroup>
                </VisualStateManager.VisualStateGroups>
            </Border>
        </DataTemplate>
    </CollectionView.ItemTemplate>

    <CollectionView.ItemsSource>
        <x:Array Type="{x:Type x:String}">
            <x:String>1</x:String>
            <x:String>2</x:String>
            <x:String>3</x:String>
            <x:String>4</x:String>
            <x:String>5</x:String>
        </x:Array>
    </CollectionView.ItemsSource>
</CollectionView>


问:
Error in debugging the vs code: could not connect to the localhost
Cannot connect to localhost .Could not debug at localhost it keeps showing this whenever i try to run the code .Please help out

json -

```<code>{
    "folders": [],
    "launch": {
        "version": "0.2.0",
        "configurations": [

        {
            "name": "Attach to Chrome",
            "port": 9222,
            "request": "attach",
            "type": "chrome",
            "webRoot": "${workspaceFolder}"
        }
        ]
    },
    "extensions": {
        "recommendations": [
            "formulahendry.code-runner"
        ]
    },
    "settings": {
        "code-runner.clearPreviousOutput": true,
        "json.format.keepLines": true,
        "json.format.enable": false,
        "code-runner.runInTerminal": true
    }
}
</code>```

i tried to run and debug code but it showed this error

Body:
Cannot connect to localhost .Could not debug at localhost it keeps showing this whenever i try to run the code .Please help out

json -

{
    "folders": [],
    "launch": {
        "version": "0.2.0",
        "configurations": [

        {
            "name": "Attach to Chrome",
            "port": 9222,
            "request": "attach",
            "type": "chrome",
            "webRoot": "${workspaceFolder}"
        }
        ]
    },
    "extensions": {
        "recommendations": [
            "formulahendry.code-runner"
        ]
    },
    "settings": {
        "code-runner.clearPreviousOutput": true,
        "json.format.keepLines": true,
        "json.format.enable": false,
        "code-runner.runInTerminal": true
    }
}

i tried to run and debug code but it showed this error


问:
Getting Error while try to run local Ceramic node?

try to run ceramic node locally through cli, but getting this error.


问:
Topological Error due to Geometry Invalidity when doing 'GEOSIntersection_r'
The error "TopologicalError: The operation 'GEOSIntersection_r' could not be performed. Likely cause is invalidity of the geometry <shapely.geometry.polygon.Polygon object at 0x0000025FB05BDA80>" keeps popping up whenever I try to run my code with certain shapefiles. This only happens with some shapefiles, though-- sometimes it'll work just fine. I just can't figure out how to fix the geometries that are giving me problems.

Here's my code:

```<code>import geopandas as gpd
import maup

bg = gpd.read_file("co_BG.zip")

precincts = gpd.read_file("co_2020.zip")

precincts = precincts.to_crs(epsg=2163)
bg = bg.to_crs(epsg=2163)

pieces = maup.intersections(bg, precincts, area_cutoff=0)
</code>```

I've tried using .buffer(0) and make_valid from shapely but I'm not sure if I did it right since I'm pretty new to this stuff. I saw that someone asked a similar question once but I read the answers and tried them but it still didn't work so either something different is going on or I did it wrong.

Body:
The error "TopologicalError: The operation 'GEOSIntersection_r' could not be performed. Likely cause is invalidity of the geometry <shapely.geometry.polygon.Polygon object at 0x0000025FB05BDA80>" keeps popping up whenever I try to run my code with certain shapefiles. This only happens with some shapefiles, though-- sometimes it'll work just fine. I just can't figure out how to fix the geometries that are giving me problems.

Here's my code:

import geopandas as gpd
import maup

bg = gpd.read_file("co_BG.zip")

precincts = gpd.read_file("co_2020.zip")

precincts = precincts.to_crs(epsg=2163)
bg = bg.to_crs(epsg=2163)

pieces = maup.intersections(bg, precincts, area_cutoff=0)

I've tried using .buffer(0) and make_valid from shapely but I'm not sure if I did it right since I'm pretty new to this stuff. I saw that someone asked a similar question once but I read the answers and tried them but it still didn't work so either something different is going on or I did it wrong.


问:
How can I design a system that can use multiple versions (updates) of a key secret value stored in Azure Keyvault
I have a file encryption/decryption logic that uses encryption-key stored in Azure KeyVault secret.
The key expires in 2 years and then we generate a new key and update the keyVault to use that for any encryption/decryptions from that time onwards. Now, when a new key is introduced, obviously the old encrypted files cannot be decrypted anymore with that.

So, I want to design the decryption process in a way that it keeps supporting decryption for all files (old or new) even after updating the key.

(The one option I thought of was get all versions of a keyValut secret and trying all version values until the one that decrypts the file - Not sure if its possible to access values in old versions of a keyVault secret)

Open to any idea/approach to reach the end goal of supporting old files' decryption in most efficient way.


问:
Pythorch LSTM timeseries prediction hidden[0] size match error
I want to learn 100 for 3000days and predict 100 next day but I don't know why this error is happen and resolve this problem
please help me

batchsize = 100, hidden_dim = 10, seq_length = 60, data_dim = 100, output_dim = 100

```<code>class Net(nn.Module):

    def __init__(self, input_dim, hidden_dim, batch_size, output_dim, layers):
        super(Net, self).__init__()
        self.hidden_dim = hidden_dim
        self.batch_size = batch_size
        self.output_dim = output_dim
        self.layers = layers

        self.lstm = nn.LSTM(input_dim, hidden_dim, num_layers=layers,
                            batch_first=True)
        self.fc = nn.Linear(hidden_dim, output_dim, bias = True)
        self.hidden = self.reset_hidden_state()

    def reset_hidden_state(self):
        return (
                torch.zeros(self.layers, self.batch_size, self.hidden_dim),
                torch.zeros(self.layers, self.batch_size, self.hidden_dim))

    def forward(self, x):
        x, self.hidden = self.lstm(x, self.hidden)
        x = self.fc(x[:, -1,:]) # [batch_size, seq_len, hidden_dim]
        return x
</code>```
```<code># Train part
def train_model(model, train_df, num_epochs = None, lr = None, verbose = 10, patience = 10):
    criterion = nn.MSELoss().to(device)
    optimizer = optim.Adam(model.parameters(), lr = learning_rate)
    nb_epochs = num_epochs

    train_hist = np.zeros(nb_epochs)

    for epoch in range(nb_epochs):
        avg_cost = 0
        total_batch = len(train_df)

        for batch_idx, samples in enumerate(train_df):

            x_train, y_train = samples
            # seq별 hidden state reset
            model.reset_hidden_state()

            model.hidden = [hidden.to(device) for hidden in model.reset_hidden_state()]
            outputs = model(x_train)

            loss = criterion(outputs, y_train)

            optimizer.zero_grad()
            loss.backward()
            optimizer.step()

            avg_cost += loss/total_batch

        train_hist[epoch] = avg_cost

        if epoch % verbose == 0:
            print('Epoch:', '%04d' % (epoch), 'train loss :', '{:.4f}'.format(avg_cost))

        if (epoch % patience == 0) & (epoch != 0):

            if train_hist[epoch-patience] < train_hist[epoch]:
                print('\n Early Stopping')

                break

    return model.eval(), train_hist
</code>```

prediction part

```<code>net = Net(data_dim, hidden_dim, batch , output_dim, 1).to(device)
model, train_hist = train_model(net, dataloader, num_epochs = nb_epochs, lr = learning_rate, verbose = 20, patience = 10)
</code>```
```<code>with torch.no_grad():
    pred = np.zeros((2940,1,100))
    for pr in range(len(trainX_tensor)):

        model.reset_hidden_state()

        predicted = model(torch.unsqueeze(trainX_tensor[pr], 0)).cpu()
        print(predicted.shape)
        #predicted = predicted.item()
        pred[pr,:,:] = predicted

    #print(pr)
    # INVERSE
    pred_inverse = scaler.inverse_transform(pred)
</code>```

Expected hidden[0] size (1, 1, 10), got [1, 100, 10]
how can i resolve hidden[0] size fix?

Body:
I want to learn 100 for 3000days and predict 100 next day but I don't know why this error is happen and resolve this problem
please help me

batchsize = 100, hidden_dim = 10, seq_length = 60, data_dim = 100, output_dim = 100

class Net(nn.Module):

    def __init__(self, input_dim, hidden_dim, batch_size, output_dim, layers):
        super(Net, self).__init__()
        self.hidden_dim = hidden_dim
        self.batch_size = batch_size
        self.output_dim = output_dim
        self.layers = layers

        self.lstm = nn.LSTM(input_dim, hidden_dim, num_layers=layers,
                            batch_first=True)
        self.fc = nn.Linear(hidden_dim, output_dim, bias = True)
        self.hidden = self.reset_hidden_state()

    def reset_hidden_state(self):
        return (
                torch.zeros(self.layers, self.batch_size, self.hidden_dim),
                torch.zeros(self.layers, self.batch_size, self.hidden_dim))

    def forward(self, x):
        x, self.hidden = self.lstm(x, self.hidden)
        x = self.fc(x[:, -1,:]) # [batch_size, seq_len, hidden_dim]
        return x

# Train part
def train_model(model, train_df, num_epochs = None, lr = None, verbose = 10, patience = 10):
    criterion = nn.MSELoss().to(device)
    optimizer = optim.Adam(model.parameters(), lr = learning_rate)
    nb_epochs = num_epochs

    train_hist = np.zeros(nb_epochs)

    for epoch in range(nb_epochs):
        avg_cost = 0
        total_batch = len(train_df)

        for batch_idx, samples in enumerate(train_df):

            x_train, y_train = samples
            # seq별 hidden state reset
            model.reset_hidden_state()

            model.hidden = [hidden.to(device) for hidden in model.reset_hidden_state()]
            outputs = model(x_train)

            loss = criterion(outputs, y_train)

            optimizer.zero_grad()
            loss.backward()
            optimizer.step()

            avg_cost += loss/total_batch

        train_hist[epoch] = avg_cost

        if epoch % verbose == 0:
            print('Epoch:', '%04d' % (epoch), 'train loss :', '{:.4f}'.format(avg_cost))

        if (epoch % patience == 0) & (epoch != 0):

            if train_hist[epoch-patience] < train_hist[epoch]:
                print('\n Early Stopping')

                break

    return model.eval(), train_hist

prediction part

net = Net(data_dim, hidden_dim, batch , output_dim, 1).to(device)
model, train_hist = train_model(net, dataloader, num_epochs = nb_epochs, lr = learning_rate, verbose = 20, patience = 10)

with torch.no_grad():
    pred = np.zeros((2940,1,100))
    for pr in range(len(trainX_tensor)):

        model.reset_hidden_state()

        predicted = model(torch.unsqueeze(trainX_tensor[pr], 0)).cpu()
        print(predicted.shape)
        #predicted = predicted.item()
        pred[pr,:,:] = predicted

    #print(pr)
    # INVERSE
    pred_inverse = scaler.inverse_transform(pred)

Expected hidden[0] size (1, 1, 10), got [1, 100, 10]
how can i resolve hidden[0] size fix?


问:
How to configure console of azure devops pipeline powershell task to properly format Write-* Cmdlets' output?
I'm using the following PowerShell task:

```<code>2022-12-09T04:30:32.5910772Z Task         : PowerShell
2022-12-09T04:30:32.5911006Z Description  : Run a PowerShell script on Linux, macOS, or Windows
2022-12-09T04:30:32.5911196Z Version      : 2.212.0
2022-12-09T04:30:32.5911349Z Author       : Microsoft Corporation
2022-12-09T04:30:32.5911615Z Help         : https://docs.microsoft.com/azure/devops/pipelines/tasks/utility/powershell
</code>```

Here is an example warning output where you can see the message is surrounded by [33;1m and [0m. I assume these are ANSI escap codes.

```<code>2022-12-09T04:30:30.8803823Z [33;1mWARNING: The provided service principal secret will be included in the 'AzureRmContext.json' file found in the user profile ( /root/.Azure ). Please ensure that this directory has appropriate protections.[0m
</code>```

Here is an example Error message output:

```<code>2022-12-09T04:30:39.5319115Z [91mInvoke-RestMethod: [0m/azp/agent/_work/r2/a/_ADsync-Utility/adsync/ADsyncUtility/adbusersync.ps1:254
2022-12-09T04:30:39.5320715Z [96mLine |
2022-12-09T04:30:39.5322096Z [96m 254 | [0m … sResponse = [96mInvoke-RestMethod $adbGroupsURL -Method GET -Headers $adb[0m …
2022-12-09T04:30:39.5323707Z [96m     | [91m               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2022-12-09T04:30:39.5325002Z [91m[96m     | [91m{"error_code":"403","message":"Invalid access to Org:
2022-12-09T04:30:39.5326245Z [96m     | [91m2660194586577136"}
2022-12-09T04:30:39.5327021Z [0m
</code>```

As a workaround, is there a way that I can configure the format of Powershell Write-Verbose, Write-Warning and Write-Error cmdlets' messages to remove these escape codes and/or possibly use the Azure DevOps Logging Command Formatting syntax?

##[warning]Warning message

##[error]Error message

Body:
I'm using the following PowerShell task:

2022-12-09T04:30:32.5910772Z Task         : PowerShell
2022-12-09T04:30:32.5911006Z Description  : Run a PowerShell script on Linux, macOS, or Windows
2022-12-09T04:30:32.5911196Z Version      : 2.212.0
2022-12-09T04:30:32.5911349Z Author       : Microsoft Corporation
2022-12-09T04:30:32.5911615Z Help         : https://docs.microsoft.com/azure/devops/pipelines/tasks/utility/powershell

Here is an example warning output where you can see the message is surrounded by [33;1m and [0m. I assume these are ANSI escap codes.

2022-12-09T04:30:30.8803823Z [33;1mWARNING: The provided service principal secret will be included in the 'AzureRmContext.json' file found in the user profile ( /root/.Azure ). Please ensure that this directory has appropriate protections.[0m

Here is an example Error message output:

2022-12-09T04:30:39.5319115Z [91mInvoke-RestMethod: [0m/azp/agent/_work/r2/a/_ADsync-Utility/adsync/ADsyncUtility/adbusersync.ps1:254
2022-12-09T04:30:39.5320715Z [96mLine |
2022-12-09T04:30:39.5322096Z [96m 254 | [0m … sResponse = [96mInvoke-RestMethod $adbGroupsURL -Method GET -Headers $adb[0m …
2022-12-09T04:30:39.5323707Z [96m     | [91m               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2022-12-09T04:30:39.5325002Z [91m[96m     | [91m{"error_code":"403","message":"Invalid access to Org:
2022-12-09T04:30:39.5326245Z [96m     | [91m2660194586577136"}
2022-12-09T04:30:39.5327021Z [0m

As a workaround, is there a way that I can configure the format of Powershell Write-Verbose, Write-Warning and Write-Error cmdlets' messages to remove these escape codes and/or possibly use the Azure DevOps Logging Command Formatting syntax?

##[warning]Warning message

##[error]Error message


问:
How to convert java.awt.font TextAttribute.TRACKING to css letter spacing?
I want to know how to convert TextAttribute.TRACKING floating point value to "points" or "pixels" in css letter-spacing.

This is what I am doing in the backend.

```<code>AttributedString as = new AttributedString("Some text");
as.addAttribute(TextAttribute.TRACKING, 0.05f);
</code>```

I have a backend that uses Java Graphics to draw text and front end where user enters the text. So my need is to show the effect in UI first without having to hit backend first.

PS: If the conversion is not possible, then what is the alternative in css for TRACKING?

Appreciate any help.

Body:
I want to know how to convert TextAttribute.TRACKING floating point value to "points" or "pixels" in css letter-spacing.

This is what I am doing in the backend.

AttributedString as = new AttributedString("Some text");
as.addAttribute(TextAttribute.TRACKING, 0.05f);

I have a backend that uses Java Graphics to draw text and front end where user enters the text. So my need is to show the effect in UI first without having to hit backend first.

PS: If the conversion is not possible, then what is the alternative in css for TRACKING?

Appreciate any help.


问:
How convert multiple attributes or sub array in excel to json with sub array inside
i want to list several school with data like below, there is major data like example below.
i list the data manualy with excel and want to convert it to json like below.

This is the example json

```<code>    [
        {
            "No": "1",
            "Country": "USA",
            "Region": "Northeast",
            "State": "Connecticut",
            "City": "New Haven",
            "University": "Albertus Magnus College",
            "Status": "Public",
            "Major": [
                    "Computer Science",
                    "Communications",
                    "Political Science",
                    "Business",
                    "Economics",
                    "English Language",
                    "Psychology",
                    "Nursing",
                    "Chemical Engineering",
                    "Biology",

                ],
            "Logo": "https://upload.wikimedia.org/wikipedia/commons/3/38/AlbertusMagnusCollgeSeal.jpg"
        },
   ]
</code>```

How to write it in excel? any suggestions? next i want to list degree too that have multiple value.

Body:
i want to list several school with data like below, there is major data like example below.
i list the data manualy with excel and want to convert it to json like below.

This is the example json

    [
        {
            "No": "1",
            "Country": "USA",
            "Region": "Northeast",
            "State": "Connecticut",
            "City": "New Haven",
            "University": "Albertus Magnus College",
            "Status": "Public",
            "Major": [
                    "Computer Science",
                    "Communications",
                    "Political Science",
                    "Business",
                    "Economics",
                    "English Language",
                    "Psychology",
                    "Nursing",
                    "Chemical Engineering",
                    "Biology",

                ],
            "Logo": "https://upload.wikimedia.org/wikipedia/commons/3/38/AlbertusMagnusCollgeSeal.jpg"
        },
   ]

How to write it in excel? any suggestions? next i want to list degree too that have multiple value.


问:
Uncaught TypeError: Error resolving module specifier “axios”. Relative module specifiers must start with “./”, “../” or “/”. I didn't get the answer
I installed "npm install axios" and imported using "import axios from 'axios'.
I wanted to post the data and get the data

These are the codes I have used.

Package.json :

```<code>{
  "name": "ceniplex-tickets",
  "version": "1.0.0",
  "description": "ticket booking app",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Aswin Anilkumar",
  "license": "ISC",
  "devDependencies": {
    "parcel": "^2.8.1",
    "parcel-bundler": "^1.8.1"
  },
  "dependencies": {
    "axios": "^1.2.1"
  }
}
</code>```

JS code (Front end) :

```<code>import axios from 'axios';

class Model {
    constructor() {
        this.array = []
    }
    getArray() {
        return this.array;
    }

    async loadTicketsFromBackend() {
        const req = await axios.get('http://localhost:3000/booking')
        const booking = req.data;

        console.log(booking);
    }

    async setArray(data) {
        const res = await axios.post('http://localhost:3000/booking',data)
        return res;
    }
}

export default Model;
</code>```

Body:
I installed "npm install axios" and imported using "import axios from 'axios'.
I wanted to post the data and get the data

These are the codes I have used.

Package.json :

{
  "name": "ceniplex-tickets",
  "version": "1.0.0",
  "description": "ticket booking app",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Aswin Anilkumar",
  "license": "ISC",
  "devDependencies": {
    "parcel": "^2.8.1",
    "parcel-bundler": "^1.8.1"
  },
  "dependencies": {
    "axios": "^1.2.1"
  }
}

JS code (Front end) :

import axios from 'axios';

class Model {
    constructor() {
        this.array = []
    }
    getArray() {
        return this.array;
    }

    async loadTicketsFromBackend() {
        const req = await axios.get('http://localhost:3000/booking')
        const booking = req.data;

        console.log(booking);
    }

    async setArray(data) {
        const res = await axios.post('http://localhost:3000/booking',data)
        return res;
    }
}

export default Model;


问:
i am having an error when deploye an ecommerce mern store on vercel
When i deploye my ecommerce Store on vercel it shows me directories rather than showing my webpage and heres the screenshot


问:
Git not able to push the code but can commit
I am able to commit the code but not able to push.

```<code>Enumerating objects: 601, done.
Counting objects: 100% (601/601), done.
Delta compression using up to 12 threads
Compressing objects: 100% (587/587), done.
Writing objects: 100% (600/600), 37.61 MiB | 28.57 MiB/s, done.
Total 600 (delta 31), reused 0 (delta 0), pack-reused 0
error: RPC failed; curl 56 OpenSSL SSL_read: error:140943FC:SSL routines:ssl3_read_bytes:sslv3 alert bad record mac, errno 0
send-pack: unexpected disconnect while reading sideband packet
fatal: the remote end hung up unexpectedly
Everything up-to-date
</code>```

I have tried to reset credentials.
Also tried

```<code>$ git config http.postBuffer 524288000
</code>```

Body:
I am able to commit the code but not able to push.

Enumerating objects: 601, done.
Counting objects: 100% (601/601), done.
Delta compression using up to 12 threads
Compressing objects: 100% (587/587), done.
Writing objects: 100% (600/600), 37.61 MiB | 28.57 MiB/s, done.
Total 600 (delta 31), reused 0 (delta 0), pack-reused 0
error: RPC failed; curl 56 OpenSSL SSL_read: error:140943FC:SSL routines:ssl3_read_bytes:sslv3 alert bad record mac, errno 0
send-pack: unexpected disconnect while reading sideband packet
fatal: the remote end hung up unexpectedly
Everything up-to-date

I have tried to reset credentials.
Also tried

$ git config http.postBuffer 524288000


问:
Cubic interpolation in Pandas raises ValueError: The number of derivatives at boundaries does not match: expected 3, got 0+0
Using the below weekly dataset, I want to resample to monthly data with cubic conversion.

```<code>Period       Values
20-Jan-89   3
27-Jan-89   4
3-Feb-89    2
10-Feb-89   5
17-Feb-89   3
24-Feb-89   5
3-Mar-89    5
10-Mar-89   6
17-Mar-89   4
24-Mar-89   5
31-Mar-89   7
7-Apr-89    6
14-Apr-89   6
21-Apr-89   4
28-Apr-89   7
5-May-89    5
12-May-89   6
19-May-89   5
26-May-89   7
2-Jun-89    7
</code>```

I used the code appended below,

```<code>q= pd.Series(df[series], index=df.index)
m = q.resample('M').interpolate(method='cubic')
</code>```

but I get error

ValueError: The number of derivatives at boundaries does not match: expected 3, got 0+0

Body:
Using the below weekly dataset, I want to resample to monthly data with cubic conversion.

Period       Values
20-Jan-89   3
27-Jan-89   4
3-Feb-89    2
10-Feb-89   5
17-Feb-89   3
24-Feb-89   5
3-Mar-89    5
10-Mar-89   6
17-Mar-89   4
24-Mar-89   5
31-Mar-89   7
7-Apr-89    6
14-Apr-89   6
21-Apr-89   4
28-Apr-89   7
5-May-89    5
12-May-89   6
19-May-89   5
26-May-89   7
2-Jun-89    7

I used the code appended below,

q= pd.Series(df[series], index=df.index)
m = q.resample('M').interpolate(method='cubic')

but I get error

ValueError: The number of derivatives at boundaries does not match: expected 3, got 0+0


问:
Tableau - different order of items when filtered vs not filtered
I have a dataset where when the category filter is set to ‘All’ the data is sorted alphabetically, which is what I want. When the category is filtered to anything other than ‘All’ (about 30 distinct categories) I want the data in the view to be sorted by a dimension: rank, where each obs has a number ranking it in order of dollar value, within each category. How can I do this? If I sort by rank, it overrides the alphabetic sorting of ‘All’ when I need each in their distinct cases. Thanks!

Tried adding ‘category’ to rows so that I could sort ‘category’ in the filter, which is the only place I need it. But this overrides the alphabetic sort when the category is default ‘all.’


问:
Stock Android Emojis Image DL
I'd like to use try and use stock android emojis to build a pixel image using emojis as pixels that I've rated based on color or brightness and assign one per image pixel that nearest matches.

How do I access the stock android images of these emojis?, I find lots of crappy compressed pixelated versions on google images but I'd like to work with the stock unmodified image data.

They must be buried somewhere on my phone or within android image/source.

Accepting all and any pointers :)

Thx!

Tony

Title: Stock Android Emojis Image DL


问:
How to use pipeline for Custom token-classification model
Model description

I add simple custom pytorch-crf layer on top of TokenClassification model. It will make the model more robust.

I train the model successfully but when I test the mode. The folder doesn't have config.json file inside it. So the pipeline function gives error as

Error:AttributeError: 'BERT_CRF' object has no attribute 'config'

CODE

```<code>class BERT_CRF(nn.Module):

   def __init__(self, bert_model, num_labels):

        super(BERT_CRF, self).__init__()
        self.bert = bert_model
        self.dropout = nn.Dropout(0.25)
        self.classifier = nn.Linear(768, num_labels)
        self.crf = CRF(num_labels, batch_first = True)

    def forward(self, input_ids, attention_mask,  labels=None, token_type_ids=None):

        outputs = self.bert(input_ids, attention_mask=attention_mask)
        sequence_output = torch.stack((outputs[1][-1], outputs[1][-2], outputs[1][-3], outputs[1][-4])).mean(dim=0)
        sequence_output = self.dropout(sequence_output)
        emission = self.classifier(sequence_output) # [32,256,17]
        if labels is not None:
            labels=labels.reshape(attention_mask.size()[0],attention_mask.size()[1])
            loss = -self.crf(log_soft(emission, 2), labels, mask=attention_mask.type(torch.uint8), reduction='mean')
            prediction = self.crf.decode(emission, mask=attention_mask.type(torch.uint8))
            return [loss, prediction]

        else:
            prediction = self.crf.decode(emission, mask=attention_mask.type(torch.uint8))
            return prediction
</code>```
```<code>tokenizer = AutoTokenizer.from_pretrained("fine-tuned_model",model_max_length=256)

bert_model = BertForTokenClassification.from_pretrained('spanbert_base',id2label=id2label,label2id=label2id)
bert_model.config.output_hidden_states=True
model = BERT_CRF(bert_model, num_labels=21)
model.load_state_dict(torch.load("fine-tuned_model/pytorch_model.bin"))
model.eval()
</code>```

token_classifier = pipeline("token-classification", model=model, aggregation_strategy="max",tokenizer=tokenizer,grouped_entities=True)

AttributeError: 'BERT_CRF' object has no attribute 'config'

Body:
Model description

I add simple custom pytorch-crf layer on top of TokenClassification model. It will make the model more robust.

I train the model successfully but when I test the mode. The folder doesn't have config.json file inside it. So the pipeline function gives error as

Error:AttributeError: 'BERT_CRF' object has no attribute 'config'

CODE

class BERT_CRF(nn.Module):

   def __init__(self, bert_model, num_labels):

        super(BERT_CRF, self).__init__()
        self.bert = bert_model
        self.dropout = nn.Dropout(0.25)
        self.classifier = nn.Linear(768, num_labels)
        self.crf = CRF(num_labels, batch_first = True)

    def forward(self, input_ids, attention_mask,  labels=None, token_type_ids=None):

        outputs = self.bert(input_ids, attention_mask=attention_mask)
        sequence_output = torch.stack((outputs[1][-1], outputs[1][-2], outputs[1][-3], outputs[1][-4])).mean(dim=0)
        sequence_output = self.dropout(sequence_output)
        emission = self.classifier(sequence_output) # [32,256,17]
        if labels is not None:
            labels=labels.reshape(attention_mask.size()[0],attention_mask.size()[1])
            loss = -self.crf(log_soft(emission, 2), labels, mask=attention_mask.type(torch.uint8), reduction='mean')
            prediction = self.crf.decode(emission, mask=attention_mask.type(torch.uint8))
            return [loss, prediction]

        else:
            prediction = self.crf.decode(emission, mask=attention_mask.type(torch.uint8))
            return prediction

tokenizer = AutoTokenizer.from_pretrained("fine-tuned_model",model_max_length=256)

bert_model = BertForTokenClassification.from_pretrained('spanbert_base',id2label=id2label,label2id=label2id)
bert_model.config.output_hidden_states=True
model = BERT_CRF(bert_model, num_labels=21)
model.load_state_dict(torch.load("fine-tuned_model/pytorch_model.bin"))
model.eval()

token_classifier = pipeline("token-classification", model=model, aggregation_strategy="max",tokenizer=tokenizer,grouped_entities=True)

AttributeError: 'BERT_CRF' object has no attribute 'config'


问:
How can end My Youtube live stream API in c#?
How to stop my livestream in YouTube while completed my live telecast using c#

How to stop the livestream Using c# Code, can you please give some suggestion

```<code>string[] scopes = { "https://www.googleapis.com/auth/youtube", "https://www.googleapis.com/auth/youtube.upload" };

                var creadentails = GoogleWebAuthorizationBroker.AuthorizeAsync(
                        new ClientSecrets
                        {
                            ClientId = YTPublishSettings.PublisherClientId,
                            ClientSecret = YTPublishSettings.PublisherClientSecret,
                        },
                        scopes, "user", default).Result;

                if (creadentails.Token.IsExpired(SystemClock.Default))
                    creadentails.RefreshTokenAsync(CancellationToken.None).Wait();

                var secrets = new ClientSecrets
                {
                    ClientId = YTPublishSettings.PublisherClientId,
                    ClientSecret = YTPublishSettings.PublisherClientSecret,
                };

                var token = new TokenResponse { RefreshToken = creadentails.Token.RefreshToken };
                var credentials = new UserCredential(new GoogleAuthorizationCodeFlow(
                new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = secrets }),
                "user", token);
                var service = new YouTubeService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = credentials,
                    ApplicationName = "**************",

                });
                var broadcast = new LiveStream
                {
                    Cdn = new CdnSettings
                    {
                        FrameRate = "35fps",
                        IngestionType = "rtmp",
                        Resolution = "720p"
                    },
                    Snippet = new LiveStreamSnippet
                    {
                        Description = Description,
                        Title = Title,
                    },

                };
                var request = service.LiveStreams.Delete(YTPublishSettings.PublisherId);
                var response = request.Execute();
                return new YouTubeStreamDeleteStatus()
                {
                    success = "Deleted",
                };
</code>```

How can end My YouTube live stream API in c#?

Body:
How to stop my livestream in YouTube while completed my live telecast using c#

How to stop the livestream Using c# Code, can you please give some suggestion

string[] scopes = { "https://www.googleapis.com/auth/youtube", "https://www.googleapis.com/auth/youtube.upload" };

                var creadentails = GoogleWebAuthorizationBroker.AuthorizeAsync(
                        new ClientSecrets
                        {
                            ClientId = YTPublishSettings.PublisherClientId,
                            ClientSecret = YTPublishSettings.PublisherClientSecret,
                        },
                        scopes, "user", default).Result;

                if (creadentails.Token.IsExpired(SystemClock.Default))
                    creadentails.RefreshTokenAsync(CancellationToken.None).Wait();

                var secrets = new ClientSecrets
                {
                    ClientId = YTPublishSettings.PublisherClientId,
                    ClientSecret = YTPublishSettings.PublisherClientSecret,
                };

                var token = new TokenResponse { RefreshToken = creadentails.Token.RefreshToken };
                var credentials = new UserCredential(new GoogleAuthorizationCodeFlow(
                new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = secrets }),
                "user", token);
                var service = new YouTubeService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = credentials,
                    ApplicationName = "**************",

                });
                var broadcast = new LiveStream
                {
                    Cdn = new CdnSettings
                    {
                        FrameRate = "35fps",
                        IngestionType = "rtmp",
                        Resolution = "720p"
                    },
                    Snippet = new LiveStreamSnippet
                    {
                        Description = Description,
                        Title = Title,
                    },

                };
                var request = service.LiveStreams.Delete(YTPublishSettings.PublisherId);
                var response = request.Execute();
                return new YouTubeStreamDeleteStatus()
                {
                    success = "Deleted",
                };

How can end My YouTube live stream API in c#?


问:
Strange behavior while creating ES domain using AWS CLI with localstack
I' trying to create AWS ElasticSearchDomain using AWS-CLI on my local machine with Localstack .
All my domain configuration in in one file called mydomain.json.
By using command awslocal es create-elasticsearch-domain --cli-input-json file://path/to/file
Here the file I'm referring to is mydomain.json.
Here are the contents of json file
mydomain.json

```<code> {
            "DomainName":"mydomain",
            "ElasticsearchVersion": "6.8",
            "ElasticsearchClusterConfig": {
              "DedicatedMasterEnabled": true,
              "DedicatedMasterCount": 3,
              "ZoneAwarenessEnabled": true,
              "InstanceCount": 3,
              "InstanceType":"m3.medium.elasticsearch",
              "DedicatedMasterType": "m3.medium.elasticsearch",
            },
            "EBSOptions" : {
                "EBSEnabled" : true,
                "VolumeSize" : 1,
                "VolumeType" : "gp2"
            },
            "Tags": [
                {
                "Key": "Name",
                "Value": "Localstack_Elasticsearch_Domain"
                }
            ]
}

</code>```

There are several errors I'm facing

It should create domain with "DedicatedMasterCount" of 3 but it creates "DedicatedMasterCount" of 1.

Even is volume size is specified as "VolumeSize" : 1 it creates it with "VolumeSize" : 10

Parameter validation failed:
Unknown parameter in input: "Tags", must be one of: DomainName, ElasticsearchVersion, ElasticsearchClusterConfig, EBSOptions, AccessPolicies, SnapshotOptions, VPCOptions, CognitoOptions, EncryptionAtRestOptions, NodeToNodeEncryptionOptions, AdvancedOptions, LogPublishingOptions, DomainEndpointOptions, AdvancedSecurityOptions, AutoTuneOptions, TagList

Body:
I' trying to create AWS ElasticSearchDomain using AWS-CLI on my local machine with Localstack .
All my domain configuration in in one file called mydomain.json.
By using command awslocal es create-elasticsearch-domain --cli-input-json file://path/to/file
Here the file I'm referring to is mydomain.json.
Here are the contents of json file
mydomain.json

 {
            "DomainName":"mydomain",
            "ElasticsearchVersion": "6.8",
            "ElasticsearchClusterConfig": {
              "DedicatedMasterEnabled": true,
              "DedicatedMasterCount": 3,
              "ZoneAwarenessEnabled": true,
              "InstanceCount": 3,
              "InstanceType":"m3.medium.elasticsearch",
              "DedicatedMasterType": "m3.medium.elasticsearch",
            },
            "EBSOptions" : {
                "EBSEnabled" : true,
                "VolumeSize" : 1,
                "VolumeType" : "gp2"
            },
            "Tags": [
                {
                "Key": "Name",
                "Value": "Localstack_Elasticsearch_Domain"
                }
            ]
}

There are several errors I'm facing

It should create domain with "DedicatedMasterCount" of 3 but it creates "DedicatedMasterCount" of 1.

Even is volume size is specified as "VolumeSize" : 1 it creates it with "VolumeSize" : 10

Parameter validation failed:
Unknown parameter in input: "Tags", must be one of: DomainName, ElasticsearchVersion, ElasticsearchClusterConfig, EBSOptions, AccessPolicies, SnapshotOptions, VPCOptions, CognitoOptions, EncryptionAtRestOptions, NodeToNodeEncryptionOptions, AdvancedOptions, LogPublishingOptions, DomainEndpointOptions, AdvancedSecurityOptions, AutoTuneOptions, TagList


问:
How to calculate mean and standard deviation of dicom image after converting it to hounsfield unit from pixel array
Need to calculate mean and  standard deviation of dicom images (set of images).
RGB image has 3 channels, gray scale image has 1 channel. how many channels do dicom images has. when we print pixel_array from header of a dicom, in how many channels arrays are viewd. converting pixel array to hounsfield unit and then trying to calculate mean and  standard deviation of dicom images

```<code># calculate mean and std deviation

from pathlib import Path
import cv2

imageFilesDir = Path(r'C:\your\dataset\dir\here\trainData')
files = list(imageFilesDir.rglob('*.png'))

# Since the std can't be calculated by simply finding it for each image and averaging like
# the mean can be, to get the std we first calculate the overall mean in a first run then
# run it again to get the std.

mean = np.array([0.,0.,0.])
stdTemp = np.array([0.,0.,0.])
std = np.array([0.,0.,0.])

numSamples = len(files)

for i in range(numSamples):
    im = cv2.imread(str(files[i]))
    im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
    im = im.astype(float) / 255.

    for j in range(3):
        mean[j] += np.mean(im[:,:,j])

mean = (mean/numSamples)

for i in range(numSamples):
    im = cv2.imread(str(files[i]))
    im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
    im = im.astype(float) / 255.
    for j in range(3):
        stdTemp[j] += ((im[:,:,j] - mean[j])**2).sum()/(im.shape[0]*im.shape[1])

std = np.sqrt(stdTemp/numSamples)

print(mean)
print(std)

# out:
</code>```

this is for RGB image, i should perform same opration for dicom image

Body:
Need to calculate mean and  standard deviation of dicom images (set of images).
RGB image has 3 channels, gray scale image has 1 channel. how many channels do dicom images has. when we print pixel_array from header of a dicom, in how many channels arrays are viewd. converting pixel array to hounsfield unit and then trying to calculate mean and  standard deviation of dicom images

# calculate mean and std deviation

from pathlib import Path
import cv2

imageFilesDir = Path(r'C:\your\dataset\dir\here\trainData')
files = list(imageFilesDir.rglob('*.png'))

# Since the std can't be calculated by simply finding it for each image and averaging like
# the mean can be, to get the std we first calculate the overall mean in a first run then
# run it again to get the std.

mean = np.array([0.,0.,0.])
stdTemp = np.array([0.,0.,0.])
std = np.array([0.,0.,0.])

numSamples = len(files)

for i in range(numSamples):
    im = cv2.imread(str(files[i]))
    im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
    im = im.astype(float) / 255.

    for j in range(3):
        mean[j] += np.mean(im[:,:,j])

mean = (mean/numSamples)

for i in range(numSamples):
    im = cv2.imread(str(files[i]))
    im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
    im = im.astype(float) / 255.
    for j in range(3):
        stdTemp[j] += ((im[:,:,j] - mean[j])**2).sum()/(im.shape[0]*im.shape[1])

std = np.sqrt(stdTemp/numSamples)

print(mean)
print(std)

# out:

this is for RGB image, i should perform same opration for dicom image


问:
Why am I not able to use User SQL Server Authentication using SQL Server Import and Export Wizard?
Data Source Screen shot

I am trying to export a table from one database to another using SQL Server Import and Export Wizard (MS SQL Server Management Studio 17).

For reasons, I am not able to use SQL Server Authentication, it would prompt error as seen in the screen shot.

It would work if I changed authentication to use Windows Authentication.   However, I need to use SQL Server Authentication to be able to select the desired table to export. Those tables would be invisible using Windows Authentication.     I logged into the database using SQL Server Authentication.

Can someone tell me what I did wrong?  Thanks!

Error Detail:

```<code>Invalid authorization specification
Invalid connection string attribute (Microsoft SQL Server Native Client 11.0)

------------------------------
Program Location:

   at System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr, OleDbConnection connection)
   at System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject)
   at System.Data.ProviderBase.DbConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionInternal.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
   at System.Data.OleDb.OleDbConnection.Open()
   at Microsoft.SqlServer.Dts.DtsWizard.DTSWizard.GetOpenedConnection(WizardInputs wizardInputs, String connEntryName)
   at Microsoft.SqlServer.Dts.DtsWizard.Step1.OnLeavePage(LeavePageEventArgs e)
</code>```

Blockquote

Body:
Data Source Screen shot

I am trying to export a table from one database to another using SQL Server Import and Export Wizard (MS SQL Server Management Studio 17).

For reasons, I am not able to use SQL Server Authentication, it would prompt error as seen in the screen shot.

It would work if I changed authentication to use Windows Authentication.   However, I need to use SQL Server Authentication to be able to select the desired table to export. Those tables would be invisible using Windows Authentication.     I logged into the database using SQL Server Authentication.

Can someone tell me what I did wrong?  Thanks!

Error Detail:

Invalid authorization specification
Invalid connection string attribute (Microsoft SQL Server Native Client 11.0)

------------------------------
Program Location:

   at System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr, OleDbConnection connection)
   at System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject)
   at System.Data.ProviderBase.DbConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionInternal.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
   at System.Data.OleDb.OleDbConnection.Open()
   at Microsoft.SqlServer.Dts.DtsWizard.DTSWizard.GetOpenedConnection(WizardInputs wizardInputs, String connEntryName)
   at Microsoft.SqlServer.Dts.DtsWizard.Step1.OnLeavePage(LeavePageEventArgs e)

Blockquote


问:
Can yolov7 detect very tiny objects from thermal images?
I was using yolov5 to detect animals on the sea surface.

but yolo had a difficult time doing it because the waves were also similar in shape and color to the birds (lots of false positives). And when the drone flew really high or when non whitish birds were involved, it didn't detect them at all. They were tiny and not really distinct to the eye. Will this issue be resolved if I use a thermal camera? I hope the thermal sensors can distinguish the cold sea and the warm animals like this,

and yolo can easily detect them even if they were tiny. Is my assumption valid? Can yolov7 be used to train and detect the thermal imagery of tiny birds?


问:
MPDF crashes on mkdir for its cache directory
I use Mpdf via composer ("mpdf/mpdf": "~8.1") and I regularly have an error related to the creation (sometimes the deletion) of a Cache directory because having many PDF files to create, the processor launches several concurrent processes. It seems that the Cache directory being unique for all processes, it regularly happens that the directory has just been created by a process A and that another process also tries to create it.
What solution can we find to avoid this problem?
Shouldn't the cache directory be private to each process, for example by giving a name based on a random string?

Here is the stack of the error received:

```<code>ERROR:  ErrorException: mkdir(): File exists in /var/app/current/vendor/mpdf/mpdf/src/Cache.php:49 Stack trace:
#0 [internal function]: log_error(2, 'mkdir(): File e...', '/var/app/curren...', 49)
#1 /var/app/current/vendor/mpdf/mpdf/src/Cache.php(49): mkdir('/var/app/curren...')
#2 /var/app/current/vendor/mpdf/mpdf/src/Cache.php(35): Mpdf\Cache->createDirectory('/var/app/curren...')
#3 /var/app/current/vendor/mpdf/mpdf/src/Cache.php(20): Mpdf\Cache->createBasePath('/var/app/curren...')
#4 /var/app/current/vendor/mpdf/mpdf/src/ServiceFactory.php(67): Mpdf\Cache->__construct('/var/app/curren...', 3600)
#5 /var/app/current/vendor/mpdf/mpdf/src/Mpdf.php(1083): Mpdf\ServiceFactory->getServices(Object(Mpdf\Mpdf), Object(Psr\Log\NullLogger), Array, Object(Mpdf\Language\LanguageToFont), Object(Mpdf\Language\ScriptToLanguage), NULL, NULL, NULL, NULL)
#6 /var/app/current/src/docs/pdfRelevePP.php(109): Mpdf\Mpdf->__construct(Array)
#7 /var/app/current/src/index.php(361): makePdfRelevePP(Array) #8 {main}
</code>```

And the code that causes it:

```<code>$mpdf = new \Mpdf\Mpdf( [
        'debug' => true,
        'allow_output_buffering' => true ] );  // <-- ERROR
$mpdf->allow_charset_conversion = true;
$mpdf->charset_in = 'utf-8';
$mpdf->setFooter( '{PAGENO} de {nbpg}' );
$mpdf->WriteHTML( $html );
$pdf_gen = $mpdf->Output( '', \Mpdf\Output\Destination::STRING_RETURN );
</code>```

Thanks for your help.

Body:
I use Mpdf via composer ("mpdf/mpdf": "~8.1") and I regularly have an error related to the creation (sometimes the deletion) of a Cache directory because having many PDF files to create, the processor launches several concurrent processes. It seems that the Cache directory being unique for all processes, it regularly happens that the directory has just been created by a process A and that another process also tries to create it.
What solution can we find to avoid this problem?
Shouldn't the cache directory be private to each process, for example by giving a name based on a random string?

Here is the stack of the error received:

ERROR:  ErrorException: mkdir(): File exists in /var/app/current/vendor/mpdf/mpdf/src/Cache.php:49 Stack trace:
#0 [internal function]: log_error(2, 'mkdir(): File e...', '/var/app/curren...', 49)
#1 /var/app/current/vendor/mpdf/mpdf/src/Cache.php(49): mkdir('/var/app/curren...')
#2 /var/app/current/vendor/mpdf/mpdf/src/Cache.php(35): Mpdf\Cache->createDirectory('/var/app/curren...')
#3 /var/app/current/vendor/mpdf/mpdf/src/Cache.php(20): Mpdf\Cache->createBasePath('/var/app/curren...')
#4 /var/app/current/vendor/mpdf/mpdf/src/ServiceFactory.php(67): Mpdf\Cache->__construct('/var/app/curren...', 3600)
#5 /var/app/current/vendor/mpdf/mpdf/src/Mpdf.php(1083): Mpdf\ServiceFactory->getServices(Object(Mpdf\Mpdf), Object(Psr\Log\NullLogger), Array, Object(Mpdf\Language\LanguageToFont), Object(Mpdf\Language\ScriptToLanguage), NULL, NULL, NULL, NULL)
#6 /var/app/current/src/docs/pdfRelevePP.php(109): Mpdf\Mpdf->__construct(Array)
#7 /var/app/current/src/index.php(361): makePdfRelevePP(Array) #8 {main}

And the code that causes it:

$mpdf = new \Mpdf\Mpdf( [
        'debug' => true,
        'allow_output_buffering' => true ] );  // <-- ERROR
$mpdf->allow_charset_conversion = true;
$mpdf->charset_in = 'utf-8';
$mpdf->setFooter( '{PAGENO} de {nbpg}' );
$mpdf->WriteHTML( $html );
$pdf_gen = $mpdf->Output( '', \Mpdf\Output\Destination::STRING_RETURN );

Thanks for your help.


问:
Angular: Active Slide Number & Total Slides in an Owl Carousel 2.0.7
I am new to Angular & using an owl carousel in my application. My catch is to display the index of current slide and total number of slides present in the carousel. The current slide index should change with changing slides. For your reference, my HTML is below:

```<code>    <div class="carousel-custom-nav">
      <img src="assets/carousel-prev.svg" class="jo-carousel-prev" (click)="carousel.previous()" />
      <p class="mr-ml-10">Active Slide Index / Total No. of Slides</p>
      <img src="assets/carousel-next.svg" class="jo-carousel-next" (click)="carousel.next()" />
    </div>
</code>```

By now you might have understood, I actually want to change the paragraph content with respective numbers.

I tried the owl events available in its documentation but couldn't achieve in angular.

Body:
I am new to Angular & using an owl carousel in my application. My catch is to display the index of current slide and total number of slides present in the carousel. The current slide index should change with changing slides. For your reference, my HTML is below:

Active Slide Index / Total No. of Slides

By now you might have understood, I actually want to change the paragraph content with respective numbers.

I tried the owl events available in its documentation but couldn't achieve in angular.


问:
InternalOAuthError: Failed to obtain access token - okta
I'm trying to authenticate my application through okta, the local code in my machine is working fine (whose callback url is http) but the same is not working in prod (its callback url would be https) not sure what's the error, I tried most of the things mentioned here still it gives the generic error message:

```<code>InternalOAuthError: Failed to obtain access token
</code>```

Has anyone able to solve this issue? It comes upto the okta page I give my credentials and MFA but after that it keeps loading eventually timing out with 504 error response. If anyone has used okta with https you can the share the code snippets it will really help.
I'm using these libraries:

```<code>"passport": "^0.4.1",
"passport-openidconnect": "^0.1.1"
</code>```

Body:
I'm trying to authenticate my application through okta, the local code in my machine is working fine (whose callback url is http) but the same is not working in prod (its callback url would be https) not sure what's the error, I tried most of the things mentioned here still it gives the generic error message:

InternalOAuthError: Failed to obtain access token

Has anyone able to solve this issue? It comes upto the okta page I give my credentials and MFA but after that it keeps loading eventually timing out with 504 error response. If anyone has used okta with https you can the share the code snippets it will really help.
I'm using these libraries:

"passport": "^0.4.1",
"passport-openidconnect": "^0.1.1"


问:
Can I swap the current context Identity user with one pulled from userManager.Users.First
MVC Framework with Identity. Switching to OIDC. OIDC server provides email address instead of UserId. ApplicationSignInManager can't find the correct user.  The user pulled from ApplicationSignInManager is much more robust with Firstname, Lastname, etc.  We would have to change a lot of code if these weren't members of the user.

We'd like to catch this event and swap out the user in Startup.cs

```<code>private Task OnSecurityTokenValidated(SecurityTokenValidatedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
{
    var user = userManager.Users.First(u => u.Email == notification.AuthenticationTicket.Identity.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").Value);
    notification.OwinContext.Authentication.SignIn(user);
</code>```

Except user we can't do that because

```<code>Cannot resolve method 'SignIn(EazeeApp.UI.Models.ApplicationUser)', candidates are:
void SignIn(Microsoft.Owin.Security.AuthenticationProperties, params System.Security.Claims.ClaimsIdentity[]) (in interface IAuthenticationManager)
</code>```

This seems kinda gross, so I'm definitely up for some better, simpler solutions.  I tried just dumping all the claims from the User into the notification.AuthenticationTicket.Identity but that won't include fields we need (but otherwise worked quite well).

Body:
MVC Framework with Identity. Switching to OIDC. OIDC server provides email address instead of UserId. ApplicationSignInManager can't find the correct user.  The user pulled from ApplicationSignInManager is much more robust with Firstname, Lastname, etc.  We would have to change a lot of code if these weren't members of the user.

We'd like to catch this event and swap out the user in Startup.cs

private Task OnSecurityTokenValidated(SecurityTokenValidatedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
{
    var user = userManager.Users.First(u => u.Email == notification.AuthenticationTicket.Identity.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").Value);
    notification.OwinContext.Authentication.SignIn(user);

Except user we can't do that because

Cannot resolve method 'SignIn(EazeeApp.UI.Models.ApplicationUser)', candidates are:
void SignIn(Microsoft.Owin.Security.AuthenticationProperties, params System.Security.Claims.ClaimsIdentity[]) (in interface IAuthenticationManager)

This seems kinda gross, so I'm definitely up for some better, simpler solutions.  I tried just dumping all the claims from the User into the notification.AuthenticationTicket.Identity but that won't include fields we need (but otherwise worked quite well).


问:
Firebase SMS authentication is delayed or sometimes not received
ISSUE

Firebase SMS authentication is delayed or sometimes not received

QUESTION

I want to know what would be the cause of such issue.

Tried to receive authentication to available phones and we receive the authentication.

Not all of the users experience the issue, but only for some.

Specific location: Adelaide, Glenelg South Australia

Date encountered: December 08, 2022


问:
Sequelize call thorws error in JEST test, how to make sequelize call in jest?
I want to test a controller which adds a record in the database, but I notice that even a select query throws an error, however when I add the record through my program, it is saved in the database.
For example only this query does not return anything but an error.

```<code>const facility = await db.facility.findOne({
        where: { id: req.body.facility_id },
        raw: true,
      });
</code>```

why does this query does not work in jest test file?

how can I solve this?

what is the best way to it?

Body:
I want to test a controller which adds a record in the database, but I notice that even a select query throws an error, however when I add the record through my program, it is saved in the database.
For example only this query does not return anything but an error.

const facility = await db.facility.findOne({
        where: { id: req.body.facility_id },
        raw: true,
      });

why does this query does not work in jest test file?

how can I solve this?

what is the best way to it?


问:
Redirection In FastAPI to a particular endpoint of frontend
I am new to FastAPI and have a FastAPI backend running on port 8000 and a Nextjs frontend running on port 3000. In the backend I want to send a redirection response so that the frontend goes to http://localhost:3000/test, but when I send response as return RedirectResponse(url='/test'), the page goes to http://localhost:8000/test (backend port) instead of going to http://localhost:3000/test (frontend port). Do I have to write the full redirection with port number also as return RedirectResponse(url='http://localhost:3000/test')?


问:
Access object properties like array for properties that are objects themselves
I hope you are doing well!

So I have the following Object

```<code>const myObject = {
   firstName:'fname',
   lastName:'lname',
   role:{
     roleID:1,
     description:'Admin'
   },
   phone: '12345',
   email:'example@gmail.com'
}
</code>```

and I want to access the properties in this method

```<code>myObject['phone']
myObject['email']
</code>```

in Order to display them in a table whose order of columns can be changed.

So my Table Column Object looks like this

```<code>const TABLE_COLUMNS=[{Header:'Phone',accessor:'phone'},{Header:'Email',accessor:'email'},...]
</code>```

but when it comes to columns like name and role, name represents the concatenation of firstName and lastName, and role can only be accesses by myObject.role.description and not directly.

Is there any way I can access the Object Properties in the method I am using at the moment?

(A method I am contemplating to use is to add a function property in my column header object and have it display them like I want but I can't save a function in a mySQL database and my columns will most probably be saved there)

Body:
I hope you are doing well!

So I have the following Object

const myObject = {
   firstName:'fname',
   lastName:'lname',
   role:{
     roleID:1,
     description:'Admin'
   },
   phone: '12345',
   email:'example@gmail.com'
}

and I want to access the properties in this method

myObject['phone']
myObject['email']

in Order to display them in a table whose order of columns can be changed.

So my Table Column Object looks like this

const TABLE_COLUMNS=[{Header:'Phone',accessor:'phone'},{Header:'Email',accessor:'email'},...]

but when it comes to columns like name and role, name represents the concatenation of firstName and lastName, and role can only be accesses by myObject.role.description and not directly.

Is there any way I can access the Object Properties in the method I am using at the moment?

(A method I am contemplating to use is to add a function property in my column header object and have it display them like I want but I can't save a function in a mySQL database and my columns will most probably be saved there)


问:
How to navigate through a directory?
I am creating a website with a simple file manager whose task is simply to open folders and search for pdf files in them. I have a "dir" root folder, and it contains other folders and files that users will work with.
Let's say the folder "dir" contains the folder "books", and in it the folders "history", "physics", "math" and so on. I can easily go to the "history" folder, but from "history" to let's say "history for kids" I can't go (I understand, it's very easy to get confused, but I tell it like it is). I looked at how I navigate through the directory and saw the following

What I should have seen:

1.dir

2.dir/history

3.dir/history/history for kids

What I saw:

1.dir

2.dir/history

3.dir/history for kids

Here is my script:

```<code><?php
    $folder = 'dir';
    if (isset($_POST['btn-act'])) {
        $folder .= '/'.$_POST['btn-act'];
    }
    echo $folder;
    if (is_dir($folder)) {
        if ($dh = opendir($folder)) {
            while (($file = readdir($dh)) !== false) {
                if ($file !='.' && $file !='..') {
                    if (is_dir($folder.'/'.$file)) {
                        echo "<li><form method='post'><img src='img/folder.png' class='folder'> <input type='submit' name='btn-act' value='$file'></form></li>";
                    } else {
                        echo "<li> <img src='img/pdf.png' class='folder'> " . $file . " " . filesize($folder.'/'.$file) ."</li>";
                    }
                }
            }
        }
    }
?>
</code>```

Title: How to navigate through a directory?

Body:
I am creating a website with a simple file manager whose task is simply to open folders and search for pdf files in them. I have a "dir" root folder, and it contains other folders and files that users will work with.
Let's say the folder "dir" contains the folder "books", and in it the folders "history", "physics", "math" and so on. I can easily go to the "history" folder, but from "history" to let's say "history for kids" I can't go (I understand, it's very easy to get confused, but I tell it like it is). I looked at how I navigate through the directory and saw the following

What I should have seen:

1.dir

2.dir/history

3.dir/history/history for kids

What I saw:

1.dir

2.dir/history

3.dir/history for kids

Here is my script:

<?php
    $folder = 'dir';
    if (isset($_POST['btn-act'])) {
        $folder .= '/'.$_POST['btn-act'];
    }
    echo $folder;
    if (is_dir($folder)) {
        if ($dh = opendir($folder)) {
            while (($file = readdir($dh)) !== false) {
                if ($file !='.' && $file !='..') {
                    if (is_dir($folder.'/'.$file)) {
                        echo "
<form method='post'> <input type='submit' name='btn-act' value='$file'></form>
";
                    } else {
                        echo "
  " . $file . " " . filesize($folder.'/'.$file) ."
";
                    }
                }
            }
        }
    }
?>


问:
How to print paper automatically without opening print dialog after clicking on print button in the angular app by using pdf Make

->Please check the screenshots after clicking the print button, print dialog is opening in the new tab and ahowing print and cancel buttons

->But my requirement is whenever we click on print button in the application it should print from the printer without opening dialog

->How can i do it in angular PDF make library


问:
How can I use pytest to test all of .py files in a directory?
I tried using this but it's giving me module not found error :

```<code>import fnmatch, os, shutil

srcdir =r"C:\......\pipelinev_0.0.2\demov.0.0.2\source"

file_list = []
for root, dirs, files in os.walk(srcdir):
    for file in files:
        if file[-3:].lower() == '.py':
            file_list.append(os.path(file))

print(file_list)

for i in file_list:
    target = import(i.index)

    def test_index():
        assert target() == "Hello World"
</code>```

and i am getting "module object is not callable error"

Body:
I tried using this but it's giving me module not found error :

import fnmatch, os, shutil

srcdir =r"C:\......\pipelinev_0.0.2\demov.0.0.2\source"

file_list = []
for root, dirs, files in os.walk(srcdir):
    for file in files:
        if file[-3:].lower() == '.py':
            file_list.append(os.path(file))

print(file_list)

for i in file_list:
    target = import(i.index)

    def test_index():
        assert target() == "Hello World"

and i am getting "module object is not callable error"


问:
How to enable secure cookie to the application which is running using Load Balancer?
Our production environment configured in N number of pods with load balancer?

Our website is only accessible using VPN.

When we enable secure cookie in application level, it does not work as expected.

Need to enabled secure flag on the application which has been hosted in kubernetes(EKS) cluster and exposed through Loadbalancer -> Ingress -> service , we need to enable secure flag and how it can be configured, do we need to offload SSL on the app level or any other way that can configure?

Note:
SSL is enabled only in Load balancer. Internally(Instances) the request are http only.


问:
debug1: Authentications that can continue: publickey,password
I'm trying to connect my ubuntu server with ssh. The lines of code that are uncommented in my sshd_config are below:

```<code>Include /etc/ssh/sshd_config.d/*
AuthorizedKeysFile  .ssh/authorized_keys
PasswordAuthentication yes
</code>```

My operating system is Mac and I've activated the remote login and remote management options in settings.
when I want to connect server with ssh -p 22 root@IP I get the below error:

How can I solve this?

Body:
I'm trying to connect my ubuntu server with ssh. The lines of code that are uncommented in my sshd_config are below:

Include /etc/ssh/sshd_config.d/*
AuthorizedKeysFile  .ssh/authorized_keys
PasswordAuthentication yes

My operating system is Mac and I've activated the remote login and remote management options in settings.
when I want to connect server with ssh -p 22 root@IP I get the below error:

How can I solve this?


问:
How to check for DolbyDigtal (AC3) support on device?
I'm trying to understand: is there a way to check if Android device supports DolbyDigital (AC3).

I found a broadcast action ACTION_HDMI_AUDIO_PLUG that indicates wether HDMI connected or not. Also it sends an array of all the supported encodings via the value EXTRA_ENCODINGS. But, as I understand, those are the values that the TV supports, not the Android device itself.