问:
How to install OpenMP on Mac M1?
I am currently studying to become a computer engineer and I need to work with OpenMP. After some research, I'm still having trouble installing it (#include <omp.h> is still not recognized). I tried libomp and llvm (with Homebrew), but I must have made a mistake along the way. Has anyone been able to use OpenMP on mac M1?

答:
A simple approach is to use brew https://brew.sh/ to install GCC or LLVM (clang), and then use that compiler.
You need to tread carefully, though, since the MacOS environment includes X86 emulation which can be confusing.

https://cpufun.substack.com/p/setting-up-the-apple-m1-for-native might help, though it's now nearly a year old...

Title: How to install OpenMP on Mac M1?


来源: stackexchange

问:
ValueError: time data '02/03/2022' does not match format '%d/%m/%y '
How to return values only within a specific date range?

I am new to python

My code is:

```<code>for report_date in REPORT_DATE_TYPES:
    if report_date in result:
        date = result[report_date].split(' ')[0]
        date = datetime.strptime(date, '%d/%m/%y ')
</code>```

but I am getting an error:

```<code>raise ValueError("time data %r does not match format %r" %
ValueError: time data '02/03/2022' does not match format '%d/%m/%y '
</code>```

How to fix this?

答: To point out the year you need to use %Y and also there is an additional space at the end of the format you gave that it's not present in the date. Try with date = datetime.strptime(date, '%d/%m/%Y')

ContentLicense: CC BY-SA 4.0

Body:
How to return values only within a specific date range?

I am new to python

My code is:

for report_date in REPORT_DATE_TYPES:
    if report_date in result:
        date = result[report_date].split(' ')[0]
        date = datetime.strptime(date, '%d/%m/%y ')

but I am getting an error:

raise ValueError("time data %r does not match format %r" %
ValueError: time data '02/03/2022' does not match format '%d/%m/%y '

How to fix this?


问:
How to assign an action for UIImageView object in Swift
I'm trying to assign an UIImageView to an action when the user taps it.

I know how to create an action for a UIButton, but how could I mimic the same behavior of a UIButton, but using a UIImageView?

答:
```<code>@IBOutlet weak var imageView: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
//ViewController is your current view controller
let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.tappedMe))
    imageView.addGestureRecognizer(tap)
    imageView.isUserInteractionEnabled = true
}

// Need to ass objective-c annotation
@objc
func tappedMe() {
    print("Tapped on Image")
}
</code>```

ContentLicense: CC BY-SA 3.0


答:
The %y refers to just the last 2 digit of the year, not the whole year as you have in the example.

20/03/21 is in format '%d/%m/%y while
20/03/2021 is in format '%d/%m/%Y(note the capital Y) therefore you just need to update the code as following

```<code>for report_date in REPORT_DATE_TYPES:
   if report_date in result:
       date = result[report_date].split(' ')[0]
       date = datetime.strptime(date, '%d/%m/%Y ')
</code>```

You can find an useful table of each flag on this link

Title: ValueError: time data '02/03/2022' does not match format '%d/%m/%y '

Body:
The %y refers to just the last 2 digit of the year, not the whole year as you have in the example.

20/03/21 is in format '%d/%m/%y while
20/03/2021 is in format '%d/%m/%Y(note the capital Y) therefore you just need to update the code as following

for report_date in REPORT_DATE_TYPES:
   if report_date in result:
       date = result[report_date].split(' ')[0]
       date = datetime.strptime(date, '%d/%m/%Y ')

You can find an useful table of each flag on this link


问:
Why is node Sequelize givng me a circular reference error?
I created a model of my database using the "sequelize-auto" package.  It has worked great up until today.  For some reason this morning it started giving me this error: ERROR:  MCAIntranet.initModels is not a function which is accompanied by the warning (node:35036) Warning: Accessing non-existent property 'initModels' of module exports inside circular dependency

This same function call (dataqueries.getSitemap) worked fine yesterday with no changes being made to this code.  The import (MCAIntranet) for the model returns an empty JSON array for some reason.

Here is all the relevant code involved.
The controller, the sequelize query file, the initModel file and the table model in order:

```<code>const express = require('express');
const router = express.Router();
const Users = require('../components/Users');
const dataQuery = require('../components/dataQueries');

router.get('/', async (req, res, next) => {
    try {
        let user = await Users.getUserName(req);
        //get groups and sitemap data
        let groups = await Users.getUserRoles(user);

        // let sitemap = await dataQuery.loadFile('./data/sitemap.json', 'ascii');
       let sitemap=await dataQuery.getSitemap(); //ERROR OCCURS AT THIS LINE

        let ret = { 'userRoles': groups, 'siteMap': sitemap };
        res.send(JSON.stringify(ret));
    } catch (ex) {
        console.log("ERROR: ", ex.message);
    }
})

module.exports = router;
</code>```
```<code>let sql = require('mssql');
let fs = require('fs');
// let { Connection } = require('../ConfigData/database');
const MCAIntranet = require('../configData/models/mcaintranet/init-models')
const DB = require('../ConfigData/Connector');

const runQuery = async (query, database) => {
    try {

        let pool = await Connection(database);
        let results = await pool.request().query(query);
        // console.log("Query results: ", results.recordsets[0])
        return results.recordset;
    } catch (ex) {
        // console.log("dataQueries.js 17", ex);
        return "False! ", ex;
    } finally {
        sql.close();
    }
}

const bulkInsert = async (database, table) => {
    let pool = await Connection(database);
    let insert = await pool.request()
    await insert.bulk(table, (err, result) => {
        if (err) {
            console.log("ERROR: " + err)
        } else {
            console.log("SUCCESS", result);
        }
    });
}

const loadFile = async (filePath, type) => {
    let file = fs.readFileSync(filePath, type);
    return file;
}

const writeFile = async (filePath, data) => {
    return fs.writeFile(
        filePath,
        data,
        (res) => { console.log(res) },
        () => {/* Empty callback function*/ })
}

const getSitemap = async () => {
    const sequelize = DB.GetDB(DB.MCAIntranet);
    const propsDB = MCAIntranet.initModels(sequelize); //ERROR OCCURS AT THIS LINE

    //get all values contained for user
    let props = await propsDB.tblSitemap.findAll({
        attributes: ['JSON']
    },
        { raw: true, output: true })
    let sitemap = props[0].dataValues.JSON;
    return JSON.parse(sitemap);
}

const writeSitemap = async (sitemap) => {
    const sequelize = DB.GetDB(DB.MCAIntranet);
    const propsDB = MCAIntranet.initModels(sequelize);
    propsDB.tblSitemap.update(
        {
            JSON: JSON.stringify(sitemap)
        },
        { where: { id: 1 } }
    )
}

module.exports = {
    loadFile: loadFile,
    writeFile: writeFile,
    runQuery: runQuery,
    bulkInsert: bulkInsert,
    getSitemap: getSitemap,
    writeSitemap: writeSitemap,
}
</code>```
```<code>var DataTypes = require("sequelize").DataTypes;
var _tblAttendance = require("./tblAttendance");
var _tblCollectorCodes = require("./tblCollectorCodes");
var _tblCollectors = require("./tblCollectors");
var _tblContactsData = require("./tblContactsData");
var _tblEmployees = require("./tblEmployees");
var _tblExpectingData = require("./tblExpectingData");
var _tblIntranetMessage = require("./tblIntranetMessage");
var _tblLANSAAccess = require("./tblLANSAAccess");
var _tblLANSAHeadings = require("./tblLANSAHeadings");
var _tblLANSAReportHeadings = require("./tblLANSAReportHeadings");
var _tblLANSAReports = require("./tblLANSAReports");
var _tblMessageDisplay = require("./tblMessageDisplay");
var _tblPDFFiles = require("./tblPDFFiles");
var _tblPagesVisited = require("./tblPagesVisited");
var _tblPreAuth = require("./tblPreAuth");
var _tblPreAuthDebtorInfo = require("./tblPreAuthDebtorInfo");
var _tblPreAuthFlatFiles = require("./tblPreAuthFlatFiles");
var _tblRetailReports = require("./tblRetailReports");
var _tblRogersFiles = require("./tblRogersFiles");
var _tblRogersTemp1 = require("./tblRogersTemp1");
var _tblRogersWirelessPayfiles = require("./tblRogersWirelessPayfiles");
var _tblRoles = require("./tblRoles");
var _tblSMS = require("./tblSMS");
var _tblSMSSent = require("./tblSMSSent");
var _tblSMSSents = require("./tblSMSSents");
var _tblShawAccts = require("./tblShawAccts");
var _tblSickDays = require("./tblSickDays");
var _tblSiteLayout = require("./tblSiteLayout");
var _tblSiteLayoutDesks = require("./tblSiteLayoutDesks");
var _tblSiteLayoutSites = require("./tblSiteLayoutSites");
var _tblSitemap = require("./tblSitemap");
var _tblStatusAccts = require("./tblStatusAccts");
var _tblStatusUpdates = require("./tblStatusUpdates");
var _tblUDWin = require("./tblUDWin");
var _tblUserProperties = require("./tblUserProperties");
var _vwUserRoles = require("./vwUserRoles");
var _tblUserRoles = require("./tblUserRoles");
var _tblUsers = require("./tblUsers");
var _tblVacationMain = require("./tblVacationMain");
var _tblVacationRequests = require("./tblVacationRequests");
var _tblVacations = require("./tblVacations");
var _vwLoggedIn = require("./vwLoggedIn");

function initModels(sequelize) {
  var tblAttendance = _tblAttendance(sequelize, DataTypes);
  var tblCollectorCodes = _tblCollectorCodes(sequelize, DataTypes);
  var tblCollectors = _tblCollectors(sequelize, DataTypes);
  var tblContactsData = _tblContactsData(sequelize, DataTypes);
  var tblEmployees = _tblEmployees(sequelize, DataTypes);
  var tblExpectingData = _tblExpectingData(sequelize, DataTypes);
  var tblIntranetMessage = _tblIntranetMessage(sequelize, DataTypes);
  var tblLANSAAccess = _tblLANSAAccess(sequelize, DataTypes);
  var tblLANSAHeadings = _tblLANSAHeadings(sequelize, DataTypes);
  var tblLANSAReportHeadings = _tblLANSAReportHeadings(sequelize, DataTypes);
  var tblLANSAReports = _tblLANSAReports(sequelize, DataTypes);
  var tblMessageDisplay = _tblMessageDisplay(sequelize, DataTypes);
  var tblPDFFiles = _tblPDFFiles(sequelize, DataTypes);
  var tblPagesVisited = _tblPagesVisited(sequelize, DataTypes);
  var tblPreAuth = _tblPreAuth(sequelize, DataTypes);
  var tblPreAuthDebtorInfo = _tblPreAuthDebtorInfo(sequelize, DataTypes);
  var tblPreAuthFlatFiles = _tblPreAuthFlatFiles(sequelize, DataTypes);
  var tblRetailReports = _tblRetailReports(sequelize, DataTypes);
  var tblRogersFiles = _tblRogersFiles(sequelize, DataTypes);
  var tblRogersTemp1 = _tblRogersTemp1(sequelize, DataTypes);
  var tblRogersWirelessPayfiles = _tblRogersWirelessPayfiles(sequelize, DataTypes);
  var tblRoles = _tblRoles(sequelize, DataTypes);
  var tblSMS = _tblSMS(sequelize, DataTypes);
  var tblSMSSent = _tblSMSSent(sequelize, DataTypes);
  var tblSMSSents = _tblSMSSents(sequelize, DataTypes);
  var tblShawAccts = _tblShawAccts(sequelize, DataTypes);
  var tblSickDays = _tblSickDays(sequelize, DataTypes);
  var tblSiteLayout = _tblSiteLayout(sequelize, DataTypes);
  var tblSiteLayoutDesks = _tblSiteLayoutDesks(sequelize, DataTypes);
  var tblSiteLayoutSites = _tblSiteLayoutSites(sequelize, DataTypes);
  var tblSitemap = _tblSitemap(sequelize, DataTypes);  //ERROR OCCURS CALLING THIS TABLE
  var tblStatusAccts = _tblStatusAccts(sequelize, DataTypes);
  var tblStatusUpdates = _tblStatusUpdates(sequelize, DataTypes);
  var tblUDWin = _tblUDWin(sequelize, DataTypes);
  var tblUserProperties = _tblUserProperties(sequelize, DataTypes);
  var vwUserRoles = _vwUserRoles(sequelize, DataTypes);
  var tblUserRoles = _tblUserRoles(sequelize, DataTypes);
  var tblUsers = _tblUsers(sequelize, DataTypes);
  var tblVacationMain = _tblVacationMain(sequelize, DataTypes);
  var tblVacationRequests = _tblVacationRequests(sequelize, DataTypes);
  var tblVacations = _tblVacations(sequelize, DataTypes);
  var vwLoggedIn = _vwLoggedIn(sequelize, DataTypes);

  return {
    tblAttendance,
    tblCollectorCodes,
    tblCollectors,
    tblContactsData,
    tblEmployees,
    tblExpectingData,
    tblIntranetMessage,
    tblLANSAAccess,
    tblLANSAHeadings,
    tblLANSAReportHeadings,
    tblLANSAReports,
    tblMessageDisplay,
    tblPDFFiles,
    tblPagesVisited,
    tblPreAuth,
    tblPreAuthDebtorInfo,
    tblPreAuthFlatFiles,
    tblRetailReports,
    tblRogersFiles,
    tblRogersTemp1,
    tblRogersWirelessPayfiles,
    tblRoles,
    tblSMS,
    tblSMSSent,
    tblSMSSents,
    tblShawAccts,
    tblSickDays,
    tblSiteLayout,
    tblSiteLayoutDesks,
    tblSiteLayoutSites,
    tblSitemap,
    tblStatusAccts,
    tblStatusUpdates,
    tblUDWin,
    tblUserProperties,
    vwUserRoles,
    tblUserRoles,
    tblUsers,
    tblVacationMain,
    tblVacationRequests,
    tblVacations,
    vwLoggedIn,
  };
}
module.exports = initModels;
module.exports.initModels = initModels;
module.exports.default = initModels;

</code>```
```<code>const sequelize = require('sequelize');
module.exports = function (sequelize, DataTypes) {
  return sequelize.define('tblSitemap', {
    id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    JSON: {
      type: DataTypes.TEXT,
      allowNull: false
    }
  }, {
    sequelize,
    tableName: 'tblSitemap',
    schema: 'dbo',
    timestamps: false
  });
};
</code>```

As the sitemap is the first data called in the application, and contains reference data for all other components (lazy loading) I am unable to test other functions.

I am sure that I am missing something small but I can't spot it.

答:
It turns out that the issue was case sensitivity.  Node is case sensitive to path names even in a Windows environment.  Therefore in the second file listed, const MCAIntranet = require('../configData/models/mcaintranet/init-models') should instead have been const MCAIntranet = require('../ConfigData/models/mcaintranet/init-models')

Note the capitalization of "C" in "../ConfigData/...."
Such a small, almost unnoticeable thing causing so much grief.

Hope this helps someone out :)

