text:
Q: Python: how to click on an opened outlook email (win32) I need to click on an opened outlook email, a specific approve link that says "Approve request".
I opened the wanted email correctly, but I can't click on the specific link.
Here is the code:
import win32com.client

outlook=win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox=outlook.GetDefaultFolder(6)

messages = inbox.Items
messages.Sort("[ReceivedTime]", Descending=True)

for i in range(100):
    message = messages.GetNext()
    print(""+message.Subject, str(message.ReceivedTime))
    if message.Subject == "Mail to approve request":
        message.Display(False)

    else:
        pass

A: You will need to parse the MailItem.HTMLBody property, extract the relevant link, launch the browser with that link.
Also, never loop through all items in a folder, use Items.Find/FindNext or Items.Restrict with a query like "[Subject]='Mail to approve request'"

A: There are several ways to open a hyperlink programmatically in Python. The How to open a URL in python page explains possible scenarios. For example:
import os
os.system("start \"\" https://example.com")

Use the HTMLBody property which returns the a string representing the HTML body of the specified item. So, you may find the required URL programmatically by parsing the message body and execute it programmatically.
And, finally, to find items that correspond to your conditions use the Find/FindNext or Restrict methods of the Items class. Read more about them in the following articles:

*

*How To: Use Find and FindNext methods to retrieve Outlook mail items from a folder (C#, VB.NET)

*How To: Use Restrict method to retrieve Outlook mail items from a folder
See Filtering Items Using Query Keywords for building a search criteria string properly.
Also you may find the AdvancedSearch method of the Application class helpful. The key benefits of using the AdvancedSearch method in Outlook are:

*

*The search is performed in another thread. You don't need to run another thread manually since the AdvancedSearch method runs it automatically in the background.

*Possibility to search for any item types: mail, appointment, calendar, notes etc. in any location, i.e. beyond the scope of a certain folder. The Restrict and Find/FindNext methods can be applied to a particular Items collection (see the Items property of the Folder class in Outlook).

*Full support for DASL queries (custom properties can be used for searching too). You can read more about this in the Filtering article in MSDN. To improve the search performance, Instant Search keywords can be used if Instant Search is enabled for the store (see the IsInstantSearchEnabled property of the Store class).

*You can stop the search process at any moment using the Stop method of the Search class.

Read more about this method in the Advanced search in Outlook programmatically: C#, VB.NET article.


text:
Q: UI5 Application breaks when called as Component So, I have this UI5 Application which works perfectly fine when called thru index.html, however it breaks (resources not found, failed to load,404 error etc) when I try to call it as Component. Both the applications (Caller & Callee) are on Gateway
Here is the application folder structure.
callee_app-Struct.jpg
link to GitHub - https://github.com/mailsandip/component_test

all the views are under zui5_trip_confirmation -> views folder..The images and models are in the respective folders.
The component.js is under the folder Component and is defined as
// define a new UIComponent
jQuery.sap.declare("components.Component");
jQuery.sap.require("sap.ui.core.UIComponent");
jQuery.sap.require("sap.ui.commons.Button");
jQuery.sap.require("sap.ui.table.Table");
//new Component
sap.ui.core.UIComponent.extend("components.Component", {
    metadata : {
        properties : {
            text: "string"
        }
    }
});
components.Component.prototype.createContent = function(){
/* trying to register the path zui5_trip_confirmation where all the views are stored */
sap.ui.localResources("zui5_trip_confirmation");
// jQuery.sap.registerModulePath('zui5_trip_confirmation','/sap/bc/ui5_ui5/sap/zui5_trip_conf/zui5_trip_confirmation');
    this.oView = sap.ui.jsview("idHome", "zui5_trip_confirmation.views.Home");
     return this.oView;
};

The caller application calls it as
jQuery.sap.registerModulePath('components','/sap/bc/ui5_ui5/sap/zui5_trip_conf/components');
var oComp1 = sap.ui.getCore().createComponent({
        name: "components",
        id: "Comp1",
        settings: {text: "Hello World"}
    });

    var oCompCont1 = new sap.ui.core.ComponentContainer("CompCont1", {
        component: oComp1
    });
    oCompCont1.placeAt("content");

When I run the caller application, I get resource not found errors on the console. Basically the Component is not able to resolve the path to the views/models/images.
What could be wrong here?
Regards
Sandip

A: With
jQuery.sap.registerModulePath('components','/sap/bc/ui5_ui5/sap/zui5_trip_conf/components')

You tell the core to look for everything that starts with "components" in "/sap/bc/[...]".
Then you say that the component name is "components". Shouldn't that be "components.Component"?
Ok, Update with Example:
(I hope this makes it clearer)
The most important part: We register the path to the folder of the component file and assign it a prefix. Inside the component we start every single Object/Element/Control/etc. with the same prefix as the component. (In your case: "zui5_conf_try").
I created the example on my server: http://dev.himmelrath.net/ui5/so_componentExample/ and you can download all the files here: http://dev.himmelrath.net/ui5/so_componentExample.zip
Ouside the component, when creating the ComponentContainer in the index.html, we register the path to all the components parts by registering its prefix.
index.html:
<!DOCTYPE HTML>

<meta http-equiv="X-UA-Compatible" content="IE=edge">

zui5_conf_try/Components.js:
// define a new UIComponent
jQuery.sap.declare("zui5_conf_try.Component");

//jQuery.sap.require("sap.ui.core.Core");
jQuery.sap.require("sap.ui.core.UIComponent");
jQuery.sap.require("sap.ui.commons.Button");
jQuery.sap.require("sap.ui.table.Table");

//new Component
sap.ui.core.UIComponent.extend('zui5_conf_try.Component',{
    metadata : {
        version : "1.0",
    },

    // DO NOT overwrite the components init method - it is used internally
    // and calls the createContent-method
    /*
    init: function() {
        alert('init222');
    },
    */

    createContent: function() {
        // Using sap.ui.localResources('views'); in this context would still
        // register the path relative to our index.html, not the Component.js
        // so we do not use it. Instead we use the same prefix as the component
        // for our views, because we know that that path must be set correctly
        // if this file has been loaded.

        // This should look for "./views/Home.view.js" relative to the components
        // path, since the components path was registered in the index.html ouside
        // the component
        var view = sap.ui.jsview("idHome", "zui5_conf_try.views.Home");
        return view;
    }
});

zui5_conf_try/views/Home.view.js:
sap.ui.jsview("zui5_conf_try.views.Home", {

   getControllerName: function() {
      return "zui5_conf_try.views.Home";
   },

   createContent: function(oController) {
      var oButton = new sap.ui.commons.Button({text:"I am zui5_conf_try.views.Home"});
      oButton.attachPress(oController.handleButtonClicked);
      return oButton;
   }

});

zui5_conf_try/views/Home.controller.js:
sap.ui.controller("zui5_conf_try.views.Home", {
   handleButtonClicked : function() {
        alert("You just clicked the view button...");
   }
});

A: Ok, so looked at it a bit more - looks like the resources are not being loaded by the Component.js , even though there is an explicit loading mentioned
--inside component.js ----

sap.ui.localResources('views');
sap.ui.resources('images');

  var view = sap.ui.jsview("idHome", "views.Home");
  return view;

---- exit ----

This is what confuses me, the core should have loaded the views with respect to the Component.js location. The same problem happens with images folder.
This seems like an issue with the Component framework.

Regards
Sandip

redpajama_set_name: RedPajamaStackExchange


text:
Q: titanium backup - Stuck on seaching application data I saved a backup with titanium, installed a different rom (clean install) and then now I am ready to restore my backup. The problem is:
When I open Titanium, it's stuck at "Searching Application Data" message and it won't let me do anything.
I already tried:

*

*uninstall and reinstall Titanium

*tried with a older version

*tried removing SU permission (no message but I can't do anything)

*tried typing in the terminal as suggested on XDA developers the following

su
restorecon -FR /data/media/0

*

*with no luck

I don't know what else to try. My backup folder has stuff in it, I just need to be able to launch the app...
Any idea? Sorry I can't be more precise but I don't really know any more details than that, apart that I am on android 7.1.1.
thanks

A: I had this issue with my S7, and I solved it by:

*

*Booting into TWRP

*Factory Reset

*Flash Lineage

*Flash OpenGapps

*Flash SuperSU SR5

*Reboot

*Install TitaniumBackup

*Restore Apps

A: I had exactly the same problem with Cyanogenmod 14.1 Nightly (the last available one from 25/12/2016) on an OnePlus One, and I've tried all the things you've done. But after deleting some unused apps I was able to start Titanium Backup. I'm sorry I can't explain this, but maybe you'll be able to run Titanium Backup by deleting some Apps.

A: I managed to fix it by reinstalling the ROM from scratch.
After a full wipe, and a complete fresh re-install, it started to work perfectly (still on android 7.1.1)

A: I fix this issue by manually moving the back up files (needed only) to another folder (will be set as back up location in the preference).. i guess some back up file cause the issue


text:
Q: How to show the change itself using git log pickaxe? I would like to search git log for a specific string to find where it was modified/deleted/added.
I knew that I can do this using pickaxe (i.e., git log -S"Text")
When I run this command, only the names of the commits where the change has occurred are shown. I also tried git log -G"Text" but no difference.
When I tried git log -p -S"Text", it showed me full comparision between two versions of files.
Is there a way to spot the exact location (line) where the text has been changed/added/deleted?
I checked related posts 1, 2 but didn't answer my question. I'm working on Windows OS.

A: Git doesn't provide a built-in way to do this, but you could use the capabilities of your pager to find the text.  For example, if you're using less, you can run git log -p -G"Text". Then you can search for "Text" in the output of this command by typing /Text. This is by far the easiest way to find what you're looking for.
There is an alternative, rather ugly way to hack around this which might meet your needs.  If you use --word-diff-regex=Text, Git will produce an alternative word-diff format which will highlight from one instance of "Text" to the next, or just the single instance if only one exists. Again, using your pager is going to be a lot nicer and easier to read.

A: Another way to achieve your goal would be to use an external diff driver, and the grepdiff utility from the patchutils package. (I answered a similar question for Linux here).
Caveat: I don't use Windows, and it seems patchutils is not available in the usual Windows package managers. So a prerequisite to this answer would be to compile grepdiff yourself (which might be too much :P). If you can do that, and find a way to install it inside Git Bash, then this approach might work.

*

*First create a script under C:\Program Files\Git\usr\bin and name it pickaxe-diff (Note: again, I don't use Windows, but I'm reading on SO that this is an easy way to add stuff to your Git Bash PATH) :
#!/bin/bash

# pickaxe-diff : external diff driver for Git.
#                To be used with the pickaxe options (git [log|show|diff[.*] [-S|-G])
#                to only show hunks containing the searched string/regex.

path=$1
old_file=$2
old_hex=$3
old_mode=$4
new_file=$5
new_hex=$6
new_mode=$7

filtered_diff=$(diff -u -p $old_file $new_file | \
                grepdiff "$GREPDIFF_REGEX" --output-matching=hunk | \
                grep -v -e '+++ ' -e '--- ')

a_path="a/$path"
b_path="b/$path"

echo "diff --git $a_path $b_path"
echo "index $old_hex..$new_hex $old_mode"
echo "--- $a_path"
echo "+++ $b_path"
echo "$filtered_diff"

*Call git log -G and tell Git to use the pickaxe-diff script as an external diff driver:
export GREPDIFF_REGEX=<string>;
GIT_EXTERNAL_DIFF=pickaxe-diff git log -p --ext-diff -G $GREPDIFF_REGEX

This will use the pickaxe-diff script just to generate the diffs, so the rest of the git log output (commit hash, message, etc) will be untouched.
Caveat
The way that the Git pickaxe work is that it limits the output to the files whose hunks change the given string/regex. This means that if another hunk in these files also contain the search string/regex, but does not change it, it will still be displayed with the above script. This is a limitation of grepdiff (up to version 0.3.4). A recently merged pull request at the patchutils project added an --only-match flag to grepdiff, which should provide the needed functionality to correctly filter out these hunks (you would need patchutils 0.4.0 or higher).

I did a write-up of my solution in this gist.


text:
Q: Do GPO login scripts run in remote desktop / terminal services sessions? I've created a login script that fires up a quick data collection task for our network inventory software. However, we have a couple 2008 servers that run Terminal Services, and a high number of users frequently RDP into it 24/7. I'd rather this particular script not run on these servers at logon because it's an unnecessary waste of server resources. I'd rather the script only run when they log onto a PC locally.
Do logon scripts, by default, run in a terminal services / remote desktop session, and if so, is there a way to configure them not to? How would I go about doing that?

A: Just check the domain of the user account before login and exit the script if it is not the same as the server name.

A: Put a Read Deny permission for the terminal server computer account on the GPO in the security advanced settings. The computer has to read the GPO before it can apply it for the user, so the deny will prevent it.


text:
Q: Too long filename prevents load of texture in three.js This is totally unbelievable. It is so that a man can go crazy. I was loading textures from a filepath like this:
pic/ekiFear.jpg
pic/ekiAnger.jpg
and so on...
The pathname is not even long but is nested into quite a deep directory if starting from the C:// or something like that. But that should not matter in this case since I am almost in the same directory?
However I had a couple of textures and the way I loaded them was indentical but only the "ekiFear"-texture loaded. The others didn't appear but there was no error message when trying to load them.
Anyway I shortened the filenames but this is madness. What if I had not had one texture with a short name. I would rip my hair before finding the problem. I don't think it should be like this. Should I send the code to MrDoob or is the problem something on my computer?


text:
Q: What is the difference between 'mapleader' and 'g:mapleader' in Vim? I don't understand the difference between let mapleader="," and let g:mapleader=",". I know that g: means that it's a global variable, but I don't clearly understand the difference. Which one should I use in my .vimrc file?

A: let mapleader=","

as stated in the doc.
Why would you want to use g:mapleader? g: is mostly used in plugins to let global variables in order to expose settings to other plugins or for you to play with in your .vimrc.

A: If the aforementioned statements are both located outside of function
definitions, they have the identical effect of setting a global variable. However, if the first statement, without the g: prefix, is used in
a function body, it defines a variable local to that function.
See :help internal-variables and especially :helpg In a function:.
Hence, outside function definitions one can access the global map-leader
variable simply as mapleader.


text:
Q: Mongoose Query Help: Paginate, Sort, Limit on Nested Array I am have a chat Mongoose model in the below is the sample data.  If this is still not clear please revert back to me with your questions. Any help is greatly appreciated.
        {
            "_id" : ObjectId("5745910831a1sd58d070a8faa"),
            "messages" : [
                {
                    "user" : "user1",
                    "message" : "How are you user1?",
                    "readInd" : "N",
                    "createDate" : ISODate("2016-05-25T11:36:00.468+0000"),
                    "_id" : ObjectId("5745912c31a1c58d070a904d")
                },
                {
                    "user" : "user1",
                    "message" : "Hello user1",
                    "readInd" : "N",
                    "createDate" : ISODate("2016-05-25T11:38:53.893+0000"),
                    "_id" : ObjectId("5745912531a1c58d070a902e")
                }
            ],
            "createDate" : ISODate("2016-05-25T11:35:20.534+0000"),
            "users" : [
                "57450b4506561ff5052f0a66",
                "57450d8108d8d22c06cf138f"
            ],
            "__v" : NumberInt(0)
        },
        {
            "_id" : ObjectId("57458e9331a1c58d070a8e30"),
            "messages" : [
                {
                    "user" : "user2",
                    "message" : "How are you user2",
                    "readInd" : "N",
                    "createDate" : ISODate("2016-05-25T11:46:03.240+0000"),
                    "_id" : ObjectId("574590f331a1c58d070a8ede")
                },
                {
                    "user" : "user2",
                    "message" : "Hello user2",
                    "readInd" : "N",
                    "createDate" : ISODate("2016-05-25T11:48:53.925+0000"),
                    "_id" : ObjectId("574590e931a1c58d070a8eab")
                }
            ],
            "createDate" : ISODate("2016-05-25T11:35:20.534+0000"),
            "users" : [
                "5745149e3aaab38706c00b64",
                "57450d8108d8d22c06cf138f"
            ],
            "__v" : NumberInt(0)
        }
        {
            "_id" : ObjectId("5745910831a1c58d070a8faa"),
            "messages" : [
                {
                    "user" : "user3",
                    "message" : "How are you user3?",
                    "readInd" : "N",
                    "createDate" : ISODate("2016-05-25T11:56:00.468+0000"),
                    "_id" : ObjectId("5745912c31a1c58d070a904d")
                },
                {
                    "user" : "user3",
                    "message" : "Hello user3",
                    "readInd" : "N",
                    "createDate" : ISODate("2016-05-25T11:58:53.893+0000"),
                    "_id" : ObjectId("5745912531a1c58d070a902e")
                }
            ],
            "createDate" : ISODate("2016-05-25T11:35:20.534+0000"),
            "users" : [
                "57450b4506561ff5052f0a66",
                "57450d8108d8d22c06cf138f"
            ],
            "__v" : NumberInt(0)
        },
        {
            "_id" : ObjectId("5745910831a1c58d070a8faa"),
            "messages" : [
                {
                    "user" : "user4",
                    "message" : "How are you user4?",
                    "readInd" : "N",
                    "createDate" : ISODate("2016-05-25T11:66:00.468+0000"),
                    "_id" : ObjectId("5745912c31a1c58d070a904d")
                },
                {
                    "user" : "user4",
                    "message" : "Hello user4",
                    "readInd" : "N",
                    "createDate" : ISODate("2016-05-25T11:68:53.893+0000"),
                    "_id" : ObjectId("5745912531a1c58d070a902e")
                }
            ],
            "createDate" : ISODate("2016-05-25T11:35:20.534+0000"),
            "users" : [
                "57450b4506561ff5052f0a66",
                "57450d8108d8d22c06cf138f"
            ],
            "__v" : NumberInt(0)
        }

below is the explanation:

*

*user1 sent 2 messages at 11:36 and 11:38 respectively

*user2 sent 2 messages at 11:46 and 11:48 respectively

*user3 sent 2 messages at 11:56 and 11:58 respectively

*user4 sent 2 messages at 11:66 and 11:68 respectively

My Expected Result is:
Pagination/limit Criteria:

*

*show 2 records per page.

*show only the Most recent message based on user.

Sample output:
Page1:
   "user" : "57450d8108d8d22c06cf138f",
   "message" : "How are you user4?"

   "user" : "57450d8108d8d22c06cf138f",
   "message" : "How are you user3?"

Page2:
   "user" : "57450d8108d8d22c06cf138f",
   "message" : "How are you user2"

   "user" : "57450d8108d8d22c06cf138f",
   "message" : "How are you user1?"

A: try this way of query , this is help to u
query for page one
db.getCollection('message').aggregate( [ { $match : { user : "57450d8108d8d22c06cf138f" } },
{ $unwind : "$messages" } ,
{ $sort : { 'messages.createDate' : -1} },
 { $limit : 2 },
 { $project : { _id: 0,'message':'$messages.message','user':'$messages.user'} } ])

query for next page
db.getCollection('message').aggregate( [ { $match : { user : "57450d8108d8d22c06cf138f" } },
    { $unwind : "$messages" } ,
    { $sort : { 'messages.createDate' : -1} },
     { $limit : 2 },{ $skip : 2 }
     { $project : { _id: 0,'message':'$messages.message','user':'$messages.user'} } ])


text:
Q: How do I troubleshoot static noise in headphones connected to a computer that persists even after replacing the sound card? I have an Asus P6T based system. I was using the on-board sound (plugging in Logitech X-230 2.1 analog speakers in the green "front speakers" 3.5mm analog output, then plugging in my headphones in that). I was quite happy with the sound quality (didn't hear any static noise if volume was turned down to my normal listening level).
Then about a week ago I started having terrible static noise from the left channel, and no normal audio on that left channel. Right channel had more static noise than usual but did have a bit of sound. I tried using the AC'97 in front of my case but that seemed to have no signal.
I decided my on-board sound card has gone bad and bought an internal sound card to replace it (Startech 7.1Ch PCI). This fixed the "no sound from left channel problem", but I still had a fairly audible static noise (not the really terrible one after my on-board sound went bad, but worse than when it was working well).
I decided the card was low quality and/or it had interference from all the other things happening inside the computer case, and bought a Sweex SC016 external USB sound card.
But even with that I have static noise in headphones (though better than with the Startech card). Positioning the USB sound card differently doesn't seem to help. Trying the other analog outputs (e.g., surround) doesn't help.
The static noise in all cases is proportional to the volume.
I have tried different headphones, but the situation is similar though perhaps the flavour of the static noise changes slightly.
So what are my options?  What is the cause of the problem, and what hardware do I need to replace?
tl;dr - Two different sound cards both still have static noise in headphones.

A: The question title has been rephrased since I created, but basically I solved my problem.
I ordered a mid-range PCI-E sound card (Asus Xonar DX) and the static noise is gone.
Whether the source of the static with the cheap PCI card and cheap external USB card was poor product quality or something else, I don't know. Perhaps you get what you pay for; the new card was about 3 times more expensive than either of these previous cards.
This is not to be constituted as endorsment of Asus products, the on-board sound card that died and caused all the issues was also by Asus. Probably a quality replacement sound card by another manufacturer would work just as fine.

A: I solved a similar problem by buying a optical output converter from ebay. Costs about $10. You can search for "Digital Optical Toslink SPDIF Converter". Go for a version with the optical cable and power supply. If your motherboard have a Toslink/SPDIF optical output, this doesn't propagate grounding noise. Some versions have power through USB cable, but it's important to power it independently, and not on the computer's USB, but on the same outlet to avoid ground loops. I also tried putting ferrite loops on the cables, but this alone didn't help.
If your motherboard don't have optical sound i'm afraid the only solution is going for the soundcard, which is much more expensive.


text:
Q: Ubuntu live CD shows windows network despite fresh HDD & unplugged cable I suspect that I had been hacked after I found a remote connection file in Windows that was set to execute a file called "Remote connection phone" or something. After booting into ubuntu live CD, Ubuntu showed me a Windows network but whenever I clicked on it it said "unable to connect".
I am using a desktop and never used W-Lan, only an ethernet cable. The network didn't disappear so I was thinking that this must've had something to do with my windows partition so I formated the entire disk and removed everything on it.
I had the ethernet cable still unplugged even until this point(writing this post from a friends computer).
So after erasing my disk I thought just to be sure, I once again booted into the Linux live CD and to my surprise the windows network is still showing up. still unable to connect to it. Not a tech geek, but my guess is that my machine has been hacked by someone withing close vincinity and it looks to me they somehow gained wireless access to my PC. A room mate or neighbor? What do you guys think?


text:
Q: Convert JSON to object type in Angular I'm having real trouble converting a JSON array to collection of objects in Angular. I've not used Angular for some time, please forgive me if any of my terminology is incorrect.
I have the following products.json file in my project:
[
  {
    "id": 1,
    "name": "Pen",
    "description": "The finest blue pen.",
    "relatedProducts": [2]
  },
  {
    "id": 2,
    "name": "A4 Paper",
    "description": "A4 sized printer paper.",
    "relatedProducts": [1]
  }
]

This product.ts file:
export class Product {
    Id: number;
    Name: string;
    Description: string;
    RelatedProducts: Array<number>;
}

My app.component.ts file:
import * as ProductsJson from '../../json-data/products.json';
import { Component, OnInit } from '@angular/core';
import { Product } from 'src/app/models/product';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  productsJson: any = ProductsJson;
  products: Array<Product>;

  ngOnInit() {
    this.products = <Product[]>this.productsJson;
    console.log(this.products);
  }
}

And finally my app.component.html:

    {{p.Id}} {{p.Name}}

My console log shows the JSON data but it seems as though I'm making some error trying to convert it to a list of Product objects. This is also preventing me from successfully using ngFor in my view as the console error shows, so nothing shows on the page. How can I perform this conversion correctly so the loop works and this data is shown on the view?

A: **- Use interface instead of class for Product.**

      export interface Product {
        id: number;
        name: string;
        description: string;
        relatedProducts: number[];
    }

**- If you need a class, then specify the parameterised constructor to assign variable values.**

  export class Product {
    id: number;
    name: string;
    description: string;
    relatedProducts: number[];

  constructor(product) {
     this.id = product.id;
    this.name: product.name;
    this.description: product.description;
    this.relatedProducts: product.relatedProducts;
   }
}

**and then inside the component you can use**

this.products = new Product(this.productsJson); // if Product is a class

OR

this.products = this.productsJson; // if Product is an interface

A: you can use class-transformer which helps you to convert plain javascript objects to real es6 classes. With this real instances you can also use class methods.
import { Component, OnInit } from "@angular/core";
import ProductsJson from "./products.json";
import {plainToClass} from "class-transformer";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  productsJson: any = ProductsJson;
  products: Array<Product>;
  constructor() {}
  ngOnInit() {
    //this.products = <Product[]>this.productsJson;
    this.products = plainToClass(Product, this.productsJson as []);
    console.log(this.products);
  }
}
export class Product {
  id: number;
  name: string;
  description: string;
  relatedProducts: Array<number>;

  getId(){
    return this.id + "_ID";
  }
}

template:

        {{p.getId()}} {{p.id}} {{p.name}}

A: look at stackblitz
Let me know still you have an issue..
thanks

A: Your model should look like below,
export interface Product {
    id: number;
    name: string;
    description: string;
    relatedProducts: number[];
}

Change the products as
 products: Product[];

and then,
this.products = this.productsJson;

A: Adding to Kushal Shah answer
this also works.
import { Component, OnInit } from "@angular/core";
import ProductsJson from "./products.json";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {

  products = <Product[]>ProductsJson;;

  constructor() {}

  ngOnInit() {
    console.log(this.products);
  }

}

export class Product {
  id: number;
  name: string;
  description: string;
  relatedProducts: Array<number>;
}

A: step by step:
Component.ts
The first, you have unuseless variables you have reduce keeping just one 'products' and initializing just like that the following code.
In ngOnInit() you must to load the array initialized before. The way to do that is casting with type any cause importing from local json generates another data model, you have to access to the property 'default' and that's all.
import * as ProductsJson from '../../json-data/products.json';
import { Component, OnInit } from '@angular/core';
import { Product } from 'src/app/models/product';

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  products: Array<Product> = new Array<Product>();

  ngOnInit() {
    this.products = (ProductsJson as any).default;
    console.log(this.products);
  }

}

