Q: Flask HTTP Server won't allow upload of multiple files at once import os
from flask import Flask, request, redirect, url_for
from werkzeug import secure_filename

UPLOAD_FOLDER = '/home/ubuntu/shared/'

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@app.route("/", methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        file = request.files['file']
        if file:
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('index'))
    return """
    <!doctype html>
    <title>Upload new File</title>

Upload new File

    <form action="" method="post" enctype="multipart/form-data">

<input type="file" multiple="" name="file">
         <input type="submit" value="Upload">
    </form>

%s

    """ % "
".join(os.listdir(app.config['UPLOAD_FOLDER'],))

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=8000, debug=False)

If I launch the server and select 2 files through the form, it only uploads one of them. I tried for serveral hours and read about 15 topics on it, including the documentation.
Nada :c
Edit:
I also tried changing:
        file = request.files['file']

into:
        file = request.files.getlist('file')

would not work either. The type of quotes have no effect either. Wasn't that a python3 thing?

A: import os, ssl
from flask import Flask, request, redirect, url_for
from werkzeug import secure_filename

UPLOAD_FOLDER = '/home/ubuntu/shared/'
certfile = "/home/ubuntu/keys/fullchain.pem"
keyfile = "/home/ubuntu/keys/privkey.pem"
ecdh_curve = "secp384r1"
cipherlist = "ECDHE-ECDSA-AES256-GCM-SHA384 ECDHE-ECDSA-CHACHA20-POLY1305"

sslcontext = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)
sslcontext.options |= ssl.OP_NO_TLSv1
sslcontext.options |= ssl.OP_NO_TLSv1_1
sslcontext.protocol = ssl.PROTOCOL_TLSv1_2
sslcontext.set_ciphers(cipherlist)
sslcontext.set_ecdh_curve(ecdh_curve)
sslcontext.load_cert_chain(certfile, keyfile)

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@app.route("/", methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        my_data = request.files.getlist('file')
        my_pass = request.form['password']
        if my_data and my_pass == 'yakumo':
            for file in my_data:
                my_handler(file)
            return redirect(url_for('index'))
    return """
    <!doctype html>
    <title>Upload new File</title>

Upload new File

    <form action="" method=post enctype=multipart/form-data>

<input type=file multiple name=file>
        <input type="password" name="password" value="">
        <input type=submit value=Upload>
    </form>

%s

    """ % "
".join(os.listdir(app.config['UPLOAD_FOLDER'],))

def my_handler(f):
    filename = secure_filename(f.filename)
    f.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=8000, ssl_context=sslcontext, threaded=True, debug=False)

I made a very rookie mistake and didn't for-loop over the multiple files being uploaded. The code here was tested without issues with 4 simultaneous file uploads. I hope it will be useful to someone.
Edit: Code updated with some sweet TLS_1.2 and a password field. Enjoy a reasonably secure upload server. Password is transferred over HTTPS.


Q: Implement Scenario outline in a cucumber-protractor through step definitions and page objects Does anyone know why this step might be showing as "undefined" when I try to run it. below you will see an example where I am trying to experiment with cucumber scenario outline and my "examples:" section has 1 entry. Also, the page objects and step def is enclosed. For some reason when I try to run it , I get an error like this:
1) Scenario: Verify user can search # ..\features\automation\regression\samplezz.feature:13
   √ Before # ..\support\world.js:21
   √ Given I navigate to the ea site # ..\step_definitions\ea_page_steps.js:4
   √ Then I click on the search icon # ..\step_definitions\ea_page_steps.js:8
   ? When I search for the word angular
       Undefined. Implement with the following snippet:

         When('I search for the word angular', function (callback) {
           // Write code here that turns the phrase above into concrete actions
           callback(null, 'pending');
         });

Here is the feature file
Feature: sampleZZ
The purpose of this feature file is to navigate to the eaAutomationa site

  Scenario Outline: Verify user can search
    Given I navigate to the ea site
    Then I click on the search icon
    When I search for the word <word>

    Examples:
    |word|
    |angular|

here is the step def:
let {Given, Then, When} = require('cucumber');

Given(/^I navigate to the ea site$/, function(){
    return browser.get(this.url.ud); });

Then(/^I click on the search icon$/, function(){
    return this.pages.udPage.click_Search();
    });

When(/^I search for the word "([^"]*)" $/, function(word){
     return this.pages.udPage.enter_SearchText(word) });

Here are the page objects
class UDPage extends require('../base_page.js') {   constructor() {
    super();
    this.eaautomation = by.css('#new_searchicon > i');
    this.eaLogo = by.css('//#header_logo');   };   click_Search() {
    return element(this.eaautomation).click();   }

  enter_SearchText(text){
    return element(this.eaautomation).sendKeys(text);   }

} module.exports = UDPage;

Note: I have a universal constructor in the framework and therefore I don't have to import any pages when I write my test.
Could someone help me understand what is the wrong with the step 3 that it keeps showing undefined?
using following
"dependencies": {
    "chai": "4.1.2",
    "chai-as-promised": "7.1.1",
    "chakram": "1.5.0",
    "cucumber": "4.0.0",
    "cucumber-html-reporter": "3.0.4",
    "fs": "0.0.2",
    "path": "0.12.7",
    "protractor": "5.3.0",
    "protractor-cucumber-framework": "4.2.0"
  }
EDITED- to add the config.js
let path = require('path'),
  environment = require('./environment');

exports.config = Object.assign({}, environment, {

  seleniumAddress: 'http://localhost:4444/wd/hub', // 'http://localhost:4444/wd/hub' to run locally

  capabilities: {
    "browserName": "chrome",
    "shardTestFiles": true,
    "maxInstances": 1,
    "ignoreProtectedModeSettings": true
  },

  specs:[
      '../features/automation/regression/sample2.feature',
  ],

  params: {
    environment: 'qa1', // dit, qa4, or qa1
    platform: 'browser', // browser or mobile
    path: {
      page_objects: path.resolve(__dirname + '/../page_objects'), // Default directory for the page objects
     page_factory: path.resolve(__dirname + '/../page_objects/page_factory.js'), // Default page factory location
     projectRoot: path.resolve(__dirname + '/../') // Default root for the automation
    }
  }

});