Body:
I created a model of my database using the "sequelize-auto" package.  It has worked great up until today.  For some reason this morning it started giving me this error: ERROR:  MCAIntranet.initModels is not a function which is accompanied by the warning (node:35036) Warning: Accessing non-existent property 'initModels' of module exports inside circular dependency

This same function call (dataqueries.getSitemap) worked fine yesterday with no changes being made to this code.  The import (MCAIntranet) for the model returns an empty JSON array for some reason.

Here is all the relevant code involved.
The controller, the sequelize query file, the initModel file and the table model in order:

const express = require('express');
const router = express.Router();
const Users = require('../components/Users');
const dataQuery = require('../components/dataQueries');

router.get('/', async (req, res, next) => {
    try {
        let user = await Users.getUserName(req);
        //get groups and sitemap data
        let groups = await Users.getUserRoles(user);

        // let sitemap = await dataQuery.loadFile('./data/sitemap.json', 'ascii');
       let sitemap=await dataQuery.getSitemap(); //ERROR OCCURS AT THIS LINE

        let ret = { 'userRoles': groups, 'siteMap': sitemap };
        res.send(JSON.stringify(ret));
    } catch (ex) {
        console.log("ERROR: ", ex.message);
    }
})

module.exports = router;

let sql = require('mssql');
let fs = require('fs');
// let { Connection } = require('../ConfigData/database');
const MCAIntranet = require('../configData/models/mcaintranet/init-models')
const DB = require('../ConfigData/Connector');

const runQuery = async (query, database) => {
    try {

        let pool = await Connection(database);
        let results = await pool.request().query(query);
        // console.log("Query results: ", results.recordsets[0])
        return results.recordset;
    } catch (ex) {
        // console.log("dataQueries.js 17", ex);
        return "False! ", ex;
    } finally {
        sql.close();
    }
}

const bulkInsert = async (database, table) => {
    let pool = await Connection(database);
    let insert = await pool.request()
    await insert.bulk(table, (err, result) => {
        if (err) {
            console.log("ERROR: " + err)
        } else {
            console.log("SUCCESS", result);
        }
    });
}

const loadFile = async (filePath, type) => {
    let file = fs.readFileSync(filePath, type);
    return file;
}

const writeFile = async (filePath, data) => {
    return fs.writeFile(
        filePath,
        data,
        (res) => { console.log(res) },
        () => {/* Empty callback function*/ })
}

const getSitemap = async () => {
    const sequelize = DB.GetDB(DB.MCAIntranet);
    const propsDB = MCAIntranet.initModels(sequelize); //ERROR OCCURS AT THIS LINE

    //get all values contained for user
    let props = await propsDB.tblSitemap.findAll({
        attributes: ['JSON']
    },
        { raw: true, output: true })
    let sitemap = props[0].dataValues.JSON;
    return JSON.parse(sitemap);
}

const writeSitemap = async (sitemap) => {
    const sequelize = DB.GetDB(DB.MCAIntranet);
    const propsDB = MCAIntranet.initModels(sequelize);
    propsDB.tblSitemap.update(
        {
            JSON: JSON.stringify(sitemap)
        },
        { where: { id: 1 } }
    )
}

module.exports = {
    loadFile: loadFile,
    writeFile: writeFile,
    runQuery: runQuery,
    bulkInsert: bulkInsert,
    getSitemap: getSitemap,
    writeSitemap: writeSitemap,
}

var DataTypes = require("sequelize").DataTypes;
var _tblAttendance = require("./tblAttendance");
var _tblCollectorCodes = require("./tblCollectorCodes");
var _tblCollectors = require("./tblCollectors");
var _tblContactsData = require("./tblContactsData");
var _tblEmployees = require("./tblEmployees");
var _tblExpectingData = require("./tblExpectingData");
var _tblIntranetMessage = require("./tblIntranetMessage");
var _tblLANSAAccess = require("./tblLANSAAccess");
var _tblLANSAHeadings = require("./tblLANSAHeadings");
var _tblLANSAReportHeadings = require("./tblLANSAReportHeadings");
var _tblLANSAReports = require("./tblLANSAReports");
var _tblMessageDisplay = require("./tblMessageDisplay");
var _tblPDFFiles = require("./tblPDFFiles");
var _tblPagesVisited = require("./tblPagesVisited");
var _tblPreAuth = require("./tblPreAuth");
var _tblPreAuthDebtorInfo = require("./tblPreAuthDebtorInfo");
var _tblPreAuthFlatFiles = require("./tblPreAuthFlatFiles");
var _tblRetailReports = require("./tblRetailReports");
var _tblRogersFiles = require("./tblRogersFiles");
var _tblRogersTemp1 = require("./tblRogersTemp1");
var _tblRogersWirelessPayfiles = require("./tblRogersWirelessPayfiles");
var _tblRoles = require("./tblRoles");
var _tblSMS = require("./tblSMS");
var _tblSMSSent = require("./tblSMSSent");
var _tblSMSSents = require("./tblSMSSents");
var _tblShawAccts = require("./tblShawAccts");
var _tblSickDays = require("./tblSickDays");
var _tblSiteLayout = require("./tblSiteLayout");
var _tblSiteLayoutDesks = require("./tblSiteLayoutDesks");
var _tblSiteLayoutSites = require("./tblSiteLayoutSites");
var _tblSitemap = require("./tblSitemap");
var _tblStatusAccts = require("./tblStatusAccts");
var _tblStatusUpdates = require("./tblStatusUpdates");
var _tblUDWin = require("./tblUDWin");
var _tblUserProperties = require("./tblUserProperties");
var _vwUserRoles = require("./vwUserRoles");
var _tblUserRoles = require("./tblUserRoles");
var _tblUsers = require("./tblUsers");
var _tblVacationMain = require("./tblVacationMain");
var _tblVacationRequests = require("./tblVacationRequests");
var _tblVacations = require("./tblVacations");
var _vwLoggedIn = require("./vwLoggedIn");

function initModels(sequelize) {
  var tblAttendance = _tblAttendance(sequelize, DataTypes);
  var tblCollectorCodes = _tblCollectorCodes(sequelize, DataTypes);
  var tblCollectors = _tblCollectors(sequelize, DataTypes);
  var tblContactsData = _tblContactsData(sequelize, DataTypes);
  var tblEmployees = _tblEmployees(sequelize, DataTypes);
  var tblExpectingData = _tblExpectingData(sequelize, DataTypes);
  var tblIntranetMessage = _tblIntranetMessage(sequelize, DataTypes);
  var tblLANSAAccess = _tblLANSAAccess(sequelize, DataTypes);
  var tblLANSAHeadings = _tblLANSAHeadings(sequelize, DataTypes);
  var tblLANSAReportHeadings = _tblLANSAReportHeadings(sequelize, DataTypes);
  var tblLANSAReports = _tblLANSAReports(sequelize, DataTypes);
  var tblMessageDisplay = _tblMessageDisplay(sequelize, DataTypes);
  var tblPDFFiles = _tblPDFFiles(sequelize, DataTypes);
  var tblPagesVisited = _tblPagesVisited(sequelize, DataTypes);
  var tblPreAuth = _tblPreAuth(sequelize, DataTypes);
  var tblPreAuthDebtorInfo = _tblPreAuthDebtorInfo(sequelize, DataTypes);
  var tblPreAuthFlatFiles = _tblPreAuthFlatFiles(sequelize, DataTypes);
  var tblRetailReports = _tblRetailReports(sequelize, DataTypes);
  var tblRogersFiles = _tblRogersFiles(sequelize, DataTypes);
  var tblRogersTemp1 = _tblRogersTemp1(sequelize, DataTypes);
  var tblRogersWirelessPayfiles = _tblRogersWirelessPayfiles(sequelize, DataTypes);
  var tblRoles = _tblRoles(sequelize, DataTypes);
  var tblSMS = _tblSMS(sequelize, DataTypes);
  var tblSMSSent = _tblSMSSent(sequelize, DataTypes);
  var tblSMSSents = _tblSMSSents(sequelize, DataTypes);
  var tblShawAccts = _tblShawAccts(sequelize, DataTypes);
  var tblSickDays = _tblSickDays(sequelize, DataTypes);
  var tblSiteLayout = _tblSiteLayout(sequelize, DataTypes);
  var tblSiteLayoutDesks = _tblSiteLayoutDesks(sequelize, DataTypes);
  var tblSiteLayoutSites = _tblSiteLayoutSites(sequelize, DataTypes);
  var tblSitemap = _tblSitemap(sequelize, DataTypes);  //ERROR OCCURS CALLING THIS TABLE
  var tblStatusAccts = _tblStatusAccts(sequelize, DataTypes);
  var tblStatusUpdates = _tblStatusUpdates(sequelize, DataTypes);
  var tblUDWin = _tblUDWin(sequelize, DataTypes);
  var tblUserProperties = _tblUserProperties(sequelize, DataTypes);
  var vwUserRoles = _vwUserRoles(sequelize, DataTypes);
  var tblUserRoles = _tblUserRoles(sequelize, DataTypes);
  var tblUsers = _tblUsers(sequelize, DataTypes);
  var tblVacationMain = _tblVacationMain(sequelize, DataTypes);
  var tblVacationRequests = _tblVacationRequests(sequelize, DataTypes);
  var tblVacations = _tblVacations(sequelize, DataTypes);
  var vwLoggedIn = _vwLoggedIn(sequelize, DataTypes);

  return {
    tblAttendance,
    tblCollectorCodes,
    tblCollectors,
    tblContactsData,
    tblEmployees,
    tblExpectingData,
    tblIntranetMessage,
    tblLANSAAccess,
    tblLANSAHeadings,
    tblLANSAReportHeadings,
    tblLANSAReports,
    tblMessageDisplay,
    tblPDFFiles,
    tblPagesVisited,
    tblPreAuth,
    tblPreAuthDebtorInfo,
    tblPreAuthFlatFiles,
    tblRetailReports,
    tblRogersFiles,
    tblRogersTemp1,
    tblRogersWirelessPayfiles,
    tblRoles,
    tblSMS,
    tblSMSSent,
    tblSMSSents,
    tblShawAccts,
    tblSickDays,
    tblSiteLayout,
    tblSiteLayoutDesks,
    tblSiteLayoutSites,
    tblSitemap,
    tblStatusAccts,
    tblStatusUpdates,
    tblUDWin,
    tblUserProperties,
    vwUserRoles,
    tblUserRoles,
    tblUsers,
    tblVacationMain,
    tblVacationRequests,
    tblVacations,
    vwLoggedIn,
  };
}
module.exports = initModels;
module.exports.initModels = initModels;
module.exports.default = initModels;