Component.html
Another point to change is properties naming you have 'Id' & 'Name' instead of 'id' and 'name'.

    {{p.id}} {{p.name}}

Entities
Product Class have to change the properties naming without Capital letters to have a correspondence with the Json Data or change Json data model to the Class anyway.
If I were you I will change also Product, using interface instead Class
export interface Product {
  id: number;
  name: string;
  description: string;
  relatedProducts: Array<number>;
}

A: UPDATE 1 [ You can go declarative way of rxjs too ]..
Use of operator of rxjs to create new stream of observable from your json file.
import {of} from 'rxjs'

productsJson = of <Product []>(ProductsJson);

export interface Product{
      id: number;
      name: string;
      description: string;
      relatedProducts: Array<number>;
}

and then in your template you can simply use async pipe ...

    {{p.id}} {{p.name}}

Update 2 [ You can simply use JSON.parse() and JSON.stringify() ]..
 productsJson: any = JSON.parse(JSON.stringify(ProductsJson));

and then use this in template like this...

     {{item.id }}

A: import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
   selector: 'app-hello-world',
   templateUrl: './hello-world.component.html',
   styleUrls: ['./hello-world.component.css'],
})
export class HelloWorldComponent implements OnInit {
   jsonString: string = '[{"title":"test"},{"title":"test2"}]';
   jsonObj: Array<object>;
   jsonObj2: Array<object> = [{ title: 'test' }, { title: 'test2' }];
  constructor() {
     this.jsonObj = JSON.parse(this.jsonString);
     this.jsonString = JSON.stringify(this.jsonObj2);
  }

