text:
Q: Adding a running total column for every inserted value by using Partition by function If you have better title for this question please let me know. Thank you for your having a look in advance.
Table I have after insert need to update total column
FK_Key  Score    Total
----------------------
121       1      NULL
121       5      NULL
121       7      NULL

What I want to do is to update the Total column by looking at the score values:
FK_Key   Score    Total
-----------------------
121        1        1
121        5        6
121        7       13

Let's say there is a new row inserted for the same foreign key in the table:
121        6       19

Every time a new insert happens, it should update the Total column summing up the values from the Score column grouped by the FK's together - here the Score is 19 i.e (1+5+7+6)
Basically I am looking for a update statement that looks through Score column and updates the value for each FK. I don't want the same value updated across all FK's
Here is the query to play with
IF OBJECT_ID('tempdb..#Table1') IS NOT NULL
   DROP TABLE #Table1
GO

CREATE TABLE #Table1
(
    FK_Key INT,
    Score INT NULL,
    Total INT NULL,
)

INSERT INTO #Table1
VALUES (121, 1, NULL), (121, 5, NULL), (121, 7, NULL), (121, 6, NULL)

SELECT * FROM #Table1

Expected result

A: As I stated in the comment, my suggestion would be to change the table structure to include a "Timestamp" kind-of column so you know when data was inserted, otherwise, you're not guaranteed of having the exact same recordset returning each time you run your query, then creating a view to get the data you want.
Your solution would look as follows:
CREATE TABLE #Table1
(
     FK_Key     INT
    ,Score      INT       NULL
    ,InsertTime DATETIME2 DEFAULT GETDATE()
)

INSERT INTO
    #Table1 (FK_Key, Score)
VALUES
    (121, 1), (121, 5), (121, 7), (121, 6)

SELECT
     FK_Key
    ,Score
    -- ,InsertTime
    ,SUM(Score) OVER (PARTITION BY FK_Key ORDER BY InsertTime ROWS UNBOUNDED PRECEDING) AS Total
FROM
    #Table1

And, obviously, that last query can just be stored as a view.
This will allow for consistent results and also deal with the situation where rows are deleted after the fact that would mess up your current running total logic.
Hope that makes sense / helps.


text:
Q: stm32 keil cannot assign array in interrupt I can not assign my array in interrupt.
My main.c function is like this:
volatile uint32_t buffer[BUFFER_LENGTH];
int main(void)
{
  while(1)
  {
    sprintf((char*)string,"%u",buffer[0]);
    BSP_LCD_DisplayStringAt(250, LINE(9), (uint8_t *)string, LEFT_MODE);
  }
}

Interrupt routine is like this:
void EXTI3_IRQHandler(void)
{
    buffer[0] = 100;
}

The display always shows 0!
The strange thing is that when I use a variable instead of an array everything works fine!
uint32_t variable;
int main(void)
{
  while(1)
  {
    sprintf((char*)string,"%u",variable);
    BSP_LCD_DisplayStringAt(250, LINE(9), (uint8_t *)string, LEFT_MODE);
  }
}

void EXTI3_IRQHandler(void)
{
    variable = 100;
}

The display shows 100! Why can't I use array in interrupt routine?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Django Oscar External CSS I just created a store using Django-Oscar - and I am getting a hard time to add external CSS, I mean, I want to replace the whole default style to a more fancy one with nice futures.
How can I replace them? I've tried their doc, and yet I am not able to replace them.


text:
Q: Mathematical Entity That Takes a Function and Returns a Function I have been pondering something lately and asked myself whether there is a mathematical construct that takes a function as its parameter and returns another function as its result?
That is, it is a function of a function that produces a function. Is there a term for this? What are some basic facts and where can I learn more about such structures?

A: These are often called operators. Some operators take two arguments, called binary, like $()\times()$ or $()-()$; others take only one, called unary, such as $()^2$.
Some examples of operators or "functions" that take functions $f(x)$ and return functions include

*

*the derivative $d/dx$

*the derivative's half-brother the gradient $\nabla$

*the derivative's twin sister the partial derivative $\partial/\partial x$

*exponentiation $[f(x)]^2$

*multiplication $2\times f(x)$

*addition $f(x)+2$

*function composition $[g\circ f](x)$ if the domain of $g$ and range of $f$ align nicely


text:
Q: Flutter TextFormField onSave() get called with empty values I want to do a Custom TextFormField so I call it when I want, but valuedata property inside onSave() keeps being empty after passing the data to it.
Here is the custom TextFormField:
class CustomTextField extends StatelessWidget {
  CustomTextField({
    Key? key,
    required this.labelText,
    required this.textInputType,
    required this.message,
    required this.valuedata,
  }) : super(key: key);

  final String labelText;
  final TextInputType textInputType;
  final String message;
  String valuedata;
  @override
  Widget build(BuildContext context) {
    return TextFormField(
      onSaved: (value) {
        valuedata = value!;
      },
      keyboardType: textInputType,
      decoration: InputDecoration(
          labelStyle: const TextStyle(
            color: Colors.green,
          ),
          labelText: labelText,
          border: OutlineInputBorder(borderRadius: BorderRadius.circular(8.0)),
          focusedBorder: OutlineInputBorder(
            borderSide: const BorderSide(color: Colors.green, width: 2.0),
            borderRadius: BorderRadius.circular(8.0),
          )),
      validator: (text) {
        if (text!.isEmpty) {
          return message;
        } else {
          return null;
        }
      },
    );
  }
}

Here where I use it:
 CustomTextField(
                      valuedata: input.input1,
                      labelText: 'name',
                      message: 'Please enter your name',
                      textInputType: TextInputType.text,
                    ),

and this is the full code where I use the CustomTextField:
class Apply extends StatefulWidget {
  const Apply({Key? key}) : super(key: key);

  @override
  _ApplyState createState() => _ApplyState();
}

class Data {
  String input1 = '';
  String input2 = '';
}