const sequelize = require('sequelize');
module.exports = function (sequelize, DataTypes) {
  return sequelize.define('tblSitemap', {
    id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    JSON: {
      type: DataTypes.TEXT,
      allowNull: false
    }
  }, {
    sequelize,
    tableName: 'tblSitemap',
    schema: 'dbo',
    timestamps: false
  });
};

As the sitemap is the first data called in the application, and contains reference data for all other components (lazy loading) I am unable to test other functions.

I am sure that I am missing something small but I can't spot it.


问:
Vue-i18n do not have default export
all! This is the first time I apply vue-i18n in my typeScript + Vue project. As the official site guided, I install it by using yarn install vue-i18n, then I want import it in main.ts via import VueI18n from 'vue-i18n', and it shows error below. Why this would happen and how could I fix it? Thanks in advance.

```<code>Module
'"/Users/scott/Desktop/Pando/uikit-main/node_modules/vue-i18n/dist/vue-i18n"'
has no default export.
Did you mean to use 'import { VueI18n } from "/Users/scott/Desktop/Pando/uikit-main/node_modules/vue-i18n/dist/vue-i18n"' instead?ts(2613)

</code>```

My vue-i18n version is "vue-i18n": "^9.1.9". If I import vue-i18n as suggested, then if I continue to type Vue.use(VueI18n), it will generate another error.

'VueI18n' only refers to a type, but is being used as a value here.ts(2693)

I think this is because vue-i18n only export some interface.

```<code>(alias) interface VueI18n<Messages = {}, DateTimeFormats = {}, NumberFormats = {}>
import VueI18n
</code>```

And backtrack the key word VueI18n in the import, I found it doesn't have any default export.

答:
Have you tried to copy the route just like this (I use Vscode) and then paste it in the import part to guarantee there are no mistakes in the route?

Also you can try with this import import { VueI18n } from "/Users/scott/Desktop/Pando/uikit-main/node_modules/vue-i18n/dist/vue-i18n" instead VueI18n from 'vue-i18n'

Title: Vue-i18n do not have default export

Body:
all! This is the first time I apply vue-i18n in my typeScript + Vue project. As the official site guided, I install it by using yarn install vue-i18n, then I want import it in main.ts via import VueI18n from 'vue-i18n', and it shows error below. Why this would happen and how could I fix it? Thanks in advance.

Module
'"/Users/scott/Desktop/Pando/uikit-main/node_modules/vue-i18n/dist/vue-i18n"'
has no default export.
Did you mean to use 'import { VueI18n } from "/Users/scott/Desktop/Pando/uikit-main/node_modules/vue-i18n/dist/vue-i18n"' instead?ts(2613)

My vue-i18n version is "vue-i18n": "^9.1.9". If I import vue-i18n as suggested, then if I continue to type Vue.use(VueI18n), it will generate another error.

'VueI18n' only refers to a type, but is being used as a value here.ts(2693)

I think this is because vue-i18n only export some interface.

(alias) interface VueI18n<Messages = {}, DateTimeFormats = {}, NumberFormats = {}>
import VueI18n

And backtrack the key word VueI18n in the import, I found it doesn't have any default export.


问:
three.js PlaneGeometry and intersectObjects
In three.js, I create a plane:

```<code>var planGeom = new THREE.PlaneGeometry( 5,5,1,1 );
var planMat = new THREE.MeshBasicMaterial( {color: 0xffff00, side: THREE.DoubleSide} );
var plan = new THREE.Mesh( planGeom, planMat );
</code>```

Then I set the vertices coordinates :

for(var i=0;i<4;i++){
    planGeom .vertices[i].x =  myCoordsTab[i].x;
    planGeom .vertices[i].y =  myCoordsTab[i].y;
    planGeom .vertices[i].z =  myCoordsTab[i].z;
}
```
<p>And finally :</p>
<pre class="lang-js prettyprint-override"><code>scene.add( plan );
</code>```

The plane appears at the good position in the 3D scene but when I output its position :

console.log(plan.position.x+' '+plan.position.y+' '+plan.position.z);
```
<p>I get <code>(0,0,0)</code>.</p>
<p>Then, when I try to check if I click on that plane with :</p>
<pre class="lang-js prettyprint-override"><code>var vector = new THREE.Vector3( mousex, mousey, 0.5 );
projector = new THREE.Projector();
projector.unprojectVector( vector, camera );
var ray = new THREE.Ray( camera.position, vector.subSelf( camera.position ).normalize() );
var intersects = ray.intersectObjects( scene.children );
</code>```

it always returns that I clicked on the plane, wherever I clicked in the scene.
I have no problem to check the clicks with a SphereGeometry for example.

So how to check a click on a PlaneGeometry if it (apparently) always stays in (0,0,0), which makes that all clicks are considered to be on the plane?

I use three.js 53, a very old version I know, but I work on a big project I started long time ago and there are too much things to change with the last version, so I hope that problem can be solved in version 53.

EDIT :

Using

plan.geometry.verticesNeedUpdate = true;
plan.geometry.computeCentroids();
```
<p>I have now something which works but not in all cases.
I have :</p>
<pre class="lang-js prettyprint-override"><code>camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 1000 );
</code>```

If I define the vertices of my PlaneGeometry like that :

planGeom .vertices[0].x =  50;
planGeom .vertices[0].y =  20;
planGeom .vertices[0].z =  -20;

planGeom .vertices[1].x =  50;
planGeom .vertices[1].y =  20;
planGeom .vertices[1].z =  20;

planGeom .vertices[2].x =  50;
planGeom .vertices[2].y =  -20;
planGeom .vertices[2].z =  -20;

planGeom .vertices[3].x =  50;
planGeom .vertices[3].y =  -20;
planGeom .vertices[3].z =  20;
```
<p>the plane is in front of the camera (at distance 50, I can see the whole plane) and intersectObjects returns that I click on the plane wherever I click in the scene, and returns for each click :</p>
<pre class="lang-js prettyprint-override"><code>(intersects[0].point.x, intersects[0].point.y, intersects[0].point.z) = (0, 0, 0)
</code>```

But if I define it like :

planGeom .vertices[0].x =  -20;
planGeom .vertices[0].y =  20;
planGeom .vertices[0].z =  -50;

planGeom .vertices[1].x =  20;
planGeom .vertices[1].y =  20;
planGeom .vertices[1].z =  -50;

planGeom .vertices[2].x =  -20;
planGeom .vertices[2].y =  -20;
planGeom .vertices[2].z =  -50;

planGeom .vertices[3].x =  20;
planGeom .vertices[3].y =  -20;
planGeom .vertices[3].z =  -50;
```
<p>the plane is on the left of the camera and intersectObjects returns exactly the coordinates of the 3D point I click on and only when I click on the plane; one click on each corner returns the coordinates of the corresponding vertex. For example :</p>
<pre class="lang-js prettyprint-override"><code>(intersects[0].point.x, intersects[0].point.y, intersects[0].point.z) = (planGeom .vertices[0].x, planGeom .vertices[0].y, planGeom .vertices[0].z)
</code>```

A click in the center of the plane gives :

(intersects[0].point.x, intersects[0].point.y, intersects[0].point.z) = (0, 0, -50)
```
<p>So now, I wonder why it doesn't work in all cases? I will do a simple example, which will be more simple than all those explanations :).</p>
<p><strong>EDIT</strong></p>
<p>Here is an example : the plane you see first, in front of the camera, returns an intersection for every click in the scene. The second plane, on the left (drag the scene to rotate), returns a good intersection point.
http://jsfiddle.net/9ggk00so/1/</p>
<p><strong>EDIT</strong></p>
<p>Working code : http://jsfiddle.net/9ggk00so/3/</p>
<p>Indeed, one instruction was missing :</p>
<pre class="lang-js prettyprint-override"><code>plan.geometry.verticesNeedUpdate = true;
plan.geometry.computeFaceNormals();//ok with that one
plan.geometry.computeCentroids();
</code>```

答: I don't think the subself and the intersectobject are the same version of three I would look to see if they deprecated for the version of three you have</p>

Body:
In three.js, I create a plane:

var planGeom = new THREE.PlaneGeometry( 5,5,1,1 );
var planMat = new THREE.MeshBasicMaterial( {color: 0xffff00, side: THREE.DoubleSide} );
var plan = new THREE.Mesh( planGeom, planMat );

Then I set the vertices coordinates :

for(var i=0;i<4;i++){
    planGeom .vertices[i].x =  myCoordsTab[i].x;
    planGeom .vertices[i].y =  myCoordsTab[i].y;
    planGeom .vertices[i].z =  myCoordsTab[i].z;
}

And finally :

scene.add( plan );

The plane appears at the good position in the 3D scene but when I output its position :

console.log(plan.position.x+' '+plan.position.y+' '+plan.position.z);

I get (0,0,0).

Then, when I try to check if I click on that plane with :

var vector = new THREE.Vector3( mousex, mousey, 0.5 );
projector = new THREE.Projector();
projector.unprojectVector( vector, camera );
var ray = new THREE.Ray( camera.position, vector.subSelf( camera.position ).normalize() );
var intersects = ray.intersectObjects( scene.children );

it always returns that I clicked on the plane, wherever I clicked in the scene.
I have no problem to check the clicks with a SphereGeometry for example.

So how to check a click on a PlaneGeometry if it (apparently) always stays in (0,0,0), which makes that all clicks are considered to be on the plane?

I use three.js 53, a very old version I know, but I work on a big project I started long time ago and there are too much things to change with the last version, so I hope that problem can be solved in version 53.

EDIT :

Using

plan.geometry.verticesNeedUpdate = true;
plan.geometry.computeCentroids();

I have now something which works but not in all cases.
I have :

camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 1000 );

If I define the vertices of my PlaneGeometry like that :

planGeom .vertices[0].x =  50;
planGeom .vertices[0].y =  20;
planGeom .vertices[0].z =  -20;

planGeom .vertices[1].x =  50;
planGeom .vertices[1].y =  20;
planGeom .vertices[1].z =  20;

planGeom .vertices[2].x =  50;
planGeom .vertices[2].y =  -20;
planGeom .vertices[2].z =  -20;

planGeom .vertices[3].x =  50;
planGeom .vertices[3].y =  -20;
planGeom .vertices[3].z =  20;

the plane is in front of the camera (at distance 50, I can see the whole plane) and intersectObjects returns that I click on the plane wherever I click in the scene, and returns for each click :

(intersects[0].point.x, intersects[0].point.y, intersects[0].point.z) = (0, 0, 0)

But if I define it like :

planGeom .vertices[0].x =  -20;
planGeom .vertices[0].y =  20;
planGeom .vertices[0].z =  -50;

planGeom .vertices[1].x =  20;
planGeom .vertices[1].y =  20;
planGeom .vertices[1].z =  -50;

planGeom .vertices[2].x =  -20;
planGeom .vertices[2].y =  -20;
planGeom .vertices[2].z =  -50;

planGeom .vertices[3].x =  20;
planGeom .vertices[3].y =  -20;
planGeom .vertices[3].z =  -50;

the plane is on the left of the camera and intersectObjects returns exactly the coordinates of the 3D point I click on and only when I click on the plane; one click on each corner returns the coordinates of the corresponding vertex. For example :