  ngOnInit() {}
}


text:
Q: Boot Mac Virtual Machine into Recovery Mode Using Windows Keyboard I have a Mac OS X virtual machine running on my Windows 10 Dell laptop. Now I want to boot the Mac VM into the recovery mode, it's expected to press and hold Command + R key combination at the boot time. But I just have a Windows keyboard, there is no either Command or Option key. So I use the Windows + R keys together but it doesn't work. Please help me get into recovery mode! Thanks!

A: Not going to happen, you have no recovery partition, nor any Apple boot ROM to act upon the Cmd/R combination even if you had a Mac keyboard.


text:
Q: Android what exactly does mediaplayer error 1, -107 mean Today I got much this error message from MediaPlayer :
06-03 17:44:02.707: E/MediaPlayer(20140): error (1, -107)

Only I can found is "-1007"'s error code describe, but that's not what I want.
And there is no anything about -107 I can find in API document.
What exactly the error code extra="-107" mean ?
Please help me to found out, thank you~

A: I have also been receiving this error message and tried sifting through the Android source code to no avail.
The only thing I can find on Google is this page (in Chinese) which seems to think it is related to a Network Link Error.


text:
Q: Refresh view in a TabItem I have a view in my first tab that changes data in a DatageStorageController. When I click the second tab it is supposed to show the datastorage but the view is not updated. How can I refresh the view? It is not a UITable View just a View.

A: I think you are write code into viewDidLoad. You should write this code into viewWillAppear Which do you want to update. on ViewAppear.
OR
Second method you can use delegate method of tabbarcontroller
Like

*