class _ApplyState extends State<Apply> {
  var formKey = GlobalKey<FormState>();
  static Data input = Data();
  var input1 = '';
  var input2 = '';
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Theme(
          data: ThemeData(primaryColor: Colors.green),
          child: Form(
            key: formKey,
            child: SingleChildScrollView(
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      "Les informations Personneles:",
                      style: TextStyle(fontWeight: FontWeight.bold),
                    ),
                    const SizedBox(
                      height: 8,
                    ),
                    CustomTextField(
                      valuedata: input.input1,
                      //data: data,
                      labelText: 'Prenom',
                      message: 'Please enter your name',
                      textInputType: TextInputType.text,
                    ),
                    const SizedBox(
                      height: 16,
                    ),
                    CustomTextField(
                      valuedata: input.input2,
                      labelText: 'Prenom',
                      message: 'Please enter your name',
                      textInputType: TextInputType.text,

                      //d,
                    ),
                    Row(
                      children: [
                        Expanded(
                            child: ElevatedButton(
                                style: ElevatedButton.styleFrom(
                                  primary: Colors.red,
                                ),
                                onPressed: () {
                                  formKey.currentState!.reset();
                                  input1 = '';
                                  input2 = '';
                                  setState(() {});
                                },
                                child: const Text('Clear'))),
                        const SizedBox(
                          width: 16,
                        ),
                        Expanded(
                            child: ElevatedButton(
                                style: ElevatedButton.styleFrom(
                                  primary: Colors.green,
                                ),
                                onPressed: () {
                                  if (formKey.currentState!.validate()) {
                                    formKey.currentState!.save();

                                    setState(() {});
                                  }
                                },
                                child: const Text('show'))),
                      ],
                    ),
                    const SizedBox(
                      height: 16,
                    ),
                    Text('Input1: ${input.input1}'),
                    Text('Input2: ${input.input1}'),
                    const SizedBox(
                      height: 16,
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

If you refer to the image input1 and input2 doesn't get the user Inputs.
My question is, with this same approach how can make the onSave() save the values on the state?

A: This is what you are looking for
class Apply extends StatefulWidget {
const Apply({Key? key}) : super(key: key);

  @override
  _ApplyState createState() => _ApplyState();
}

class Data {
  List<String> inputs = ['',''];
}

class _ApplyState extends State<Apply> {
  var formKey = GlobalKey<FormState>();
  static Data input = Data();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Theme(
          data: ThemeData(primaryColor: Colors.green),
          child: Form(
            key: formKey,
            child: SingleChildScrollView(
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      "Les informations Personneles:",
                      style: TextStyle(fontWeight: FontWeight.bold),
                    ),
                    const SizedBox(
                      height: 8,
                    ),
                    createTextField('label1', TextInputType.datetime, 'msg', 0),
                    createTextField('label2', TextInputType.datetime, 'msg', 1),
                    Row(
                      children: [
                        Expanded(
                            child: ElevatedButton(
                                style: ElevatedButton.styleFrom(
                                  primary: Colors.red,
                                ),
                                onPressed: () {
                                  formKey.currentState!.reset();
                                  //input1 = '';
                                  //input2 = '';
                                  setState(() {});
                                },
                                child: const Text('Clear'))),
                        const SizedBox(
                          width: 16,
                        ),
                        Expanded(
                            child: ElevatedButton(
                                style: ElevatedButton.styleFrom(
                                  primary: Colors.green,
                                ),
                                onPressed: () {
                                  if (formKey.currentState!.validate()) {
                                    formKey.currentState!.save();

                                    setState(() {});
                                  }
                                },
                                child: const Text('show'))),
                      ],
                    ),
                    const SizedBox(
                      height: 16,
                    ),
                    Text('Input1: ${input.inputs[0]}'),
                    Text('Input2: ${input.inputs[1]}'),
                    const SizedBox(
                      height: 16,
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
  createTextField(String labelText, TextInputType textInputType, String message, int index) => TextFormField(
      onSaved: (value) {
        setState(() {
          input.inputs[index] = value!;
        });
      },
      keyboardType: textInputType,
      decoration: InputDecoration(
          labelStyle: const TextStyle(
            color: Colors.green,
          ),
          labelText: labelText,
          border: OutlineInputBorder(borderRadius: BorderRadius.circular(8.0)),
          focusedBorder: OutlineInputBorder(
            borderSide: const BorderSide(color: Colors.green, width: 2.0),
            borderRadius: BorderRadius.circular(8.0),
          )),
      validator: (text) {
        if (text!.isEmpty) {
          return message;
        } else {
          return null;
        }
      },
    );
}


text:
Q: WebView Woocommerce Cart Page I am creating a simple android app to navigate through my Woocommerce store (using android webview for that).
Problem is when I reach cart page -> page loads correctly at first but when i click on update quantity or delete a product from the cart, page goes blank.
I really do not know what is the solution to this issue.
I guess that I should buy an already made android app to do this.
I am using Android Studio 3.
Is there anyone who have had this issue before?
Thank you.

A: You can attach webview to chrome debugger console and check what exactly is happening there. Although it's very difficult to debug for here but surely you will get help from chrome debugger.
If you can attach some screenshots of woocommerce website that might be helpful.
Thanks


text:
Q: Corrupt jars from Spring Web MVC maven dependency Recently, I came across an instance in which Spring Web MVC maven dependency intermittently downloads corrupt jars. The following was the dependency along with its version I was using:
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>3.0.7.RELEASE</version>
</dependency>

When searching further, I found that I was not the only person to experience such an issue. For example, posts in several forums suggest that this dependency seems to intermittently provide corrupt jars.
http://crunchify.com/cannot-be-read-or-is-not-a-valid-zip-file-how-to-fix-maven-build-path-error-with-corrupted-jar-file/
What is the root cause for this problem? Is cleaning the m2 repo and running fresh builds the only solution to this  issue, as suggested mostly?


text:
Q: XSLT for-each loop and nodes with different pattern I have the following structure of xml data to transform:
     <chapter>
          <title>Text</title>
          <subtitle>Text</subtitle>
          <paragraph>Text</paragraph>
          <paragraph>Text</paragraph>
          <subtitle>Text</subtitle>
          <paragraph>Text</paragraph>
          <other>Text</other>
      </chapter>

      <chapter>
          <title>Text</title>
          <paragraph>Text</paragraph>
          <paragraph>Text</paragraph>
          <paragraph>Text</paragraph>
          <other>Text</other>
      </chapter>

      <chapter>
          <title>Text</title>
          <paragraph>Text</paragraph>
          <subtitle>Text</subtitle>
          <paragraph>Text</paragraph>
          <paragraph>Text</paragraph>
          <other>Text</other>
      </chapter>

As you can see, the subtitles in the different chapters have no permanent pattern. In the output, I need to set the subtitles on the same place like the are in the xml. For the paragraph tags, I use a for-each loop. Like this:
<xsl:template match="chapter">
  <xsl:for-each select="paragraph">
    <xsl:value-of select="."/>
  </xsl:for-each>
</xsl:template>

And now, I need to set the subtitles above, between or among the paragraphs in the order they are in the xml. How can I do this? Please help!

A: By using
 <xsl:for-each select="paragraph">

You are pulling all the paragraph elements out first, You could change that to
<xsl:for-each select="*">

To process all elements in order, but it is better (or at least more idiomatic xslt) to avoid for-each and use apply-templates instead.
<xsl:template match="chapter">
   <xsl:apply-templates/>
</xsl:template>

<xsl:template match="title">
Title: <xsl:value-of select="."/>
</xsl:template>

<xsl:template match="subtitle">
SubTitle: <xsl:value-of select="."/>
</xsl:template>

<xsl:template match="paragraph">
 <xsl:text>

</xsl:text>
 <xsl:value-of select="."/>
<xsl:text>

</xsl:text>
</xsl:template>

A: Would this do it?
<xsl:template match="chapter">
  <xsl:for-each select="paragraph | subtitle">
    <xsl:value-of select="."/>
  </xsl:for-each>
</xsl:template>

But as David Carlisle points out, the typical XSLT approach is to split this out into templates, and this especially makes sense if you want special handling for certain ones:
<xsl:template match="chapter">
   <xsl:apply-templates select="paragraph | subtitle" />
</xsl:template>

<xsl:template match="paragraph">
   <xsl:value-of select="." />
</xsl:template>

<xsl:template match="subtitle">
   <!-- do stuff with subtitles -->
</xsl:template>


text:
Q: Errors on trying to get a list of installed modules on openshift/nodejs Trying to setup a simple node app hosted on openshift - using the restify and mongojs modules. The only change I have made to the app is adding
"restify": "latest",
"mongojs": "latest"

to the dependencies section in the package.json, followed by a git push.
Since I want to setup a local dev/testing environment as well, am using the documentation provided at http://openshift.github.io/documentation/oo_cartridge_guide.html#local-development-testing
as described in the docs - if I run
ssh <uid>@<appname>.rhcloud.com npm list -g

I get a long list of errors ending with
npm WARN unmet dependency /opt/rh/nodejs010/root/usr/lib/node_modules/ws requires options@'latest' but will load
npm WARN unmet dependency /opt/rh/nodejs010/root/usr/lib/node_modules/options,
npm WARN unmet dependency which is version 0.0.5
npm ERR! missing: npm@*, required by undefined@undefined
npm ERR! missing: openshift-node-web-proxy@*, required by undefined@undefined
npm ERR! invalid: options@0.0.5 /opt/rh/nodejs010/root/usr/lib/node_modules/options
npm ERR! not ok code 0

The error body contains a lot of errors like ...
glob error { [Error: EACCES, readdir '/opt/rh/nodejs010/root/usr/lib/node_modules/npm/man/man3/whoami.3']
  errno: 3,
  code: 'EACCES',
  path: '/opt/rh/nodejs010/root/usr/lib/node_modules/npm/man/man3/whoami.3' }
glob error { [Error: EACCES, readdir '/opt/rh/nodejs010/root/usr/lib/node_modules/npm/man/man3/whoami.3']
  errno: 3,
  code: 'EACCES',
  path: '/opt/rh/nodejs010/root/usr/lib/node_modules/npm/man/man3/whoami.3' }

What is the recommended course of action?
How to fix these errors?
Is the application in a broken state?

A: On Openshift, you cannot should not install stuff globally.
Use instead local module, and if you need to run executables (like coffee, mocha, grunt...), launch them from the node_modules\.bin folder.
--- EDIT ---
As said in the official documentation, it's possible to install stuff globally, but it's not recommended. I guess you should have sufficient right.

the better alternative though is to install them in the home directory of the currently logged user on your local machine/workstation.

If you really need stuff on global, consider putting them into your cartdrige: it will be more handy when scalling on different VMs


text:
Q: Can anyone tell me step by step way to install Logkeys Keylogger in Ubuntu 14.04? Can anyone tell me step by step way to install Logkeys Keylogger in Ubuntu 14.04?
I saw the various answer on this forum but none of them is working exactly.I want to know it for educational purpose only.

A: From the installation instructions

*

*Download the source.

*You need to install "autotools" and can do that with ...
apt-get update
apt-get install -y autotools

*The installation is done with:
$ cd ~/Downloads/
$ unzip logkeys-master.zip
$ cd logkeys-master

$ ./autogen.sh
$ cd build
$ ../configure

$ make
$ sudo make install


text:
Q: Why do notebooks sometimes need a battery reset? I just recently had to reset the battery [disconnect and replace the battery] of my Acer Swift 1 since it wouldn't turn on. To my surprise they actually built in a little hole in the back of the device that enables resetting it with a paperclip.
This made wonder however. I've had this issue with almost every notebook i've owned so far. Can someone explain to me what causes it?
Thanks


text:
Q: In python, when does pass by reference occur? I have a code as below,
attractions = [[] for i in range(5)]

def add_attraction(attraction):
  attractions_for_destination = attractions[2]
  attractions_for_destination.append(attraction)
  return

pass by reference occurs in 3rd line "attractions_for_destination = attractions[2]". The general idea of pass by reference that I have is that it happens between actual parameter and formal parameter. But the above line is a simple assignment code. Can pass by reference happen in a simple assignment code?
If so, if I write
attractions_for_destination = attractions[2] + ": best attraction site"

will altering the value force the newly made variable to use a new memory space?

A: Saying pass by reference or pass by value isn't really applicable to python. For example consider Java. Everything in Java is pass by value, everything. However the value of an object is the reference to the object. So it is, in a way, pass by reference since mutating the object will be reflected to the calling context. Calling it "pass by value" is a bit confusing since for people used to C-family (where this distinction is more straightforward) assume that pass by value means you won't modify the underlying argument passed.
So saying Java is "pass by value" is true but possibly confusing. It is a more relevant statement at much lower levels of the language (like when talking about how the compiler handles passing arguments but not at the level of application programmer).
Python is similar. The confusion about the Java example actually lead Python to not say if it is pass by value/reference. http://stupidpythonideas.blogspot.com/2013/11/does-python-pass-by-value-or-by.html
So for programming, it is save to assume that any object is "passed by reference" (technically no but essentially yes). It is more complicated than that but that link explains it in more depth.


text:
Q: How to store images in DB from DataGridView - C#? I have DataGridView control in my form and the last column type is image.
How I can let the user select image in DataGridView and save it in the DB?
Thanks in advance.

A: Don't store the image itself in the DB bt in the filesystem and in tue DB store the images name only. This is a better option than stuffing data into DB blobs.

A: You can store arbitrary files in a SQL Server database by using a field with type BLOB ("Binary Large OBject"). Create a column of this type in your table, then you can load file data into it by referencing a file on the hard drive, probably using a stored procedure
There are quite a few articles on using BLOBS; here is a good-looking tutorial: Part one, part two.
Here is some sample code from that article that is specifically adding a BLOB value from a file:
INSERT INTO BLOBTest
(BLOBName, BLOBData)
SELECT 'First test file',
    BulkColumn FROM OPENROWSET(
        Bulk 'C:\temp\nextup.jpg', SINGLE_BLOB) AS BLOB

Whether or not you should do this is an entirely different question.


text:
Q: git lfs "Object does not exist on the server" We've got a git repo which uses lfs for large file tracking. We've been using it for quite a while and it's going ok. However, we have 3 objects which are referenced in a commit but haven't been uploaded to the server. I've tried to get everyone to do a full push of all of their lfs objects, but it's tough to get everyone who has had anything to do with the repo to do this.
Is there anything we can do to avoid this error?
Alternatively, how can I find out which file it is pointing to and which commit so that I can more intelligently figure out who is responsible and get them to push all their files from their machine (if they still have it)?


text:
Q: How to get all parametrs from get request in Param in their sequence I have such get request: localhost:8080/check?id=10&id=1&num=2&id=13
I get params like this:
@GetMapping("/check")
@ResponseBody
public void getCheck(@RequestParam LinkedMultiValueMap<String,Long> ex){
    System.out.println(ex);
}

Console: {id=[10, 1, 13], num=[2]}
But I need to get all data in its sequence like this:
{id=[10],id=[1],num=[2],id=[13]}
How can I do this?


text:
Q: Splitting HTML file doesn't work I'm trying to build very simple web page (one page , spited into 2 parts, each part will have it's own html file):
Welcome.html & Welcome.css:

        <link rel="stylesheet" type="text/css" href="Welcome.css">

            bottom

#bottom {
    height: 50%;
    background-color: blue;
}

#top {
    height: 50%;
    background-color: orange;
}

I want that Welcome.html file will get the top content from external html file
Top.html

      Test -> TOP

But is seems that there is no request for Top.html file in the Node.js Log:
var express = require('express');
var app = express();
var fs = require('fs');
var bodyParser = require('body-parser');

app.use(bodyParser.json())

/*
 *  Home page
 */
app.get('/', function (req, res) {
   clearLogScreen();
   console.log("[/] Got request for '/'");
   res.sendFile( __dirname + '/Welcome.html');
})

app.get('/Welcome.css', function(req, res) {
  console.log("[/Welcome] Got request for 'Welcome.css'");
  res.sendFile(__dirname + "/" + "Welcome.css");
});

app.get('/Top', function(req, res) {
  console.log("[/Top] Got request for 'Welcome.top'");
  res.sendFile(__dirname + "/" + "Top.html");
});

/*
 *  Startup
 */
var server = app.listen(8081, function () {
   var host = server.address().address
   var port = server.address().port

   // start
   console.log("-----------------------------")
   console.log("Dirname: " + __dirname);
   console.log("App listening at http://%s:%s", host, port)
})

I guess I'm missing something very easy, but can't find the mistake.

A: Kindly checkout templatesjs; It will help insert html inside another html.

A: I'm not sure what "w3-include-html" is, but if it does what it is supposed to do (based on the name), then try changing its value from "/Top.html" to "/Top". Or, alternatively, try changing the url route "/Top" to "/Top.html" in your express app.
One side note: Your included html ("Top.html") should not be a complete html. Try removing html, header and body tags. It should be a fragment.


text:
Q: is the window global object reassignable? As simple as this:

window = 'Hello world';
console.log(window);

I am pretty sure this should work and post in console 'Hello world', but it doesn't.

A: No. In sloppy mode, it'll fail silently. In strict mode, you'll see an explicit error.

'use strict';
window = 'Hello world';
console.log(window);

You can't reassign it. I think the best you could do is to create a new variable named window not on the top level.

(() => {
  const window = 'Hello world';
  console.log(window);
})();


text: Q: How can we configure different columns preferences for each repository and cabinet in Documentum webtop Currently when I set columns in "tool->preference" the same columns starts to show for all the repository, even if the columns/attribute I chose in first repository does not exists in 2nd repository. Still it shows those attributes/columns in second repository.


text:
Q: Flask-SQLAlchemy,How to sort results in Many-to-Many Relationship? I am using flask-sqlalchemy.
I want to add an ORDER column in Many-to-Many Relationship.
my models:
image_category_association = db.Table('category_image_relation',
    db.Column('id', db.Integer, primary_key=True),
    db.Column('category_id', db.Integer, db.ForeignKey('image_category.category_id')),
    db.Column('image_id', db.Integer, db.ForeignKey('image.image_id')),
    db.Column('order', db.Integer, unique=True, autoincrement=True)
)

class ImageCategory(db.Model):
    __bind_key__ = 'ads'
    __tablename__ = 'image_category'

    category_id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255), default='')
    add_time = db.Column(db.Integer, default=0)
    images = db.relationship('Image', secondary=image_category_relation, backref='categories', lazy='dynamic')

class Image(db.Model):
    __bind_key__ = 'ads'
    __tablename__ = 'image'

    image_id = db.Column(db.Integer, primary_key=True)
    add_time = db.Column(db.Integer, default=0)
    hash = db.Column(db.String(64), default='')
    url = db.Column(db.String(255), default='')

category = ImageCategory.query.get(1)
category.images.append(image1, image2, image3)
images = category.images.all()  # order by the ORDER column

Is it possible to update the ORDER column value in table image_category_association?
And how do i sort the category.images.all() order by the ORDER column.

A: Use an association object - see self-contained example below (I've left out some of your fields). The order is created/updated in the ImageCategoryToImageAssociation class - see the build_db method to see how it's used.
Also note the order_by="ImageCategoryToImageAssociation.order" in the ImageCategory images attribute db.relationship definition - category_1 has its images inserted out-of-order but querying the database returns them in sorted order.
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = 'super-secret'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
app.config['SQLALCHEMY_ECHO'] = True
db = SQLAlchemy(app)

class ImageCategoryToImageAssociation(db.Model):
    __tablename__ = 'image_categories_to_image_association'
    image_category_id = db.Column(db.Integer, db.ForeignKey('image_categories.id'), primary_key=True)
    image_id = db.Column(db.Integer, db.ForeignKey('images.id'), primary_key=True)
    order = db.Column(db.Integer, default=0)
    image = db.relationship("Image", back_populates="categories")
    category = db.relationship("ImageCategory", back_populates="images")

class ImageCategory(db.Model):
    __tablename__ = 'image_categories'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255), unique=True)
    images = db.relationship(ImageCategoryToImageAssociation, back_populates="category", order_by="ImageCategoryToImageAssociation.order")

class Image(db.Model):
    __tablename__ = 'images'
    id = db.Column(db.Integer, primary_key=True)
    url = db.Column(db.String(255), default='')
    categories = db.relationship(ImageCategoryToImageAssociation, back_populates="image")

@app.route('/')
def index():

    _html = ""
    categories = ImageCategory.query.all()
    for category in categories:
        _html += "
Category : {category}
".format(category=category.name)
        _html += "
"
        for assoc in category.images:
            _html += "
Image : {url}; Order: {order}
".format(url=assoc.image.url, order=assoc.order)

        _html += "
"

    return _html

def build_db():

    db.drop_all()
    db.create_all()

    # Add Categories
    category_1 = ImageCategory(name="First Category")
    db.session.add(category_1)
    category_2 = ImageCategory(name="Second Category")
    db.session.add(category_2)

    # Add Images
    image_1 = Image(url="First Image")
    db.session.add(image_1)
    image_2 = Image(url="Second Image")
    db.session.add(image_2)

    image_3 = Image(url="Third Image")
    db.session.add(image_3)

    # Associate images with category 1
    a_1 = ImageCategoryToImageAssociation(order=0)
    a_1.image = image_1
    category_1.images.append(a_1)

    a_2 = ImageCategoryToImageAssociation(order=2)
    a_2.image = image_2
    category_1.images.append(a_2)

    a_3 = ImageCategoryToImageAssociation(order=1)
    a_3.image = image_3
    category_1.images.append(a_3)

    # Associate images with category 2 in reverse order
    a_1 = ImageCategoryToImageAssociation(order=2)
    a_1.image = image_1
    category_2.images.append(a_1)

    a_2 = ImageCategoryToImageAssociation(order=1)
    a_2.image = image_2
    category_2.images.append(a_2)

    a_3 = ImageCategoryToImageAssociation(order=0)
    a_3.image = image_3
    category_2.images.append(a_3)

    db.session.commit()

@app.before_first_request
def before_first_request():
    build_db()

if __name__ == '__main__':
    app.run()


text: Q: For which values of  the graph  (hypercube) admits an Eulerian circuit I have found Qn is an n regulat graph which means if n is even, it admits an Eulerian circuit, is this justification correct for my math homework or do I need to go into more details? Thank you


text:
Q: Login using different user in a different page? using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using MSSQLConnector;
using System.Data;

namespace SoftwareAnalysisAndDesign.SAD
{
    public partial class OnlineAppSyss : System.Web.UI.Page
    {
        private MSConnector connector = new MSConnector();
        //string queries for each DataSet
        string query = null;
        string teacherquery = null;
        string subjectquery = null;
        string schoolfeequery = null;
        string accountdetailsquery = null;
        int rowcounter = 0;
        int teachercounter = 0;

        //DataSet and DataTable initialization
        private DataSet studentData;
        private DataSet subjectData;
        private DataSet schoolfeeData;
        private DataSet teacherData;
        private DataSet accountdetailsData;
        private DataTable subjectTable;
        private DataTable schoolfeeTable;
        private DataTable accountdetailsTable;
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            if (dropdownrole.SelectedItem.Value == "Admin")
            {
                Admin();
            }
            else if (dropdownrole.SelectedItem.Value == "Student")
            {
                Student();
            }
            else if (dropdownrole.SelectedItem.Value == "Teacher")
            {
                Teacher();
            }
        }
        public void Admin()
        {
            //String decleration
            string adminusername = (this.UserName.Value);
            string adminpass = (this.Password.Value);

            try
            {
                if (adminusername == "admin" && adminpass == "cmpe1234")
                {
                    Session["adminlogin"] = adminusername;
                    Response.Redirect("AdministratorPage.aspx");
                }
            }
            catch
            {
                Response.Write("<script language=javascript>alert('Username and password does not match. Try again');</script>");
            }
        }
        public void Student()
        {
            //Connection String
            connector.ConnectionString = "Data Source=keith;Initial Catalog=SAD;Integrated Security=True";

            //String decleration
            string username = (this.UserName.Value);
            string pass = (this.Password.Value);

            //query database from sql server management studio for student
            query = "select studentid,password,firstname,lastname,course,year from student";

            //execute query for student
            studentData = connector.ExecuteQuery(query);

            try
            {
                for (; ; )
                {
                    //string decleration and getting each rows of the Student database
                    string userid = studentData.Tables[0].Rows[rowcounter]["StudentID"].ToString();
                    string password = studentData.Tables[0].Rows[rowcounter]["Password"].ToString();
                    string firstname = studentData.Tables[0].Rows[rowcounter]["FirstName"].ToString();
                    string lastname = studentData.Tables[0].Rows[rowcounter]["LastName"].ToString();
                    string course = studentData.Tables[0].Rows[rowcounter]["Course"].ToString();
                    string year = studentData.Tables[0].Rows[rowcounter]["Year"].ToString();

                    //For Student Condition
                    if (username == userid && pass == password)
                    {
                        //For Student Data Sessions
                        Session["login"] = userid;
                        Session["firstname"] = firstname;
                        Session["lastname"] = lastname;
                        Session["course"] = course;
                        Session["year"] = year;

                        //For Account Details Data
                        accountdetailsquery = "select StudentID,FirstName,MiddleName,LastName,Age,Province,City,Course,Year,College,Department,ContactNumber,Email from student where studentid = " + username + "";

                        //query database from sql server management studio for student as accountDetails Information
                        accountdetailsData = connector.ExecuteQuery(accountdetailsquery);

                        accountdetailsTable = accountdetailsData.Tables[0];
                        Session["AccountDetails"] = accountdetailsTable;

                        //For SchoolFee Data
                        //query database from sql server management studio for schoolfee
                        schoolfeequery = "select DatePaid,AmountPaid,CurrentBalance,TotalBalance,Semester from schoolfee where studentid = " + username + "";

                        //execute query for schoolfee
                        schoolfeeData = connector.ExecuteQuery(schoolfeequery);

                        //get all data rows for SchoolFee and store it into DataTable
                        schoolfeeTable = schoolfeeData.Tables[0];
                        Session["SchoolFee"] = schoolfeeTable;

                        //For Subject Data
                        //query database from sql server management studio for subject
                        subjectquery = "select CourseNo,CourseDescription,Units,Day,StartTime,EndTime,Room from subject where studentid = " + username + "";

                        //execute query for subject
                        subjectData = connector.ExecuteQuery(subjectquery);

                        //get all data rows for Subject and store it into DataTable
                        subjectTable = subjectData.Tables[0];
                        Session["Subjects"] = subjectTable;

                        //Redirect the page to Student Page after the user successfully logs in.
                        Response.Redirect("StudentPage.aspx", true);

                        break;
                    }
                    else
                    {
                        rowcounter++;
                    }
                }

            }
            catch
            {
                Response.Write("<script language=javascript>alert('Username and password does not match. Try again');</script>");
            }

        }
        public void Teacher()
        {
            //Connection String
            connector.ConnectionString = "Data Source=keith;Initial Catalog=SAD;Integrated Security=True";

            //String decleration
            string username = (this.UserName.Value);
            string pass = (this.Password.Value);

            //query database from sql server management studio for student
            teacherquery = "select teacherid,password,firstname,lastname,department,position from teacher";

            //execute query for student
            teacherData = connector.ExecuteQuery(teacherquery);

            try
            {
                for (; ; )
                {
                    //string decleration and getting each rows of the Teacher database
                    string teacheruserid = teacherData.Tables[0].Rows[rowcounter]["TeacherID"].ToString();
                    string teacherpassword = teacherData.Tables[0].Rows[rowcounter]["Password"].ToString();
                    string teacherfirstname = teacherData.Tables[0].Rows[rowcounter]["FirstName"].ToString();
                    string teacherlastname = teacherData.Tables[0].Rows[rowcounter]["LastName"].ToString();
                    string teacherdepartment = teacherData.Tables[0].Rows[rowcounter]["Department"].ToString();
                    string teacherposition = teacherData.Tables[0].Rows[rowcounter]["Position"].ToString();

                    //For Teacher Condition
                    if (username == teacheruserid && pass == teacherpassword)
                    {
                        Session["teacherlogin"] = teacheruserid;
                        Session["teacherfirstname"] = teacherfirstname;
                        Session["teacherlastname"] = teacherlastname;
                        Session["department"] = teacherdepartment;
                        Session["position"] = teacherposition;

                        //Redirect the page to Student Page after the user successfully logs in.
                        Response.Redirect("TeacherPage.aspx", true);
                        break;
                    }
                    else
                    {
                        rowcounter++;
                    }
                }
            }
            catch
            {
                Response.Write("<script language=javascript>alert('Username and password does not match. Try again (teacher)');</script>");
            }
        }
    }
}

My problem is I can't access the teacher page in this code, it will only access the student page. What Condition should I use in my system to avoid redundancy?
This is my aspx Code for dropdownlist:
<asp:DropDownList runat="server" id="dropdownrole">
    <asp:ListItem Text="Admin">Admin</asp:ListItem>
    <asp:ListItem Text="Student">Student</asp:ListItem>
    <asp:ListItem Text="Teacher">Teacher</asp:ListItem>
</asp:DropDownList>

and the login button:
 protected void Button1_Click(object sender, EventArgs e)
        {
            if (dropdownrole.SelectedItem.Value == "Admin")
            {
                Admin();
            }
            else if (dropdownrole.SelectedItem.Value == "Student")
            {
                Student();
            }
            else if (dropdownrole.SelectedItem.Value == "Teacher")
            {
                Teacher();
            }
        }

I want to have a condition that If a username and password input detects either of the 2 users, it will redirect to their specific webpage. Please Help.

A: You didn't select teacher password in your teacherquery therefor the teacherpassword is always null that why the condition password == teacherpassword is always false.
Like DPac pointed out, you don't need to query all of rows just to verify the username & password, just select username & password only first, if it is correct then select all of rows you want and assign them to sessions, then redirect.
About the problem if student's username is as same as teacher's username, there will be whole lot of troubles, to avoid it (without doing whole lot of thing) is to add 1 more int row in both tables named userRole (ex: 1 = admin, 2 = teacher, 3 = student etc.) and allow it to be null. After that go in each table and update that row to proper value (for example in student table: UPDATE student SET userRole = 3). After update all of row then go to Design and set the userRole to not allow null Now the username + userRole combination (should have been your primary key) will make your life much easier.

A: Although i would prefer @ronaldinho's way of giving a RoleId column  to both tables.Here is what you can do without disturbing the database.
Just add a dropdownlist with items "Teacher" and "Student" on your login page.So when some one tries to log in they have to select their role and then enter. This way you can direct the code as
   protected void Button1_Click(object sender, EventArgs e)
    {
        if (dropdownrole.SelectedItem.Text == "Admin")
        {
            Admin();
        }
        else if (dropdownrole.SelectedItem.Text == "Student")
        {
            Student();
        }
        else if (dropdownrole.SelectedItem.Text == "Teacher")
        {
            Teacher();
        }
    }

See if it is possible for you


text:
Q: Modal opens onload page I have this code for modal, but it only appears when the button assigned for this modal is clicked.
I want my modal to be automatically loaded along with the page without clicking any button.
How will I do that?
jQuery(document).ready(function() {

//select all the a tag with name equal to modal
jQuery('a[name=account]').click(function(e) {
    //Cancel the link behavior
    e.preventDefault();

    //Get the A tag
    var id = jQuery(this).attr('href');

    //Get the screen height and width
    var maskHeight = jQuery(document).height();
    var maskWidth = jQuery(window).width();

    //Set heigth and width to mask to fill up the whole screen
    jQuery('#mask').css({'width':maskWidth,'height':maskHeight});

    //transition effect
    jQuery('#mask').fadeIn(400);
    jQuery('#mask').fadeTo(400,0.8);

    //Get the window height and width
    var winH = jQuery(window).height();
    var winW = jQuery(window).width();

    //Set the popup window to center
    jQuery(id).css('top',  winH/2-jQuery(id).height()/2);
    jQuery(id).css('left', winW/2-jQuery(id).width()/2);

    //transition effect
    jQuery(id).fadeIn(400);

});

//if close button is clicked
jQuery('.window .close').click(function (e) {
    //Cancel the link behavior
    e.preventDefault();

    jQuery('#mask').hide();
    jQuery('.window').hide();
});

jQuery(window).resize(function () {

    var box = jQuery('#boxes .window');

    //Get the screen height and width
    var maskHeight = jQuery(document).height();
    var maskWidth = jQuery(window).width();

    //Set height and width to mask to fill up the whole screen
    jQuery('#mask').css({'width':maskWidth,'height':maskHeight});

    //Get the window height and width
    var winH = jQuery(window).height();
    var winW = jQuery(window).width();

    //Set the popup window to center
    box.css('top',  winH/2 - box.height()/2);
    box.css('left', winW/2 - box.width()/2);

});
});

A: Like this
function pop(id) {

    //Get the screen height and width
    var maskHeight = jQuery(document).height();
    var maskWidth = jQuery(window).width();

    //Set heigth and width to mask to fill up the whole screen
    jQuery('#mask').css({'width':maskWidth,'height':maskHeight});

    //transition effect
    jQuery('#mask').fadeIn(400);
    jQuery('#mask').fadeTo(400,0.8);

    //Get the window height and width
    var winH = jQuery(window).height();
    var winW = jQuery(window).width();

    //Set the popup window to center
    jQuery(id).css('top',  winH/2-jQuery(id).height()/2);
    jQuery(id).css('left', winW/2-jQuery(id).width()/2);

    //transition effect
    jQuery(id).fadeIn(400);

}

jQuery(document).ready(function() {
    pop("some ID");
    //select all the a tag with name equal to modal
    jQuery('a[name=account]').click(function(e) {
      //Cancel the link behavior
      e.preventDefault();

      //Get the A tag
      var id = jQuery(this).attr('href');
      pop(id);

    });
.
.
.

A: You can put jQuery('a[name=account]').trigger('click') at the end of your .ready function handler. But note that with selector like 'a[name=account]' click will be triggered on all <a name="account" and that may cause multiple modal windows to appear. Or popup for the last a will appear. Possibly you will need to set an id for some  in order to call only popup of that
jQuery(document).ready(function() {

//select all the a tag with name equal to modal
jQuery('a[name=account]').click(function(e) {
     ....
});

//if close button is clicked
jQuery('.window .close').click(function (e) {
    .....
});

jQuery(window).resize(function () {

    ....

});
jQuery('a[name=account]').trigger('click');
});


text:
Q: SUDS and Namespaces in XML Attributes I'm having a bit of trouble getting SUDS to play nicely with the NetSuite SOAP API.  I've played around with SoapUI to send NetSuite XML that works for the call that I want, but I'm not able to get it to work with Python.  Here's the working XML:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:urn="urn:messages_2015_1.platform.webservices.netsuite.com"
xmlns:urn1="urn:core_2015_1.platform.webservices.netsuite.com"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
>
   <soapenv:Header>
      <urn:preferences>
      </urn:preferences>
      <urn:partnerInfo>
      </urn:partnerInfo>
      <urn:applicationInfo>

      </urn:applicationInfo>
      <urn:passport>
         <urn1:email>*****</urn1:email>
         <urn1:password>*****</urn1:password>
         <urn1:account>*****</urn1:account>
         <!--Optional:-->
         <urn1:role internalId=*****>
         </urn1:role>
      </urn:passport>
   </soapenv:Header>
   <soapenv:Body>
      <urn:get>
        <urn1:baseRef internalId="2026" type="customer" xsi:type="urn1:RecordRef"/>
      </urn:get>
   </soapenv:Body>
</soapenv:Envelope>

In Python I've generated a RecordRef object and populated it, but it doesn't care for my input:
>>> recordRef = client.factory.create('ns4:RecordRef')
>>> recordRef
(RecordRef){
   name = None
   _internalId = ""
   _externalId = ""
   _type = ""
 }
>>> recordRef._internalId = 2026
>>> recordRef._type = 'customer'
>>> recordRef
(RecordRef){
   name = None
   _internalId = 2026
   _externalId = ""
   _type = "customer"
 }
>>> client.service.get(recordRef)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/suds/client.py", line 521, in __call__
    return client.invoke(args, kwargs)
  File "/usr/local/lib/python2.7/dist-packages/suds/client.py", line 581, in invoke
    result = self.send(soapenv)
  File "/usr/local/lib/python2.7/dist-packages/suds/client.py", line 619, in send
    description=tostr(e), original_soapenv=original_soapenv)
  File "/usr/local/lib/python2.7/dist-packages/suds/client.py", line 670, in process_reply
    raise WebFault(fault, replyroot)
suds.WebFault: Server raised fault: 'org.xml.sax.SAXException: Invalid type: customer'
>>>

When I take a look at the XML that's being sent out I notice that xsi:type is being set, but type is not.

If I set customer (really xsi:customer) to the same value that worked in SoapUI  I get an error about customer not being set:
(ReadResponse){
   status =
      (Status){
         _isSuccess = False
         statusDetail[] =
            (StatusDetail){
               _type = "ERROR"
               code = "RCRD_TYPE_REQD"
               message = "The record type is required."
            },
      }
 }
>>> recordRef
(RecordRef){
   name = None
   _internalId = 2026
   _externalId = ""
   _type = "ns1:RecordRef"
 }

I haven't done anything with SOAP in about five years, and never at all in Python before now.  Any suggestions will be appreciated.

A: Figured it out, I need to write a plugin that calls the marshalled() method:
class FixXML(suds.plugin.MessagePlugin):
        def __init__(self):
                pass

        def marshalled(self, context):
                #the attribute type is really xsi:type, which we need to set but is being handled wrong
                #get the Netsuite data type
                wsdlDataType = context.envelope.getChild('Body').getChild('get').getChild('baseRef').getAttribute('type').getValue()
                #now rewrite xsi:type so its something namespacey
                context.envelope.getChild('Body').getChild('get').getChild('baseRef').getAttribute('type').setValue('ns0:RecordRef')
                #next we need to add a type attribute without a namespace that contains the data type from the wsdl
                typeAttr = suds.sax.attribute.Attribute('type')
                typeAttr.setValue(wsdlDataType)
                context.envelope.getChild('Body').getChild('get').getChild('baseRef').append(typeAttr)


text:
Q: JWT authentication and the purpose of refresh token I'm trying to wrap my mind around JWT authentication. I've read a lot of articles and SO questions, but some of them are getting old and I still didn't get satisfactory answers.
I've read this SO question and from José F. Romaniello's answer I understand that:

*

*with refresh token client requests new access token before the old one has expired (it is normal, expected behavior)

*on mobile apps tokens never expire

Also on auth0 it says:

You can request new access tokens until the refresh token is on the
DenyList. Applications must store refresh tokens securely because they
essentially allow a user to remain authenticated forever.

So what's the point of having time limited access token if refresh token can request for new access tokens forever?
Then I've read this SO question, which references the SO question from above. In his answer qre0ct says:

...assume that if Bob has compromised the refresh token, he would be
using it to generate an access token (because access token is the only
thing which is authorized to access resources through the APIs). As
soon as Bob (attacker) requests with the newly generated access token
because Alice's (genuine user) access token is still valid, the server
would see this as an anomaly, because for a single refresh token there
can be only one authorized access token at a time.

If we presume that it is normal for a client to request new access token at any moment (every hour, or every time the user opens the web application, as José F. Romaniello said), how will server distinguish if it's Alice or Bob who's making a request for a new access token? And why would this be anomaly?
Also, a lot of people say that the advantage of JWT authentication is that server doesn't make DB calls. But from above quotation from auth0, they mention DenyList. So I guess there must be a DB call on every request to check if the token is not blacklisted? Is the no DB calls thing a myth?
And if I have to keep record of blacklisted tokens, why not just use access tokens and blacklist them if necessary? I cannot understand the advantage of having two tokens, because if either one of them gets stolen, the thief can stay logged in forever (especially in the context of mobile apps where refresh token lasts forever)
Thanks in advance for your patience and time.

A: After I've slept it over the things got clear(er).
My problem was that I was observing refresh token exclusively from the point of view of security. And from that point of view I still don't understand if/what advantages usage of refresh token brings.
What I've realized is that the purpose of refresh token is to reduce DB calls - instead of checking if access token is blacklisted on every client request, a DB call is made only when new access token is requested (so every access-token-lifetime), to verify if refresh token is blacklisted or the new access token can be issued.

A: Couple questions here...
Might be easiest to answer this by starting with the intent of each token type - there's actually 3 types of token that all have different uses:

*

*Access token

*ID token

*Refresh token

Access tokens are uses as bearer tokens on back-end API requests and are used for auth. They're often JWTs that don't contain PII. If an access token is compromised (e.g. if it's used in unencrypted request and intercepted) it would typically only have a lifetime of 10-15 mins, so there's a limited time frame where the attacker can use it.
ID tokens are received by public client apps and shouldn't leave the app. They're often JWTs and might contain PII e.g. a users name, email, phone so that the app can just get this information from the ID token without needing to make a back-end request.
Refresh tokens are used to streamline the authentication process for subsequent auths. Instead of having to sign-in with username & password/OTP, you can just use a PIN or biometrics to unlock the refresh token and perform a refresh token exchange to the IDP to get a new access and ID token (and potentially even new refresh tokens if performing refresh token rotation). Refresh tokens are opaque and should be stored securely on the app. There needs to be a bit more security around refresh tokens as they've often got a lifetime of several months whereas a single access token might only have a lifetime of a few minutes - typically 10-15 mins. If a refresh token is compromised, it can be used to get new access tokens until it eventually expires (potentially after multiple months). Refresh tokens should be stored securely on a device - typically the device key-store/chain and not leave the device. Historically refresh tokens have only been used in native apps where they can be stored securely on the device, and NOT in browser-based SPAs, but I think there might be some changes to these guidelines with the advent of refresh token rotation.

For question about using JWT authentication and that server doesn't make DB calls. What is meant here is that JWT auth is distributed. A JWT can be validated by simply verifying the digital signature without needing to make any subsequent network request (aside from an initial lazy loaded request to get the public signing key). Alternatively with opaque tokens, you'd need to make network request every time to some kind of data store to validate the token.

WRT blacklisted tokens, once an access token is issued, we typically don't call back to the IDP to validate the token (it's all distributed auth), so there's no concept of blacklisting an access token. A refresh token on the other hand can be blocked on the IDP, so when a user/device attempts a refresh token exchange (to get new access/ID tokens) the IDP can block the request if the refresh token has been revoked. Note: there are some fine-grained authZ strategies to block access tokens before they expire on your back-end, but it can get quite complex.


text:
Q: Get exit code for Powershell Core script hosted in .NET Core I am attempting to run a set of PowerShell scripts from within a .NET Core app using the framework outlined here. The basic code is below:
using (var ps = Powershell.Create()) {
    ps.AddScript(script);
    var output = new PSDataCollection<PSObject>();
    await ps.InvokeAsync<PSObject, PSObject>(null, output);
}

My question is, how could I retrieve the exit code of the script?

A: This does not appear to be possible, although if it is I would love to know how it is done. As an alternative I am using Write-Output to indicate the exit code before calling exit in my script. Data written using Write-Output is available in the output collection.


text:
Q: SSRS XSLT for XML Output - Transform Subset of Attributes to Elements I'm having trouble wrapping my head around transforming a subset of attributes to child elements. My goal is to have a stylesheet that SSRS can refer to in shaping the output.
The example code I've seen transforms all of the attributes and I can't understand how to be selective.
Here is the source file, output as an XML file from SSRS.
<?xml version="1.0" encoding="utf-8"?>
<Report xsi:schemaLocation="_x0031_4Q_CSV http://MySSRSServer/ReportServer?%2FTRR%20Reports%2F14Q_CSV&rs%3ACommand=Render&rs%3AFormat=XML&rs%3ASessionID=uuurm045z4bsq2maejbbb045&rc%3ASchema=True" Name="14Q_CSV" textbox1="14Q_CSV Period:201711 Publish Date: 12/7/2017 4:38:49 PM" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="_x0031_4Q_CSV">
  <table1>
    <Detail_Collection>
      <Detail ID_RSSD="1037003" D_DT="2017-11-30T00:00:00" CQSCS383="S0004260053" Transtype="I" CQSCF841="2020-01-23T00:00:00" CQSCP082="CUSIP" CQSCP083="31384YCC8" CQSCS370="N" CQSCP084="Agency MBS" CQSCP085="FN 537467" CQSCP087="50768.00" CQSCP088="53330.00" CQSCP089="50667.00" CQSCP090="12484343.00" CQSCP091="0.00" CQSCP092="AFS" CQSCP093="2017-11-30T00:00:00" CQSCP094="0.070363000000" CQSCP095="2000-04-01T00:00:00" CQSCS371="USD" CQSCHK21="105.2563040000" />
      <Detail ID_RSSD="1037003" D_DT="2017-11-30T00:00:00" CQSCS383="S0004260054" Transtype="I" CQSCF841="2020-01-23T00:00:00" CQSCP082="CUSIP" CQSCP083="31384YCD6" CQSCS370="N" CQSCP084="Agency MBS" CQSCP085="FN 537468" CQSCP087="96069.00" CQSCP088="106433.00" CQSCP089="96069.00" CQSCP090="12066524.00" CQSCP091="0.00" CQSCP092="AFS" CQSCP093="2017-11-30T00:00:00" CQSCP094="0.067115000000" CQSCP095="2000-04-01T00:00:00" CQSCS371="USD" CQSCHK21="110.7884470000" />
      <Detail ID_RSSD="1037003" D_DT="2017-11-30T00:00:00" CQSCS383="S0004260057" Transtype="I" CQSCF841="2020-01-23T00:00:00" CQSCP082="CUSIP" CQSCP083="31384YCH7" CQSCS370="N" CQSCP084="Agency MBS" CQSCP085="FN 537472" CQSCP087="133804.00" CQSCP088="151158.00" CQSCP089="134964.00" CQSCP090="6415504.00" CQSCP091="0.00" CQSCP092="AFS" CQSCP093="2017-11-30T00:00:00" CQSCP094="0.064967000000" CQSCP095="2000-04-01T00:00:00" CQSCS371="USD" CQSCHK21="111.9988700000" />
      <Detail ID_RSSD="1037003" D_DT="2017-11-30T00:00:00" CQSCS383="S0004260058" Transtype="I" CQSCF841="2020-01-23T00:00:00" CQSCP082="CUSIP" CQSCP083="31384YCJ3" CQSCS370="N" CQSCP084="Agency MBS" CQSCP085="FN 537473" CQSCP087="188500.00" CQSCP088="198238.00" CQSCP089="186974.00" CQSCP090="7054878.00" CQSCP091="0.00" CQSCP092="AFS" CQSCP093="2017-11-30T00:00:00" CQSCP094="0.074321000000" CQSCP095="2000-04-01T00:00:00" CQSCS371="USD" CQSCHK21="106.0240080000" />
      <Detail ID_RSSD="1037003" D_DT="2017-11-30T00:00:00" CQSCS383="S0004260059" Transtype="I" CQSCF841="2020-01-23T00:00:00" CQSCP082="CUSIP" CQSCP083="31384YCK0" CQSCS370="N" CQSCP084="Agency MBS" CQSCP085="FN 537474" CQSCP087="53662.00" CQSCP088="56159.00" CQSCP089="52828.00" CQSCP090="6033726.00" CQSCP091="0.00" CQSCP092="AFS" CQSCP093="2017-11-30T00:00:00" CQSCP094="0.079403000000" CQSCP095="2000-04-01T00:00:00" CQSCS371="USD" CQSCHK21="106.3062160000" />
      <Detail ID_RSSD="1037003" D_DT="2017-11-30T00:00:00" CQSCS383="S0004260060" Transtype="I" CQSCF841="2020-01-23T00:00:00" CQSCP082="CUSIP" CQSCP083="31384YCL8" CQSCS370="N" CQSCP084="Agency MBS" CQSCP085="FN 537475" CQSCP087="53958.00" CQSCP088="57002.00" CQSCP089="53518.00" CQSCP090="5710436.00" CQSCP091="0.00" CQSCP092="AFS" CQSCP093="2017-11-30T00:00:00" CQSCP094="0.076705000000" CQSCP095="2000-04-01T00:00:00" CQSCS371="USD" CQSCHK21="106.5098890000" />
    </Detail_Collection>
  </table1>
</Report>

I need to retain the first four attributes within the Detail node, rename the node as shown, and transform the rest to child elements of the Detail node.
Here is the desired outcome:

<?xml version="1.0" encoding="UTF-8" standalone="true"?>
<SCRTS_Data_Collect LAST_ASOF_TSTMP="2019-11-06T00:00:00.000" DATA_ASOF_TSTMP="2019-11-06T00:00:00.000">
    <SCRTS_Data_Collect_MS ID_RSSD="1037003" D_DT="2019-09-30T00:00:00" CQSCS383="S0010160276" TRANSTYPE="I">
        <CQSCF841>11/06/2019</CQSCF841>
        <CQSCP082>CUSIP</CQSCP082>
        <CQSCP083>36202K2Q7</CQSCP083>
        <CQSCS370>N</CQSCS370>
        <CQSCP084>Agency MBS</CQSCP084>
        <CQSCP085>G2 8883</CQSCP085>
        <CQSCP087>8917</CQSCP087>
        <CQSCP088>9008</CQSCP088>
        <CQSCP089>8911</CQSCP089>
        <CQSCP090>5200000</CQSCP090>
        <CQSCP091>0</CQSCP091>
        <CQSCP092>AFS</CQSCP092>
        <CQSCP093>09/30/2019</CQSCP093>
        <CQSCP094>0.07108</CQSCP094>
        <CQSCP095>10/07/2000</CQSCP095>
        <CQSCS371>USD</CQSCS371>
        <CQSCHK21>101.090333</CQSCHK21>
    </SCRTS_Data_Collect_MS>
</SCRTS_Data_Collect>

The stylesheet I've been working on has the following code:

  <!-- rule to copy everything else  xmlns="_x0031_4Q_CSV" -->
  <xsl:template match="*/@*" xmlns="_x0031_4Q_CSV">

    <xsl:element name="{name()}">
    <xsl:value-of select="."/>
    </xsl:element>

  <xsl:apply-templates/>
  </xsl:template>

Obviously this transforms all of the attributes to elements. I've put a variety of node paths in place of the */@ match, but then I get nothing back, so that's clearly wrong.
Apologies in advance if this is not clear. I haven't worked with XSLT for quite a few years.

A: Niether your stylesheet it's complete nor your output it's well explained, but for transforming attibutes into elements you could a transformation similar to this:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:d="_x0031_4Q_CSV">
  <xsl:template match="node()|@*">
    <xsl:copy>
        <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>
  <xsl:template match="d:Detail">
    <xsl:variable name="white-list" select="@ID_RSSD|@D_DT|@CQSCS383|@Transtype"/>
    <xsl:copy>
        <xsl:apply-templates select="$white-list"/>
        <xsl:apply-templates select="@*[count(.|$white-list)!=count($white-list)]"
                             mode="element"/>
        <xsl:apply-templates select="node()"/>
    </xsl:copy>
  </xsl:template>
  <xsl:template match="@*" mode="element">
    <xsl:element name="{name()}">
        <xsl:value-of
            select="."/>
    </xsl:element>
  </xsl:template>
</xsl:stylesheet>

Output:
<Report xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="_x0031_4Q_CSV"
        xsi:schemaLocation="_x0031_4Q_CSV http://MySSRSServer/ReportServer?%2FTRR%20Reports%2F14Q_CSV&rs%3ACommand=Render&rs%3AFormat=XML&rs%3ASessionID=uuurm045z4bsq2maejbbb045&rc%3ASchema=True"
        Name="14Q_CSV"
        textbox1="14Q_CSV Period:201711 Publish Date: 12/7/2017 4:38:49 PM">
  <table1>
      <Detail_Collection>
         <Detail ID_RSSD="1037003"
                 D_DT="2017-11-30T00:00:00"
                 CQSCS383="S0004260053"
                 Transtype="I">
            <CQSCF841 xmlns="">2020-01-23T00:00:00</CQSCF841>
            <CQSCP082 xmlns="">CUSIP</CQSCP082>
            <CQSCP083 xmlns="">31384YCC8</CQSCP083>
            <CQSCS370 xmlns="">N</CQSCS370>
            <CQSCP084 xmlns="">Agency MBS</CQSCP084>
            <CQSCP085 xmlns="">FN 537467</CQSCP085>
            <CQSCP087 xmlns="">50768.00</CQSCP087>
            <CQSCP088 xmlns="">53330.00</CQSCP088>
            <CQSCP089 xmlns="">50667.00</CQSCP089>
            <CQSCP090 xmlns="">12484343.00</CQSCP090>
            <CQSCP091 xmlns="">0.00</CQSCP091>
            <CQSCP092 xmlns="">AFS</CQSCP092>
            <CQSCP093 xmlns="">2017-11-30T00:00:00</CQSCP093>
            <CQSCP094 xmlns="">0.070363000000</CQSCP094>
            <CQSCP095 xmlns="">2000-04-01T00:00:00</CQSCP095>
            <CQSCS371 xmlns="">USD</CQSCS371>
            <CQSCHK21 xmlns="">105.2563040000</CQSCHK21>
         </Detail>
         <Detail ID_RSSD="1037003"
                 D_DT="2017-11-30T00:00:00"
                 CQSCS383="S0004260054"
                 Transtype="I">
            <CQSCF841 xmlns="">2020-01-23T00:00:00</CQSCF841>
            <CQSCP082 xmlns="">CUSIP</CQSCP082>
            <CQSCP083 xmlns="">31384YCD6</CQSCP083>
            <CQSCS370 xmlns="">N</CQSCS370>
            <CQSCP084 xmlns="">Agency MBS</CQSCP084>
            <CQSCP085 xmlns="">FN 537468</CQSCP085>
            <CQSCP087 xmlns="">96069.00</CQSCP087>
            <CQSCP088 xmlns="">106433.00</CQSCP088>
            <CQSCP089 xmlns="">96069.00</CQSCP089>
            <CQSCP090 xmlns="">12066524.00</CQSCP090>
            <CQSCP091 xmlns="">0.00</CQSCP091>
            <CQSCP092 xmlns="">AFS</CQSCP092>
            <CQSCP093 xmlns="">2017-11-30T00:00:00</CQSCP093>
            <CQSCP094 xmlns="">0.067115000000</CQSCP094>
            <CQSCP095 xmlns="">2000-04-01T00:00:00</CQSCP095>
            <CQSCS371 xmlns="">USD</CQSCS371>
            <CQSCHK21 xmlns="">110.7884470000</CQSCHK21>
         </Detail>
         <Detail ID_RSSD="1037003"
                 D_DT="2017-11-30T00:00:00"
                 CQSCS383="S0004260057"
                 Transtype="I">
            <CQSCF841 xmlns="">2020-01-23T00:00:00</CQSCF841>
            <CQSCP082 xmlns="">CUSIP</CQSCP082>
            <CQSCP083 xmlns="">31384YCH7</CQSCP083>
            <CQSCS370 xmlns="">N</CQSCS370>
            <CQSCP084 xmlns="">Agency MBS</CQSCP084>
            <CQSCP085 xmlns="">FN 537472</CQSCP085>
            <CQSCP087 xmlns="">133804.00</CQSCP087>
            <CQSCP088 xmlns="">151158.00</CQSCP088>
            <CQSCP089 xmlns="">134964.00</CQSCP089>
            <CQSCP090 xmlns="">6415504.00</CQSCP090>
            <CQSCP091 xmlns="">0.00</CQSCP091>
            <CQSCP092 xmlns="">AFS</CQSCP092>
            <CQSCP093 xmlns="">2017-11-30T00:00:00</CQSCP093>
            <CQSCP094 xmlns="">0.064967000000</CQSCP094>
            <CQSCP095 xmlns="">2000-04-01T00:00:00</CQSCP095>
            <CQSCS371 xmlns="">USD</CQSCS371>
            <CQSCHK21 xmlns="">111.9988700000</CQSCHK21>
         </Detail>
         <Detail ID_RSSD="1037003"
                 D_DT="2017-11-30T00:00:00"
                 CQSCS383="S0004260058"
                 Transtype="I">
            <CQSCF841 xmlns="">2020-01-23T00:00:00</CQSCF841>
            <CQSCP082 xmlns="">CUSIP</CQSCP082>
            <CQSCP083 xmlns="">31384YCJ3</CQSCP083>
            <CQSCS370 xmlns="">N</CQSCS370>
            <CQSCP084 xmlns="">Agency MBS</CQSCP084>
            <CQSCP085 xmlns="">FN 537473</CQSCP085>
            <CQSCP087 xmlns="">188500.00</CQSCP087>
            <CQSCP088 xmlns="">198238.00</CQSCP088>
            <CQSCP089 xmlns="">186974.00</CQSCP089>
            <CQSCP090 xmlns="">7054878.00</CQSCP090>
            <CQSCP091 xmlns="">0.00</CQSCP091>
            <CQSCP092 xmlns="">AFS</CQSCP092>
            <CQSCP093 xmlns="">2017-11-30T00:00:00</CQSCP093>
            <CQSCP094 xmlns="">0.074321000000</CQSCP094>
            <CQSCP095 xmlns="">2000-04-01T00:00:00</CQSCP095>
            <CQSCS371 xmlns="">USD</CQSCS371>
            <CQSCHK21 xmlns="">106.0240080000</CQSCHK21>
         </Detail>
         <Detail ID_RSSD="1037003"
                 D_DT="2017-11-30T00:00:00"
                 CQSCS383="S0004260059"
                 Transtype="I">
            <CQSCF841 xmlns="">2020-01-23T00:00:00</CQSCF841>
            <CQSCP082 xmlns="">CUSIP</CQSCP082>
            <CQSCP083 xmlns="">31384YCK0</CQSCP083>
            <CQSCS370 xmlns="">N</CQSCS370>
            <CQSCP084 xmlns="">Agency MBS</CQSCP084>
            <CQSCP085 xmlns="">FN 537474</CQSCP085>
            <CQSCP087 xmlns="">53662.00</CQSCP087>
            <CQSCP088 xmlns="">56159.00</CQSCP088>
            <CQSCP089 xmlns="">52828.00</CQSCP089>
            <CQSCP090 xmlns="">6033726.00</CQSCP090>
            <CQSCP091 xmlns="">0.00</CQSCP091>
            <CQSCP092 xmlns="">AFS</CQSCP092>
            <CQSCP093 xmlns="">2017-11-30T00:00:00</CQSCP093>
            <CQSCP094 xmlns="">0.079403000000</CQSCP094>
            <CQSCP095 xmlns="">2000-04-01T00:00:00</CQSCP095>
            <CQSCS371 xmlns="">USD</CQSCS371>
            <CQSCHK21 xmlns="">106.3062160000</CQSCHK21>
         </Detail>
         <Detail ID_RSSD="1037003"
                 D_DT="2017-11-30T00:00:00"
                 CQSCS383="S0004260060"
                 Transtype="I">
            <CQSCF841 xmlns="">2020-01-23T00:00:00</CQSCF841>
            <CQSCP082 xmlns="">CUSIP</CQSCP082>
            <CQSCP083 xmlns="">31384YCL8</CQSCP083>
            <CQSCS370 xmlns="">N</CQSCS370>
            <CQSCP084 xmlns="">Agency MBS</CQSCP084>
            <CQSCP085 xmlns="">FN 537475</CQSCP085>
            <CQSCP087 xmlns="">53958.00</CQSCP087>
            <CQSCP088 xmlns="">57002.00</CQSCP088>
            <CQSCP089 xmlns="">53518.00</CQSCP089>
            <CQSCP090 xmlns="">5710436.00</CQSCP090>
            <CQSCP091 xmlns="">0.00</CQSCP091>
            <CQSCP092 xmlns="">AFS</CQSCP092>
            <CQSCP093 xmlns="">2017-11-30T00:00:00</CQSCP093>
            <CQSCP094 xmlns="">0.076705000000</CQSCP094>
            <CQSCP095 xmlns="">2000-04-01T00:00:00</CQSCP095>
            <CQSCS371 xmlns="">USD</CQSCS371>
            <CQSCHK21 xmlns="">106.5098890000</CQSCHK21>
         </Detail>
      </Detail_Collection>
  </table1>
</Report>

Do note: attributes should be output before any other node type, Kaysian method for exclusion.


text:
Q: How do I Make Particle Object follow Mouse Movement I want the particle object to simply follow the mouseX and mouseY location on movement. Can I replace the "origin" values with a mouseX and Y somehow?
  void run() {
    update();
    display();
  }

  // Method to update position
  void update() {
    velocity.add(acceleration);
    location.add(velocity);
    lifespan -= 2.0;
  }

    // Method to display
  void display() {
    stroke(0, lifespan);
    strokeWeight(2);
    fill(127, lifespan);
    ellipse(location.x, location.y, 12, 12);
  }

  // Is the particle still useful?
  boolean isDead() {
    if (lifespan < 0.0) {
      return true;
    } else {
      return false;
    }
  }
 }

A: Take a look at this example:
PVector pos;
PVector vel;
PVector acc;

void setup()
{
  size(400, 400);
  pos = new PVector(width / 2, height / 2);
  vel = new PVector(0, 0);
  acc = new PVector(0, 0);
}

void draw()
{
  background(255);
  followMouse();
  update();
  ellipse(pos.x, pos.y, 10, 10);
}

void followMouse()
{
  PVector mouse = new PVector(mouseX, mouseY);
  //calculating what acceleration would be needed to instantly reach the mouse
  acc = mouse.sub(pos);
  //reducing the acceleration to not reach the mouse instantly
  acc.mult(0.1);
}

void update()
{
  vel.add(acc);
  //dampening the velocity, so the ball gets slower when close to the mouse
  vel.mult(0.8);
  pos.add(vel);
}

A: This example is even simpler and easier to understand - hope it helps.
float x;
float y;
float easing = 0.05;

void setup() {
  size(640, 360);
  noStroke();
}

void draw() {
  background(51);

  float targetX = mouseX;
  float dx = targetX - x;
  x += dx * easing;

  float targetY = mouseY;
  float dy = targetY - y;
  y += dy * easing;

  ellipse(x, y, 66, 66);
}

A: Processing's lerp() function is suitable for this (as you're looking for the particle to lerp towards the mouse cursor).
posX = lerp(posX, mouseX, 0.5);
posY = lerp(posY, mouseY, 0.5);

The final parameter (0.5 here) is the amount to interpolate between the two values where 0.1 is very near the current particle position; 0.5 is halfway in-between the particle position and cursor position, etc.

Lerp is short for linear interpolation. You may find other forms of interpolation (or easing) to be more suitable to model the movement of your particle, such those from the penner easing collection:


text:
Q: Parallel Knight's Tour algorithm Currently I have a knight's tour algorithm that is working.
I uses a combination of:

*

*Backtracking

*Warnsdorf's Rule

The algorithm does the following:
Checks to see if the board is solved (all squares visited)
    If true: return true
else proceed:

Make a set of possible moves from current positions
Sort the set based on the number of moves available from those positions.

Go through the set. (Recursive call made here)
    If returned True:
       Set Solution board to appropriate number
       Return true
    else
      go back to last position
      return false.

It works okay. It is not the best solution.
I am trying to increase the speed using parallelization, in particular, using C++ threading (#include<thread>).
What is the algorithm for this? So far the only ways I have tried have false sharing issues, shared memory issues or won't run at all.

A: Granted this is for C++, after calling the #include<thread> header, a simple way of creating threads is:
#include <iostream>
#include <thread>

void testThread()
{
    std::cout<<"Thread\n";
}

int main(int argc, char * argv[])
{
    std::testThread t(testThread);
    t.join();

    return 0;
}

The std::testThread t(testThread); calls the thread creation while t.join(); joins them after completion. But this is all without using locks. If I were you I would go over same examples online - there are a ton of resources - that show how to implement locks in a safe manor.
A thing to note is that you must make sure that the sequential version of the code can actually benefit from being run in parallel since thread creation can be costly.


text:
Q: Prove that $x^{15}-4x^7+2x^5 - 6$ has no roots in $\mathbb{Q}$
Prove $x^{15}-4x^7+2x^5 - 6$ has no roots in $\mathbb{Q}$.

I know I've learned the process for this before but I cannot recall how the factoring works.
By the Rational Root Theorem $6$ is our only candidate. If I recall correctly I can use Fermat's Little theorem but I can't find any thing in my old notes.
If anyone can suggest a source for similar stuff, it would be greatly appreciated.

A: You just have to apply the rational root theorem in the correct way.
A polynomial $p(x)=x^m+\ldots+6\in\mathbb{Z}[x]$ has a rational root iff it vanishes at some $x\in\{\pm 1,\pm 2,\pm 3,\pm 6\}$. Your polynomial does not, so it has no rational root.
Tsemo Aristide's answer is even more powerful: by Eisenstein's criterion (wrt $p=2$) your polynomial is irreducible over $\mathbb{Q}$.

A: you can apply the Eisenstein for p=2
https://en.wikipedia.org/wiki/Eisenstein%27s_criterion


text:
Q: Is it possible to use extract-struct-info outside a macro? Consider the following racket code to get a list of accessors of a given struct:
#lang racket

(require (for-syntax syntax/parse racket/struct-info racket/list))

(struct point [x y])

;; get the list of accessors from a struct
;; ex. (get point) = '(point-x point-y)
(define-syntax (get stx)
  (syntax-parse stx
    [(_ struct)

     (define struct-info (extract-struct-info (syntax-local-value #'struct)))
     (define accessors-list (map syntax-e  (fourth struct-info)))

     #``(#,@accessors-list)]))

(get point)

Using syntax-local-value, we can extract the value of the identifier bound by the pattern variable struct.
Using extract-struct-info, we can extract the structure type information in a list form (it has 6 elements). From here the accessors list can be extracted (it's the fourth element in the list).
Question
How can I access the information about a struct (as shown in Structure Type Transformer Binding) at the non-macro level? The two functions above cannot be used directly on structs outside a transformer because the struct is a procedure at that point (and extract-struct-info takes in a struct-info).

A: You cannot use syntax-local-value and extract-struct-info at run time. You must use run-time struct introspection instead.
If you make your struct transparent, like this:
(struct point [x y] #:transparent)

then you can get analogous values from a point instance using struct-info and struct-type-info:
(define a-point (point 3 4))
(define-values (type skipped?) (struct-info a-point))
;; type = #<struct-type:point>, skipped = #f
(define-values (name inits autos acc mut imms super super-skipped?)
  (struct-type-info type))
(acc a-point 0) ;; => 3

The value of type above is the same as struct:point (implicitly defined by the struct definition), so if you know you're dealing with a point struct specifically, you coud use that instead. You still need #:transparent (or you need a sufficiently powerful inspector) to use struct-type-info, though.


text:
Q: Ordinal encoding of column in polars I would like to do an ordinal encoding of a column. Pandas has the nice and convenient method of pd.factorize(), however, I would like to achieve the same in polars.
 df = pl.DataFrame({"a": [5, 8, 10], "b": ["hi", "hello", "hi"]})
┌─────┬───────┐
│ a   ┆ b     │
│ --- ┆ ---   │
│ i64 ┆ str   │
╞═════╪═══════╡
│ 5   ┆ hi    │
├╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ 8   ┆ hello │
├╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ 10  ┆ hi    │
└─────┴───────┘

desired result:
┌─────┬─────┐
│ a   ┆ b   │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 0   ┆ 0   │
├╌╌╌╌╌┼╌╌╌╌╌┤
│ 1   ┆ 1   │
├╌╌╌╌╌┼╌╌╌╌╌┤
│ 2   ┆ 0   │
└─────┴─────┘

A: You can join with a dummy DataFrame that contains the unique values and the ordinal encoding you are interested in:
df = pl.DataFrame({"a": [5, 8, 10], "b": ["hi", "hello", "hi"]})

unique = df.select(
    pl.col("b").unique(maintain_order=True)
).with_row_count(name="ordinal")

df.join(unique, on="b")

Or you could "misuse" the fact that categorical values are backed by u32 integers.
df.with_column(
    pl.col("b").cast(pl.Categorical).to_physical().alias("ordinal")
)

Both methods output:
shape: (3, 3)
┌─────┬───────┬─────────┐
│ a   ┆ b     ┆ ordinal │
│ --- ┆ ---   ┆ ---     │
│ i64 ┆ str   ┆ u32     │
╞═════╪═══════╪═════════╡
│ 5   ┆ hi    ┆ 0       │
├╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┤
│ 8   ┆ hello ┆ 1       │
├╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┤
│ 10  ┆ hi    ┆ 0       │
└─────┴───────┴─────────┘

A: Here's another way to do it although I doubt it's better than the dummy Dataframe from @ritchie46
df.with_columns([pl.col('b').unique().list().alias('uniq'),
                pl.col('b').unique().list().arr.eval(pl.element().rank()).alias('uniqid')]).explode(['uniq','uniqid']).filter(pl.col('b')==pl.col('uniq')).select(pl.exclude('uniq')).with_column(pl.col('uniqid')-1)

There's almost certainly a way to improve this but basically it creates a new column called uniq which is a list of all the unique values of the column as well as uniqid which (I think, and seems to be) the 1-index based order of the values.  It then explodes those creating a row for ever value in uniq and then filters out the ones rows that don't equal the column b.  Since rank gives the 1-index (rather than 0-index) you have to subtract 1 and exclude the uniq column that we don't care about since it's the same as b.

A: If the order is not important you could use .rank(method="dense")
>>> df.select(pl.all().rank(method="dense") - 1)
shape: (3, 2)
┌─────┬─────┐
│ a   ┆ b   │
│ --- ┆ --- │
│ u32 ┆ u32 │
╞═════╪═════╡
│ 0   ┆ 1   │
├╌╌╌╌╌┼╌╌╌╌╌┤
│ 1   ┆ 0   │
├╌╌╌╌╌┼╌╌╌╌╌┤
│ 2   ┆ 1   │
└─────┴─────┘

If it is - you could:
>>> (
...    df.with_row_count()
...      .with_columns([
...         pl.col("row_nr").first()
...           .over(col)
...           .rank(method="dense")
...           .alias(col) - 1
...         for col in df.columns
...      ])
...      .drop("row_nr")
... )
shape: (3, 2)
┌─────┬─────┐
│ a   ┆ b   │
│ --- ┆ --- │
│ u32 ┆ u32 │
╞═════╪═════╡
│ 0   ┆ 0   │
├╌╌╌╌╌┼╌╌╌╌╌┤
│ 1   ┆ 1   │
├╌╌╌╌╌┼╌╌╌╌╌┤
│ 2   ┆ 0   │
└─────┴─────┘


text:
Q: Count remaining items in order to calculate percentages I have a page where a user has to drag items from an area elsewhere on a screen.
When all items are dragged out -- 100% task is accomplished.
I would like to calculate what % of the task is accomplished on each drag and drop (when an items is dragged out of gray area).
How do I count remaining items within an area?
How do I convert into percentages?
Shall I calculate what each item's worth in terms of % on page load and then subtract?

A: Something like this should work.
$(document).ready(function(){
    var startCount = $('#launchPad .card').length,

    $("#dropZone").bind( "drop", function(event, ui) {
        var currentCount = $('#launchPad .card').length;
        alert(currentCount/startCount);
    });

});

A: Based on Chris May's comment, try this :
var startCount = $("#launchPad .card").length;

$(".stack").bind( "drop", function(event, ui) {
    var currentCount = startCount - $("#launchPad .card").length + 1;
    alert(currentCount / startCount * 100 + "%");
});

Here it starts since the first drop from 0% to 100%
Fiddle here: http://jsfiddle.net/qQdZy/
EDIT :
This should fix the problem :)
var startCount = $("#launchPad .card").length;

$(".stack").bind( "drop", function(event, ui) {
    var currentCount = startCount - $("#launchPad .card").length;
    if (currentCount != startCount)
        currentCount++;
    alert(currentCount / startCount * 100 + "%");
});

New fiddle : http://jsfiddle.net/qQdZy/1/
NEW EDIT :
Ok, I have changed my solution. Here it works :
var startCount = $("#launchPad .card").length;
var moveFromLaunch = false;

$(".card").bind( "dragstart", function(event, ui) {
  moveFromLaunch = true;
});

$(".stack").bind( "drop", function(event, ui) {
    var currentCount = $("#launchPad .card").length;
    if (moveFromLaunch)
        currentCount--;
    currentCount = startCount - currentCount;
    moveFromLaunch = false;
    alert(currentCount / startCount * 100 + "%");
});

Fiddle : http://jsfiddle.net/qQdZy/3/


text:
Q: C# DriveInfo class causes windows error popup When using the DriveInfo class occasionally displays a windows message popup:

The code that I am working with is fairly standard:
var driveInfos = DriveInfo.GetDrives();
foreach (DriveInfo driveInfo in driveInfos)
{
    if (driveInfo.IsReady &&
        (driveInfo.DriveType == DriveType.Network || driveInfo.DriveType == DriveType.Removable))
        try
        {
            var driveText = string.Format("{0} ({1})", driveInfo.VolumeLabel, driveInfo.Name);

Having had a look on the web it turns out that this is an uncommon error but one that seems be due to environmental issues on the machine (people report it happening when running things like chrome).  A lot of people have fixed this by cleaning up old usb references.
The error doesn't actually stop the program from working normally apart from displaying the message. ( And doesn't get trapped in the catch block )
As its a wpf application that is a going to be distributed and run on end users pc's I rather that the message box is not displayed.  How can I do this and what are the implications?
Edit:
Further investigation showed that this behavior may be being caused because that the code is being executed through a background worker and two instances of it are running at the same time.
Taking the same code and executing without using a background worker it seems to run without issue.

A: I tested your code and it runs with no problem. It seems be using driveInfo.IsReady cause your problem, because of it calls for every drives (CD/DVD/...). Check DriveType first and then check IsReady; like this:
if (driveInfo.DriveType == DriveType.Network ||
    driveInfo.DriveType == DriveType.Removable)
    if (driveInfo.IsReady)
    {
       var driveText = string.Format("{0} ({1})",
                                     driveInfo.VolumeLabel, driveInfo.Name);
    }


text:
Q: Is there a way to estimate the probability that the next number in a time series will be 0? I have a set of 50,000 time series lasting 31 years (each time series for each of 50,000 cells). I would like to find the probability that the next year will go to 0 given the values in previous years.

A: If you assume that you actually can use previous data to infer future data, then:
learn the statistical distribution and use it to predict the probability of a future value.
A simple recipe would be to take all data and sort it into bins, with each bin index representing one of the possible values in that series, normalize the counted values (i.e. divide the count you got by the total amount of samples) and you get the probability for each of the values.
P.S. don't use this for the stock market :)


text:
Q: Convert text files to Microsoft Excel that can accommodate more than 65536 rows I found Python code (as below) to convert text files to Microsoft Excel and it works. However 65,536 is the maximum number of spreadsheet rows supported by Excel 97, Excel 2000, Excel 2002 and Excel 2003 whereas Excel 2007, 2010 and 2013 support 1,048,576 rows.
Since my text files contain more than 65,536 rows, how do I modify the code so that it could work best to convert text files to Excel versions that can cater for 1,048,576 rows?
import glob
import csv
import xlwt

for filename in glob.glob("C:\Users\MSI\Desktop\Line Item Besar\\*.txt"):
    spamReader = csv.reader((open(filename, 'rb')), delimiter='|',quotechar='"')
    encoding = 'latin1'
    wb = xlwt.Workbook(encoding=encoding)
    sheet=xlwt.Workbook()
    sheet = wb.add_sheet('sheet 1')
    newName = filename
    for rowx, row in enumerate(spamReader):
        for colx, value in enumerate(row):
            sheet.write(rowx, colx, value)
    wb.save(newName.replace('.txt','.xls'))

print "Done"

A: You need to save your file as .xlsx, a modern XML-like format that is now used instead of old binary .xls. However, there are several questions on SO stating that xlwt doesn't work with .xlsx, so probably you have to switch to another module, for example XlsxWriter.

A: XlsxWriter and OpenPyXL support creating Excel xlxs files with 1 million rows.
Here is a version of your program using XlsxWriter:
import glob
import csv
from xlsxwriter import Workbook

for filename in glob.glob("C:\path\*.txt"):
    spamReader = csv.reader((open(filename, 'rb')),
                            delimiter='|', quotechar='"')

    newName = filename.replace('.txt', '.xlsx')

    workbook = Workbook(newName, {'strings_to_numbers': True})
    worksheet = workbook.add_worksheet()

    for rowx, row in enumerate(spamReader):
        for colx, value in enumerate(row):
            worksheet.write(rowx, colx, value)

    workbook.close()

print "Done"


text:
Q: java skewed shape when rotated So I have a shape and I want to rotate it with respect to the y-axis. I'm pretty sure my rotation matrix is correct, here's how the rotation matrix looks like in our guide:

And here's the code I implemented:
public static void rotate3Dy(float[] xCoords, float[] yCoords, float[] zCoords, float angle) {
    float cosine_angle = (float) Math.cos(angle);
    float sine_angle = (float) Math.sin(angle);

    for (int i = 0; i < yCoords.length; i++) {
        xCoords[i] = (xCoords[i] * cosine_angle) + (zCoords[i] * sine_angle) + 0;
        zCoords[i] = (-xCoords[i] * sine_angle) + (zCoords[i] * cosine_angle) + 0;
    }
}

Rotating the shape up/down/left/right alone looks fine, but when I rotate it either left or right after being rotated up/down it starts getting skewed.

What am I missing/doing wrong here?

A: Presumably the skew is caused by the following flaw in your rotation transform: In the loop of your rotate3Dy-method you transform xCoords[i] and then you use
the transformed value to transform zCoords[i] instead of computing the latter with the untransformed value of xCoords[i].
Try the following: Clone the xCoords-array before its transformation i.e. replace
    for (int i = 0; i < yCoords.length; i++) {
        xCoords[i] = (xCoords[i] * cosine_angle) + (zCoords[i] * sine_angle) + 0;
        zCoords[i] = (-xCoords[i] * sine_angle) + (zCoords[i] * cosine_angle) + 0;
    }

with
    float[] xCoordsTmp = xCoords.clone();
    for (int i = 0; i < yCoords.length; i++) {
        xCoords[i] = (xCoordsTmp[i] * cosine_angle) + (zCoords[i] * sine_angle) + 0;
        zCoords[i] = (-xCoordsTmp[i] * sine_angle) + (zCoords[i] * cosine_angle) + 0;
    }

Maybe that fixes the problem.


text:
Q: Core Data one to many relationship get Data I am storing JSON Data to CoreData with a one-to-many relationship. I am able to get the data back, using NSFetchRequest and fast enumeration, but the data is not coming in the order format I need and it cannot be used in my UITableViewCells how can i do this
this is my code
this is my datamodel
https://www.dropbox.com/s/1e1ujrjxtkjy9h9/Screen%20Shot%202015-04-29%20at%205.14.31%20pm.png?dl=0
_appDelegate = [[UIApplication sharedApplication]delegate];
    _managedObjectContext = [_appDelegate managedObjectContext];

    NSFetchRequest * fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"DealSection"];
    [fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"sectionID == %@",_sectionID]];
    [fetchRequest setReturnsObjectsAsFaults:NO];
    NSArray * sortDescriptor = [NSArray arrayWithObjects:nil];
    [fetchRequest setSortDescriptors:sortDescriptor];
    NSError * error;
    NSArray * data = [_managedObjectContext executeFetchRequest:fetchRequest error:&error];
    _fetchData = data;

    for (DealSection * section in _fetchData) {
        for (Deal * deal in [section alldeals]) {
            NSLog(@"%@",[deal nameAttribute]);
        }
    }

i put this all code in the ViewDidLoad
here am getting the data from NSLog but my problem am able to print the data but am not able to pass the data to the table view

A: The JSON snippet that you have posted shows that (contrary to my supposition in the comments, apologies) each Deal can have many DealSections.
Your DealSection entity has a relationship entitled alldeals that is currently a to-one relationship.  I.e. each DealSection can have only one Deal.  I think this should be to-many.  To take an example, the deal in the JSON you posted has sections with ID=6 (name="Services") and ID=8 (name="Wellness").  Suppose you had another deal with a section with ID=6 - do you want to use establish the relationship with the existing DealSection, or to create a new DealSection?
Currently your code creates a new DealSection, but I think you probably want the relationship with the existing DealSection.  For that to work, you will need to
a) amend your data model to make the relationship many-many.
b) amend the code where you store the data for the many-many relationship, so that it starts by trying to fetch a DealSection with the correct ID.  If one is found, add that DealSection to the Deal's sectionRelation.  If it is not found, created a new DealSection and add that to the Deal.
EDIT
To display the data in a tableView, you need to implement three datasource methods:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // A table view section for each DealSection:
    return [self.fetchData count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    DealSection *dealSection = self.fetchData[section];
    NSArray *deals = [dealSection.alldeals allObjects];
    return [deals count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    // Amend this identifier to match your cell prototype
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    // Set up the cell...
    DealSection *dealSection = (DealSection *)self.fetchData[indexPath.section];
    NSArray *deals = [dealSection.alldeals allObjects];
    Deal *deal = (Deal *)deals[indexPath.row];
    cell.textLabel.text = deal.nameAttribute;
    return cell;
}

This is basic table view stuff, so if any of it is unclear I recommend the tutorial I mentioned in comments.


text:
Q: jQuery scroll event css-transform causes flickering in Safari I now this is a very common bug/problem and there are many proposals out there which I already tried…
So here is my setup:
HTML

CSS
body {
    width: 100%;
    height: 300%;
}

#test {
    position: absolute;
    -webkit-backface-visibility: hidden;
    -webkit-perspective: 1000;
}

jQuery
var $window = $(window)
$window.scroll(function(){
    var $test = $('#test'),
    offset = $window.scrollTop();
    $test.css({
        'transform': 'translateY('+ Math.round(offset*1.2) + 'px) translateZ(0)'
    })
})

I tried several configurations which all "failed" in Safari. Even though this is a really simple test-setup it keeps on flickering/stuttering while scrolling. Any ideas?
I have a project with nested, scroll-animated elements to create a nice, new kind of parallax effect – no problem for Firefox and Chrome…
Thanks in advance!


text:
Q: "obvious url in rails" first off all please excuse me if i dont use all the right terminology. I have the URL issue with my rails app. Basically it works but I just find the url to be a bit too "obvious" and maybe a security issue.
example i have a user resource the users show page will go to websitename.com/users/user_id right ? This is probably convention but how do i go about changing that to display something random ? I tried using a secure token (not sure if it was the right thing to do) and sessions are saved in the token but the url is still quite obvious. Authorization works and non-signed in users cant just visit lets say user with id one lol. Please if this dosent make sense I will try and clarify just ask. Thanks.
Edit.
Also can some one explain to me what a token does then, my understanding was instead of saving a user session with the user id and the id hets displayed, a users session was saved in a secure token and the token (generally random string)  got displayed. wrong??

A: You can overwrite the to_param method for your user object. You could then have i.e. a column in the database, where you store a hash that is your param for the object. See also the Rails guides section for that.

A: Try https://rubygems.org/gems/friendly_id
It allows to have permalinks in urls instead of plain IDs