(intersects[0].point.x, intersects[0].point.y, intersects[0].point.z) = (planGeom .vertices[0].x, planGeom .vertices[0].y, planGeom .vertices[0].z)

A click in the center of the plane gives :

(intersects[0].point.x, intersects[0].point.y, intersects[0].point.z) = (0, 0, -50)

So now, I wonder why it doesn't work in all cases? I will do a simple example, which will be more simple than all those explanations :).

EDIT

Here is an example : the plane you see first, in front of the camera, returns an intersection for every click in the scene. The second plane, on the left (drag the scene to rotate), returns a good intersection point.
http://jsfiddle.net/9ggk00so/1/

EDIT

Working code : http://jsfiddle.net/9ggk00so/3/

Indeed, one instruction was missing :

plan.geometry.verticesNeedUpdate = true;
plan.geometry.computeFaceNormals();//ok with that one
plan.geometry.computeCentroids();


问:
How to increase font size in the Xcode editor?
To increase font-size in Xcode is a pain.</p>

答:
It is Aug 2011, Xcode 4.1 and it continues to be nightmare.  Why not allow Cmd+ and Cmd- like everywhere else.
< end rant >

As suggested by other respondents I suggest that you copy your preferred theme before you tweak the fonts for there is no ease way to undo.

In my case, all I wanted to do was increase the font size.  Mercifully you can select multiple items (Shift+select or Cmd+select) and set the font for all the ones selected in one fell swoop.

Minor relief for a major irritation.


问:
How can I create external tables with Hive?
This is the script I run on Hive:

```<code>CREATE EXTERNAL TABLE 'people'(
    'name' string,
    'surname' string,
    'age' string)
ROW FORMAT SERDE
    'org.apache.hadoop.hive.serde2.avro.AvroSerDe'
STORED AS INPUTFORMAT
    'org.apache.hadoop.hive.ql.io.avro.AvroContainerInputFormat'
OUTPUTFORMAT
    'org.apache.hadoop.hive.ql.io.avro.AvroContainerOutputFormat'
LOCATION
    'gs://directory/subdirectory/'
TBLPROPERTIES (
    'avro.schema.url'='gs://directory/schema.avsc',
    'transient_lastDdlTime'='1644235388');
</code>```

I get this error:
Error while compiling statement:

FAILED: ParseException line 1:22 cannot recognize input near ''people'' '(' ''nam'' in table name

答:
could you pls enclose them with backtick( `)</p>
```<code>CREATE EXTERNAL TABLE `people`(
    `name` string,
    `surname` string,
    `age` string)
...
</code>```

Body:
This is the script I run on Hive:

CREATE EXTERNAL TABLE 'people'(
    'name' string,
    'surname' string,
    'age' string)
ROW FORMAT SERDE
    'org.apache.hadoop.hive.serde2.avro.AvroSerDe'
STORED AS INPUTFORMAT
    'org.apache.hadoop.hive.ql.io.avro.AvroContainerInputFormat'
OUTPUTFORMAT
    'org.apache.hadoop.hive.ql.io.avro.AvroContainerOutputFormat'
LOCATION
    'gs://directory/subdirectory/'
TBLPROPERTIES (
    'avro.schema.url'='gs://directory/schema.avsc',
    'transient_lastDdlTime'='1644235388');

I get this error:
Error while compiling statement:

FAILED: ParseException line 1:22 cannot recognize input near ''people'' '(' ''nam'' in table name

Body:
could you pls enclose them with backtick( `)

CREATE EXTERNAL TABLE `people`(
    `name` string,
    `surname` string,
    `age` string)
...


问:
Underscore as a JavaScript variable?
In this post, Nick Craver provided an answer in which he used:

```<code>function(_, id)
</code>```

This code doesn't declare the underscore as a variable before using it. My search on google and on here only points to references to the use of the underscore as a prefix., not as the variable itself. What does it do? I like the solution by Nick but that bit bothers me.

答:
I saw this pattern in some legacy code (that was breaking on _ not being defined) and it turned out it was supposed to use this library:

https://underscorejs.org/

Title: Underscore as a JavaScript variable?

Body:
In this post, Nick Craver provided an answer in which he used:

function(_, id)

This code doesn't declare the underscore as a variable before using it. My search on google and on here only points to references to the use of the underscore as a prefix., not as the variable itself. What does it do? I like the solution by Nick but that bit bothers me.


问:
Bash and IFS: string split to an array with specific separator based on a complete word-term
With the following code:

```<code>string="[Git status]^functionGitStatus"
IFS='^' read -r -a array <<< "$string"
echo "${array[@]}"
echo "size: '${#array[@]}'"
for e in "${array[@]}"; do
   echo "'$e'"
done
</code>```

It works as expected and shows:

```<code>[Git status] functionGitStatus
size: '2'
'[Git status]'
'functionGitStatus'
</code>```

I did do a research and for example at

How to split a string into an array in Bash?

is possible use ,  (command with empty space)

If I try to accomplish the same approach:

```<code>string="[Git status]^ functionGitStatus"
IFS='^ ' read -r -a array <<< "$string"
echo "${array[@]}"
echo "size: '${#array[@]}'"
for e in "${array[@]}"; do
   echo "'$e'"
done
</code>```

I got:

```<code>[Git status] functionGitStatus
size: '3'
'[Git'
'status]'
'functionGitStatus'
</code>```

sadly not as expected (even when only exists one ocurrence with ^ )

I want to know if is possible to use a complete word-term as separator for example:

```<code>string="[Git status]-fn:-functionGitStatus"
IFS='-fn:-' read -r -a array <<< "$string"
echo "${array[@]}"
echo "size: '${#array[@]}'"
for e in "${array[@]}"; do
   echo "'$e'"
done
</code>```

But it shows:

```<code>[Git status]      u ctio GitStatus
size: '9'
'[Git status]'
''
''
''
''
''
'u'
'ctio'
'GitStatus'
</code>```

Seems is not possible or perhaps there is a special flag to interpret how complete word-term. If is not possible what other function would help in this scenario?

答:
With bash parameter expansion and mapfile:

$ string='[Git status]-fn:-functionGitStatus'
$ mapfile -t array <<< "${string//-fn:-/$'\n'}"
$ echo "${array[@]}"
[Git status] functionGitStatus
$ echo "size: '${#array[@]}'"
2
$ for e in "${array[@]}"; do echo "'$e'"; done
'[Git status]'
'functionGitStatus'
```

Explanation: "${string//-fn:-/$'\n'}" is a bash parameter expansion with substitution: all (because // instead of /) -fn:- substrings in string are replaced by $'\n', that is, a newline (the $'...' syntax is documented in the QUOTING section of bash manual). <<< is the here-string redirection operator. It "feeds" the mapfilecommand with the result of the parameter expansion with substitution. mapfile -t array (also documented in the bash manual) stores its input in the bash array named array, one line per cell, removing the trailing newline character (-t option).

Body:
With the following code:

string="[Git status]^functionGitStatus"
IFS='^' read -r -a array <<< "$string"
echo "${array[@]}"
echo "size: '${#array[@]}'"
for e in "${array[@]}"; do
   echo "'$e'"
done

It works as expected and shows:

[Git status] functionGitStatus
size: '2'
'[Git status]'
'functionGitStatus'

I did do a research and for example at

How to split a string into an array in Bash?

is possible use ,  (command with empty space)

If I try to accomplish the same approach:

string="[Git status]^ functionGitStatus"
IFS='^ ' read -r -a array <<< "$string"
echo "${array[@]}"
echo "size: '${#array[@]}'"
for e in "${array[@]}"; do
   echo "'$e'"
done

I got:

[Git status] functionGitStatus
size: '3'
'[Git'
'status]'
'functionGitStatus'

sadly not as expected (even when only exists one ocurrence with ^ )

I want to know if is possible to use a complete word-term as separator for example:

string="[Git status]-fn:-functionGitStatus"
IFS='-fn:-' read -r -a array <<< "$string"
echo "${array[@]}"
echo "size: '${#array[@]}'"
for e in "${array[@]}"; do
   echo "'$e'"
done

But it shows:

[Git status]      u ctio GitStatus
size: '9'
'[Git status]'
''
''
''
''
''
'u'
'ctio'
'GitStatus'

Seems is not possible or perhaps there is a special flag to interpret how complete word-term. If is not possible what other function would help in this scenario?

Body:
With bash parameter expansion and mapfile:

$ string='[Git status]-fn:-functionGitStatus'
$ mapfile -t array <<< "${string//-fn:-/$'\n'}"
$ echo "${array[@]}"
[Git status] functionGitStatus
$ echo "size: '${#array[@]}'"
2
$ for e in "${array[@]}"; do echo "'$e'"; done
'[Git status]'
'functionGitStatus'

Explanation: "${string//-fn:-/$'\n'}" is a bash parameter expansion with substitution: all (because // instead of /) -fn:- substrings in string are replaced by $'\n', that is, a newline (the $'...' syntax is documented in the QUOTING section of bash manual). <<< is the here-string redirection operator. It "feeds" the mapfilecommand with the result of the parameter expansion with substitution. mapfile -t array (also documented in the bash manual) stores its input in the bash array named array, one line per cell, removing the trailing newline character (-t option).


问:
Send query params from Jinja template
I can't figure out if it's possible to pass query parameters from a static html page to a view for processing. I have now implemented the functionality I need using path parameters. I want to do the same, but with query parameters

main.py

```<code>from helpers.utils import CustomURLProcessor

app = FastAPI()

app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
templates.env.globals['CustomURLProcessor'] = CustomURLProcessor
</code>```

events.py

```<code>router = APIRouter()
templates = Jinja2Templates(directory="templates")

@router.post('/invite/{event_invite}/sender/{sender}')
async def decline_event_invite(
        request: Request,
        event_invite: int,
        sender: int,
):
    #logic
</code>```

routes.py

```<code>api_router.include_router(events.router, prefix="/event")
</code>```

html

```<code>{{ url_for('decline_event_invite',  event_invite=invite.id, sender=invite.sender) }}
</code>```

It's works with  "POST /event/invite/15/sender/3 HTTP/1.1" as a sample

Try with query params

```<code>@router.post('/invite')
async def decline_event_invite(
        request: Request,
        event_invite: Optional[str] = None,
        sender: Optional[str] = None,
):
    # logic