A: Remove the double quote around "([^"]*)" in step definition, there is no quote in feature file.
When(/^I search for the word ([^"]*)$/, function(word){});

 enter_SearchText(text) {
    var me = this;

    // wait 15 seconds
    return browser.sleep(15*1000).then(function(){
        return element(me.eaautomation).sendKeys(text);
    });
 }


Q: Change backup folder from /var/backup to different/external-shared folder in Magento 2 I need to change my backup directory to some other directory which is different from Magento installation root directory. How can i do this?

A: You need to override helper & it's function
magento\vendor\magento\module-backup\Helper\Data.php
public function getBackupsDir()
{
    return $this->_filesystem->getDirectoryWrite(DirectoryList::VAR_DIR)->getAbsolutePath('backups');
}

Instead of backups give ur folder name
How to override? http://blog.chapagain.com.np/magento-2-override-rewrite-block-model-controller-helper-using-plugin-preference/

A: Helper-Data.php
public function getBackupDir()
{
return    $this->_filesystem->getDirectoryWrite(DirectoryList::VAR_DIR)->getAbsolutePath('backups');
}

Override Helper Data file


Q: How to Parse and display a table in Jsoup android i have some problems with jsoup.
this is the link i want to parse: http://roosters.gepro-osi.nl/roosters/rooster.php?klassen%5B%5D=L2vp&type=Klasrooster&wijzigingen=1&school=905/ . I want to select te table content and display it nice and clean in my app. this is the script i already have:
    package rsg.deborgen.nl;

     import org.jsoup.Jsoup;
     import org.jsoup.nodes.Document;
     import org.jsoup.select.Elements;

     import android.app.Activity;
     import android.os.Bundle;
     import android.view.View;
     import android.widget.Button;
     import android.widget.TextView;

     public class Lindenborg1Activity extends Activity {
Button btn_2p;

// blog url
static final String BLOG_URL = "http://roosters.gepro-osi.nl/roosters/rooster.php?klassen%5B%5D=L2vp&type=Klasrooster&wijzigingen=1&school=905/";

@Override
public void onCreate(Bundle savedInstanceState) {
    // set layout view
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    btn_2p =(Button) findViewById(R.id.button1);

    btn_2p.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            // process

                // set layout view
                setContentView(R.layout.rooster);

            try {
                ((TextView)findViewById(R.id.tv)).setText(getBlogStats());
            } catch (Exception ex) {
                ((TextView)findViewById(R.id.tv)).setText("Error");
            }
        }

        protected String getBlogStats() throws Exception {
            String result = "";
            // get html document structure
            Document document = Jsoup.connect(BLOG_URL).get();
            // selector query
            Elements nodeBlogStats = document.select("td.tableheader");
            // check results
            if(nodeBlogStats.size() > 0) {
                // get value
                result = nodeBlogStats.get(0).text();
            }

            // return
            return result;

(i leaved away the end because of it was going wrong with code block)
but if i run it now it shows me the whole site and i want only the text in the table.
so please help me, thanks!
(Ps. this script is from another tut but i can't remeber its name and sorry for my nooblism and bad english :D )

A: try    document.select("tr.AccentDark td.tableheader")


Q: How to get every nth line into different arrays I need to create a program that seperates every name and each type of scores the students are taking.(test finals etc) The file I'm reading looks like this:
*Puckett, Karen
10 10 9.5 10 10 8 9.5 10 10 10 9 10 10 10 0
4 3 5 3 5 2 3 2 1.5 1 5 3.5
17.5 24 22 23.5 22 23
90 91
96
*

It repeats for a total of 16 students. The method I created for the name looks like this so far:
public static String[] name(String output, int i) {
String[] names = new String[16];
String name = nulll
while (i<16) {
name = ???;
names[i] = name;
i++;
}
return names;
}

If i find what I need to set the name variable to I think I will be able to repeat them for each method and finish the rest of the requirements. variable i starts at 0 and comes from the main method and output is the string I made from the text file I'm reading from, and also comes from the main method.


Q: To solve a PDE by separation of variables
To Solve: $\displaystyle py^3+qx^2=0$
where $p = \dfrac{\partial z}{\partial x}$, $q = \dfrac{\partial z}{\partial y}$.

My attempt:
Let $\displaystyle z=X(x)Y(y)$. So, $\displaystyle X'Yy^3+XY'x^2=0$
Separating the variables, $\displaystyle \frac{X'}{Xx^2}=\frac{-Y'}{Yy^3}$
Now how do I integrate this ? $X$ is an unknown function and $x$ is a variable. I don't know how to proceed?

A: You've got
$$\dfrac{X'}{Xx^2} = -\dfrac{Y'}{Yy^3}$$
where the LHS cannot contain any terms of $y$ (as $X$ is purely a function of $x$), and the RHS, similarly, cannot contain any terms of $x$. But as the two are equal, this implies that they cannot contain any terms of $x$ or $y$ $-$ in other words, they are equal to a constant (say $k$). Thus:
$$\dfrac{X'}{Xx^2} = -\dfrac{Y'}{Yy^3} = k \Rightarrow\\
X' = kXx^2,\ -Y' = kYy^3 \Rightarrow\\
\boxed{X' - kx^2X = 0\\
Y' + ky^3Y = 0}
$$
These are ODEs that can be easily solved (and $k$ is an arbitrary constant).


Q: How to measure total disk I/O per hour I have a cloud server were we get billed also for disk IO usage. Here is an example from the stats:
04/Sep/2013 07:24:19
04/Sep/2013 08:24:19
0,5 GB / 1 vCPU (0,08 Kr. per hour): Charge for 44.7578125GB disk I/O

So for one hour we get billed for around 45 GB disk I/O.
To me that sounds like a lot of traffic and I would like to do some monitoring  to check it myself. I know about tools like dstat and sysstat etc but I have not found any examples showing totals for one hour (or other timeframe). Most examples is averaging the results, like this command:
dstat -tdD total 60

Here, it shows disk I/O measuring for 60 seconds, but it is averaged. So if I copy a large file, I will see the number increase while copying, but as soon as it is finished, the number will decrease again. I other words, I don't end up with a true total for that period.
How can I log the total amount of disk I/O in a given timeframe?

A: You can use the tool iostat to collect the disk utilization information. It takes several arguments, including the switch, -d:
   -d     Display the device utilization report.

It also takes an argument in seconds an interval of how frequent it should re-run.  The value 3600 would be the number of seconds in an hour.
Example
$ iostat -d 3600
Linux 2.6.35.14-106.fc14.x86_64 (grinchy)   09/04/2013  _x86_64_    (4 CPU)

Device:            tps   Blk_read/s   Blk_wrtn/s   Blk_read   Blk_wrtn
sda              20.53        71.86      1259.61   20308334  356000380
dm-0              4.92        39.02        28.81   11027610    8143376
dm-1              0.54         0.93         3.38     261472     954912
dm-2            156.65        31.87      1227.42    9006394  346902056

The output from this command could be redirected to a file:
$ iostat -d 3600 >> iostat_hrly.log

Meaning of the units
If you consult the man page for iostat it has pretty good descriptions of the units.
excerpt
   Blk_read/s
         Indicate the amount of data read from the device expressed in a
         number of blocks per second. Blocks are equivalent to sectors with
         kernels 2.4 and later and  therefore have a size of 512 bytes. With
         older kernels, a block is of indeterminate size.

  Blk_wrtn/s
         Indicate the amount of data written to the device expressed in a
         number of blocks per second.

  Blk_read
         The total number of blocks read.

  Blk_wrtn
         The total number of blocks written.

So a block is 512 bytes, so the Blk_read/s in terms of MB for device sda would be, 71.86 * 512 bytes = 36.79232 kilobytes/sec.
There are additional switches that will change the units automatically in the output.
excerpt from iostat man page
-h     Make the NFS report displayed by option -n easier to read by a human.

-k     Display statistics in kilobytes per second instead of blocks per
       second.  Data displayed are valid only with kernels 2.4 and later.

-m     Display statistics in megabytes per second instead of blocks or
       kilobytes per second.  Data displayed are valid only with kernels
       2.4 and later.

Example in KB/s
So this might be more useful, showing the throughput in KB/s:
$ iostat -dk 3600
Linux 2.6.35.14-106.fc14.x86_64 (grinchy)   09/05/2013  _x86_64_    (4 CPU)

Device:            tps    kB_read/s    kB_wrtn/s    kB_read    kB_wrtn
sda              20.85        47.25       663.81   15475096  217427086
dm-0              5.01        20.00        14.43    6549301    4725068
dm-1              0.54         0.58         1.60     189064     524872
dm-2            165.30        26.65       647.78    8730281  212177124


Q: Generating synonyms using pyDictionary I would like to return all the synonyms for a particular word using pyDictionary. However, I can only retrieve the first five synonyms. for example;
>>>from PyDictionary import PyDictionary
>>>dictionary=PyDictionary()
>>>dictionary.synonym("beautiful")
>>>[u'alluring', u'cute', u'fascinating', u'magnificent', u'marvelous']

Extended  list
[u'alluring', u'cute', u'fascinating', u'magnificent', u'marvelous', 'delicate', 'dazzling', 'delightful', 'elegant','fascinating' etc].
See thesaurus for the full list as pyDictionary uses Thesaurus.
Any idea on how to retrieve the complete list of synonyms for a word? and besides WordNet, are they any other recommended lexical databases for synonym generation that can be used with python?
Thanks.


Q: "Adding" Dictionaries in Python?
Possible Duplicate:
python dict.add_by_value(dict_2) ?

My input is two dictionaries that have string keys and integer values. I want to add the two dictionaries so that the result has all the keys of the input dictionaries, and the values are the sum of the input dictionaries' values.
For clarity, if a key appears in only one of the inputs, that key/value will appear in the result, whereas if the key appears in both dictionaries, the sum of values will appear in the result.
For example, say my input is:
a = dict()
a['cat'] = 1
a['fish'] = 10
a['aardvark'] = 1000

b = dict()
b['cat'] = 2
b['dog'] = 200
b['aardvark'] = 2000

I would like the result to be:
{'cat': 3, 'fish': 10, 'dog': 200, 'aardvark': 3000}

Knowing Python there must be a one-liner to get this done (it doesn't really have to be one line...). Any thoughts?

A: How about that:
dict( [ (n, a.get(n, 0)+b.get(n, 0)) for n in set(a)|set(b) ] )

Or without creating an intermediate list (generator is enough):
dict( (n, a.get(n, 0)+b.get(n, 0)) for n in set(a)|set(b) )

Post Scriptum:
As a commentator addressed correctly, there is a way to implement that easier with the new (from Py2.7) collections.Counter class. As much I remember, this version was not available when I wrote the answer:
from collections import Counter
dict(Counter(a)+Counter(b))

A: One liner (as sortof requested): get key lists, add them, discard duplicates, iterate over result with list comprehension, return (key,value) pairs for the sum if the key is in both dicts, or just the individual values if not. Wrap in dict.
>>> dict([(x,a[x]+b[x]) if (x in a and x in b) else (x,a[x]) if (x in a) else (x,b[x]) for x in set(a.keys()+b.keys())])
{'aardvark': 3000, 'fish': 10, 'dog': 200, 'cat': 3}

A: result in a:
for elem in b:
    a[elem] = a.get(elem, 0) + b[elem]

result in c:
c = dict(a)
for elem in b:
    c[elem] = a.get(elem, 0) + b[elem]

A: Not in one line, but ...
import itertools
import collections
a = dict()
a['cat'] = 1
a['fish'] = 10
a['aardvark'] = 1000
b = dict()
b['cat'] = 2
b['dog'] = 200
b['aardvark'] = 2000
c = collections.defaultdict(int)
for k, v in itertools.chain(a.iteritems(), b.iteritems()):
    c[k] += v

You can easily extend it to a larger number of dictionaries.


Q: Maven Surefire Plugin doesn't run expected tests in directory In a maven submodule, I have unit tests and acceptance tests with cucumber. I want mvn test to run only the unit tests.
The structure is the following:

Initially, the problem was that the mvn test goal was running only the cucumber tests (acceptance tests). So I noticed that the Maven Surefire Plugin, that manages what will be run in the mvn test goal, was defined in the parent pom.
So I decided to override it in the child pom by defining the Maven Surefire Plugin in the child pom as well, and changing some configurations with the  tag, trying to make it so that mvn test would only run the unit tests:
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>3.0.0-M3</version>
    <configuration>
        <reuseForks>true</reuseForks>
        <forkCount>1</forkCount>
        <includes>
            <include>unittests/**/*</include>
        </includes>
    </configuration>

</plugin>

According to surefire's documentation, the path specified in the  tag is relative to the directory containing generated test classes, typically src/test/java.

However, it would make more sense to call it testSourceDirectory, because when I run mvn -X test I get the following:
[DEBUG]   (s) projectBuildDirectory = /home/myname/parent-module/child-module/target
[DEBUG]   (s) redirectTestOutputToFile = false
[DEBUG]   (s) remoteRepositories = [      id: central
      url: https://repo.maven.apache.org/maven2
   layout: default
snapshots: [enabled => false, update => daily]
 releases: [enabled => true, update => never]
]
[DEBUG]   (s) reportFormat = brief
[DEBUG]   (s) reportsDirectory = /home/myname/parent-module/child-module/target/surefire-reports
[DEBUG]   (f) rerunFailingTestsCount = 0
[DEBUG]   (f) reuseForks = true
[DEBUG]   (s) runOrder = alphabetical
[DEBUG]   (s) session = org.apache.maven.execution.MavenSession@58434b19
[DEBUG]   (f) shutdown = testset
[DEBUG]   (s) skip = false
[DEBUG]   (f) skipAfterFailureCount = 0
[DEBUG]   (s) skipTests = false
[DEBUG]   (s) suiteXmlFiles = []
[DEBUG]   (s) tempDir = surefire
[DEBUG]   (s) testClassesDirectory = /home/myname/parent-module/child-module/target/test-classes
[DEBUG]   (s) testFailureIgnore = false
[DEBUG]   (s) testNGArtifactName = org.testng:testng
[DEBUG]   (s) testSourceDirectory = /home/myname/parent-module/child-module/src/test/java
[DEBUG]   (s) threadCountClasses = 0
[DEBUG]   (s) threadCountMethods = 0
[DEBUG]   (s) threadCountSuites = 0
[DEBUG]   (s) trimStackTrace = true
[DEBUG]   (s) useFile = true
[DEBUG]   (s) useManifestOnlyJar = true
[DEBUG]   (f) useModulePath = true
[DEBUG]   (s) useSystemClassLoader = true
[DEBUG]   (s) useUnlimitedThreads = false
[DEBUG]   (s) workingDirectory = /home/myname/parent-module/child-module

Currently, with the include tag that I added, it finds no tests to run. I have some questions, for example, why does the documentation mention testClassesDirectory if that 's where the .class files are instead of Test*.java files, because that's what we want to include, right? .java tests, not the .class compiled ones.
Also, assuming the include tags are relative to testSourceDirectory instead of testClassesDirectory, why doesn't my include work? Because my testSourceDirectory is pointing to /home/myname/parent-module/child-module/src/test/java, if I put next to it unittests/**/* it should skip any directories with the ** glob and get any files with the * glob, right?


Q: How to log out from AWS Cognito in ASP.NET Core I'm trying to implement authentication using AWS Cognito in a ASP.NET Core 5 web app.
I can get authenticated, but now I want to implement a logout function.
I can kind of get the logout to work, in that ASP.NET thinks I'm not authenticated.
In my Startup.cs I have:
options.SignedOutRedirectUri = Configuration["Authentication:Cognito:SignedOutRedirectUri"];

options.Events = new OpenIdConnectEvents()
{
    OnRedirectToIdentityProviderForSignOut = context =>
    {
        var logoutUri = options.SignedOutRedirectUri;
        context.Response.Redirect(logoutUri);
        context.HandleResponse();

        return Task.CompletedTask;
    }
};

In my appsettings.json I have:
  "SignedOutRedirectUri": "https://mydomain.auth.us-east-2.amazoncognito.com/logout?client_id=<<clientid>>&response_type=code&redirect_uri=https://localhost:44306/Home/LoggedOut"

In my Logout controller, I have:
        await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
        await HttpContext.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme);

        return Redirect("/Home/LoggedOut");

So when I click my Logout link, I am redirected to /Home/LoggedOut and I am no longer authenticated (in that User.Identity.IsAuthenticated = false).
But when I go to any page with [Authorize] on it, it automatically re-authenticates me to the same user I was logged in as - it never gives me a chance to log in as a different user. I want it to take me to the Cognito login dialog and ask me to authenticate again. So it looks like something is not getting cleared somewhere, I suppose on the AWS Cognito side of things.
Why isn't this sending me back to the login dialog to re-authenticate? I thought a GET to the AWS /logout endpoint was supposed to that.

A: I think the issue is the parameters of the URL you are constructing for AWS Logout endpoint. (you haven't set logout_uri)
https://docs.aws.amazon.com/cognito/latest/developerguide/logout-endpoint.html example 1 shows the required parameters to logout and redirect back to the client.
Here is how I've done it.
options.Events = new OpenIdConnectEvents()
{
    OnRedirectToIdentityProviderForSignOut = context =>
    {
        context.ProtocolMessage.IssuerAddress =
           GetAbsoluteUri(Configuration["Authentication:Cognito:EndSessionEndPoint"], Configuration["Authentication:Cognito:Authority"]);
        context.ProtocolMessage.SetParameter("client_id", Configuration["Authentication:Cognito:ClientId"]);
        context.ProtocolMessage.SetParameter("logout_uri", "https://localhost:5001");
        return Task.CompletedTask;
    }
};

The logout_uri must match exactly the configured signout url on AWS app client settings.
Helper method
 private string GetAbsoluteUri(string signoutUri, string authority)
        {
            var signOutUri = new Uri(signoutUri, UriKind.RelativeOrAbsolute);
            var authorityUri = new Uri(authority, UriKind.Absolute);

            var uri = signOutUri.IsAbsoluteUri ? signOutUri : new Uri(authorityUri, signOutUri);
            return uri.AbsoluteUri;
        }

Logging out is done with the two lines below. As you worked out, the first line is logging you out locally by clearing out the local authentication cookie, the second line ordinarily would call off to an end_session endpoint on your IDP to log out of your IDP, however as cognito doesn't have and end_session endpoint, you override that when you configure the middleware via OnRedirectToIdentityProviderForSignOut event, instructing it instead to call off to the logout endpoint that cognito does have, and that's where this URL is used. Since you hadn't constructed that correctly it never logs out of cognito.
public async Task Logout()
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            await HttpContext.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme);
        }

and the configuration values
...
"EndSessionEndPoint": "logout",
"ClientId": "<your client id>",
"Authority": "https://<your domain>.auth.<your region>.amazoncognito.com"
...

hopefully that helps.


Q: Python sort in a dictionary and a set I'm creating a book index and I have read in a text file of words and their pages and have created this dictionary called 'index'
index={'spanning tree': {16, 99}, 'vertex': {54}, 'depth first search': {55}, 'shortest path': {55}, 'connected': {28, 54}, 'neighbor': {64, 27, 77}, 'path': {72, 19}}

Now I want to alphabetize the keys and put the numbers in chronological order-
Am I able to do this in the dictionary format or do I need to convert it to a list or a string?
I tried doing this...
ind=list(index)
ind.sort()
return ind

and I got a list of the keys in alphabetical order but am not sure how to approach the numbers because they are in sets...
Any advice?

A: You'll have to convert the sets to lists too if you want to apply ordering.
The sorted() function gives you a sorted list from any iterable, letting you skip a step:
for key in sorted(index):
    print('{:<20}{}'.format(key, ', '.join(str(i) for i in sorted(index[key]))))

Short demo:
>>> sorted(index)
['connected', 'depth first search', 'neighbor', 'path', 'shortest path', 'spanning tree', 'vertex']
>>> sorted(index['connected'])
[28, 54]
>>> for key in sorted(index):
...     print('{:<20}{}'.format(key, ', '.join(str(i) for i in sorted(index[key]))))
...
connected           28, 54
depth first search  55
neighbor            27, 64, 77
path                19, 72
shortest path       55
spanning tree       16, 99
vertex              54

A: You can use the collections module in the standard library which has an OrderedDict type which is just a dict that remembers order of insertion.
If you want a dictionary in alphabetical order, where your values are ordered lists:
sorted_index = collections.OrderedDict(sorted(zip(index, map(sorted, index.values()))))

Since that is a bit of an ugly line you can expand it out as.
sorted_items = sorted(index.items())
sorted_items = [(k, sorted(v)) for k, v in sorted_items]
sorted_index = collections.OrderedDict(sorted_items)


Q: How to let MySQL NOW() function return the user time I ran into a very tricky MySQL issue..
Our DB is using type DateTime for the updated_at column, and now is too late to change it back to TimeStamp. I'm thus trying to add a trigger to update this updated_at column on table changing. The following is what I did:
CREATE TRIGGER foo_schema.bar_datetime_trigger BEFORE UPDATE ON foo_schema.bar
FOR EACH ROW
set NEW.updated_at = NOW();
The NOW() function here returns the DB time; however, what I actually want is to set the udpated_at as the user time (Meaning the time of the user who made changes to table bar). Is it possible to handle this in MySQL?


Q: Why does a Hidden Window appear when taking a screenshot in WPF using C#? I have a WPF application that helps me take Screenshots of the entire screen.
The application contains a small Window with a button inside, which if I click on, a capture of the screen is taken, and saved on my drive.
I wanted to hide this little Window just before the capture is taken, so it won't be included in the capture, here's what I tried :
StartSnipping = new RelayCommand(() =>
                 {
                   // I hide it here !!
                   WindowVisibility = Visibility.Hidden;

                   //Than I take the screen shot
                   var screen = Screen.PrimaryScreen;
                   var bitmap = new Bitmap(screen.Bounds.Width, screen.Bounds.Height);
                   using (var graphics = Graphics.FromImage(bitmap))
                   {
                     graphics.CopyFromScreen(new Point(screen.Bounds.Left,
                                                       screen.Bounds.Top),
                                             new Point(0, 0),
                                             screen.Bounds.Size);
                   }

                   //I save the screen shot
                   bitmap.Save(@"C:/Users/Aymen/Desktop/test.png", ImageFormat.Png);
                 });

Now, assuming that the line :
WindowVisibility = Visibility.Hidden;

really works, well, I'm sure of this because after all that method completes running, the window is indeed hidden.
And assuming that the screenshot is successfully taken and saved and still contains that window, which is supposed to be hidden like 1 second before the screen capture, my question is :
Why this hidden window is still appearing in the screenshot ?? and what should I do to make it not appear in the screenshot ??

A: Not sure but it seems that using :
WindowVisibility = Visibility.Hidden;

Doesn't help keeping the window from appearing when taking a screenshot, I had to hide the window using the .Hide() method:
Application.Current.MainWindow.Hide();

That worked just well, bust still doesn't have any explanation why the Visibility.Hidden keeps the window appearing in screenshots.


Q: How to create a bivariate distribution from copula and marginals? Is there some way to create a bivariate distribution from a fitted copula and 2 marginals? I have finally managed to fit a copula to my stock returns using the package fCopulae and would like to calculate the VaR of a portfolio consisting of these two stocks. As far as i can tell, this can be done by simulating from the bivariate distribution and looking at the desired quantile for the VaR. Sadly i dont know how to create this Bivariate distribution from these inputs in R...incidentally, this can be accomplished using bivd() in S+/EVANESCE package...
anyone know the equivalent for R? Thanks!

A: There is rMvdc in package copula for generating random numbers form a multivariate distributions with specific margins and known copula.


Q: using a ssl enabled node.js sveltekit app alongside tomcat server which is currently hosting apps in https I am currently having a server with tomcat web server hosting few apps in https. Now we built a sveltekit app that is not static. I am trying to add this app be exposed as a https site.
I found many articles that point out using apache as a reverse proxy and pointing to the node.js app. However in my case, there are already 2 apps on tomcat running in https.
I this case, kindly confirm if i need to move all the ssl logic to the apache and setup tomcat to run in http and allow apache to receive https and forward to tomcat as http and return the response back. I am also starting to experiment with this, but wanted to know if this is a production ready approach.


Q: What color does plot.xts use? Does anybody know what colours plot.xts uses? I can't find anything on the help page.
I would like to use the same colours in my legend.
Or is there another way to get the same plot with addLegend()?
Here the code I am using:
library(xts)
library(PerformanceAnalytics)
library(TTR)

xts1 <- xts(matrix(rnorm(300), ncol = 3), order.by = as.Date(1:100))
xts2 <- xts(matrix(rnorm(300), ncol = 3), order.by = as.Date(1:100))
colnames(xts1) <- c("A", "B", "C")
colnames(xts2) <- c("A", "B", "C")

plot_chart <- function(x) {
  ff <- tempfile()
  png(filename = ff)
  chart.CumReturns(x)
  dev.off()
  unlink(ff)
}

m <- matrix(c(1, 2, 3, 3), nrow = 2, ncol = 2, byrow = TRUE)
layout(mat = m, heights = c(0.8, 0.1))

par(mar = c(2, 2, 1, 1))
plot_chart(xts1)
addSeries(reclass(apply(xts1, 2, runSD), xts1))

par(mar = c(2, 2, 1, 1))
plot_chart(xts2)
addSeries(reclass(apply(xts2, 2, runSD), xts2))

par(mar=c(0, 0, 1, 0))
plot(1, type = "n", axes = FALSE, xlab = "", ylab = "")

# which colors do I have to insert in here?
plot_colors <- c("blue", "green", "pink")
legend(x = "top", inset = 0,
       legend = colnames(xts1),
       col = plot_colors, lwd = 7, cex = .7, horiz = TRUE)

A: Answer
Use the colorset argument of chart.CumReturns:
plot_chart <- function(x, col) {
  ff <- tempfile()
  png(filename = ff)
  chart.CumReturns(x, colorset = col)
  dev.off()
  unlink(ff)
}

par(mar = c(2, 2, 1, 1))
plot_chart(xts1, col = plot_colors)
addSeries(reclass(apply(xts1, 2, runSD), xts1))

par(mar = c(2, 2, 1, 1))
plot_chart(xts2, col = plot_colors)
addSeries(reclass(apply(xts2, 2, runSD), xts2))


Q: How to develop custom cocoa-pod of your existing Xcode project? If you want to create you own cocoapods with storyboards, XIBs, resources and with other frameworks such as Alamofire, MBProgressHUD etc.

A:
Easy steps to create Cocoapod from existing xcode project

*

*Create a repository on your git account (Repo name, check README,
choose MIT under license).

*Copy the url of your repository.Open terminal and run following command.
git clone copied your repository url

*Now copy your Xcode project inside the cloned repository folder on
your Mac. Now run following commands
git add -u to add all files (if not added use: git add filepath/folder)
git commit -m "your custom message"
git push origin master

*Create a new release to go to your git repository or run following commands
git tag 1.0.0
git push --tags

*First, we need to make sure that you have CocoaPods installed and
ready to use in your Terminal. run the following command:
sudo gem install cocoapods --pre
Creating a Podspec

*

*All Pods have a podspec file. A podspec, as its name suggests,
defines the specifications of the Pod! Now let’s make one, run
following command on terminal
touch PodName.podspec

*After adding and modifying your .podspec file. Validate your .podspec
file by hitting following command on terminal
pod lib lint

*Once you validate it successfully without errors run following
command to register you and build cocoapod respectively
pod trunk register
pod trunk push PodName.podspec
If all goes well, you will get this on terminal

  PodName (1.0.0) successfully published
  February 5th, 02:32
 https://cocoapods.org/pods/PodName
  Tell your friends!

Yeah!!!!! congrats you have got your pod link. Use wherever you want to use it.

A: Here is some useful links . You can follow the same.
https://www.appcoda.com/cocoapods-making-guide/
https://www.raywenderlich.com/5823-how-to-create-a-cocoapod-in-swift


Q: IBM Worklight 6.0 - iOS app always stuck on the second launch I have an issue with Worklight 6.0 while testing my app in an iOS device and iOS Simulator.

*

*First, when I install the app on iOS device / iOS Simulator using Xcode "run" button, it works.

*But after I stop it and launch it again from the Springboard, it freezes / is blocked on splash screen.

I am using Eclipse 4.2.1 for Mac with Worklight 6.0 plugin. I also use Xcode 4.6.
I have tested with three newly created projects, and also with a blank one, and I always have the same issue.
When I test with a project created by a previous Worklight version, it works (for example athe HelloWorklightApp sample project).

A: *

*What's the difference between "newly created projects" and "a blank one"?

*Did you change the HTML filename of the application in your-project\apps\your-app\common prior to deployment?

*Also, while this is probably not related, but do note that if using Worklight 6.0, make sure that you have installed it in Eclipse 4.2.2; not 4.0 not 4.1 not 4.2.1, only 4.2.2.

*Is this an upgraded installation of Worklight, or a new one in a new Eclipse instance and a new workspace?


Q: Calculus chain rule clarification Chain rule clarification:

Please have a look at the picture before continuing to read my query as this picture provides the context. On the fourth line of working (the one before the final simplified answer), could I get some clarification on the use of chain rule here?
Referring to the line above this one, $d/dt(df/dg) x dg/dt = dg/dt x d/dg(df/dg) x dg/dt$ (ignoring the part on the right of the addition). Does this mean $d/dt(df/dg) = dg/dt x d/dg(df/dg)$ since $dg/dt x d/dg = d/dt$ with the $dg$ cancelling out on the LHS. Since I have never come across this in my life, could someone please explain this is some depth if what I wrote here is true. If false could someone give me an explanation of the working. Sorry in advance if my English is not clear as it is not my native language.


Q: When I click on my name, and scroll to my questions, why no indication which questions have approved answer? I click on my name. I scroll down to (my) questions. Many have answers. In some cases, one of the answers has been ticked or checked, meaning that I have accepted one of the answers as resolution to my question. When a question reaches that status, I would like it to be displayed somehow differently, so I don't have to browse that question again. How can I make that happen?

A: This is very much indicated. On StackOverflow, the answer count for a question with an accepted answer is printed in yellow; on questions without an accepted answer it's white. If you move your cursor over the answer count, this is also stated in the tool tip.
On SuperUser, the distinction is green background / white background; on meta it's (pale) yellow / white again. On ServerFault it's green text / white text.

A: On your question list (questions you ask) you can immediately see the ones where you have accepted an answer.
On your answer list (questions you answered) you can immediately see the ones where you won the accepted answer.
As of yet there is no method to indicate questions you have answered which have been accepted and the accepted answer was not yours.


Q: 3D Camera Rotation in OpenGL: How to prevent camera jitter? I'm fairly new to OpenGL and 3D programming but I've begun to implement camera rotation using quaternions based on the tutorial from http://www.cprogramming.com/tutorial/3d/quaternions.html . This is all written in Java using JOGL.
I realise these kind of questions get asked quite a lot but I've been searching around and can't find a solution that works so I figured it might be a problem with my code specifically.
So the problem is that there is jittering and odd rotation if I do two different successive rotations on one or more axis. The first rotation along the an axis, either negatively or positively, works fine. However, if I rotate positively along the an axis and then rotate negatively on that axis then the rotation will jitter back and forth as if it was alternating between doing a positive and negative rotation.
If I automate the rotation, (e.g. rotate left 500 times then rotate right 500 times) then it appears to work properly which led me to think this might be related to the keypresses. However, the rotation is also incorrect (for lack of a better word) if I rotate around the x axis and then rotate around the y axis afterwards.
Anyway, I have a renderer class with the following display loop for drawing `scene nodes':
private void render(GLAutoDrawable drawable) {
    GL2 gl = drawable.getGL().getGL2();
    gl.glClear(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT);

    gl.glMatrixMode(GL2.GL_PROJECTION);
    gl.glLoadIdentity();
    glu.gluPerspective(70, Constants.viewWidth / Constants.viewHeight, 0.1, 30000);
    gl.glScalef(1.0f, -1.0f, 1.0f); //flip the y axis

    gl.glMatrixMode(GL2.GL_MODELVIEW);
    gl.glLoadIdentity();

    camera.rotateCamera();
    glu.gluLookAt(camera.getCamX(), camera.getCamY(), camera.getCamZ(), camera.getViewX(), camera.getViewY(), camera.getViewZ(), 0, 1, 0);
    drawSceneNodes(gl);
}

private void drawSceneNodes(GL2 gl) {
    if (currentEvent != null) {
        ArrayList<SceneNode> sceneNodes = currentEvent.getSceneNodes();
        for (SceneNode sceneNode : sceneNodes) {
            sceneNode.update(gl);
        }
    }

    if (renderQueue.size() > 0) {
        currentEvent = renderQueue.remove(0);
    }
}

Rotation is performed in the camera class as follows:
public class Camera {
    private double width;
    private double height;
    private double rotation = 0;

    private Vector3D cam = new Vector3D(0, 0, 0);
    private Vector3D view = new Vector3D(0, 0, 0);
    private Vector3D axis = new Vector3D(0, 0, 0);

    private Rotation total = new Rotation(0, 0, 0, 1, true);

    public Camera(GL2 gl, Vector3D cam, Vector3D view, int width, int height) {
        this.cam = cam;
        this.view = view;
        this.width = width;
        this.height = height;
    }

    public void rotateCamera() {
        if (rotation != 0) {
            //generate local quaternion from new axis and new rotation
            Rotation local = new Rotation(Math.cos(rotation/2), Math.sin(rotation/2 * axis.getX()), Math.sin(rotation/2 * axis.getY()), Math.sin(rotation/2 * axis.getZ()), true);

            //multiply local quaternion and total quaternion
            total = total.applyTo(local);

            //rotate the position of the camera with the new total quaternion
            cam = rotatePoint(cam);

            //set next rotation to 0
            rotation = 0;
        }
    }

    public Vector3D rotatePoint(Vector3D point) {
        //set world centre to origin, i.e. (width/2, height/2, 0) to (0, 0, 0)
        point = new Vector3D(point.getX() - width/2, point.getY() - height/2, point.getZ());

        //rotate point
        point = total.applyTo(point);

        //set point in world coordinates, i.e. (0, 0, 0) to (width/2, height/2, 0)
        return new Vector3D(point.getX() + width/2, point.getY() + height/2, point.getZ());
    }

    public void setAxis(Vector3D axis) {
        this.axis = axis;
    }

    public void setRotation(double rotation) {
        this.rotation = rotation;
    }
}

The method rotateCamera generates the new permenant quaternions from the new rotation and previous rotations while the method rotatePoint merely multiplies a point by the rotation matrix generated from the permenant quaternion.
The axis of rotation and the angle of rotation are set by simple key presses as follows:
    @Override
public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_W) {
        camera.setAxis(new float[] {1, 0, 0});
        camera.setRotation(0.1f);
    }
    if (e.getKeyCode() == KeyEvent.VK_A) {
        camera.setAxis(new float[] {0, 1, 0});
        camera.setRotation(0.1f);
    }
    if (e.getKeyCode() == KeyEvent.VK_S) {
        camera.setAxis(new float[] {1, 0, 0});
        camera.setRotation(-0.1f);
    }
    if (e.getKeyCode() == KeyEvent.VK_D) {
        camera.setAxis(new float[] {0, 1, 0});
        camera.setRotation(-0.1f);
    }
}

I hope I've provided enough detail. Any help would be very much appreciated.

A: About the jittering: I don't see any render loop in your code. How is the render method triggered? By a timer or by an event?
Your messed up rotations when rotating about two axes are probably related to the fact that you need to rotate the axis of the second rotation along with the total rotation of the first axis. You cannot just apply the rotation about the X or Y axis of the global coordinate system. You must apply the rotation about the up and right axes of the camera.
I suggest that you create a camera class that stores the up, right and view direction vectors of the camera and apply your rotations directly to those axes. If this is an FPS like camera, then you'll want to rotate the camera horizontally (looking left / right) about the absolute Y axis and not the up vector. This will also result in a new right axis of the camera. Then, you rotate the camera vertically (looking up / down) about the new right axis. However, you must be careful when the camera looks directly up or down, as in this case you can't use the cross product of the view direction and up vectors to obtain the right vector.


Q: Get key value of matching case insensitive string I'm attempting to pull some specific data from the "id" field but jq matches are being case sensitive and creating an issue with the searches (not matching, basically, so returning 0 results).
JSON Example:
{
  "created_at": "2020-01-17T12:54:02Z",
  "primary": true,
  "verified": true,
  "deliverable_state": "deliverable",
  "undeliverable_count": 0,
  "updated_at": "2020-01-17T12:54:03Z",
  "url": "http://www.website.com",
  "id": 376062709553,
  "user_id": 374002305374,
  "type": "email",
  "value": "test-1234567@domain.com"
}
{
  "created_at": "2019-02-07T20:49:41Z",
  "primary": false,
  "verified": true,
  "deliverable_state": "deliverable",
  "undeliverable_count": 0,
  "updated_at": "2019-02-07T20:49:41Z",
  "url": "http://www.website.com",
  "id": 366235941554,
  "user_id": 374002305374,
  "type": "email",
  "value": "MyEmail@domain.com"
}

When running jq against the following, I get the correct return:
$ jq -r '. | select(.value=="MyEmail@domain.com") .id' sample.json
366235941554

But if I run with the incorrect case, eg.
$ jq -r '. | select(.value=="Myemail@domain.com") .id' sample.json

...I do not get a result.  I've read through some of the documentation but unfortunately, I do not understand the test/match/capture flags for insensitive search (https://stedolan.github.io/jq/manual/#RegularexpressionsPCRE) or how to get it to operate with this "locate and give me the value" request.
I've searched seemingly everywhere but I'm unable to find any examples of this being used.

A: You don't really need regexp for this.
select(.value | ascii_downcase == "myemail@domain.com") .id

But if you insist on it, below is how you perform a case-insensitive match using test/2.
select(.value | test("MyEmail@domain.com"; "i")) .id


Q: How do I update a pre-formatted DataGridView bound to a list? I have a DataGridView that I am binding to the Values collection of a dictionary.  In my form's constructor, I can create the dictionary and bind the columns of the DataGridView to fields in the structure that will be contained in the dictionary:
        m_tasks = new Dictionary<int,OperationsTaskLabeledData>();
        var taskArray = from task in m_tasks.Values select new {
        StartDate = task.m_start_task_date.ToString("M/dd H:mm"),
        EndDate = task.m_task_date.ToString("M/dd H:mm"),
        Description = task.m_short_desc,
        Object = task.m_device_id,
        InitialLocation = task.m_initial_location,
        FinalLocation = task.m_final_location };
        dgvFutureTasks.DataSource = taskArray.ToArray();

I want this code in the form's constructor so that the columns can be formatted, and I won't have to reformat them every time data in the grid is updated.
When I actually have data to display in this datagridview, what do I do with it?  I will call this function:
private void DisplayFutureTasks(IEnumerable<OperationsTaskLabeledData> tasks)

But I don't know what to do inside this function.
I can just re-bind the datagridview control and reformat all of the columns each time the control is updated, but that seems very wasteful.  I'm sure there's a better way to do it, and I'd much rather do this in some reasonable fashion instead of using ugly brute force.

A: I have now figured out how to do what I want to do.
I know the columns I will need at design time, so in the IDE I add the columns to my datagridview and format them as desired.  I then set the AutoGenerateColumns property of the grid view to false.  For some unknown reason, that property is not available in the designer and has to be set in code.  Finally, I can set the DataPropertyName of each column to the name of the corresponding field in the structure I will be linking to.  For example, here is the LINQ code I will be using to generate the data source:
taskArray = from task in tasks select new {
                                StartDate = task.m_start_task_date.ToString("M/dd H:mm"),
                                EndDate = task.m_task_date.ToString("M/dd H:mm"),
                                Description = task.m_short_desc,
                                Object = task.m_device_id,
                                InitialLocation = task.m_initial_location,
                            FinalLocation = task.m_final_location };
.DataSource = taskArray.ToArray();

And here is the code in my form's constructor to set the DataPropertyName properties:
dgvFutureTasks.AutoGenerateColumns = false;
dgvFutureTasks.Columns["colStartTime"].DataPropertyName = "StartDate";
dgvFutureTasks.Columns["colFinishTime"].DataPropertyName = "EndDate";
dgvFutureTasks.Columns["colDescription"].DataPropertyName = "Description";
dgvFutureTasks.Columns["colObject"].DataPropertyName = "Object";
dgvFutureTasks.Columns["colInitialLocation"].DataPropertyName = "InitialLocation";
dgvFutureTasks.Columns["colFinalLocation"].DataPropertyName = "FinalLocation";

At this point, the DataGridView displayed the data as expected.
RobR


Q: previous website advertise on the google advert on the currently visited website I have observed that when I visit some websites (e.g. ebay, flipkart, etc) and move on to another website, I start to see items from the previous website on the google advert on the currently visited website.
ie , when the visitor moves on from 'mysite.com' to another website 'example.com', i need to display advertisement of 'mysite.com' (to promote mysite.com) on exmaple.com's google advert area.
how this works? is we have any control on this? or google is handling this?

A: Although this is off-topic but to answer your question, this is called re-targeting. You can do that using google adwords program - it works through the use of cookies.

A: It's called remarketing in AdWords and there are various flavours of it on the platform. There are dedicated remarketing campaign type templates available when creating a new campaign in AdWords.


Q: rowExpansion inside datatable inside multiple tabs inside tabview referring to row object in last tab only I have a p:tabView several dynamic p:tab, each of these tabs contain an identical p:dataTable. Ech datatable row contains a p:rowExpansion.
Problem:
When I click the rowToggler for any row it always uses the row from the last tab.
Symptoms:
If I go to tab1 and click expand on row1, then the contents are build using the row1 from the last tab.
If I go to tab1 and click expand on row10 where there is only 9 rows in the last tab, then the row object is null.
Solutions?
I understand that the rowExpansion is loaded lazily, so only once the rowToggler is clicked. Is there a way to prevent this and load the contents upfront? This would solve my problem perfectly.
Alternatively, is there a way to give the rowExpansion any hint as to which row it belongs to? Can I access the current rowKey or rowIndex in order to pass it on to the backing bean?
What I tried
Ideally, the tabs should be dynamic, so I use c:forEach and put my datatable under that.
I also tried to hardcode the tabs and use ui:include under those with my datatable in a separate xhtml file, but no change.
The closest question related to my problem I found was:
Primefaces dataTable inside tabView the row selection not working correctly
But there was no answer for it.
Here is what is looks like:

        <p:tabView rendered="#{controller.model.hasPerformances}"
                   styleClass="#{controller.fontClass} }"
                   activeIndex="#{controller.model.performanceIndex}">
            <p:ajax event="tabChange" listener="#{controller.onTestTabChanged}"/>
            <c:forEach var="performance" items="#{controller.model.performances}">
                <p:tab title="#{controller.getPerformanceDisplayName(performance)}">

                    <p:dataTable id="testTable"
                                 var="row"
                                 value="#{controller.model.testData.getRows(performance)}"
                                 styleClass="#{controller.fontClass}"
                                 style="margin-top: 10px;"
                                 widgetVar="testTable">

                        <f:facet name="header">
                            <div style="height:30px;">
                                #{controller.getPerformanceTestTitleName(performance)}
                            </div>
                        </f:facet>

                        <p:column style="width:1ch" class="tlga-table-column-expand" exportable="false">
                            <p:rowToggler/>
                        </p:column>

                        <p:columns value="#{controller.model.testData.columns}"
                                   var="column"
                                   style="#{column.style}"
                                   styleClass="#{row.getCellClass(column)}"
                                   columnIndexVar="colIndex">
                            <f:facet name="header">
                                <h:outputText value="#{column.title}"/>
                            </f:facet>
                            <h:outputText value="#{row.getCellValue(column)}"/>
                        </p:columns>

                        <p:rowExpansion>
                            <p:dataGrid columns="3"
                                        styleClass="test-collapsed-area"
                                        value="#{row.collapsedCells}"
                                        var="collapsedCell">
                                <p:panelGrid columns="2" styleClass="test-collapsed-value">
                                    <h:outputLabel value="#{collapsedCell.title}"
                                                   class="#{controller.fontClass} presentation-label"/>
                                    <h:outputText value="#{collapsedCell.value}"
                                                  class="#{controller.fontClass} presentation-text"/>
                                </p:panelGrid>
                            </p:dataGrid>
                        </p:rowExpansion>
                    </p:dataTable>

                </p:tab>
            </c:forEach>

        </p:tabView>
    </p:panel>


Q: How to keep a variable in memory until the app quits I have a singleton object in iOS that when instantiated parses a CSV file and then holds the results. I would like to make this object universally accessible and I would like it to not be released from memory until the app quits. I am running ARC so I cannot do manual retains.
Is there a way I can do this so it will work with ARC?
Header File:
#import <Foundation/Foundation.h>
#import "CHCSV.h"
#import "RCParserObject.h"

@interface ParserStore : NSObject <CHCSVParserDelegate>
{
    // CSV Variables
    RCParserObject *item;
    NSMutableArray *data;
    NSMutableArray *parsedData;
    int fields;
    bool open;
}

@property (atomic, retain) RCParserObject *item;
@property (atomic, retain) NSMutableArray *data;
@property (atomic, retain) NSMutableArray *parsedData;
@property (atomic) int fields;
@property (atomic) bool open;

+ (ParserStore *) defaultStore;

- (void) parseCSVFile:(NSString*)file;
- (void) categorizeData;

Implementation File
#import "ParserStore.h"
#import "RCParserObject.h"
#import "RCDetailItem.h"

static ParserStore *defaultStore;

@implementation ParserStore

@synthesize item, data, parsedData, fields, open;

# pragma mark -
# pragma mark Singleton Methods

+ (ParserStore *) defaultStore
{
    if (!defaultStore)
    {
        defaultStore = [[super allocWithZone:NULL] init];
    }
    return defaultStore;
}

+ (id) allocWithZone:(NSZone *)zone
{
    return [self defaultStore];
}

- (id) init
{
    NSLog(@"Running init on parser store");

    if (defaultStore)
    {
        NSLog(@"Self data count is %d, right before return", self.parsedData.count);
        return defaultStore;
    }

    // NSLog(@"This better only happen once");
    self = [super init];
    [self setParsedData:[[NSMutableArray alloc] init]];
    [self parseCSVFile:@"ContentNoPathFileExt2ASCII"];
    [self categorizeData];
    // NSLog(@"Self data count is %d when first created", self.parsedData.count);

    return self;
}

    @property (atomic, retain) RCParserObject *item;
    @property (atomic, retain) NSMutableArray *data;
    @property (atomic, retain) NSMutableArray *parsedData;
    @property (atomic) int fields;
    @property (atomic) bool open;

    + (ParserStore *) defaultStore;

    - (void) parseCSVFile:(NSString*)file;
    - (void) categorizeData;

    @end

A: +(MySingleton *)singleton {
    static dispatch_once_t pred;
    static MySingleton *shared = nil;
    dispatch_once(&pred, ^{
        shared = [[MySingleton alloc] init];
        shared.someVar = someValue; // if you want to initialize an ivar
    });
    return shared;
}

From anywhere:
NSLog(@"%@",[MySingleton singleton].someVar);

Note that your iOS app already has a singleton that you can access anywhere:
AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];

A: a simple singleton would be something like... in the .h:
@interface Foo : NSObject

+ (Foo *)sharedInstance;

@end

and in the .m:
static Foo *_foo = nil;

@implementation Foo

+ (Foo *)sharedInstance {
  if (!_foo)
    _foo = [[Foo alloc] init];
  return _foo;
}

@end


Q: Continuous Animation Android I want to make an image move on the Y axis downwards but then come back in the initial position not by redrawing but also by animation. How can I do this? I have tried 2 ways: creating 2 separate animations in the .java file, and then by creating an xml. In the xml I've tried writing a  command inside another < set> command and didn't work. Also i've tried a  command inside another < translate> command. So ... any ideas may be appreciated!

A: Android includes some commands in code rather than XML that will move things around.  There's a great guide here that will help you learn how to implement them.
From there, implement an animation listener to tell when the first animation ends (as seen in the Google documentation here) ain order to start the second animation after the first.


Q: Tkinter - Entry widget text to go to next line instead of continuing to the side so I made my entry widget for user input and made ipady larger. I thought this would make it so the text will automatically go to the next line but the text continues on. Is it possible to make the entry so that the text goes down instead and if it passes the length of ipady then create a scrollbar?
    def body(self, master):
#input fields for username and passwords
        Label(master, text="Name:").grid(row=1, column=1, sticky=W),
        Label(master, text="Date:").grid(row=2, column=1, sticky=W)
        Label(master, text=":").grid(row=4)
        Label(master, text=":").grid(row=3, column=3)
        Label(master, text=":").grid(row=5)
        Label(master, text=":").grid(row=7)
        Label(master, text="L").grid(row=6)

        self.text = tk.StringVar()
        self.text.set(':')

        self.text1 = tk.StringVar()
        self.text1.set(':')

#input fields for tags
#Entry fields
        self.e1 = Entry(master)
        self.e2 = Entry(master)
        self.e3 = Entry(master, textvariable = self.text)
        self.e4 = Entry(master)
        self.e5 = Entry(master, textvariable = self.text1)
        self.e6 = Entry(master)
        self.e7 = Entry(master)

#Entry field Placement
        self.e1.grid(row=1, column=1, columnspan=2, ipadx=50)
        self.e2.grid(row=2, column=1, columnspan=2, ipadx=50)
        self.e3.grid(row=4, column=1, ipadx=150)
        self.e4.grid(row=4, column=3, ipadx=150, ipady=75)
        self.e5.grid(row=5, column=1, ipadx=150, ipadx=75)
        self.e6.grid(row=5, column=3, ipadx=150)
        self.e7.grid(row=6, column=1, ipadx=10, sticky=W)

A:
Is it possible to make the entry so that the text goes down instead ...?

No, it is not. The Entry widget is specifically designed for single-line input. If you need multiple lines you need to use the Text widget.

A: Entry widgents have only a single line. You'll have to use a 'Text' widget and print ('\n') for every entery letter.


Q: Tabs click not working when using ng-repeat I have a script to add custom tabs on runtime.All the tabs are being created but for some reason those created with ng-repeat can't be selected, is like a plain label. What am I missing?

News

Meet the team

Related articles

Videos

{{t.Title}}

    <asp:Literal ID="AddNewTab" runat="server"></asp:Literal>


Q: SQL most efficient way to check if rows from one table are also present in another I have two DB tables each containing email addresses
One is mssql with 1.500.000.000 entries
One is mysql with    70.000.000 entries

I now want to check how many identical email addresses are present in both tables.
i.e. the same address is present in both tables.
Which approach would be the fastest:
1. Download both datasets as csv, load it into memory and compare in program code
2. Use the DB queries to get the overlapping resultset.
if 2 is better: What would be a suggested SQL query?

A: I would go with a DBQuery. Set up a linked server connection between the two DBs (probably on the MSSQL side), and use a simple inner join query to produce the list of e-mails that occur in both tables:
select a.emailAddress
from MSDBServ.DB.dbo.Table1 a
join MySqlServ.DB..Table2 b
    on a.EmailAddress = b.EmailAddress

Finding the set difference, that's going to take more processor power (and it's going to produce at least 1.4b results in the best-case scenario of every MySql row matching an MSSQL row), but the query isn't actually that much different. You still want a join, but now you want that join to return all records from both tables whether they could be joined or not, and then you specifically want the results that aren't joined (in which case one side's field will be null):
select a.EmailAddress, b.EmailAddress
from MSDBServ.DB.dbo.Table1 a
full join MySqlServ.DB..Table2 b
    on a.EmailAddress = b.EmailAddress
where a.EmailAddress IS NULL OR b.EmailAddress IS NULL

A: Table1 has the 70,000,000 email addresses, table2 has the 1,500,000,000.  I use Oracle so the Upper function may or may not have an equivalent in MySQL.
Select EmailAddress from table1 where Upper(emailaddress) in (select Upper(emailaddress) from table2)

Quicker than comparing spreadsheets and this assumes both tables are in the same database.

A: You could do a sql query to check how many identical email addresses are present in two databases: first number is how many duplicates, second value is the email address.
SELECT COUNT(emailAddr),emailAddr FROM table1 A
INNER JOIN
table2 B
ON A.emailAddr = B.emailAddr


Q: Import bacpac from SQL Azure into local server fails.
We are trying to import a bacpac into a local SQL 2017 instance but it gives the following error. This suddenly started happening, previously we didn't have any problem with it so I can't think of any change that could have caused this.
Copying the SQL database via the portal into another SQL Azure server still works thou.
This is a rather big database (12GB of data, bacpac is around 900mb thou).
I'm really baffled why he is giving me some sort of SQL Server 2014 error.
My current SQL server version:
Microsoft SQL Server 2017 (RTM) - 14.0.1000.169 (X64)   Aug 22 2017 17:04:49   Copyright (C) 2017 Microsoft Corporation  Developer Edition (64-bit) on Windows 10 Pro 10.0  (Build 16299: )

A: Please install the  latest versions of SSMS, then try to run the wizard again. Please download the latest version from here.

A: I know this is not a permanent solution but by removing the FK constraints it could export and import the database. It was all focused around 1 rather large table.
I have no idea what's the possible underlying issue here. Now I have to copy the production database to another server on Azure, remove the constraints there and back-up that database instead but it gets the job done.


Q: ASP.NET DataList for a single item Context: In an ASP.NET application, I need the behavior of the ItemTemplate / EditItemTemplate that the  DataList control provides. However, I only need one item in my control, which makes the DataList seems like overkill.
Question: Is there a control in ASP.NET made to store a single item that has the template content behavior of the DataList and DataGrid? Should I use a DataList for only one item?

A: Why don't you use the FormView or DetailsView? They are meant to display one item (at the time).


Q: Plotly.js draw shape to ymax In plotly.js i want do draw a rectangle, that goes from a certain y-coordinate to the top of the plot (i.e. max y that is displayed). Following figure shows what i currently have.  And here the code that i am using to draw it:
{
type: 'rect',
xref: 'x',
yref: 'y',
x0: 0,
y0: 0,
x1: 5,
y1: 9000,
// ... visuals
}

Instead i want the y-coordinates of the rectangle to begin at 9000 (something like y0: 9000) and always end at the top of the plot (y1: ~12400), without having to manually declare y1. Is that possible?
Thank you very much for help!

A: y0 and y1 value 0-1 refer the yaxis amplitude.
So you can set y0 and y1 value 0-1 in your layout configuration of the shape and setting the yref as 'paper'. Further documentation can be found here.
 {
    type: 'rect',
    xref: 'x',
    yref: 'paper',
    x0: 0,
    y0: 0, //y0: 0~1 range
    x1: 5,
    y1: 1,//y1: 0~1 range
    // ... visuals
    }

Example


Q: Getting null values while reading application.yaml file in java I am trying to fetch the data from my application.yaml file which contain profile details, into variables
application.yaml file contents
spring.profiles.active: dev
---
spring.config.activate.on-profile: dev

application.id : dev-app
my.server : localhost:8080
---
spring.config.activate.on-profile: uat

application.id : uat-app
my.server : localhost:8081

App.java
@SpringBootApplication
public class App {

@Value("${application.id}")
private String applicationId;

@Value("${my.server}")
private String server;

 public static void main(String args[]) {

    SpringApplication.run(App.class, args);

    App app = new App();
    app.display();

}

public void display(){
   System.out.println("Application Id : "+ applicationId);
   System.out.println("Server : "+ server);
}

}

Output:
2022-06-08 19:38:29 main INFO  App:640 - The following 1 profile is active: "dev"
2022-06-08 19:38:30 main INFO  App:61 - Started App in 2.266 seconds (JVM running for 3.345)
Application Id : null
Server : null

Could you please help me to understand why it is not picking the values from yaml file?

A: in your yml, what you have is formatted in a ".properties' file format, you need to format your property to yml format. So, your yml file should be in the format (something like this):
spring:
  profiles:
    active: dev
  config:
    activate:
  onProfile: dev

application:
  id : dev-app

etc...


Q: How to replace  youtube link to using Regex in Yahoo pipe Most of Youtube video included to the website using  tag,
Is there any way to convert such iframe:
<iframe height="360" frameborder="0" width="640" src="www.youtube.com/embed/Xz3zC0axQwA?feature=player_detailpage" allowfullscreen=""></iframe>

to finally look only like this:
http://www.youtube.com/embed/Xz3zC0axQwA

I would like to use Regex + Yahoo pipe

A: RegEx: (?:<iframe.+src=")([^"]+)(?:.*>)
Then you'll have a captured group $1 containing only the src url.


Q: Image path to stored in Pinia not passing through to component I'm creating a card carousel with a Spotify style thumbnail, (image as background, text on top). Content is stored in a Pinia store which I will be hooking up to Firebase eventually. I'm trying to set the image background but am getting this error
GET http://127.0.0.1:5173/%60$%7B%7Bcontent.image%7D%7D%60 404 (Not Found)
Here is my store code (condensed to the important bits)
export const useContentStore = defineStore('contentStore', {
  state: () => {
    return {
      guides: [{
        title: 'XX',
        date: 'X',
        description: "X",
        image: './assets/images/content/thumbnail.png',
        id: '1',
      }]
    }
  }
})

Here is where I am trying to access that image path
<template>

{{content.title}}

</template>

And here is where the cards are being called
<template>

Guides

      <GeneralCard
        v-for="(content, index) in contentStore.guides"
        :key="content.id"
        :content="content"
      />

</template>

My gut instinct is that it's an issue with transferring the string through the store to the template, but I don't have any clue how to fix it. I've tried escaping the characters, using template literals on both the stored path and the image tag, played with URL() a bit, and I'm pretty sure it's not an issue with the actual path of the image (it works when I plug the path directly into the image tag)
Thanks for any help you can give!

A: The src attribute on the img is set improperly. It should be


Q: On the algebraic formulation of the Clifford algebra I apologize in advance for a rather wordy question.
As a physicist trying to learn new mathematics, I figured this was the place to ask. I am having trouble understanding the algebraic formulation of Clifford algebras and I am (hopefully) looking for some clarity.
I will say from the get-go, that my understanding of quotient spaces and ideals are elementary. By this I mean, that I understand the basic definitions at  face-value and some of the simpler examples, though both subjects has always been somewhat confusing to me. So forgive my ignorance in advance.
What I understand:
Up until now, my understanding of Clifford algebras is the following (I'll be brief and omit details):
If $(V,g)$ is a vector space, equipped with a symmetric, bilinear form $g : V \times V \rightarrow \mathbb{F}$, then the Clifford algebra $\text{C}\ell (V,g)$  of $V$ is the algebra spanned by the elements of $V$, subject to the condition that $v^2=g(v,v)$.
From this, I can deduce and understand that $\text{C}\ell^{\pm} (\mathbb{R}^n)$ is the algebra generated by the vectors subject to $v_i v_j +v_j v_i = \pm 2 \delta_{ij}$. I understand also that the Clifford product of any two vectors $u,v$ may be written as $uv=u \cdot v + u \wedge v$, where $u \cdot v$ is the inner product and $u \wedge v$ is the wedge product. From this, the representations of the various Clifford algebras follows (both in the real and complex cases) and I'm pretty happy.
What I don't understand:
Now, if  I move on to more advanced texts, I often come across the following:
If $T(V)$ is the tensor algebra $T(V) := \bigoplus_{k=0}^{\infty} V^{k \otimes}$, with $T^0(V) = \mathbb{F}$, then the Clifford algebra $\text{C}\ell(V,g)$ is the quotient $\text{C}\ell (V,g)=T(V)/I(V)$ of $T(V)$ by the ideal $I(V)$, generated by the elements of the form $v \otimes u + u \otimes v -2g(u,v)$.
Though I know what all the ingredients are, I simply do not see the correlation between this definition and the more "geometric" notion of a Clifford algebra! All my intuitions about the subject are gone.
From my (again, very basic) understanding of quotient spaces, $\text{C}\ell (V,g)$ should be the space of equivalence classes, where $u \sim v$ iff $u = v+w$ for some $w \in I(V)$.
Working from the definition of the ideal, I can deduce that $u \otimes v \sim \frac{1}{2}(u\otimes v-v \otimes u)+g(u,v) = u \wedge v + g(u,v)$, but I cannot get much further and it does not do any wonders for my understanding.
I will try to be concrete:
Questions:
1) How is the "algebraic" definition of the Clifford algebra $\text{C}\ell(V,g)$ (above) related to the concept of the Clifford algebra as the algebra generated by elements in $V$, subject to the condition that $v^2=g(v,v)$ (in the most general sense)?
2) How does one obtain the Clifford product, now that the Clifford algebra is a space of equivalence classes?
3) Why is this definition of the Clifford algebra "useful", as opposed to the geometric formulation?

A: I'm also going to start with a bit of a disclaimer: my knowledge of Clifford Algebras is fairly elementary (I know the algebraic definition, I have a vague idea that they're useful in physics in some way and that quantum group theorists all care about them, and they're occasionally interesting examples of things that I do care about), but I do know a fair amount about tensor products, tensor algebras, quotient spaces and the like, so hopefully we can get somewhere between us.

*

*I think it might be most useful here if I start with an example, I'll use the same one that you used: $\mathcal{Cl}^{\pm}(\mathbb{R}^n)$. To show that the two conditions being imposed are equivalent, use the Polarization Identity: $u\otimes v + v\otimes u = 2g(u,v) = g(u+v,u+v)-g(u,u)-g(v,v)$, so taking $u = v$ gives $v\otimes v = \frac{1}{2}(g(2v,2v)-2g(v,v)) = g(v,v)$ (the other direction is by a proof identical to the one that you used for the $\mathcal{Cl}^\pm(\mathbb{R}^n)$ example). I think the key thing to notice here is that your "subject to the condition that..." is already a quotient: quotienting out by the ideal generated by a set $S$ is exactly the same as imposing the condition that all elements in $S$ are zero. In this case, your $v^2 = g(v,v)$ condition corresponds exactly to quotienting out by the ideal generated by all elements of the form $v^2 - g(v,v)$, which that proof mentioned above will show is precisely the ideal in your algebraic definition.

*Essentially, exactly the same as in the other case: we have a distinguished copy of $V$ living inside $\mathcal{Cl}(V,V)$, and we can extend $g$ from that to the whole of $\mathcal{Cl}(V,V)$ (this is yet another thing that breaks in the characteristic 2 case).

*Basically, because we know an awful lot about tensor products and quotient algebras, and it's kinda useful to be able to make use of that. Also, because it is, in many ways, more concrete than your geometric definition: whereas you say "the [free-est] algebra generated by the elements of $V$", this definition simply substitutes in what that free-est algebra is: it's the quotient of the free algebra generated by $V$ by the ideal associated to that condition, and the free algebra generated by $V$ is exactly that infinite direct sum of tensor products of $V$ in the algebraic definition. So all that this definition is doing is taking your definition, and writing down what all of the things in it actually are.


Q: Micro optimize pointer + unsigned + 1 Hard as it may be to believe the construct p[u+1] occurs in several places in innermost loops of code I maintain such that getting the micro optimization of it right makes hours of difference in an operation that runs for days.
Typically *((p+u)+1) is most efficient.  Sometimes *(p+(u+1)) is most efficient.  Rarely *((p+1)+u) is best. (But usually an optimizer can convert *((p+1)+u) to *((p+u)+1) when the latter is better, and can't convert *(p+(u+1)) with either of the others).
p is a pointer and u is an unsigned.  In the actual code at least one of them (more likely both) will already be in register(s) at the point the expression is evaluated.  Those facts are critical to the point of my question.
In 32-bit (before my project dropped support for that) all three have exactly the same semantics and any half decent compiler simply picks the best of the three and the programmer never needs to care.
In these 64-bit uses, the programmer knows all three have the same semantics, but the compiler doesn't know.  So far as the compiler knows, the decision of when to extend u from 32-bit to 64-bit can affect the result.
What is the cleanest way to tell the compiler that the semantics of all three are the same and the compiler should select the fastest of them?
In one Linux 64-bit compiler, I got nearly there with p[u+1L] which causes the compiler to select intelligently between the usually best *((p+u)+1) and the sometimes better *(p+( (long)(u) + 1) ).  In the rare case *(p+(u+1)) was still better than the second of those, a little is lost.
Obviously, that does no good in 64-bit Windows.  Now that we dropped 32-bit support, maybe p[u+1LL] is portable enough and good enough.  But can I do better?
Note that using std::size_t instead of unsigned for u would eliminate this entire problem, but create a larger performance problem nearby.  Casting u to std::size_t right there is almost good enough, and maybe the best I can do.  But that is pretty verbose for an imperfect solution.
Simply coding (p+1)[u] makes a selection more likely to be optimal than p[u+1].  If the code were less templated and more stable, I could set them all to (p+1)[u] then profile then switch a few back to p[u+1].  But the templating tends to destroy that approach (A single source line appears in many places in the profile adding up to serious time, but not individually serious time).
Compilers that should be efficient for this are GCC, ICC and MSVC.

A: The answer is inevitably compiler and target specific, but even if 1ULL is wider than a pointer on whatever target architecture, a good compiler should optimize it away.  Which 2's complement integer operations can be used without zeroing high bits in the inputs, if only the low part of the result is wanted? explains why a wider computation truncated to pointer width will give identical results as doing computation with pointer width in the first place.  This is why compilers can optimize it away even on 32bit machines (or x86-64 with the x32 ABI) when 1ULL leads to promotion of the + operands to a 64bit type.  (Or on some 64bit ABI for some architecture where long long is 128b).

1ULL looks optimal for 64bit, and for 32bit with clang.  You don't care about 32bit anyway, but gcc wastes an instruction in the return p[u + 1ULL];.  All the other cases are compiled to a single load with scaled-index+4+p addressing mode.  So other than one compiler's optimization failure, 1ULL looks fine for 32bit as well.  (I think it's unlikely that it's a clang bug and that optimization is illegal).
int v1ULL(std::uint32_t u) { return p[u + 1ULL]; }
//   ...  load u from the stack
//    add     eax, 1
//    mov     eax, DWORD PTR p[0+eax*4]

instead of
    mov     eax, DWORD PTR p[4+eax*4]

Interestingly, gcc 5.3 doesn't make this mistake when targeting the x32 ABI (long mode with 32bit pointers and a register-call ABI similar to SySV AMD64).  It uses a 32bit address-size prefix to avoid using the upper 32b of edi.
Annoyingly, it still uses an address-size prefix when it could save a byte of machine code by using a 64bit effective address (when there's no chance of overflow/carry into the upper32 generating an address outside the low 4GiB).  Passing the pointer by reference is a good example:
int x2   (char *&c) { return *c; }
//    mov     eax, DWORD PTR [edi]  ; upper32 of rax is zero
//    movsx   eax, BYTE PTR [eax]   ; could be byte [rax], saving one byte of machine code

Err, actually I forget.  32bit addresses might sign-extend to 64b, not zero-extend.  If that's the case, it could have used movsx for the first instruction, too, but that would have cost a byte because movsx has a longer opcode than mov.
Anyway, x32 is still an interesting choice for pointer-heavy code that wants more registers and a nicer ABI, without the cache-miss hit of 8B pointers.

The 64bit asm has to zero the upper32 of the register holding the parameter (with mov edi,edi), but that goes away when inlining.  Looking at godbolt output for tiny functions is a valid way to test this.
If we want to make doubly sure that the compiler isn't shooting itself in the foot and zeroing the upper32 when it should know it's already zero, we could make test functions with an arg passed by reference.
int v1ULL(const std::uint32_t &u) { return p[u + 1ULL]; }
//  mov     eax, DWORD PTR [rdi]
//  mov     eax, DWORD PTR p[4+rax*4]


Q: Azure pipeline powershell and git on windows server 2019 gives error in output I have a problem with azure pipeline and one of my servers.
The server where it fails is  a windows 2019 server.
If I in powershell call git, then it treats all warnings and following lines as errors.
If I do the same thing on two og my different servers - no issues - even though same outout.
This is the error returned:
CD to  D:\web\test\testsite.com
 ##[error]git : Warning: Permanently added the RSA host key for IP address 'X' to the list of known hosts.
##[error]git : From bitbucket.org:SITE
##[error]At C:\azagent\A1\_work\_temp\c1ff2d2b-c773-4adc-9040-155e92a914bd.ps1:12 char:1
+ git pull origin master
+ ~~~~~~~~~~~~~~~~~~~~~~
##[error]    + CategoryInfo          : NotSpecified: (From bitbucket....b/fletcocarpets:String) [], RemoteException
##[error]    + FullyQualifiedErrorId : NativeCommandError
##[error]
##[error]PowerShell exited with code '1'.

Git does make the pull and everything is actually OK. But for some reason - on this server - azure pipelines treats the text as errors.
Any ideas why? hard to explain the problem aswell properly on text.
This is how its returned on the server where it works, as an example:
CD to  D:\web\testsite.com
Warning: Permanently added the RSA host key for IP address 'X' to the list of known hosts.
From bitbucket.org:SITE
* branch            master     -> FETCH_HEAD
 ...
 1 file changed, 27 insertions(+), 23 deletions(-)
 ##[section]Finishing: PowerShell Script - GIT

A: I found out what helped me. Thought I had tried it - but seems not:
Added this to the top. for some reason this server and git needs this:
$env:GIT_REDIRECT_STDERR = '2>&1'


Q: Brought a Linux C++ Console Application to a Win32 C++ App using VS2010 and the search function from  is no longer working Just like the title says, I've been working on a fairly large program and have come upon this bug. I'm also open to alternatives for searching a file for a string instead of using . Here is my code narrowed down:
istreambuf_iterator<char> eof;
ifstream fin;
fin.clear();

fin.open(filename.c_str());

if(fin.good()){
 //I outputted text to a file to make sure opening the file worked, which it does
}

//term was not found.
if(eof == search(istreambuf_iterator<char>(fin), eof, term.begin(), term.end()){
   //PROBLEM: this code always executes even when the string term is in the file.
}

So just to clarify, my program worked correctly in Linux but now that I have it in a win32 app project in vs2010, the application builds just fine but the search function isn't working like it normally did. (What I mean by normal is that the code in the if statement didn't execute because, where as now it always executes.)
NOTE: The file is a .xml file and the string term is simply "administration."
One thing that might or might not be important is to know that filename (filename from the code above) is a XML file I have created in the program myself using the code below. Pretty much I create an identical xml file form the pre-existing one except for it is all lower case and in a new location.
void toLowerFile(string filename, string newloc, string& newfilename){
  //variables
  ifstream fin;
  ofstream fout;
  string temp = "/";
  newfilename = newloc + temp + newfilename;
  //open file to read
  fin.open(filename.c_str());
    //open file to write
    fout.open(newfilename.c_str());
    //loop through and read line, lower case, and write
    while (fin.good()){
      getline (fin,temp);
        //write lower case version
        toLowerString(temp);
        fout << temp << endl;
    }
    //close files
    fout.close();
    fin.close();
}

void toLowerString(string& data){
    std::transform(data.begin(), data.end(), data.begin(), ::tolower);
}

A: I'm afraid your code is invalid - the search algorithm requires forward iterators, but istreambuf_iterator is only an input iterator.
Conceptually that makes sense - the algorithm needs to backtrack on a partial match, but the stream may not support backtracking.
The actual behaviour is undefined - so the implementation is allowed to be helpful and make it seem to work, but doesn't have to.
I think you either need to copy the input, or use a smarter search algorithm (single-pass is possible) or a smarter iterator.
(In an ideal world at least one of the compilers would have warned you about this.)

A: Generally, with Microsoft's compiler, if your program compiles and links a main() function rather than a wmain() function, everything defaults to char. It would be wchar_t or WCHAR if you have a wmain().  If you have tmain() instead, then you are at the mercy of your compiler/make settings and it's the UNICODE macro that determines which flavor your program uses.  But I doubt that char_t/wchar_t mismatch is actually the issue here because I think you would have got an warning or error if all four of the search parameters didn't use the same the same character width.
This is a bit of a guess, but try this:
if(eof == search(istreambuf_iterator<char>(fin.rdbuf()), eof, term.begin(), term.end())


Q: How to get a User's Group from Azure Active Directory after Authentication After registering an app in my azure active directory, i can get the user in a callback :
    object(Magium\ActiveDirectory\Entity)#262 (1) {
  ["data":protected]=>
  array(16) {
    ["aud"]=> string(36) "xxxxxxxxxxxxxxxxxxxx"
    ["iss"]=> string(75) "https://login.microsoftonline.com/xxxxxxxxxxxxxxxxxxxx/v2.0"
    ["iat"]=> int(xxxxxxxxxxxxxxxxxxxx)
    ["nbf"]=> int(xxxxxxxxxxxxxxxxxxxx)
    ["exp"]=> int(xxxxxxxxxxxxxxxxxxxx)
    ["aio"]=> string(140) "xxxxxxxxxxxxxxxxxxxx"
    ["email"]=> string(20) "xxxxxxxxxxxxxxxxxxxx@xxxxxxxxxxxxxxxxxxxx.com"
    ["idp"]=> string(61) "https://sts.windows.net/xxxxxxxxxxxxxxxxxxxx/"
    ["name"]=> string(13) "xxxxxxxxxxxxxxxxxxxx"
    ["oid"]=> string(36) "xxxxxxxxxxxxxxxxxxxx"
    ["preferred_username"]=> string(20) "xxxxxxxxxxxxxxxxxxxx@xxxxxxxxxxxxxxxxxxxx.com"
    ["sub"]=> string(43) "xxxxxxxxxxxxxxxxxxxx"
    ["tid"]=> string(36) "xxxxxxxxxxxxxxxxxxxx"
    ["uti"]=> string(22) "xxxxxxxxxxxxxxxxxxxx"
    ["ver"]=> string(3) "2.0"
    ["access_token"]=> string(1910) "xxxxxxxxxxxxxxxxxxxx"
  }
}

but how do i access the group he belongs to which i have declared in my azure active directory?
ps: the code to get the user is this:
    @php
session_start();

$config = [
    'authentication' => [
    'ad' => [
        'client_id' => 'xxxxxxx',
        'client_secret' => 'xxxxxxx',
        'enabled' => 'yes',
        'directory' => "xxxxxxx",
        'return_url' => 'xxxxxxx'

        ]
    ]
];

$request = new \Zend\Http\PhpEnvironment\Request();

$ad = new \Magium\ActiveDirectory\ActiveDirectory(
    new \Magium\Configuration\Config\Repository\ArrayConfigurationRepository($config),
    Zend\Psr7Bridge\Psr7ServerRequest::fromZend(new \Zend\Http\PhpEnvironment\Request())
);

$entity = $ad->authenticate();
echo $entity->getName() . '
';
echo $entity->getPreferredUsername() . '
';
@endphp

I clicked on Azure Active Directory-> Groups -> Create a group -> add users -> done.
Thats how i created the group.
But in my callback for the user i cant get it to work.
I am completely clueless please help.
Thanks a ton guys!

A: You are looking for a memberOf attribute which it seems is not present. If you are using openLDAP, memberof attribute is hidden by default. Check that setting once. Also make sure that anonymous access is allowed for this attribute.


Q: How to add a sliding div to these CSS Message Bubbles? new to webdev so bear with me. I am developing a prototype of a Messaging Application, I have most of the basics worked out and I'm trying to add the little touches to make it feel nicer to use. I'm trying to make it so that when an individual message is hovered over, the time that message was sent will slide out from the message.
Here is my code at the moment: http://codepen.io/RBrNx/pen/GNzOWr
(Note: Click on "Toni" again and his message will appear, small bug. You can also send messages from the text box).
Now here are some images showing what I mean:
http://imgur.com/a/elB04
Ideally I think the 2nd one would look better.
I tried to implement it by adding a span inside the bubble like so:

Test Message13.45

.hover-time{
   position: relative;
   left: 60px;
}

But that made the inside of the bubble stretch to account for the Span.
How can this be done?
EDIT: Thanks to Antidecaf I managed to get the left side working and figured out the right hand side as well. Here is the CSS I added:
.container .right .bubble.you .hover-time {
    display: none;
    position: absolute;
    left: 110%;
    color: #999;
    width: 100px;
}

.container .right .bubble.me .hover-time {
    display: none;
    position: absolute;
    right: 90%;
    color: #999;
    width: 100px;
}

These deal with the left hand messages (from the person you are messaging) and the right hand messages (from me). I also added:
.container .right .bubble.you:hover .hover-time{
    display: inline-block;
}
.container .right .bubble.me:hover .hover-time{
    display: inline-block;
}

So that the hover-time span is shown on hover.

A: You can do this with the markup you suggested by positioning .hover-time relative to .bubble. To do this, add position: relative to .bubble and position: absolute to .hover-time. Here's some more info on the technique.

13.45Test Message

CSS for positioning timestamp to the right:
.bubble {
    position: relative;
}

.hover-time {
    position: absolute;
    left: 110%;
    color: #999;
}

Same approach goes for positioning it to the left, but in this case you'll need to add a bit of margin to the bubble in order to free up space for the timestamp:
.bubble {
    position: relative;
    margin-left: 50px;
}

.hover-time {
    position: absolute;
    left: -50px;
    color: #999;
}

A:

Test Message 13.45

Works for me. You'll probably want to spice it up a little with some transform or other fancy anim stuff.
EDIT: Perhaps you meant like so:

Test Message 13.45

Border and width just to have a visual guide.

A: Maybe I'm misunderstanding, but are you styling the DIV as the speech bubble, then taking the span inside the div and telling it 'but not you buddy, you are special'?
If so, isn't it cleaner and less headaches to put your text message in a span also, styling the span as text bubble, and keeping the div as an invisible structural element?


Q: React Native overlapping touchables trigger at the same time I've got two Touchables that overlap. Clicking the overlapping area makes them both fire. I want only the child onPress event to trigger (i.e. only the onUpVote/onDownVote function).
<TouchableHighlight onPress={onPress} underlayColor={colors.focus}>
  <View style={styles.container}>
    <AppText>{question.content}</AppText>
    <View style={styles.voteContainer}>
      <UpVoteButton
        voted={voted}
        voteCount={question.upVotes}
        onPress={onUpVote}
      />
      <DownVoteButton
        voted={false}
        voteCount={question.downVotes}
        onPress={onDownVote}
      />
    </View>
  </View>
</TouchableHighlight>

and that's the VoteButton element
<TouchableWithoutFeedback onPress={onPress}>
  <View style={styles.voteContainer}>
    <AppText style={styles.voteCount}>{voteCount}</AppText>
    <AntDesign
      name={voted ? "like1" : "like2"}
      style={{
        fontSize: 18,
        color: defaultStyles.colors.focus,
        paddingBottom: 3,
      }}
    />
  </View>
</TouchableWithoutFeedback>

The idea is that if the user presses the thumbs up/down icon area then the onDownVote gets handled. Pressing anywhere else within the list item is supposed to take you to a different screen.
App layout

A: I'd suggest to import TouchableOpacity from here:
https://github.com/software-mansion/react-native-gesture-handler
Both overlapping touchables should fire onPress prop


Q: DeepStack - Prepare dataset / custom models with Python and LabelIMG I'm looking to buy Blue Iris as it incorporates DeepStack AI and the capability to train custom models.
I started to follow the DeepStack win / PC "Prepare dataset / custom models" guide, see below
https://docs.deepstack.cc/custom-models/datasetprep/index.html#step-1-install-labelimg

*

*Install Python 3.10.7 (ok)

*Type pip3 install pyqt5 lxml in Python - however this syntax does not work?

I hope someone can provide guidance to resolve this issue or recommend an alternative option.


Q: how to inject an instance of configuration when creating instance of the injected class? I have a simple situation:
class MyClass @Inject() (configuration: Configuration) {

    val port = configuration.get[String]("port")

    ...

}

and now I want to use MyClass in some other object:
object Toyota extends Car {

  val myClass = new MyClass(???)

  ...

}

but I dont know how when I use MyClass i give it the configuration instance i annotated that will be injected when MyClass is going to be instantiated..
im using play2.6/juice/scala
thanks!

A: First of all, you should decide if dependency injection is really what you need. Basic idea of DI: instead of factories or objects themselves creating new objects, you externally pass the dependencies, and pass the instantiation problem to someone else.
You suppose to go all in with it if you rely on framework, that is why no way of using new along with DI. You cannot pass/inject a class into the scala object, here is a draft of what you can do:
Play/guice require some preparation.
Injection Module to tell guice how to create objects (if you cannot do this if annotations, or want to do it in one place).
class InjectionModule extends AbstractModule {
  override def configure() = {
    // ...
    bind(classOf[MyClass])
    bind(classOf[GlobalContext]).asEagerSingleton()
  }
}

Inject the injector to be able to access it.
class GlobalContext @Inject()(playInjector: Injector) {
  GlobalContext.injectorRef = playInjector
}

object GlobalContext {
  private var injectorRef: Injector = _

  def injector: Injector = injectorRef
}

Specify which modules to enable, because there can be more than one.
// application.conf
play.modules.enabled += "modules.InjectionModule"

And finally the client code.
object Toyota extends Car {

  import GlobalContext.injector

  // at this point Guice figures out how to instantiate MyClass, create and inject all the required dependencies
  val myClass = injector.instanceOf[MyClass]

  ...

}

A simple situation expanded with a frameworks help. So, you should really consider other possibilities. Maybe it would be better to pass the configs as an implicit parameter in your case?
For dependency injection with guice take a look at:
ScalaDependencyInjection with play and Guice wiki