*(void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController

With this method you can receive argument viewController which you are selected.
[viewController viewDidLoad];
It's mean you load view again.
you also call
[viewController viewWillAppear];

A: well, you could implement the UITabBarDelegate protocol and update your controllers view in
'tabBar:didSelectItem'. But this approach is maybe not the most clean one! The second controller should somehow be notified on data changes, so that he can update its view. Maybe take a look at KVO/KVC!


text:
Q: who can help me to count the average of all these numbers, typeORM? who can help me to count the average of all these numbers, and show in company object?
company is connected to categories with the many-to-many connection, as well as review is connected to company with the many-to-one connection . rating is connected to review with one-to-one.
  public async getAll({ skip, take, query, categoriesId }: CompanyFilterDto) {
    const queryBuilder = this._companyRepository
      .createQueryBuilder('company')
      .leftJoinAndSelect('company.categories', 'categories')
      .leftJoin('company.review', 'reviews')
      .leftJoin('reviews.rating', 'rating')
      .groupBy('company.id, categories.id')
      .addSelect('avg(rating.device + rating.ensure + rating.education + rating.socialBonuses + rating.salary + Rating.fines + rating.careerGrowth + Rating.geography + Rating.comfort + Rating.complexity)/5' , 'rating')
      .andWhere('company.isDeleted = :bool', { bool: false })
      .orderBy('company.id', 'DESC');
    if (query) {
      queryBuilder.andWhere('LOWER(company.title) LIKE :query', {
        query: `%${query}%`,
      });
    }
    if (categoriesId.length > 0) {
      queryBuilder.andWhere('categories.id IN (:...categoryIds)', {
        categoryIds: categoriesId,
      });
    }
    queryBuilder.take(take).skip(skip);
    const [companies, companiesCount] = await queryBuilder.getManyAndCount();
    return { companies, companiesCount };
  }


text:
Q: Removing metadata from components in generated swagger and their associated $refs in responses We are using the Swashbuckle.AspNetCore package for swagger.  We have a lot of calls that return polymorphic objects such as SortEntry<type> or VersionedObject<type> and it seems that the generated components in the swagger contains a bunch of meta data about these objects like such:
"Data.SortEntry`1[[Data.Search.Enums.DetailsSortType, Data, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]"

Not to get too into the weeds but this is only really a problem due to our process, where we validate the API contract using the generated swagger.  So this metadata causes problems because it contains a version property that will change each time and fail our build.
My question is, is there a way to suppress this metadata that is being generated?  In previous versions of Swashbuckle (<3.0) this was not a problem for whatever reason.
Edit:  Here is an example of what one of these components would look like in back when we were using Swashbuckle.AspNetCore 2.x and generating swagger json v2.0:
SortEntry[DetailsSortType]

We are using Swashbuckle.AspNetCore @ 5.6.3 and are generating OpenAPI 3.0 swagger.

A: After looking through some other issues here I ended up find this:
https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1803
I was able to pull the TypeContext.cs code that was originally available in SwashBuckle.AspNetCore 4.x.x and implement a custom schema id using that.  Works great.


text:
Q: pandas tz_convert giving different offset for same timezone I am trying to use tz_convert function of pandas timestamp object and there I am facing a strange issue. Let's say we have two timestamps, Timestamp('2020-04-16 10:59:36.227000+0000', tz='UTC') and Timestamp('2020-01-29 20:02:32.483000+0000', tz='UTC'). Now when I do the following:
obj1 = pd.Timestamp('2020-01-29 20:02:32.483000+0000', tz='UTC')
obj1.tz_convert('CST6CDT')

#Output: Timestamp('2020-01-29 14:02:32.483000-0600', tz='CST6CDT')

obj2 = pd.Timestamp('2020-04-16 10:59:36.227000+0000', tz='UTC')
obj2.tz_convert('CST6CDT')

#Output: Timestamp('2020-04-16 05:59:36.227000-0500', tz='CST6CDT')

Clearly, for the same timezone the time offset is different. Can someone tell what is the reason of this weird error? I am using pandas version 1.1.4


text:
Q: Trouble understanding the openpyxl axis attributes: axId and crosses I'm unable to interpret what the two attributes do.
This is a code snippet from the openpyxl docs
from openpyxl import Workbook
from openpyxl.chart import (
    LineChart,
    BarChart,
    Reference,
    Series,
)

wb = Workbook()
ws = wb.active

rows = [
    ['Aliens', 2, 3, 4, 5, 6, 7],
    ['Humans', 10, 40, 50, 20, 10, 50],
]

for row in rows:
    ws.append(row)

c1 = BarChart()
v1 = Reference(ws, min_col=1, min_row=1, max_col=7)
c1.add_data(v1, titles_from_data=True, from_rows=True)

c1.x_axis.title = 'Days'
c1.y_axis.title = 'Aliens'
c1.y_axis.majorGridlines = None
c1.title = 'Survey results'

# Create a second chart
c2 = LineChart()
v2 = Reference(ws, min_col=1, min_row=2, max_col=7)
c2.add_data(v2, titles_from_data=True, from_rows=True)
c2.y_axis.axId = 200
c2.y_axis.title = "Humans"

# Display y-axis of the second chart on the right by setting it to cross the x-axis at its maximum
c1.y_axis.crosses = "max"
c1 += c2

ws.add_chart(c1, "D4")

wb.save("secondary.xlsx")

Especially this comment:
Display y-axis of the second chart on the right by setting it to cross the x-axis at its maximum
It states that the y-axis of the second chart (LineChart) shall be displayed on the right. But the opposite is happening in the picture.
Also, what exactly does axId do?
Thanks!


text:
Q: JMS topic get clientID's Can i get ClientID's of all jms topic subscribers? I use Jboss AS 6 (HornetQ).
Off course, i can send query to all of them and read replies, but i'm looking for more elegant solution.

A: With HornetQ you can list all the core-queues using JMX-management.
You can just list the queues under org.hornetq.core (on the JMX view). The client-id will just be part of the name.


text:
Q: autoloader conflicts, fail to open stream I write autoloader in my controller file to load a class file. This load class in the services folder well. But it will cause this issue when load class not in services folder.

[2017-05-11 17:38:23] production.ERROR: exception 'ErrorException'
  with message 'include(/var/www/market/app/services/ProductDomain.php):
  failed to open stream: No such file or directory' in
  /var/www/market/app/controllers/CloudController.php:27

public function __construct()
{
    spl_autoload_register(function($classname) {
        include app_path() . '/services/' . $classname . '.php';
    });
}

This may caused by confilct with other autoloader, may be laravel's autoloader. I want to know how to make my autoloader to just load class file under services folder, remaining other class files to be loaded by laravel framework's autoloader.
How to solve this. Thank you in advance.

A: If file physically exist, and you have correct permission on it (you can do chmod 777 for testing)  Try composer install, after that composer dump-autoload -o

A: I solved this by check the file exist first.  And the autoloaders have loading sequence.
manual,

If there must be multiple autoload functions, spl_autoload_register()
  allows for this. It effectively creates a queue of autoload functions,
  and runs through each of them in the order they are defined. By
  contrast, __autoload() may only be defined once.

public function __construct()
{
    spl_autoload_register(function($classname) {
        if(file_exists(app_path() . '/services/' . $classname . '.php'))
            include app_path() . '/services/' . $classname . '.php';
    });
}

So my defined autoloader will load the php class before laravel framework's autoloader.


text:
Q: .net core Fullcalendar get data by giving month We are using fullcalendar with .net core- ef core. We are getting all the event data by passing it to fullcalendar.That means a lot of event.Then It creates event calendar with theese data default by this month. What I want is make it lazy. When getting data, it would returns only events giving month.
in c#
public JsonResult GetEvents(E_Model model){
     var list = _Service.GetEvents().ToList();
   }

in js ajax calling file
function GetEvents() {

        var events = [];
        $.ajax({
            type: "POST",
            url: "/calHome/GetEvents",
            data: { model: data },
            success: function (data) {
                calender.style.display = 'block';
                $.each(data, function (i, v) {
                    events.push({
                        id: v.id,
                        title: v.name,
                        description: v.description,
              //i got start and end moment
             start: moment(v.start),
                    end: v.end != null ? moment(v.end) : null,});
        })
        GenerateCalender(events);

}

Generate calendar
function GenerateCalender(events) {
    $('#calender').fullCalendar('destroy');
    $('#calender').fullCalendar({
        contentHeight: 800,
        firstDay: 1,
        defaultDate: new Date(),
        timeFormat: 'HH:mm',
 eventLimit: true,
        events: events,
}

ajax GetEvents calls GetEvents in controller it returns json then GetEvents in ajax calls genaretecalendar. When Calling the GetEvents metod in aja.
I want to make it when I press the prev or next button, it will give the month to controller and get data by month. I tryed to listen prev event like
$('.fc-prev-button').one('click',function (e) {
                console.log('prev, do something');
            });

NEW
 events: {
            type: "POST",
            url: "/home/GetEvents",
            data: function () { // a function that returns an object
                return {

                };
            }

Controller
[HttpPost]
 public JsonResult GetEvents(FiltModel model)
                               //model includes string start, end

A: The best way to achieve this is to use the events as JSON feed pattern described in the fullCalendar documentation.
Essentially it works like this: if you tell fullCalendar the URL of your controller action, it will automatically make a new request to the server whenever the date range changes in the calendar (and it does not already have downloaded events for that date range). It will also automatically append "start" and "end" date parameters to the request - so then all your server has to do is read those parameters and use them in your database query to filter the results being returned to the calendar. You can also, optionally, append other relevant data to the request as well - such as your other filter options.
So in your case you would end up with code something like this:
JavaScript - fullCalendar events configuration:
events: {
  type: "POST",
  url: "/home/GetEvents",
  data: function () { // a function that returns an object
  return {
    //your filter object goes here
  };
}

Controller:
[HttpPost]
public JsonResult GetEvents(FiltModel model) {
   //...where the FiltModel class includes start and end parameters - ideally these should be DateTime objects, not strings.

   //... then, query the database using the filter options in the model, and return JSON in the format required by fullCalendar
}


text:
Q: Mock presence of Authorize attribute I was wondering how you could mock that a controller is decorated with the [Authorize] attribute in MVC3? I am using a custom membership provider. I would like to test that a controller been decorated with the attribute and you are authorized and what happens when you are not. I'm using Moq. Any good suggestions on this?!
UPDATE:
I'm currently getting an NullreferenceException saying "object reference not set to an instance of an object". It's the same error as previously mentioned in this post NullReferenceException while using Authorize Attribute
This is related to the Authorize attribute. I'm running under iis and not using cassini. Does anyone know if this is somehow related to applicaton pool and user rights. The tests that I have for the authorize attribute wont work until this is fixed.
Maybe there is some other way of testing the Authorize attribute? Big thanks in advance.
UPDATE2
So after some extensive research and debugging help from a colleague I mentioned to fix the problem with the [Authorize] attribute. It appears as though this line in the web.config was missing:
<modules runAllManagedModulesForAllRequests="true">

Strangely enough this did not cause problem for another colleague that was sharing the trunk or in beta environment. It only caused problems for me locally. This might have been related to something in the GAC. Anyhow all works now.
Thanks.

A: I wrote a blog post about exactly that a couple of months ago:
http://thomasardal.com/unit-testing-attribute-decorations/


text:
Q: Days passed between two java date with different timezone I got two Date but one is CET and the other is CEST.
   Calendar calFrom = Calendar.getInstance();
            calFrom.set( 2013, 2, 20,0,0,0);
            Calendar calTo = Calendar.getInstance();
            calTo.set( 2013, 3, 5,0,0,0);

        long daysPassed= (calTo.getTime().getTime() - calFrom.getTime().getTime()) / (1000 * 60 * 60 * 24);
        System.out.println("calFrom: " + calFrom.getTime());
        System.out.println("calTo: " + calTo.getTime());
        System.out.println("daysPassed: " + daysPassed);

The output says:
calFrom: Wed Mar 20 00:00:00 CET 2013
calTo: Fri Apr 05 00:00:00 CEST 2013
daysPassed: 15

However Microsoft excel says the difference between the two days is 16!
How it is possible to calculate the days passed like Excel?

A: JodaTime seems like to handle this issue:
http://kodejava.org/how-do-i-get-number-of-days-between-two-dates-in-joda/


text:
Q: How to fetch wordpress function in custom page In wordpress how can we use functions like is_user_logged_in(), we can use this function in any page like header.php , sidebar.php
In wordpress page we are making a form which will be submitted using ajax. Suppose we are gatering form's data on a page 'submitform.php' whose url is www.mysite.com/submitform.php which is totally a custom page.
Now how will I be able to know using is_user_logged_in(); function whether user is logged in or not. because submitform.php is a simple page outside wordpress.

A: At the top of your custom PHP file, use the following to load WordPress core functionality. This assumes your file is in the root of the installation:
define('WP_USE_THEMES', false);
require('wp-blog-header.php');


text:
Q: How to match earliest and latest start times and print them out along with their corresponding details? I need to print the earliest and latest start times for each user along with their corresponding information using awk. I am not allowed to use sort. If there is a tie for the latest or earliest start time, then take the one with the UID that comes first alphabetically.
This is what I have tried so far:
BEGIN { }
{
   if( $5 <= $5 ) {
     lateTime = $5;
   }
   else {
     earlyTime = $5;
   }
END {
    print("Earliest Start Time:", $1, $2, $3, $4, earlyTime, $5, $6, $7);
    print("Latest Start Time:", $1, $2, $3, $4, lateTine, $5, $6, $7);
}

I have tried to compare the 5th field with itself as its iterating through, but I'm having trouble with the logic of it all. Any help is appreciated.
I am given this text file.
UID   PID  PPID C STIME TTY    TIME     CMD
adz110 5344 5334 0 08:47 pts/2  00:00:00 bash
dmq292 6908 6854 0 08:53 pts/1  00:00:00 bash
adz110 7227 7150 0 08:54 pts/9  00:00:00 who
erg474 7466 7461 0 08:54 pts/10 00:00:00 ls
dmq292 7966 7960 0 08:55 pts/13 00:00:00 assign1 . sh if of
xle135 8636 8628 0 08:58 pts/15 00:00:00 bash
xle135 8983 8636 0 08:59 pts/15 00:00:00 ssh ctf . cs . utsarr . net
zeh458 9057 1980 0 08:59 pts/7  00:00:00 vim prog . c

and it needs to look like this afterwards:
Earliest Start Time:
adz110 5344 5334 0 08:47 pts/2 00:00:00 bash
Latest Start Time:
xle135 8983 8636 0 08:59 pts/15 00:00:00 ssh ctf.cs.utsarr.net

A: Try this:
awk 'FNR==1{next} FNR==2{timeE=timeL=$5;lineE=lineL=$0;} timeE>$5{lineE=$0;timeE=$5} timeL<$5{lineL=$0;timeL=$5} END{print "Earliest Start Time:\n" lineE "\nLatest Start Time:\n" lineL}' file

Put in multiple lines for readability:
awk '
FNR==1{next}
FNR==2{
    timeE=timeL=$5;
    lineE=lineL=$0;
}

timeE>$5{
    lineE=$0;
    timeE=$5
}

timeL<$5{
    lineL=$0;
    timeL=$5
}

END{
    print "Earliest Start Time:\n" lineE "\nLatest Start Time:\n" lineL
}' file

A: Given the input you provided all you need is:
$ awk 'FNR==2{beg=$0} !seen[$5]++{end=$0} END{print "Earliest" ORS beg ORS "Latest" ORS end}' file
Earliest
adz110 5344 5334 0 08:47 pts/2  00:00:00 bash
Latest
xle135 8983 8636 0 08:59 pts/15 00:00:00 ssh ctf . cs . utsarr . net

If that's not adequate then update your question to provide more truly representative sample input/output.


text:
Q: insert record if not exists in sql, duplicate column name i wanted a solution to insert a record if it isn't there so i searched here and found a solution but i have another problem
INSERT INTO closed_answers (question_id, subject_id)
SELECT * FROM (SELECT 2, 2) AS tmp
WHERE NOT EXISTS (
    SELECT question_id FROM closed_answers WHERE question_id = 2 AND subject_id = 2
) LIMIT 1

the output is
#1060 - Duplicate column name '2'

if i used any 2 numbers that aren't identical it will work but the problem arise when the 2 numbers are the same

A: INSERT INTO closed_answers (question_id, subject_id)
SELECT * FROM (SELECT 2 a, 2 b) AS tmp
WHERE NOT EXISTS (
    SELECT 1 FROM closed_answers WHERE question_id = 2 AND subject_id = 2
) LIMIT 1

Your select statement with the subquery is strange an unnecessary, but the problem was that you did not name the columns being selected.  When using exists, it is sufficient to just select 1, rather than a field.  Also the limit 1 was not necessary.

A: The smallest change to make your SQL work is to add aliases to your select statement:
INSERT INTO closed_answers (question_id, subject_id)
SELECT * FROM (SELECT 2 AS question_id, 2 AS subject_id) AS tmp
WHERE NOT EXISTS (
    SELECT question_id
    FROM closed_answers
    WHERE question_id = 2 AND subject_id = 2
) LIMIT 1

However if you have a unique constraint on (question_id, subject_id) then you can use INSERT IGNORE instead:
INSERT IGNORE INTO closed_answers (question_id, subject_id)
VALUES (2, 2)


text:
Q: Code recognizing first digit in .Value only I have the following code which works except for one issue.
It recognizes the value in column H and highlights rows that do not contain a number of 40 or greater in column H for that row.
However, the code below is actually looking for the first digit to be 4 or great, highlighting any row that starts with the numbers 1, 2 or the as the first digit in column H. Hence, it is highlighting rows where the column H value is 100.
Sub color40()

Sheets("40+").Select

Lastrow = Cells(Rows.Count, 1).End(xlUp).Row
For i = 2 To Lastrow
If Worksheets("40+").Cells(i, 8).Value < "40" Then
    Range(Cells(i, 2), Cells(i, 8)).Interior.color = RGB(160, 140, 150)

End If
Next i

End Sub

A: "40" is text, 40 is a number.  When you wrap a number in quotes it won't evaluate numbers normally, it evaluates them as strings.  Try this:
Sub color40()

Sheets("40+").Select

Lastrow = Cells(Rows.Count, 1).End(xlUp).Row
For i = 2 To Lastrow
If Cells(i, 8).Value < 40 Then
    Range(Cells(i, 2), Cells(i, 8)).Interior.color = RGB(160, 140, 150)

End If
Next i

End Sub

A: If you want to evaluate only 1 digit you can do it using LEFT function.
Syntax:
LEFT( text, [number_of_characters] )

Example:
If LEFT(Worksheets("40+").Cells(i, 8).Value, 1) < 4 Then
    Range(Cells(i, 2), Cells(i, 8)).Interior.color = RGB(160, 140, 150)
End If

Remember to change the value that you need to evaluate.


text:
Q: Elm byte decoding within Http.get I'm pretty new to elm and stuck with a problem regarding populating my model with data from my backend. I'm curently able to make a get request to the server which returns a byte[] (the data is any kind of image,audio or video), which works fine when just displaying this data by for example Html.img. When I try to use Http.get (src: https://package.elm-lang.org/packages/elm/http/latest/Http) to populate my model it requires a decoder. The problem is, that Bytes.Decode.bytes requires an Int to know how many bytes have to be decoded.
So my question is: Is there any way to access the byte width while still matching the type pattern of Http.get?
Here's a simple example of my problem:

import Bytes exposing (Bytes)
import Bytes.Decode exposing (Decoder, bytes, decode)
import GeneralTypes exposing (Msg(..))
import Http

getMediaFromUrl : Cmd Msg
getMediaFromUrl = Http.get
        { url = "http://localhost:8090/image/2006/aa@a.de/session"
        , expect = Http.expectBytes GetThumbnail decodeBytes
        }

decodeBytes: Bytes.Bytes -> Decoder Bytes
decodeBytes bytesToDecode= let
                fileSize =
                    bytesToDecode |> Bytes.width
              in
              Bytes.Decode.bytes fileSize

module GeneralTypes exposing (..)

import Bytes exposing (Bytes)
import Http

type Msg = GetThumbnail (Result Http.Error Bytes)

A: The expectBytes function requires you to specify a Bytes decoder, which is useful if you immediately want to translate the bytes into something more meaningful in your code.
If, however, you want to retain the raw Bytes in your application without having to clone or otherwise read the bytes at this time, you may find expectBytesResponse more useful. It has the signature:
expectBytesResponse : (Result x a -> msg) -> (Response Bytes -> Result x a) -> Expect msg

This does not take a decoder as input. It takes two functions which let you translate Response Bytes to a Result and another function (the first argument) which lets you translate that Result into a Msg. Through each of those steps you can retain the original Bytes reference, to do with as you please at a later time.
You will, however, have to manually handle more HTTP response scenarios, but at least you gain full control over what to do with your Bytes.


text:
Q: Troubleshooting Unity IoC container exception ("The given assembly name or codebase was invalid") In my codebase, I have created a container sucessfully, but then run into an exception when trying to configure it:
_container = new UnityContainer();
var unityConfigurationSection = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
if (unityConfigurationSection != null)
{
    try
    {
        unityConfigurationSection.Configure(_container);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
    }
}

the unityConfigurationSection.Configure(_container); line is what does me in. I get:
The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)
It looks like there's a type that can't be resolved from its name, judging from the stack trace.
But how do I figure out what type?

A: The exception indicates that the name of the assembly that was requested is in some way not able to be parsed and looked up. If the assembly name was valid but it just wasn't found you'd get a different error.
Usually the message of the exception includes the assembly that failed to resolve.
For instance, this code throws the exact exception:
var asm = Assembly.Load("test,,;''");

This is obviously not a valid assembly name, so you get:
System.IO.FileLoadException: 'Could not load file or assembly '"test\,\,;''"' or one of its dependencies. The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)'
I'd debug the code and see if you can get to the message of the exception.
One thing I'd try is to go into Tools -> Options -> Debugging -> Enable Just My Code and remove the check mark. This should let you see the unwrapped exception that gets thrown when Unity tries to resolve the dependency.
Another quick approach would be to handle the AssemblyResolve Event. Whenever an assembly that was looked for by name fails to resolve for whatever reason that Event is invoked. The args parameter contain the name of the assembly that was tried to be resolved.
Put this as the first line in your Program:
AppDomain.CurrentDomain.AssemblyResolve += Resolver;

and then put this method into the same class:
private static Assembly Resolver(object sender, ResolveEventArgs args)
{
    string assemblyName = args.Name;
    throw new Exception(args.Name);
}

Now you can set a breakpoint and check out the name of the assembly that tried to get resolved.


text:
Q: file was built for archive which is not the architecture being linked (armv7s) I'm using the new OData4ObjC framework for IOS 6, but when I try to run it keeps telling me this error.
I have followed the instructions found here https://github.com/ElizabethDuncan/OData4ObjC.
I also changed the framework to an older one to see if that is the problem. I don't know if I'm missing something.

A: In the future, to check what architectures a library/executable is compiled for you should use the lipo -info command.  Like so:

mitchellge$ lipo -info /Users/mitchellge/Downloads/libMSODataLib.a
  --> Architectures in the  fat file:
  /Users/mitchellge/Downloads/libMSODataLib.a are: armv6 armv7

As you can see, the library (libMSODataLib.a) that is bundled with OData4ObjC is compiled for the armv6 and armv7 architectures and not the armv7s.  One fix is to go into your project's build settings and change Valid Architectures from armv7 armv7s to just armv7


text:
Q: Obtain a Span over a struct without making a copy of the struct I have been experimenting with Span<T> as part of ReadOnlySequence<T> and System.IO.Pipelines.
I am currently trying to obtain a Span<T> over a struct without using unsafe code and without making a copy of that struct.
My struct is simply:
    [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)]
    public struct Packet
    {
        public byte TestByte;
    }

Method 1 - which works - but feels "unsafe"
    //
    // Method 1 - uses Unsafe to get a span over the struct
    //
    var packet = new Packet();
    unsafe
    {
        var packetSpan = new Span<byte>(&packet, Marshal.SizeOf(packet));

        packetSpan[0] = 0xFF; // Set the test byte
        Debug.Assert(packet.TestByte == 0xFF, "Error, packetSpan did not update packet.");
            // ^^^ Succeeds
        packet.TestByte = 0xEE;
        Debug.Assert(packetSpan[0] == 0xEE, "Error, packet did not update packetSpan.");
            // ^^^ Succeeds
    }

Method 2 - which doesn't work as intended as it requires a copy
    //
    // Method 2
    //
    // This doesn't work as intended because the original packet is actually
    // coppied to packet2Array because it's a value type
    //
    // Coppies the packet to an Array of Packets
    // Gets a Span<Packet> of the Array of Packets
    // Casts the Span<Packet> as a Span<byte>
    //
    var packet2 = new Packet();

    // create an array and store a copy of packet2 in it
    Packet[] packet2Array = new Packet[1];
    packet2Array[0] = packet2;

    // Get a Span<Packet> of the packet2Array
    Span<Packet> packet2SpanPacket = MemoryExtensions.AsSpan<Packet>(packet2Array);

    // Cast the Span<Packet> as a Span<byte>
    Span<byte> packet2Span = MemoryMarshal.Cast<Packet, byte>(packet2SpanPacket);

    packet2Span[0] = 0xFF; // Set the test byte
    Debug.Assert(packet2.TestByte == 0xFF, "Error, packet2Span did not update packet2");
        // ^^^ fails because packet2 was coppied into the array, and thus packet2 has not changed.
    Debug.Assert(packet2Array[0].TestByte == 0xFF, "Error, packet2Span did not update packet2Array[i]");
        // ^^^ succeeds

    packet2.TestByte = 0xEE;
    Debug.Assert(packet2Span[0] == 0xEE, "Error, packet2 did not update in packet2Span");
        // ^^^ fails because packet2Span is covering packet2Array which has a copy of packet2
    packet2Array[0].TestByte = 0xEE;
    Debug.Assert(packet2Span[0] == 0xEE, "Error, packet2 did not update in packet2Span");
        // ^^^ succeeds

Further research shows that
Span<T> can be implicitly cast from a byte[], eg, I could do
Span<byte> packetSpan = new Packet().ToByteArray();

But any current implementation of ToByteArray() I have is still making a copy of the Packet struct.
I can't do some something like:
Span<byte> packetSpan = (byte[])packet;
    // ^^ Won't compile

A: You have to do it in an unsafe context because it's unsafe by the real meaning of the word, because if you are not careful enough you will shoot yourself in the foot. Here's why:
Consider the following code:
Span<byte> GiveMeSpan()
{
    MyLovelyStruct value = new MyLovelyStruct();
    unsafe
    {
        return new Span<byte>(&value, sizeof(MyLovelyStruct));
    }
}

The instance of MyLovelyStruct which we create in GiveMeSpan() lives in the method's call stack and what your doing is taking its address, giving it to the Span<byte>, and returning the Span<byte>. Once a method returns it pops its stack frame, thus the memory that your MyLovelyStruct is living in will become free and may be reclaimed by the next method that the caller calls and corrupt it.
But that's not all, what if your MyLovelyStruct is living in an object field like this:
class MyLovelyClass
{
    private MyLovelyStruct value;

    public void Foo()
    {
        unsafe
        {
            var span = new Span(&value, sizeof(MyLovelyStruct));
            Process(span);
        }
    }
}

// Declaration
Process(Span<byte> span);

And a GC happens when Process() method is processing your MyLovelyStruct and MyLovelyClass suddenly gets moved in the memory (Yes, GC move's objects in the memory, read here)? Yes, your Span<byte> which points to MyLovelyStruct will no longer point to the new MyLovelyStruct address and your program becomes corrupt.
So in order to safely wrap a struct using Span<byte> or any other pointer type, you have to make sure:

*

*The instance is living in a fixed memory position (for example in the stack or unmanaged memory like a memory block allocated by Marshal.AllocHGlobal)

*The instance memory will not be claimed until you are done with the pointer

So unsafe keyword is needed and even if you can bypass it, it is up to you to warn the readers of your code about it.

A: There's no way of acquiring a Span<byte> over an arbitrary struct without unsafe, since such a span would allow you to change any bit of the struct in any way, possibly violating the type's invariants - that's inherently an unsafe operation.
Okay, but what about ReadOnlySpan<byte>? Notice that you had to put the StructLayoutAttribute on your struct for your code to be sensible. That should be a hint. Imagine trying to write an even simpler method, one that returns a byte[] for any arbitrary T where T : struct. You have to find out the size of the struct first, don't you? Well, how do you find out the size of a struct in C#? You can either use the sizeof operator, which requires an unsafe context and needs the struct to be an unmanaged type; or you can Marshall.SizeOf which is wonky and works only on structs with sequential or explicit byte layout. There's no safe, general way, thus you cannot do that.
The Span<T> and ReadOnlySpan<T> weren't designed with accessing struct bytes in mind, but rather with spanning fragments of arrays, which have a known size and are guaranteed to be sequential.
If you are confident that you know what you're doing, you can do that in an unsafe context - that's what it's for. But note that your solution with unsafe doesn't generalise to arbitrary structs, for the reasons noted above.
If you intend your struct to be used as a buffer for IO operations, you might want to look into fixed size buffers. They also require an unsafe context, but you can encapsulate the unsafeness inside your struct and return a Span<byte> to that fixed buffer. Basically anything that tackles the byte structure of objects in memory requires unsafe in .NET, as memory management is the thing that this "safety" refers to.

A: As it turns out, it is possible to do this, and in fact has been possible for quite some time... since dotnet core 2.1, if the docs are to be believed!
The magic ingredient is MemoryMarshal.CreateSpan, which "Creates a new span over a portion of a regular managed object."

        var packet = new Packet() { TestByte = 123 };
        var span = MemoryMarshal.CreateSpan<Packet>(ref packet, 1);
        var bytes = MemoryMarshal.Cast<Packet, byte>(span);
        bytes[0] = 100;

        Console.WriteLine(packet.TestByte);

Outputs 100 as you'd hope.
You're prevented from doing anything too stupid here, because MemoryMarshal.Cast raises an ArgumentException if the to- or from-types contain any managed references. MemoryMarshal.CreateSpan comes with a bunch of caveats and offers you a new way to shoot yourself in the foot, but hey... it doesn't require unsafe so go wild!

This method should be used with caution. It is dangerous because the length argument is not checked. Even though the ref is annotated as scoped, it will be stored into the returned span, and the lifetime of the returned span will not be validated for safety, even by span-aware languages.

(scoped ref is a dotnet 7/C# 11 feature, but the method is available in older versions of dotnet without that particular keyword)
The blurb does not mention pinning at all, and I don't believe you need to worry about it. The span is constructed around a managed reference to the underlying struct (the ref packet bit) which is not a dumb pointer. As such I'd expect relocations of the struct (eg. because the managed object it was a member of to was moved by the GC) would be handled transparently by the runtime.

Just to confirm, you can absolutely do stuff like this:
        var packet = new Packet() { TestByte = 123 };
        var span = MemoryMarshal.CreateSpan<Packet>(ref packet, 100);
        var bytes = MemoryMarshal.Cast<Packet, byte>(span);
        new Random().NextBytes(bytes);

and cause a crash. So whilst this isn't unsafe in the keyword sense, it is absolutely not safe.


text:
Q: How to prove a formula for the sum of powers of $2$ by induction? How do I prove this by induction?

Prove that for every natural number n, $ 2^0 + 2^1 + ... + 2^n = 2^{n+1}-1$

Here is my attempt.
Base Case: let $ n = 0$ Then, $2^{0+1} - 1 = 1$ Which is true.
Inductive Step to prove is: $ 2^{n+1} = 2^{n+2} - 1$
Our hypothesis is: $2^n = 2^{n+1} -1$
Here is where I'm getting off track. Lets look at the right side of the last equation: $2^{n+1} -1$ I can rewrite this as the following.
$2^1(2^n) - 1$ But, from our hypothesis $2^n = 2^{n+1} - 1$ Thus:
$2^1(2^{n+1} -1) -1$ This is where I get lost. Because when I distribute through I get this.
$2^{n+2} -2 -1$ This is wrong is it not? Am I not applying the rules of exponents correctly here? I have the solution so I know what I'm doing is wrong. Here is the correct proof.

A: HINT $\ $ Here's the inductive proof for summing a general geometric series.
THEOREM $\rm\quad 1 + x + \cdots + x^{n-1}\ =\ \dfrac{x^{n}-1}{x-1}$
Proof $\ $ Base case: It is true for $\rm\ n = 1\:,\:$ viz. $\rm\ 1 = (x-1)/(x-1)\:$.
Inductive step: Suppose it is true for $\rm\ n = k\:.\ $ Then we have
$$\rm\ x^k + (x^{k-1} +\: \cdots\: + 1)\:\ =\:\ x^k +\frac{x^k-1}{x-1}\ =\  \frac{x^{k+1}-1}{x-1}$$
which implies it is true for $\rm\: n = k+1\:,\:$ thus completing the inductive proof.
The proof you seek is just the special case $\rm\ x = 2\ $.

A: An easy way to do this is using binary. Here's an idea of what I mean:

*

*$2^0$ in binary is $1$

*$2^1$ in binary is $10$

*$2^2$ in binary is $100$

For a general rule:

$2^n$ in binary is $100\cdots0$ (n zeros)

Add those together and you get
$2^0 + 2^1 + ... + 2^n$ in binary is $11...11$ ($n+1$ ones).
Now it's obvious that adding 1 to that gives you
$$100\cdots00 \quad\text {($n+1$ zeros)}$$
Which as we all know is $2^{n+1}$.
Thus $2^{n+1} - 1$ is equal so the sum of powers of two up to $2^n$.

A: Both

*

*Inductive Step to prove is: $ 2^{n+1} = 2^{n+2} - 1$

*Our hypothesis is: $2^n = 2^{n+1} -1$

are wrong and should be

*

*Inductive Step to prove is: $ 2^0 + 2^1 + ... + 2^n + 2^{n+1} = 2^{n+2} - 1$

*Our hypothesis is: $ 2^0 + 2^1 + ... + 2^n = 2^{n+1}-1$

Add $2^{n+1}$ to both sides of the hypothesis and you have the step to prove since $2^{n+1}-1 +2^{n+1} =  2^{n+2} - 1$

A: I don't see the answer I like here, so I'm writing my own.
Basic proof:
We wish to prove $2^0 + 2^1 + ... + 2^{n-1} = 2^n - 1$ for all $n$. We can verify by inspection this is true for n=1. Next, assume that $2^0 + 2^1 + ... + 2^{n} = 2^{n+1} - 1$.
$(2^0 + 2^1 + ... + 2^n) + 2^{n+1} = (2^{n+1} - 1) + 2^{n+1} = 2 \cdot 2^{n+1} - 1 = 2^{n+2} - 1$, so we have shown $2^0 + 2^1 + ... + 2^{n-1} = 2^{n} - 1$ is true for all n.

A: let $S = 2^0 + 2^1 + 2^2 + .... + 2^{n-1}$
so $2S = 2^1 + 2^2 + 2^3 + 2^n$
then $2S - S = S = (2^1 - 2^0) + (2^2 - 2^1) + ... + (2^{n-1} - 2^{n-1}) + 2^n = 2^n - 1$
and we got $2^0 + 2^1 + 2^2 + .... + 2^{n-1} = 2^n - 1$


text:
Q: How I can execute python virtual environment files with php shell execute? I have tried to run the Github: https://github.com/atbaker/wikipedia-question-generator
I have created the virtual environment using the following instruction: https://github.com/atbaker/wikipedia-question-generator#installing-with-python-34
$ pyvenv venv
$ source venv/bin/activate
$ pip install -r requirements.txt
$ python -m textblob.download_corpora

Install the command line tool so you can use the tool easily:
$ pip install -e folder_name

Now the environment is completed.
My code ran properly on the commandline using the following:
wikitrivia 'tony'

Now I have tried to use it using php shell script as follows:
<? php
$out = shell_exec('wikitrivia "tony" ');
echo $out;
?>

But there is nothing on the output screen. I tried to run the command php -v and have shown the version. But the command wikitrivia "tony" is not working. I am using AWS Ubuntu environment.
My php version is 7 and the python version is 3.5
Hope this helps. Kindly, let me know what I can do?

A: I did it recently as a cron task.
You need to execute script from working dir with interpreter from venv.
Somethin like that:
<? php
$out = shell_exec('cd FULL_YOUR_PYTON_WORKING_DIR && YOUR_VENV/bin/python FULL_PATH_TO_YOUR_SCRIPT.py "tony"');
echo $out;
?>


text:
Q: Find the all the pairs $(n,m) \in \mathbb{N} \times \mathbb{N}$ with the property that $ 2^n+3^m $ is divisible by $23$. Find the all the pairs $(n,m) \in \mathbb{N} \times \mathbb{N}$ with the property that $ 2^n+3^m $ is divisible by $23$.
I'm not really sure how to start this one, but since I found it in a book on group theory, such an approach might also be possible.

A: Powers of two modulo $23$: $1,2,4,8,16,9,18,13,3,6,12,1 \ldots$
Powers of three modulo $23$: $1,3,9,4,12,13,16,2,6,18,8,1\ldots$
Find all the pairs $(n,m)$ such that $n$ is in the first set and $m$ is in the second, with $n+m=23$.

A: As $\displaystyle 2^3\cdot3=24\equiv1\pmod{23},$
$\displaystyle 2^n+3^m\equiv0\pmod{23}\iff 2^{n+3m}\equiv-3^m\cdot2^{3m}\equiv-(3\cdot2^3)^m$
$\displaystyle\implies2^{n+3m}\equiv-1\pmod{23}$
Now as $23$ is prime, $\displaystyle a^2\equiv1,a\equiv\pm1\pmod{23}$ for $(a,23)=1$
and $\displaystyle2^5=32\equiv9,2^{10}\equiv9^2=81\equiv12,2^{11}\equiv2\cdot12\equiv1$
So, there is no integer exponent$(e)$ of $2$ such that $2^e\equiv-1\pmod{23}$
Hence, the system admits no solution in integers

Alternatively,
HINT:
As $3^3\equiv2^2\pmod{23},$
Case $1:$ If $\displaystyle m=3r+1,2^n+3^m=2^n+3^{3r+1}\equiv 2^n+3\cdot2^{2r}\pmod{23}$
So, we need $\displaystyle 2^{n-2r}\equiv-3\pmod{23}$
Observe that there is no integer exponent$(e)$ of $2$ such that $2^e\equiv-3\pmod{23}$
Case $2:$ If $\displaystyle m=3r+2$
Case $3:$ If $\displaystyle m=3r$

A: Hint:
Look up Fermat's little theorem.
Solution:
We are looking for $n,m$ such that $2^n+3^m\equiv 0$ modulo $23$. By Fermat's little theorem $2^{22}\equiv 3^{22}\equiv 1$. Thus it only remains to check the pairs $(n,m)$ with $0\le n,m<22$. This is just $484$ numbers therefore it can be done with a computer, e.g. using Wolfram alpha with Table[mod(2^n+3^m,23)=0,{n,0,21},{m,0,21}]

It returns a huge table with the entries only being False, therefore there are no natural numbers $n,m$ such that $2^n+3^m$ is divisible by $23$.

A: Suppose a solution to $2^{n}\equiv-3^m$ (everything in this answer is $\pmod {23}$.) I'll show that this implies $-2$ is a quadratic residue $\pmod {23}$, which is false.
Lemma. $n$ is odd.
Firstly, we know $3\equiv 7^2$, so $2^{n}\equiv-7^{2m}$. Now, the inverse of two $2^{-1}$ is $\equiv 12$, so $-1\equiv7^{2m}12^{n}$. If $n$ were even, $-1$ would be a quadratic residue $\pmod {23}$, which is false.

Set $n=2k+1$. This implies $-2\equiv 7^{2m}12^{2k}=\left(7^m12^k\right)^2$, so $-2$ is a quadratic residue $\pmod {23}$, but this is false. Therefore, there are no solutions $(m, n)$.

A: Notice that $\ {\rm mod}\ 23\!:\  3\equiv 1/8\equiv \color{#0a0}{2^{-3}},\ \ 2\equiv 5^2\Rightarrow\ 2^{11}\equiv 5^{22}\equiv \color{#c00}1\,$ by $\,\mu$Fermat.  Therefore
$$ 2^{\large n} \equiv -3^{\large m} \equiv -\color{#0a0}{2^{\large -3\color{black}{\large m}}}\ \Rightarrow\ 2^{\large n+3m}\equiv -1\smash{\overset{\large\ (\ \ )^{11}}\Rightarrow} \color{#c00}1 \equiv -1 \,\Rightarrow\,\Leftarrow\qquad\  $$
Remark $\ $ Alternatively, note $\, 3\equiv 7^2$ so $\ 3^{11}\equiv 7^{22}\equiv 1$ hence $\ 2^n \equiv -3^m\smash{\overset{\large\ (\ \ )^{11}}\Rightarrow}1\equiv -1.\ $ Therefore, the proof essentially boils down to the fact that the product of the two squares $2^n$ and $3^{-m}$ cannot equal $-1$ since it is not a square (by Euler's Criterion)


text:
Q: How to make changes to objects in the page above I have a NavigationView that loads a page into its associated frame.
On the loaded page there is a button, how can I use this button to change the properties of the NavigationView.
I know that to update the page in the frame is:
Frame.Navigate(typeof(Window2));

So I thought it might be:
Frame.NavigationView.IsEnabled = False

But this isn't valid.
Is there a way to do this?

A: You can not set NavigationView.IsEnabled directly from loaded page.You can set a property in a  viewmodel to bind with the IsEnabled of navigationView.When you navigate a new page by Frame.Navigate(),pass the viewmodel to the new page.You can set the property to false when you click the button in the page.In this case,the navigationView will be disabled.
.xaml:
<NavigationView IsEnabled="{x:Bind MyViewModel.IsEnabled,Mode=OneWay}">
        <NavigationView.MenuItems>
            <NavigationViewItem Content="Item 1"></NavigationViewItem>
        </NavigationView.MenuItems>
        <Frame x:Name="ContentFrame"/>
</NavigationView>

.cs:
public class ViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged = delegate { };

    private bool isEnabled = false;
    public bool IsEnabled {
        get { return isEnabled; }
        set {
            isEnabled = value;
            OnPropertyChanged();
        }
    }
    public void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

public sealed partial class MainPage: Page
{
    public MainPage()
    {
        this.InitializeComponent();
        MyViewModel = new ViewModel();
    }
    private ViewModel MyViewModel { get; set; }
}

When you want to navigate a new page,pass the viewmodel:
ContentFrame.Navigate(typeof(Page1),MyViewModel);

Page1.cs:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
    isEnabledVM = (e.Parameter as ViewModel);
}
private ViewModel isEnabledVM { get; set; }
private async void Button_Click(object sender, RoutedEventArgs e)
{
    isEnabledVM.IsEnabled = false;
}


text:
Q: Stack Overflow accessibility with screen reading software? As a blind user of both Stack Overflow and Server Fault I was wondering if any thought has been given to making the sites more accessible? Most things work well enough such as asking and answering questions, but some things are not accessible such as upvoting comments. It would also be nice if there were headings or another quick way to jump from answer to answer.

A: It's extremely difficult for us to judge a site's accessibility.  I'd say the thing to do is to outline the problems you've observed in good detail, and post each one as a separate question on Meta Stack Exchange.

A: Good point. Too often we forget about the visually-impaired. I spent a couple months working on revamping a client's website after spending 10 or so minutes on the phone with a man who uses jaws to surf the web.

A: I was just wondering about this as I was trying to manipulate parts of SO pages in conkeror and having some troubles due to the markup that is used in places, particularly in comments. I installed a screen reader, but must confess I don't know anything about them so I couldn't really judge how well it worked. The general idea of making things more usable in a screen reader seems fairly straight forward however. As John Topley pointed out, Dive into Accessibility is a pretty quick read that points out easy ways to improve in this area, such as adding summaries to tables.

A: Only a "read out loudly" feature would not be sufficient (though it is necessary one).
To make the site friendly to blinds / people with severe visual impairment / deaf-blinds peoples; it needs something more.
You'll need also a

*

*sound indicator, when the mouse pointer enters at a definite field / icon / button. In cases of toolbar, icons, buttons, hyperlinks you need to read-out loud the name of button.

*accessibility to all sorts of Braille touch-monitor and braille printers

*accessibility to a vibrator, in cases of a phone/ any other gadget provide a vibration system. It would work similar as sound-indicators of icons, buttons and borders.

*audio guide for all help articles, notifications, warnings etc.

*tutorial links about Braille, especially for guides/ companions/ parents/ teachers of the blind or deaf-blind person.

*Also for normal monitor, each paragraph (English) along with a Braille  transcript (printable in normal printer) especially for guides/ assistants/ parents/ teachers of the blind person, to assist better.
Those who do not want these features; would be able to turn off or on it.
Agree; the responsibility is not much of SE-network; but the responsibilities go more to the browser and system-softwares publishers and hardware manufacturers to make the entire Earth more disabled friendly; but SE developers may keep a concern to design the site with additional supports and increased hardware access capability.


text:
Q: pySNMP sequence on managed objects for setCmd According to the documentation the setCmd varBinds reference is a sequence of managed objects.  However, I have tried to pass a list [(oid0, value0), (oid1, value1)] or a tuple ((oid0, value0), (oid1, value1)) or a set set([(oid0, value0), (oid1, value1)]) and all of them fail with the error "too many values to unpack".  I need to be able send a single set request with multiple varbinds.I can successfully send each managed object, e.g., (oid0, value0) as a separate setCmd.  Any ideas how I can do this?

A: As shown on the examples page, passing a variable number of (oid, value) tuples to the setCmd() is a way to add multiple var-binds to request message.
The following code will build and send SNMP SET message with three var-binds:
cmdGen.setCmd(
    cmdgen.CommunityData('public'),
    cmdgen.UdpTransportTarget(('localhost', 161)),
    ('1.3.6.1.2.1.1.2.0', rfc1902.ObjectName('1.3.6.1.4.1.20408.1.1')),
    ('1.3.6.1.2.1.1.2.0', '1.3.6.1.4.1.20408.1.1'),
    ('1.3.6.1.2.1.1.5.0', rfc1902.OctetString('new system name'))
)

A: Try asterisk
abc = ((oid0, value0), (oid1, value1), (oid2, value2))
errorIndication, errorStatus, errorIndex, varBinds = cmdgen.CommandGenerator().setCmd(
    self.authData, cmdgen.UdpTransportTarget((host_addr, 161)), *abc)


text:
Q: 24 V transistor switch acting strangely I am working on a project to switch a spring-applied brake (datasheet, page 84, MCNB 2GR) using a Teensy 3.5.
I only have limited electronics knowledge and am struggling with weird behaviour from the transistor. I have previously asked for some help in this post and have applied the help to create the following circuit:

As opposed to my previous question, I have switched to using a Teensy 3.5 which only supplies 3.3 V as an output on the digital pins.
The idea is to use a Sharp PC817 (datasheet) to isolate the Teensy and the 24 V circuit and then use a 2N3904 (datasheet) to turn on off the 24 V for the brake which is symbolised as R1.
The strange behaviour starts after a few seconds of sending a 3.3 V signal to the opto-isolator. At first the circuit works as expected and the brake turns on and off based on the current state of the output pin. However after some time (probably about 5-10 seconds), the brake doesn't turn off anymore (i.e., it still receives enough power to be in its on-state) when the output pin is turned off. The only way to turn it off is to turn off the 24 V DC power supply.
After some investigation, I found that the transistor gets extremely hot, hot enough to cause burn marks when touching it for less than a second. Considering that the circuit works normally after a little while, I think this issue is transistor related and has some relation to its temperature. I have also taken voltage readings on the transistor and have found the following:
When turned off: E: 0 V, B: 0 V, C: 23.96 V
When just turned on: E: 0.125 V, B: 0.84 V, C: 5.76 V
When turned off after being on 5-10 sec: E: 0.075 V, B: 0.493 V, C: 8.6 V
It seems to me as if the transistor does not completely turn off and still letting enough voltage/current through to keep the electromagnet in the brake engaged.
I am not entirely sure if the temperature is the problem. I am guessing that I may have either chosen the wrong resistance values in my circuit or that maybe the transistor is no good for what I want to do.
Is there a way to fix this without changing the transistor?

A: A brake is an electrogmagnetic component. It has a resistance but is mainly inductive.
When the brake is turned off the current will tend to continue flowing and a spike or back electromotive force will appear which will overheat or destroy the transistor after it is blocked.
Adding a freewheeling or flyback diode will allow current flow in this condition and protect the transistor:

A: In addition to the flyback diode problem, the fact that VCE (collector/emitter voltage) is 5.64V when the transistor is on means that it's not fully on. This greatly increases the amount of power dissipated in the transistor, which causes it to heat up more. Overheating can also damage a transistor.
You might need to increase the base current by decreasing R2, or even by adding another transistor stage between U1 and Q1 (if U1 is too weak). Q1's datasheet should tell you the needed amount of base current.


text:
Q: why does spring security give empty password to password encoder? I am using spring security with BCrypt Password encoder for authentication. when i want to login, Spring security fetchs user data with JPA correctly but for checking raw password with encoded password it gives null string as encoded password to password encoder.
spring security config :
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("userDetailsServiceImpl")
    private UserDetailsService userDetailsService;

    @Bean
    public PasswordEncoder passwordEncoder(){
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        return encoder;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception{
        auth.userDetailsService(userDetailsService)
        .passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/").hasAuthority("USER")
                .antMatchers("/css/**","/font/**","/js/**","/image/**").permitAll()
                .antMatchers("/register").permitAll()
                .and().formLogin().loginPage("/login").successForwardUrl("/").permitAll()
                .and().logout().logoutSuccessUrl("/login");
    }
}

userDetailsServise :
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private UserRepository userRepo;

    @Autowired
    public UserDetailsServiceImpl(UserRepository userRepo){
        this.userRepo = userRepo;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
         User user = userRepo.findByUsername(username);
         if(user != null) {
             System.out.println(user.toString());
             return user;
         }
         throw new UsernameNotFoundException("User "+ username +" not found");
    }
}

user entity:
@Entity
@Table(name = "users")
public class User implements UserDetails {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_seq")
    @SequenceGenerator(name = "user_seq", sequenceName = "users_id_seq",allocationSize = 1)
    private long id;

    @NotEmpty
    @Column(nullable = false, unique=true)
    private String username;

    @Email
    @Column(nullable = false, updatable = false, unique = true)
    private String email;

    @Column(nullable = false)
    private String password;

    @Column(nullable = false)
    private boolean enabled;

    @CreationTimestamp
    @Column(name = "creation_time")
    private Timestamp creationTime;

    @ElementCollection(fetch = FetchType.EAGER)
    @CollectionTable(joinColumns = @JoinColumn(name="user_id"))
    private List<Authority> authorities;
...

logs:
2019-05-31 19:51:58.888 DEBUG 7181 --- [nio-8080-exec-3] w.a.UsernamePasswordAuthenticationFilter : Request is to process authentication
2019-05-31 19:51:58.889 DEBUG 7181 --- [nio-8080-exec-3] o.s.s.authentication.ProviderManager     : Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
2019-05-31 19:51:59.245 DEBUG 7181 --- [nio-8080-exec-3] tor$SharedEntityManagerInvocationHandler : Creating new EntityManager for shared EntityManager invocation
2019-05-31 19:51:59.388  INFO 7181 --- [nio-8080-exec-3] o.h.h.i.QueryTranslatorFactoryInitiator  : HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select user0_.id as id1_1_, user0_.creation_time as creation2_1_, user0_.email as email3_1_, user0_.enabled as enabled4_1_, user0_.password as password5_1_, user0_.username as username6_1_ from users user0_ where user0_.username=?
Hibernate: select authoritie0_.user_id as user_id1_0_0_, authoritie0_.authorities as authorit2_0_0_ from user_authorities authoritie0_ where authoritie0_.user_id=?
User{
id=8
, username='username'
, email='mail@example.com'
, password='$2a$10$TyQ8x0KUP9Nrtzo2ljfNfei4S3h1kFpYEb5/CDs2lKSDzMJECQ./q'
, enabled=true
, creationTime=2019-05-31 19:32:12.948
, authorities=[USER]}
2019-05-31 19:51:59.758  WARN 7181 --- [nio-8080-exec-3] o.s.s.c.bcrypt.BCryptPasswordEncoder     : Empty encoded password
2019-05-31 19:51:59.758 DEBUG 7181 --- [nio-8080-exec-3] o.s.s.a.dao.DaoAuthenticationProvider    : Authentication failed: password does not match stored value
2019-05-31 19:51:59.773 DEBUG 7181 --- [nio-8080-exec-3] w.a.UsernamePasswordAuthenticationFilter : Authentication request failed: org.springframework.security.authentication.BadCredentialsException: Bad credentials

I create following password encoder and I figure out that spring security gives a null string as encoded password to password encoder.
@Component
public class MyPasswordEncoder implements PasswordEncoder {

    BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

    @Override
    public String encode(CharSequence rawPassword) {
        return encoder.encode(rawPassword);
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {

        System.out.println("raw password: " + rawPassword + "\t encoded passwod: "+ encodedPassword);

        return encoder.matches(rawPassword,encodedPassword);
    }
}

logs with custom password encoder:
2019-06-01 03:19:52.759 DEBUG 7870 --- [nio-8080-exec-5] w.a.UsernamePasswordAuthenticationFilter : Request is to process authentication
2019-06-01 03:19:52.759 DEBUG 7870 --- [nio-8080-exec-5] o.s.s.authentication.ProviderManager     : Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
2019-06-01 03:19:53.036 DEBUG 7870 --- [nio-8080-exec-5] tor$SharedEntityManagerInvocationHandler : Creating new EntityManager for shared EntityManager invocation
2019-06-01 03:19:53.095  INFO 7870 --- [nio-8080-exec-5] o.h.h.i.QueryTranslatorFactoryInitiator  : HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select user0_.id as id1_1_, user0_.creation_time as creation2_1_, user0_.email as email3_1_, user0_.enabled as enabled4_1_, user0_.password as password5_1_, user0_.username as username6_1_ from users user0_ where user0_.username=?
Hibernate: select authoritie0_.user_id as user_id1_0_0_, authoritie0_.authorities as authorit2_0_0_ from user_authorities authoritie0_ where authoritie0_.user_id=?
User{
id=8
, username='username'
, email='mail@example.com'
, password='$2a$10$TyQ8x0KUP9Nrtzo2ljfNfei4S3h1kFpYEb5/CDs2lKSDzMJECQ./q'
, enabled=true
, creationTime=2019-05-31 19:32:12.948
, authorities=[USER]}
raw password: password   encoded passwod: null
2019-06-01 03:19:53.413  WARN 7870 --- [nio-8080-exec-5] o.s.s.c.bcrypt.BCryptPasswordEncoder     : Empty encoded password
2019-06-01 03:19:53.413 DEBUG 7870 --- [nio-8080-exec-5] o.s.s.a.dao.DaoAuthenticationProvider    : Authentication failed: password does not match stored value
2019-06-01 03:19:53.415 DEBUG 7870 --- [nio-8080-exec-5] w.a.UsernamePasswordAuthenticationFilter : Authentication request failed: org.springframework.security.authentication.BadCredentialsException: Bad credentials

full source on github : https://github.com/yrostami/spring_sample

A: BCryptPasswordEncoder will compare the password from the loaded user with the password entered from the login form to see if they match. If the former is null , it will give Empty encoded password warning.
So by looking at how you load the users  , it turns out that your UserDetailsService will always return an User with a null password because you hardcode it in getPassword() (Btw, getUsername() also has the same problem). So change to following should fix it :
@Override
public String getPassword() {
    return this.password;
}

@Override
public String getUsername() {
    return this.username;
}


text:
Q: Thread join hangs Thread join is hanging in case of single producer and multiple consumer case.
I am attaching the codebase below:
1) This is the Consumer Thread
class ConsumerThread-
{
    wqueue<WorkItem*>& m_queue;
-
  public:
    ConsumerThread(wqueue<WorkItem*>& queue) : m_queue(queue) {}

    std::thread start() {
      return std::thread( [=] {runThr();} );
    }
-
    void runThr() {
        // Remove 1 item at a time and process it. Blocks if no items are-
        // available to process.
        for (int i = 0;; i++) {
            printf("thread %lu, loop %d - waiting for item...\n",-
                  std::this_thread::get_id(), i);
            WorkItem* item = (WorkItem*)m_queue.remove();
            printf("thread %lu, loop %d - got one item\n",-
                  std::this_thread::get_id(), i);
            printf("thread %lu, loop %d - item: message - %s, number - %d\n",-
                  std::this_thread::get_id(), i, item->getMessage(),-
                   item->getNumber());
            delete item;
        }
    }
};

2) This is Work Item
class WorkItem
{
    std::string m_message;
    int    m_number;
-
  public:
    WorkItem(const char* message, int number)-
          : m_message(message), m_number(number) {}
    ~WorkItem() {}
-
    const char* getMessage() { return m_message.c_str(); }
    int getNumber() { return m_number; }
};

3).  This class is has the queue where the producer pushes and consumers consume the WorkItem.
template <typename T> class wqueue
{
    std::list<T>                  m_queue;
    std::mutex               m_mutex;
    std::condition_variable  m_condv;-

  public:
    wqueue() {}
    ~wqueue() {}

    void add(T item) {
        m_mutex.lock();
        m_queue.push_back(item);
        m_condv.notify_one();
        m_mutex.unlock();
    }

    T remove() {
        std::unique_lock<std::mutex> lk(m_mutex);
        while(m_queue.size() == 0)
            m_condv.wait(lk);
        T item = m_queue.front();
        m_queue.pop_front();
        return item;
    }
    int size() {
        m_mutex.lock();
        int size = m_queue.size();
        m_mutex.unlock();
        return size;
    }
};

4) This is the class containing the main function
int main(int argc, char* argv[])
{

    // Process command line arguments
    if ( argc != 2 ) {
        printf("usage: %s <iterations>\n", argv[0]);
        exit(-1);
    }
    int iterations = atoi(argv[1]);

    // Create the queue and consumer (worker) threads
    wqueue<WorkItem*>  queue;
    ConsumerThread* thread1 = new ConsumerThread(queue);
    ConsumerThread* thread2 = new ConsumerThread(queue);

    std::thread t1 = thread1->start();
    std::thread t2 = thread2->start();

    t1.join();
    t2.join();

    // Add items to the queue
    WorkItem* item;
    for (int i = 0; i < iterations; i++) {
        item = new WorkItem("abc", 123);
        queue.add(item);
        item = new WorkItem("def", 456);
        queue.add(item);
        item = new WorkItem("ghi", 789);
        queue.add(item);
    }

The  t1.join() and t2.join() hangs mentioned in the section 4.

A: Your consumer thread has no terminating condition so it runs forever:
for (int i = 0;; i++) // never ends

Joining a thread won't magically make it break out of its loop, you need to set an ended flag or something.
Also when the wqueue is empty all threads trying to remove() an element will block:
    while(m_queue.size() == 0)
        m_condv.wait(lk);

You try to join() the threads before putting anything in them.

A: There is nothing wrong with the behaviour, calling join() on a thread object will simply wait until the thread finishes before continuing. Your problem is rather that your threads don't terminate, which is a whole different issue.
In particular in a producer-consumer setup, both peers typically sit and wait for work. Unless you explicitly tell them not to wait for work any longer, they will sit there forever! If you in turn wait for them to finish, you will also wait forever, which is your problem. You need to signal them to stop looping and additionally you might have to interrupt them from waiting for work.