</code>```

And get

```<code>    raise NoMatchFound()
starlette.routing.NoMatchFound
</code>```

html template without any change

Can I pass query parameters from the template to the fastapi logic to processing this url /event/?event_invite=15&sender=3?

答:
This is Starlette's issue (i.e., url_for() receives path parameters, not query parameters). What you could do is to create a custom URL processor (as shown below) and use it to pass path and/or query parameters as well.

import urllib

class CustomURLProcessor:
    def __init__(self):
        self.path = ""
        self.request = None

    def url_for(self, request: Request, name: str, **params: str):
        self.path = request.url_for(name, **params)
        self.request = request
        return self

    def include_query_params(self, **params: str):
        parsed = list(urllib.parse.urlparse(self.path))
        parsed[4] = urllib.parse.urlencode(params)
        return urllib.parse.urlunparse(parsed)
```
<p>Remember to add the <code>CustomURLProcessor</code> class to the templates' global environment:</p>
```templates.env.globals['CustomURLProcessor'] = CustomURLProcessor
```
<p>Then, use in Jinja template, as below:</p>
```{{ CustomURLProcessor().url_for(request, 'decline_event_invite').include_query_params(event_invite=invite.id, sender=invite.sender) }}
```
<p>Please have a look at this answer for a complete working example. Also, this feature might be introduced into the next version of Starlette #1385. Thus, you may want to keep an eye on it.</p>
<h1>More options on how to make a class accessible from Jinja templates</h1>
<p>Alternative options to make <code>CustomURLProcessor</code> class accessible from Jinja templates, in case <code>templates.env.globals['CustomURLProcessor'] = CustomURLProcessor</code> didn't work for you, throwing the following error: <code>jinja2.exceptions.UndefinedError: 'CustomURLProcessor' is undefined</code>.</p>
<p><strong>Option 1</strong></p>
```templates.env.globals.update(CustomURLProcessor=CustomURLProcessor)
```
<p><strong>Option 2</strong></p>
```import helpers.utils
templates.env.globals['CustomURLProcessor'] = helpers.utils.CustomURLProcessor
# or, equivalently
templates.env.globals.update(CustomURLProcessor=helpers.utils.CustomURLProcessor)
```
<p>You could even add the whole module, and use in Jinja template like this <code>helpers.CustomURLProcessor().url_for(request...</code>.</p>
```import helpers.utils
templates.env.globals['helpers'] = helpers.utils
```
<p><strong>Option 3</strong></p>
<p>The last option would be to pass it as part of your <code>TemplateResponse</code>.</p>
```return templates.TemplateResponse("index.html",  {"request": request, "CustomURLProcessor": CustomURLProcessor})
```
<p>If none of the above worked, perhaps other options described here might help, or the problem likely lies elsewhere.</p>
<h1>Update - About including query params</h1>
<p>Regarding sending query parameters from a Jinja template, you can now use Starlette's <code>starlette.datastructures.URL</code>, which provides an <code>include_query_params</code> method.</p>
<p>To use, import the <code>URL</code> class and make it accessible from Jinja2 templates:</p>
<pre class="lang-py prettyprint-override"><code>from starlette.datastructures import URL

templates = Jinja2Templates(directory="templates")
templates.env.globals['URL'] = URL
</code>```

Then, use in Jinja template as shown below:

```<code>{{ URL(url_for('decline_event_invite')).include_query_params(event_invite=invite.id, sender=invite.sender) }}

</code>```

Title: Send query params from Jinja template

Body:
I can't figure out if it's possible to pass query parameters from a static html page to a view for processing. I have now implemented the functionality I need using path parameters. I want to do the same, but with query parameters

main.py

from helpers.utils import CustomURLProcessor

app = FastAPI()

app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
templates.env.globals['CustomURLProcessor'] = CustomURLProcessor

events.py

router = APIRouter()
templates = Jinja2Templates(directory="templates")

@router.post('/invite/{event_invite}/sender/{sender}')
async def decline_event_invite(
        request: Request,
        event_invite: int,
        sender: int,
):
    #logic

routes.py

api_router.include_router(events.router, prefix="/event")

html

{{ url_for('decline_event_invite',  event_invite=invite.id, sender=invite.sender) }}

It's works with  "POST /event/invite/15/sender/3 HTTP/1.1" as a sample

Try with query params

@router.post('/invite')
async def decline_event_invite(
        request: Request,
        event_invite: Optional[str] = None,
        sender: Optional[str] = None,
):
    # logic

And get

    raise NoMatchFound()
starlette.routing.NoMatchFound

html template without any change

Can I pass query parameters from the template to the fastapi logic to processing this url /event/?event_invite=15&sender=3?

Body:
This is Starlette's issue (i.e., url_for() receives path parameters, not query parameters). What you could do is to create a custom URL processor (as shown below) and use it to pass path and/or query parameters as well.

import urllib

class CustomURLProcessor:
    def __init__(self):
        self.path = ""
        self.request = None

    def url_for(self, request: Request, name: str, **params: str):
        self.path = request.url_for(name, **params)
        self.request = request
        return self

    def include_query_params(self, **params: str):
        parsed = list(urllib.parse.urlparse(self.path))
        parsed[4] = urllib.parse.urlencode(params)
        return urllib.parse.urlunparse(parsed)

Remember to add the CustomURLProcessor class to the templates' global environment:

templates.env.globals['CustomURLProcessor'] = CustomURLProcessor

Then, use in Jinja template, as below:

{{ CustomURLProcessor().url_for(request, 'decline_event_invite').include_query_params(event_invite=invite.id, sender=invite.sender) }}

Please have a look at this answer for a complete working example. Also, this feature might be introduced into the next version of Starlette #1385. Thus, you may want to keep an eye on it.

More options on how to make a class accessible from Jinja templates

Alternative options to make CustomURLProcessor class accessible from Jinja templates, in case templates.env.globals['CustomURLProcessor'] = CustomURLProcessor didn't work for you, throwing the following error: jinja2.exceptions.UndefinedError: 'CustomURLProcessor' is undefined.

Option 1

templates.env.globals.update(CustomURLProcessor=CustomURLProcessor)

Option 2

import helpers.utils
templates.env.globals['CustomURLProcessor'] = helpers.utils.CustomURLProcessor
# or, equivalently
templates.env.globals.update(CustomURLProcessor=helpers.utils.CustomURLProcessor)

You could even add the whole module, and use in Jinja template like this helpers.CustomURLProcessor().url_for(request....

import helpers.utils
templates.env.globals['helpers'] = helpers.utils

Option 3

The last option would be to pass it as part of your TemplateResponse.

return templates.TemplateResponse("index.html",  {"request": request, "CustomURLProcessor": CustomURLProcessor})

If none of the above worked, perhaps other options described here might help, or the problem likely lies elsewhere.

Update - About including query params

Regarding sending query parameters from a Jinja template, you can now use Starlette's starlette.datastructures.URL, which provides an include_query_params method.

To use, import the URL class and make it accessible from Jinja2 templates:

from starlette.datastructures import URL

templates = Jinja2Templates(directory="templates")
templates.env.globals['URL'] = URL

Then, use in Jinja template as shown below:

{{ URL(url_for('decline_event_invite')).include_query_params(event_invite=invite.id, sender=invite.sender) }}


问:
Convert to regular date, time and AM or PM
I am trying to convert a date that is returned to me with it in this format:

2022-02-09T14:43:32

I am trying to get it to look like this

2/9/2022 2:43PM

I tried this but it says it is not a valid format.

```<code>workRow["ShiftStart"] = DateTime.ParseExact(theTempsDataSet.Tables[0].Rows[i]["shiftStartTime"].ToString(), "dd/mm/yyyy hh:mmtt", CultureInfo.InvariantCulture).ToString();
</code>```

答:
try this

```<code>var dtStr="2022-02-09T14:43:32";
var dt=  DateTime.Parse(dtStr);
dtStr = dt.ToString("M/d/yyyy h:mmtt", CultureInfo.InvariantCulture);
</code>```

or who loves in one line

```<code>var dt=  DateTime.Parse("2022-02-09T14:43:32").ToString("M/d/yyyy h:mmtt", CultureInfo.CreateSpecificCulture("en-US"));
</code>```

Body:
I am trying to convert a date that is returned to me with it in this format:

2022-02-09T14:43:32

I am trying to get it to look like this

2/9/2022 2:43PM

I tried this but it says it is not a valid format.

workRow["ShiftStart"] = DateTime.ParseExact(theTempsDataSet.Tables[0].Rows[i]["shiftStartTime"].ToString(), "dd/mm/yyyy hh:mmtt", CultureInfo.InvariantCulture).ToString();

Body:
try this

var dtStr="2022-02-09T14:43:32";
var dt=  DateTime.Parse(dtStr);
dtStr = dt.ToString("M/d/yyyy h:mmtt", CultureInfo.InvariantCulture);

or who loves in one line

var dt=  DateTime.Parse("2022-02-09T14:43:32").ToString("M/d/yyyy h:mmtt", CultureInfo.CreateSpecificCulture("en-US"));


问:
Using Laravel 6.x eloquent (or similar method) to get row by JSON column data
I have the following Laravel 6.x collection output when I run first() on that particular Model from a table called workflow_conflicts. As you can see the conflicts column is a JSON column and has data stored in this manner below.

```<code>Models\WorkflowConflict {
     id: 2190,
     created_at: "2022-02-10 12:18:28",
     updated_at: "2022-02-10 12:22:36",
     action: "approved",
     conflicts: "[{"text": "validatorword 1218" "word": "validatorword", "indicies": {"end": 13, "start": 0}, "workflow_id": 4334}]",
     user: Models\User {
       id: 17843,
       suspended: 0,
     },
   }
</code>```

I am trying to figure out how would I use the Laravel Eloquent (I am using Tinker) how would I perform a search on the conflicts json values such as the values from text and word.

For instance - the following below would return the object fine in Tinker, but I am unsure how to perform a similar search on the conflicts row which is JSON data.

```<code>WorkflowConflict::where('action', 'approved')->first();
</code>```

-- Expected result from within Tinker --

```<code>WorkflowConflict::where('conflicts->text', 'validatorword 1218')->first();
=> Models\WorkflowConflict {
     id: 2190,
     created_at: "2022-02-10 12:18:28",
     updated_at: "2022-02-10 12:22:36",
     action: "approved",
     conflicts: "[{"text": "validatorword 1218" "word": "validatorword", "indicies": {"end": 13, "start": 0}, "workflow_id": 4334}]",
     user: Models\User {
       id: 17843,
       suspended: 0,
     },
   }
</code>```

-- Actual result from within Tinker --

```<code>WorkflowConflict::where('conflicts->text', 'validatorword 1218')->first();
=> null
</code>```

TLDR - trying to search using the JSON column values in Laravel

答:
Since your data is wrapped by an array, you could use a whereRaw:

WorkflowConflict::whereRaw('json_contains(conflicts, json_object("text", "validatorword 1218"))')->first();
```

Body:
I have the following Laravel 6.x collection output when I run first() on that particular Model from a table called workflow_conflicts. As you can see the conflicts column is a JSON column and has data stored in this manner below.

Models\WorkflowConflict {
     id: 2190,
     created_at: "2022-02-10 12:18:28",
     updated_at: "2022-02-10 12:22:36",
     action: "approved",
     conflicts: "[{"text": "validatorword 1218" "word": "validatorword", "indicies": {"end": 13, "start": 0}, "workflow_id": 4334}]",
     user: Models\User {
       id: 17843,
       suspended: 0,
     },
   }

I am trying to figure out how would I use the Laravel Eloquent (I am using Tinker) how would I perform a search on the conflicts json values such as the values from text and word.

For instance - the following below would return the object fine in Tinker, but I am unsure how to perform a similar search on the conflicts row which is JSON data.

WorkflowConflict::where('action', 'approved')->first();

-- Expected result from within Tinker --

WorkflowConflict::where('conflicts->text', 'validatorword 1218')->first();
=> Models\WorkflowConflict {
     id: 2190,
     created_at: "2022-02-10 12:18:28",
     updated_at: "2022-02-10 12:22:36",
     action: "approved",
     conflicts: "[{"text": "validatorword 1218" "word": "validatorword", "indicies": {"end": 13, "start": 0}, "workflow_id": 4334}]",
     user: Models\User {
       id: 17843,
       suspended: 0,
     },
   }

-- Actual result from within Tinker --

WorkflowConflict::where('conflicts->text', 'validatorword 1218')->first();
=> null

TLDR - trying to search using the JSON column values in Laravel


答:
You could do it this way:</p>
```<code>DELETE
FROM users
WHERE
   id between 754 and 759
OR id between 765 and 799
</code>```

Title: Delete ranges of id's

Body:
I have this huge SQL query which I would like to reduce:

DELETE
FROM users
WHERE id in (754, 755, 756, 757, 758, 759, 795, 796, 797, 798, 799, 765,
766, 767, 768, 769, 770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794);

I tried:

DELETE
FROM users
WHERE id => 754 AND id <= 759
AND id => 795 AND id <= 799
AND id => 765 AND id <= 794;

But I get error:

ERROR: syntax error at or near "=>"
Position: 42

Do you know how I can fix this issue?

Body:
You could do it this way:

DELETE
FROM users
WHERE
   id between 754 and 759
OR id between 765 and 799


问:
Any particular reason why this switch-case statement in js is returning undefined?
Here is my code. I have cross checked with online docs and couldn't find any reason for this to not work.

let marks = 90;
switch (marks) {
  case 1:
    if (marks <= 100 && marks >= 80) {
      console.log("Very Good");
    }
    break;
  case 2:
    if (marks >= 60 && marks <= 79) {
      console.log("Good");
    }
    break;
  case 3:
    if (marks >= 30 && marks <= 59) {
      console.log("Can do better");
    }
    break;
  case 4:
    if (marks < 30) {
      console.log("Fail");
    }
    break;
}```

答:
```<code>let marks = 90;
switch (marks<=100) {
 case marks <= 100 && marks>=80:
    console.log("Very Good");
    break
 case ( marks >=60 && marks <= 79) :
    console.log("Good")
    break;
 case (marks >= 30 && marks <=59):
    console.log("Can do better");
    break;
  case (marks < 30) :
    console.log("Fail");
    break;
  }
</code>```

This should work your switch cases don't make sense

Body:
let marks = 90;
switch (marks<=100) {
 case marks <= 100 && marks>=80:
    console.log("Very Good");
    break
 case ( marks >=60 && marks <= 79) :
    console.log("Good")
    break;
 case (marks >= 30 && marks <=59):
    console.log("Can do better");
    break;
  case (marks < 30) :
    console.log("Fail");
    break;
  }

This should work your switch cases don't make sense


问:
SQL Server, subset a table and create new column based on condition
If I have a table in SQL as:

id
code

1
6

1
8

1
4

2
3

2
7

2
4

3
7

3
6

3
7

What I need to do, logically is:

Get the top row of each group when grouped by id, ordered by code

Create a new column to show if the code column contained a 7 anywhere, within the group

Desired result:

id
code
c7

1
4
N

2
3
Y

3
6
Y

I think it needs a "CASE WHEN" statement in the SELECT, but have not worked it out. What query can I execute to get this?

答:
There is probably a better way to do this, but what comes to mind is that first you have to partition the table to get the top one based on whatever that criteria is, then join back against itself to find the ones with the 7

declare @table1 table (id int not null, code int not null)

insert into @table1 (id, code)
values
(1,6),
(1,8),
(1,4),
(2,3),
(2,7),
(2,4),
(3,7),
(3,6),
(3,7)

select id, code, c7
from (
    select t.id ,t.code
        ,(CASE WHEN c.id is null then 'N' else 'Y' END) as c7
        ,ROW_NUMBER() OVER (PARTITION BY t.id order by t.code) AS p
    from @table1 t
        left outer join (
            select id, code, 'Y' as c7
            from @table1
            where code = 7) c on c.id = t.id
    ) sorted
where sorted.p = 1
```


问:
Java Reflection: Get a Field's Value where the Field is of an Interface Type
Say, there is a class (A) which has a field (myField). The type of the field myField is an interface (I). Everything is public.

I need to invoke a method of the class which is a type of the *myField *. My code is the following:

```<code> Field myField = getField(myClass, "fieldName");
 Class fieldClass = myField.getType(); // returns I

 try {
        Class[] params = {String.class};
        Method method = fieldClass.getMethod("methodName", params);

        Object[] paramsObj = {new String("input")};
        boolean result = (Boolean) method.invoke(WHAT_MUST_I_PUT_HERE, paramsObj);
} catch...
</code>```

As you can see the problem is I can't do thing like:

```<code>WHAT_MUST_I_PUT_HERE = myField.getClass() // returns Field
</code>```

Can somebody help me?

EDIT: I have tried to use

```<code>TargetClass o = (TargetClass) myField.get(myClass)
</code>```

but caught the IllegalArgumentException

答:
The first argument to the invoke method is simply the object on which to call the method.  So let's say you got a non-static method corresponding to I.m(String).  You need an instance of I to invoke it on (since this is a non-static method).

Presumably you want to call the equivalent of myField.m(input) via reflection, hence you simply pass in myField as the first argument:

```<code>boolean result = (Boolean) method.invoke(myField, paramsObj);
</code>```

Body:
Say, there is a class (A) which has a field (myField). The type of the field myField is an interface (I). Everything is public.

I need to invoke a method of the class which is a type of the *myField *. My code is the following:

 Field myField = getField(myClass, "fieldName");
 Class fieldClass = myField.getType(); // returns I

 try {
        Class[] params = {String.class};
        Method method = fieldClass.getMethod("methodName", params);

        Object[] paramsObj = {new String("input")};
        boolean result = (Boolean) method.invoke(WHAT_MUST_I_PUT_HERE, paramsObj);
} catch...

As you can see the problem is I can't do thing like:

WHAT_MUST_I_PUT_HERE = myField.getClass() // returns Field

Can somebody help me?

EDIT: I have tried to use

TargetClass o = (TargetClass) myField.get(myClass)

but caught the IllegalArgumentException

Body:
The first argument to the invoke method is simply the object on which to call the method.  So let's say you got a non-static method corresponding to I.m(String).  You need an instance of I to invoke it on (since this is a non-static method).

Presumably you want to call the equivalent of myField.m(input) via reflection, hence you simply pass in myField as the first argument:

boolean result = (Boolean) method.invoke(myField, paramsObj);


问:
Search for value contained in array of objects in property of object contained in array
can someone help me with this?
I need a function that given a fieldID, searchs within objects and returns the objectID that fieldID is in.

```<code>  const objects = [
    {
      objectID: 11,
      fields: [
        { id: 12, name: 'Source ID' },
        { id: 12, name: 'Source ID' },
      ],
    },
    {objectID: 14,
      fields: [
        { id: 15, name: 'Creator' },
      ],},
    {objectID: 16,
      fields: [
        { id: 17, name: 'Type' },
        { id: 18, name: 'Name' },
        { id: 19, name: 'Description' },
      ],},
  ];
</code>```

SOLVED:
Got it working like this:

```<code> const getObjectID = fieldId => {
    for (const object of objects) {
      if (object.fields.find(field => field.id === fieldId)) {
        return object.objectID;
      }
    }
  };
</code>```

答:
This will work:</p>
```<code>const getObjectId = (fieldID) => {
const object = objects.find(object => object.fields.find(field => field.id === fieldID )!== undefined)
if(object) return object.objectID;
return null
}
</code>```

Body:
can someone help me with this?
I need a function that given a fieldID, searchs within objects and returns the objectID that fieldID is in.

  const objects = [
    {
      objectID: 11,
      fields: [
        { id: 12, name: 'Source ID' },
        { id: 12, name: 'Source ID' },
      ],
    },
    {objectID: 14,
      fields: [
        { id: 15, name: 'Creator' },
      ],},
    {objectID: 16,
      fields: [
        { id: 17, name: 'Type' },
        { id: 18, name: 'Name' },
        { id: 19, name: 'Description' },
      ],},
  ];

SOLVED:
Got it working like this:

 const getObjectID = fieldId => {
    for (const object of objects) {
      if (object.fields.find(field => field.id === fieldId)) {
        return object.objectID;
      }
    }
  };

Body:
This will work:

const getObjectId = (fieldID) => {
const object = objects.find(object => object.fields.find(field => field.id === fieldID )!== undefined)
if(object) return object.objectID;
return null
}


问:
Assert ReactiveSecurityContextHolder.getContext() in the StepVerifier of my WebFilter Webflux
I am migrating our security library which is Servlet based.

I need to use ReactiveSecurityContextHolder.getContext() instead of SecurityContextHolder.getContext().

I have a WebFLux WebFilter that modifies the Authentication.

```<code>  @Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
...
   return chain.filter(exchange).subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication));

}
</code>```

I would like to assert the Authentication in ReactiveSecurityContextHolder.getContext().
StepVerifier.create(filter.filter(MockServerWebExchange.from(request), filterChain)).expectNext(...).verifyComplete();

No matter what I try, the context is null because I have to subscribe to the Mono returned by ReactiveSecurityContextHolder.getContext().

I tried ReactiveSecurityContextHolder.getContext().block() without success.

May be the way I try to test it is wrong.

答:
A way to do it is to use the WebFilterChain which is basically a lambda.

So we can have a WebFilterChain : (exchange) -> Mono.empty()

But we need a lambda that will use ReactiveSecurityContextHolder.getContext() instead of Mono.empty();

The result looks like :

```<code>    var request = MockServerHttpRequest
            .get("/api/test")
            .header(HttpHeaders.AUTHORIZATION, "Bearer " + jwt);

    var exchange = MockServerWebExchange.from(request);

    StepVerifier.create(filter.filter(
            exchange,
            it -> ReactiveSecurityContextHolder.getContext()
                    .map(SecurityContext::getAuthentication)
                    .map(JWTAuthentication.class::cast)
                    .doOnSuccess(auth -> assertThat(auth.getUserId()).isEqualTo("username"))
                    .doOnSuccess(auth -> assertThat(auth.getJwt()).isEqualTo(jwt))
                    .doOnSuccess(auth -> assertThat(auth.getSubscriptions()).isEmpty())
                    .then()
    )).verifyComplete();
</code>```

Body:
I am migrating our security library which is Servlet based.

I need to use ReactiveSecurityContextHolder.getContext() instead of SecurityContextHolder.getContext().

I have a WebFLux WebFilter that modifies the Authentication.

  @Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
...
   return chain.filter(exchange).subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication));

}

I would like to assert the Authentication in ReactiveSecurityContextHolder.getContext().
StepVerifier.create(filter.filter(MockServerWebExchange.from(request), filterChain)).expectNext(...).verifyComplete();

No matter what I try, the context is null because I have to subscribe to the Mono returned by ReactiveSecurityContextHolder.getContext().

I tried ReactiveSecurityContextHolder.getContext().block() without success.

May be the way I try to test it is wrong.

Body:
A way to do it is to use the WebFilterChain which is basically a lambda.

So we can have a WebFilterChain : (exchange) -> Mono.empty()

But we need a lambda that will use ReactiveSecurityContextHolder.getContext() instead of Mono.empty();

The result looks like :

    var request = MockServerHttpRequest
            .get("/api/test")
            .header(HttpHeaders.AUTHORIZATION, "Bearer " + jwt);

    var exchange = MockServerWebExchange.from(request);

    StepVerifier.create(filter.filter(
            exchange,
            it -> ReactiveSecurityContextHolder.getContext()
                    .map(SecurityContext::getAuthentication)
                    .map(JWTAuthentication.class::cast)
                    .doOnSuccess(auth -> assertThat(auth.getUserId()).isEqualTo("username"))
                    .doOnSuccess(auth -> assertThat(auth.getJwt()).isEqualTo(jwt))
                    .doOnSuccess(auth -> assertThat(auth.getSubscriptions()).isEmpty())
                    .then()
    )).verifyComplete();


问:
How to encrypt a column using nifi
For security reasons I need to encrypt a column before putting the data in the repository.
How can I do this using python or some processor.
I tried to use the cryptography library but without success.
If you can guide me which is the best way I would be very grateful.</p>

答:
Take a look at ScriptedTransformRecord, it should allow you to do arbitrary operations on whichever field/columns you like. If you're using a Python library, remember that the script engine is Jython and cannot import modules that aren't pure Python (CPython modules for example). Java has crypto libraries so you could achieve this with Groovy instead.

There is a Jira to cover an EncryptAttributes processor, but perhaps there should be one for Expression Language and/or RecordPath functions as well.

Title: How to encrypt a column using nifi


问:
How do you timeout a twisted test that uses pytest?
I'm working on converting some tests from using Nose and twisted, to using Pytest and twisted, as Nose is no longer in development. The easiest way to convert the tests is by editing the custom decorator that each test has. This decorator is on every test, and defines a timeout for the individual test.

I've tried using  @pytest.mark.timeout, but the only method that's worked is the 'thread' method, but this stops the entire test run and won't continue on to the next test. Using the method 'signal' fails to stop the test, but I can see an error present in the junitxml file.

```<code>def inlineCallbacksTest ( timeout = None ):

    def decorator ( method ):
        @wraps ( method )
        @pytest.mark.timeout(timeout = timeout, method = 'signal' )
        @pytest.inlineCallbacks
        def testMethod ( *args, **kwargs ):
            return method(*args, **kwargs)
        return testMethod
    return decorator
</code>```

The tests themselves use twisted to start up and send messages to the software. I don't need the tests to cancel any twisted processes or locks. I would just like pytest to mark the test as a failure after the timeout, and then move onto the next test.

Below is the error I see in the xml file when using signal method of timeout.

```<code></system-out><system-err>
+++++++++++++++++++++++++++++++++++ Timeout ++++++++++++++++++++++++++++++++++++

~~~~~~~ Stack of PoolThread-twisted.internet.reactor-2 (139997693642496) ~~~~~~~
  File "/usr/lib64/python2.7/threading.py", line 784, in __bootstrap
    self.__bootstrap_inner()
  File "/usr/lib64/python2.7/threading.py", line 811, in __bootstrap_inner
    self.run()
  File "/usr/lib64/python2.7/threading.py", line 764, in run
    self.__target(*self.__args, **self.__kwargs)
  File "/usr/lib64/python2.7/site-packages/twisted/python/threadpool.py", line 190, in _worker
    o = self.q.get()
  File "/usr/lib64/python2.7/Queue.py", line 168, in get
self.not_empty.wait()
  File "/usr/lib64/python2.7/threading.py", line 339, in wait
waiter.acquire()

~~~~~~~ Stack of PoolThread-twisted.internet.reactor-1 (139997702035200) ~~~~~~~
      File "/usr/lib64/python2.7/threading.py", line 784, in __bootstrap
        self.__bootstrap_inner()
  File "/usr/lib64/python2.7/threading.py", line 811, in __bootstrap_inner
    self.run()
  File "/usr/lib64/python2.7/threading.py", line 764, in run
    self.__target(*self.__args, **self.__kwargs)
  File "/usr/lib64/python2.7/site-packages/twisted/python/threadpool.py", line 190, in _worker
    o = self.q.get()
  File "/usr/lib64/python2.7/Queue.py", line 168, in get
    self.not_empty.wait()
  File "/usr/lib64/python2.7/threading.py", line 339, in wait
    waiter.acquire()

+++++++++++++++++++++++++++++++++++ Timeout ++++++++++++++++++++++++++++++++++++
Unhandled Error
Traceback (most recent call last):
  File "/usr/lib64/python2.7/site-
packages/twisted/internet/base.py", line 1169, in run
    self.mainLoop()
--- <exception caught here> ---
  File "/usr/lib64/python2.7/site-
packages/twisted/internet/base.py", line 1181, in mainLoop
    self.doIteration(t)
  File "/usr/lib64/python2.7/site-
packages/twisted/internet/epollreactor.py", line 362, in doPoll
    l = self._poller.poll(timeout, len(self._selectables))
  File "/usr/lib/python2.7/site-packages/pytest_timeout.py", line 110, in handler
    timeout_sigalrm(item, timeout)
  File "/usr/lib/python2.7/site-packages/pytest_timeout.py", line 243, in timeout_sigalrm
    pytest.fail('Timeout >%ss' % timeout)
  File "/usr/lib/python2.7/site-packages/_pytest/outcomes.py", line 85, in fail
    raise Failed(msg=msg, pytrace=pytrace)
builtins.Failed: Timeout >5.0s
</system-err>
</code>```

I have looked around for a similar solution, and the closest I could find was this question. Any help or suggestions would be appreciated.

答:
Coming back to this after 4+ years with an answer. The problem seems to be the exception from the test getting caught by the twisted reactor. I was able to resolve this by updating the version of twisted. Twisted versions since 16.5 have a new Deferred function call addTimeout (Docs). Using that, I was able to modify the original decorator to the following. Now whenever a test times out, it simply raises an exception and moves on to the next one. May not be the most elegant, but I hope this helps someone else out!

```<code>    import twisted.internet.defer as defer
    import pytest_twisted as pt
    from functools import wraps

    def inlineCallbacksTest ( timeout = None ):

        def testDecorator ( testFunc ):

            def timeoutError ( value, timeout ):

                raise Exception ( "Test Timeout: {} secs have expired".format ( timeout ) )

            @wraps ( testFunc )
            def wrapper ( *args, **kwargs ):

                testDefer = pt.inlineCallbacks ( testFunc )( *args, **kwargs )
                testDefer.addTimeout ( timeout, reactor, timeoutError )
                return testDefer

            return wrapper
        return testDecorator
</code>```

Body:
I'm working on converting some tests from using Nose and twisted, to using Pytest and twisted, as Nose is no longer in development. The easiest way to convert the tests is by editing the custom decorator that each test has. This decorator is on every test, and defines a timeout for the individual test.

I've tried using  @pytest.mark.timeout, but the only method that's worked is the 'thread' method, but this stops the entire test run and won't continue on to the next test. Using the method 'signal' fails to stop the test, but I can see an error present in the junitxml file.

def inlineCallbacksTest ( timeout = None ):

    def decorator ( method ):
        @wraps ( method )
        @pytest.mark.timeout(timeout = timeout, method = 'signal' )
        @pytest.inlineCallbacks
        def testMethod ( *args, **kwargs ):
            return method(*args, **kwargs)
        return testMethod
    return decorator

The tests themselves use twisted to start up and send messages to the software. I don't need the tests to cancel any twisted processes or locks. I would just like pytest to mark the test as a failure after the timeout, and then move onto the next test.

Below is the error I see in the xml file when using signal method of timeout.

</system-out><system-err>
+++++++++++++++++++++++++++++++++++ Timeout ++++++++++++++++++++++++++++++++++++

~~~~~~~ Stack of PoolThread-twisted.internet.reactor-2 (139997693642496) ~~~~~~~
  File "/usr/lib64/python2.7/threading.py", line 784, in __bootstrap
    self.__bootstrap_inner()
  File "/usr/lib64/python2.7/threading.py", line 811, in __bootstrap_inner
    self.run()
  File "/usr/lib64/python2.7/threading.py", line 764, in run
    self.__target(*self.__args, **self.__kwargs)
  File "/usr/lib64/python2.7/site-packages/twisted/python/threadpool.py", line 190, in _worker
    o = self.q.get()
  File "/usr/lib64/python2.7/Queue.py", line 168, in get
self.not_empty.wait()
  File "/usr/lib64/python2.7/threading.py", line 339, in wait
waiter.acquire()

~~~~~~~ Stack of PoolThread-twisted.internet.reactor-1 (139997702035200) ~~~~~~~
      File "/usr/lib64/python2.7/threading.py", line 784, in __bootstrap
        self.__bootstrap_inner()
  File "/usr/lib64/python2.7/threading.py", line 811, in __bootstrap_inner
    self.run()
  File "/usr/lib64/python2.7/threading.py", line 764, in run
    self.__target(*self.__args, **self.__kwargs)
  File "/usr/lib64/python2.7/site-packages/twisted/python/threadpool.py", line 190, in _worker
    o = self.q.get()
  File "/usr/lib64/python2.7/Queue.py", line 168, in get
    self.not_empty.wait()
  File "/usr/lib64/python2.7/threading.py", line 339, in wait
    waiter.acquire()

+++++++++++++++++++++++++++++++++++ Timeout ++++++++++++++++++++++++++++++++++++
Unhandled Error
Traceback (most recent call last):
  File "/usr/lib64/python2.7/site-
packages/twisted/internet/base.py", line 1169, in run
    self.mainLoop()
--- <exception caught here> ---
  File "/usr/lib64/python2.7/site-
packages/twisted/internet/base.py", line 1181, in mainLoop
    self.doIteration(t)
  File "/usr/lib64/python2.7/site-
packages/twisted/internet/epollreactor.py", line 362, in doPoll
    l = self._poller.poll(timeout, len(self._selectables))
  File "/usr/lib/python2.7/site-packages/pytest_timeout.py", line 110, in handler
    timeout_sigalrm(item, timeout)
  File "/usr/lib/python2.7/site-packages/pytest_timeout.py", line 243, in timeout_sigalrm
    pytest.fail('Timeout >%ss' % timeout)
  File "/usr/lib/python2.7/site-packages/_pytest/outcomes.py", line 85, in fail
    raise Failed(msg=msg, pytrace=pytrace)
builtins.Failed: Timeout >5.0s
</system-err>

I have looked around for a similar solution, and the closest I could find was this question. Any help or suggestions would be appreciated.

Body:
Coming back to this after 4+ years with an answer. The problem seems to be the exception from the test getting caught by the twisted reactor. I was able to resolve this by updating the version of twisted. Twisted versions since 16.5 have a new Deferred function call addTimeout (Docs). Using that, I was able to modify the original decorator to the following. Now whenever a test times out, it simply raises an exception and moves on to the next one. May not be the most elegant, but I hope this helps someone else out!

    import twisted.internet.defer as defer
    import pytest_twisted as pt
    from functools import wraps

    def inlineCallbacksTest ( timeout = None ):

        def testDecorator ( testFunc ):

            def timeoutError ( value, timeout ):

                raise Exception ( "Test Timeout: {} secs have expired".format ( timeout ) )

            @wraps ( testFunc )
            def wrapper ( *args, **kwargs ):

                testDefer = pt.inlineCallbacks ( testFunc )( *args, **kwargs )
                testDefer.addTimeout ( timeout, reactor, timeoutError )
                return testDefer

            return wrapper
        return testDecorator


问:
Displaying audio and video content on android
For a project in work, we are getting a multimedia company to make 7 x 3 minutes film = around 21 minutes of video. ( with H.264/1280x720/1000kbps = about 200 Mb) which will then be stored on a MicroSD on the Samsung Galaxy S. These video files will be called by an app that I am developing.
They will also record all the text in audio (voice-over) as a separate file = about 60 minutes audio (with mp3 size about 60 Mb)
Total media around 260 Mb. They will be working on a Apple computer.

I know very little about multimedia - even though I apparantly have a masters in it - and was wondering if someone could help me answer some of these questions?

What would be the max suitable size for each of the files if stored on a 4GB Micro SD?

What is the minimum quality for display on a Samsung Galaxy S?

What is the best file format for display on the device?

Thanks

答:
What would be the max suitable size for each of the files if stored on a 4GB Micro SD?

File Size is a function of video bitrate and duration of the clip. Video Bitrate is usually proportional to Video Resolution. For a 21 minute clip, @ 8 Mbps, File Size would be ~ (21 * 60 * 8) /8, i.e.  1.2 GB. This should be okay for you.

What is the minimum quality for display on a Samsung Galaxy S?

Galaxy S I think has WVGA Screen Resolution, however it can decode up to 720P. i.e. You can run a video of resolution 1280x720. If the particulr Galaxy S you are talking about, has HDMI output, then you can go ahead with 720P Content. Otherwise, on phone you wont see the difference between 720P Vs WVGA playback.

What is the best file format for display on the device?

Android comes with H264/MP4 combination. These days bluray content (High definition video) is becoming popular. i.e. 1080P / 720P H264/mkv format. This you can use if the phone supports mkv. Otherwise go with 720P H264 in MP4.

Shash


问:
Type 'T[K]' does not satisfy the constraint 'string | number | symbol'
I am creating a simple function to remove duplicates from an array in typescript.

I know there are many different ways to achieve the goal, but my end goal is to learn how types work, so I don't need a solution that differs from my existing code.

My Pseudo code:

function will take in array of objects and key of object as parameters

array of objects will be converted to a dictionary to only have unique entries

construct the array from object and return it.

Working code example using javascript:

```<code>function removeDuplicates(arr, propName) {
  const newArr = [];
  const lookup = {};

  for (let i in arr) {
    lookup[arr[i][propName]] = arr[i];
  }

  for (let i in lookup) {
    newArr.push(lookup[i]);
  }

  return newArr;
}
</code>```

Typescript code (throwing type error)

I am trying to convert that function to Typescript, but stuck at declaring types for lookup variable.

Here is my typescript code:

```<code>function removeDuplicates<T, K extends keyof T>(arr: T[], propName: K) {
  const newArr: T[] = [];
  const lookup: Partial<Record<T[K], T>> = {};
                               ^^^^ here is the error

  for (let i in arr) {
    lookup[arr[i][propName]] = arr[i];
  }

  for (let i in lookup) {
    newArr.push(lookup[i]);
  }

  return newArr;
}
</code>```

Error:

```<code>Type 'T[K]' does not satisfy the constraint 'string | number | symbol'
</code>```

I know why I am getting the error. I am getting the error because value of object.key can be anything. But in my use case, I want to restrict the developer to pass in only the key whose value is either string | number. But I don't know how to do that in typescript.

答:
As you said, you're getting the error because while K is constrained to be a key from the array element type T, there is nothing saying that the property at that key T[K] is itself key-like:

```<code>function removeDuplicates<T, K extends keyof T>(arr: T[], propName: K) {
    const lookup: Partial<Record<T[K], T>> = {}; // error!
}

removeDuplicatesOops([{ a: new Date(), b: "hey" }], "a"); // no error
</code>```

In TypeScript, a type is "keylike" if it's assignable to string | number | symbol, which is given a convenient alias PropertyKey.

We can't constrain T[K] directly, but we can constrain K and/or T so that T[K] is effectively constrained. The easiest way to get your desired behavior where the compiler realizes that Partial<Record<T[K], T>> is an acceptable thing is to constrain T so that the property type at the keys in K must be assignable to PropertyKey:

```<code>function removeDuplicates<T extends Record<K, PropertyKey>, K extends keyof T>(
  arr: T[], propName: K) {
    const lookup: Partial<Record<T[K], T>> = {};
    // okay
}

removeDuplicates([{ a: new Date(), b: "hey" }], "a");
// ---------------> ~
// Type 'Date' is not assignable to type 'PropertyKey'.
</code>```

Yes, the constraints on T and K are circular, but in an allowable way (although it's sometimes tricky to avoid circularity warnings in situations like this).  Note that the error appears on the keys of the arr argument and not the propName argument itself.  If you really need the latter then you can constrain K even further like

```<code>function removeDuplicates<
    T extends Record<K, PropertyKey>,
    K extends keyof { [P in keyof T as T[P] extends PropertyKey ? P : never]: any }
>(arr: T[], propName: K) {
    const lookup: Partial<Record<T[K], T>> = {};
    // okay
}

removeDuplicates([{ a: new Date(), b: "hey" }], "a"); // error!
// -------------------------------------------> ~~~
//Argument of type '"a"' is not assignable to parameter of type '"b"'.
</code>```

But this might be more complicated than you are looking for (and it would take me too far afield to explain how that K constraint works).

Playground link to code

Body:
I am creating a simple function to remove duplicates from an array in typescript.

I know there are many different ways to achieve the goal, but my end goal is to learn how types work, so I don't need a solution that differs from my existing code.

My Pseudo code:

function will take in array of objects and key of object as parameters

array of objects will be converted to a dictionary to only have unique entries

construct the array from object and return it.

Working code example using javascript:

function removeDuplicates(arr, propName) {
  const newArr = [];
  const lookup = {};

  for (let i in arr) {
    lookup[arr[i][propName]] = arr[i];
  }

  for (let i in lookup) {
    newArr.push(lookup[i]);
  }

  return newArr;
}

Typescript code (throwing type error)

I am trying to convert that function to Typescript, but stuck at declaring types for lookup variable.

Here is my typescript code:

function removeDuplicates<T, K extends keyof T>(arr: T[], propName: K) {
  const newArr: T[] = [];
  const lookup: Partial<Record<T[K], T>> = {};
                               ^^^^ here is the error

  for (let i in arr) {
    lookup[arr[i][propName]] = arr[i];
  }

  for (let i in lookup) {
    newArr.push(lookup[i]);
  }

  return newArr;
}

Error:

Type 'T[K]' does not satisfy the constraint 'string | number | symbol'

I know why I am getting the error. I am getting the error because value of object.key can be anything. But in my use case, I want to restrict the developer to pass in only the key whose value is either string | number. But I don't know how to do that in typescript.

Body:
As you said, you're getting the error because while K is constrained to be a key from the array element type T, there is nothing saying that the property at that key T[K] is itself key-like:

function removeDuplicates<T, K extends keyof T>(arr: T[], propName: K) {
    const lookup: Partial<Record<T[K], T>> = {}; // error!
}

removeDuplicatesOops([{ a: new Date(), b: "hey" }], "a"); // no error

In TypeScript, a type is "keylike" if it's assignable to string | number | symbol, which is given a convenient alias PropertyKey.

We can't constrain T[K] directly, but we can constrain K and/or T so that T[K] is effectively constrained. The easiest way to get your desired behavior where the compiler realizes that Partial<Record<T[K], T>> is an acceptable thing is to constrain T so that the property type at the keys in K must be assignable to PropertyKey:

function removeDuplicates<T extends Record<K, PropertyKey>, K extends keyof T>(
  arr: T[], propName: K) {
    const lookup: Partial<Record<T[K], T>> = {};
    // okay
}

removeDuplicates([{ a: new Date(), b: "hey" }], "a");
// ---------------> ~
// Type 'Date' is not assignable to type 'PropertyKey'.

Yes, the constraints on T and K are circular, but in an allowable way (although it's sometimes tricky to avoid circularity warnings in situations like this).  Note that the error appears on the keys of the arr argument and not the propName argument itself.  If you really need the latter then you can constrain K even further like

function removeDuplicates<
    T extends Record<K, PropertyKey>,
    K extends keyof { [P in keyof T as T[P] extends PropertyKey ? P : never]: any }
>(arr: T[], propName: K) {
    const lookup: Partial<Record<T[K], T>> = {};
    // okay
}

removeDuplicates([{ a: new Date(), b: "hey" }], "a"); // error!
// -------------------------------------------> ~~~
//Argument of type '"a"' is not assignable to parameter of type '"b"'.

But this might be more complicated than you are looking for (and it would take me too far afield to explain how that K constraint works).

<a href="https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABAJwKYFs4DdUBEQAOANjBAIZSoDOA8nAVQDwAqANIgNKKoAelYAEyqIA1qgCecYImYA+ABRlkyAFwyA2gF12BZPQByZdKjUcAlIgDeAKER3EEBFSiIicOCMJqACkthkiRgAlVEdkARZ1Dm0ZWVlEAF4rAF8Abmtk62s0TBx8YlIKajoGeXVLRDI1MFQAd0RcIvkzdgAjNQAiAAsJDsRkmI6yDrNUxAB6ccQwOG5lOGQs0EhYBBQMbDxCEnJKJmZuPlRBYRCwiI52bz0CVGQocQ4JWVZbey5efiFRCSlYxWUamYWh0N0MxlMFhs9gcThcbg8XkQvnuMACwVCCwiwOi7Dk8SSljSbzsk0QHjI4gyWRym3yOyKVDKFSq0zqDSaLUQ7UQ3V6-UGw1G1jJdz0yAAhDJxLdEAByRqUOWIGDCGYuMhUKgwADmYDIrSIqEQUFmD1lcuu9DuDye4jlADoluBoPAkLS8ttCnsALILVCMEkyQ5fU6Y8KMS7Im42x7PV4wj5HE4-STSCrqbwqpBiNPBzUabyaEPHb5W273OPiRAAfmRiGqqBwyE0ajIYGrmQUSlUGhiugMRhMnChQccYGcrncngIPj8aMCZyxkVxsQJKXSMLJFKpmWyG09BV21D9aGZlUb9UVqGabU6PXEfQG7CGIzGovmkpF4wAgsgdSAxhgC4fzmsacqvsqqrTHAGparq+qGsapqIAQShDpQyDktIYHyh0rQdI6QA" rel="nofollow noreferrer">Playground link to code


问:
Json request string
i have this code that works but im pretty sure there is a better way to do this, can you guys help?

```<code>jsrqs = 2022-02-08 14:01:56,048 sdc-web-sockets-pp /moe.com/SMART/logs/srf/srf-web-sockets.log: 2022-02-08 14:01:50,308 srf-web-sockets-pp-1 INFO [null:-1] (executor-thread-19) Op16 - Station : id-00003:vdeURRi8v8evU8AZWEnIwtbrucvjdeZyJL42, MessageId: a8a3e920-88e7-11ec-8f9b-c904565fadef, request message: {"action":"Boot","messageId":"a8d3r920-88e7-11ec-8f9b-c9074d5fadef","type":"CALL","uniqueId":"a8a3e920-88e7-11ec-8f9b-c9074d5fadef","payload":"{"Vendor":"vendorname","PointModel":"pointname","PointSerialNumber":"123456789","firmwareVersion":"1.1.1.8"}"}
</code>```

this is my code, it works but its "ugly"

```<code>                if "BOOT" in jsrqs.upper():
                    j1,j2ff = jsrqs.split(r"payload")
                    j2f = j2ff.replace("\\", "")
                    j2a = j2f[3:]
                    size = len(j2a)
                    j2 = j2a[:size - 2]
                    stud_obj = json.loads(j2)

                    inp_vendor.delete('1.0', END)
                    inp_model.delete('1.0', END)
                    inp_sn.delete('1.0', END)
                    inp_firmware.delete('1.0', END)

                    inp_firmware.insert("1.0", str(stud_obj['firmwareVersion']))
                    inp_model.insert("1.0", str(stud_obj['PointModel']))
                    inp_sn.insert("1.0", str(stud_obj['PointSerialNumber']))
                    inp_vendor.insert("1.0", str(stud_obj['PointVendor']))
</code>```

答:
I think my code would help u,splitting the response body where we need. worked for me</p>
```<code>import json

jsrqs = """2022-02-08 14:01:56,048 sdc-web-sockets-pp /moe.com/SMART/logs/srf/srf-web-sockets.log: 2022-02-08 14:01:50,308 srf-web-sockets-pp-1 INFO [null:-1] (executor-thread-19) Op16 - Station : id-00003:vdeURRi8v8evU8AZWEnIwtbrucvjdeZyJL42, MessageId: a8a3e920-88e7-11ec-8f9b-c904565fadef, request message: {"action":"Boot","messageId":"a8d3r920-88e7-11ec-8f9b-c9074d5fadef","type":"CALL","uniqueId":"a8a3e920-88e7-11ec-8f9b-c9074d5fadef","payload":"{"Vendor":"vendorname","PointModel":"pointname","PointSerialNumber":"123456789","firmwareVersion":"1.1.1.8"}"}"""

if "BOOT" in jsrqs.upper():
    resp = json.loads(str(jsrqs.split('payload":"')[1][:-2]))

    print(resp['Vendor'])
    print(resp['PointModel'])
    print(resp['firmwareVersion'])
    print(resp['PointSerialNumber'])
</code>```

Title: Json request string

Body:
i have this code that works but im pretty sure there is a better way to do this, can you guys help?

jsrqs = 2022-02-08 14:01:56,048 sdc-web-sockets-pp /moe.com/SMART/logs/srf/srf-web-sockets.log: 2022-02-08 14:01:50,308 srf-web-sockets-pp-1 INFO [null:-1] (executor-thread-19) Op16 - Station : id-00003:vdeURRi8v8evU8AZWEnIwtbrucvjdeZyJL42, MessageId: a8a3e920-88e7-11ec-8f9b-c904565fadef, request message: {"action":"Boot","messageId":"a8d3r920-88e7-11ec-8f9b-c9074d5fadef","type":"CALL","uniqueId":"a8a3e920-88e7-11ec-8f9b-c9074d5fadef","payload":"{"Vendor":"vendorname","PointModel":"pointname","PointSerialNumber":"123456789","firmwareVersion":"1.1.1.8"}"}

this is my code, it works but its "ugly"

                if "BOOT" in jsrqs.upper():
                    j1,j2ff = jsrqs.split(r"payload")
                    j2f = j2ff.replace("\\", "")
                    j2a = j2f[3:]
                    size = len(j2a)
                    j2 = j2a[:size - 2]
                    stud_obj = json.loads(j2)

                    inp_vendor.delete('1.0', END)
                    inp_model.delete('1.0', END)
                    inp_sn.delete('1.0', END)
                    inp_firmware.delete('1.0', END)

                    inp_firmware.insert("1.0", str(stud_obj['firmwareVersion']))
                    inp_model.insert("1.0", str(stud_obj['PointModel']))
                    inp_sn.insert("1.0", str(stud_obj['PointSerialNumber']))
                    inp_vendor.insert("1.0", str(stud_obj['PointVendor']))

Body:
I think my code would help u,splitting the response body where we need. worked for me

import json

jsrqs = """2022-02-08 14:01:56,048 sdc-web-sockets-pp /moe.com/SMART/logs/srf/srf-web-sockets.log: 2022-02-08 14:01:50,308 srf-web-sockets-pp-1 INFO [null:-1] (executor-thread-19) Op16 - Station : id-00003:vdeURRi8v8evU8AZWEnIwtbrucvjdeZyJL42, MessageId: a8a3e920-88e7-11ec-8f9b-c904565fadef, request message: {"action":"Boot","messageId":"a8d3r920-88e7-11ec-8f9b-c9074d5fadef","type":"CALL","uniqueId":"a8a3e920-88e7-11ec-8f9b-c9074d5fadef","payload":"{"Vendor":"vendorname","PointModel":"pointname","PointSerialNumber":"123456789","firmwareVersion":"1.1.1.8"}"}"""

if "BOOT" in jsrqs.upper():
    resp = json.loads(str(jsrqs.split('payload":"')[1][:-2]))

    print(resp['Vendor'])
    print(resp['PointModel'])
    print(resp['firmwareVersion'])
    print(resp['PointSerialNumber'])