text:
Q: How to generate the 256 bit binary representation of an encoded signature value? Sorry for the somewhat vague question, but I am not sure what information I am exactly looking for.
I am using mitmproxy to analyze specific requests sent to the server. These requests have a part named signature that is encoded with base64:
"signature":{"value":"SkmsMFNubSonX13bhnR9fOaWQ3c+ObXMDJZXJqV1BuUEBXkYLJCtzsQh2HaGpEEKUjN2wlvVK3YKss2O0ElwYXgv0qAERSKNuiWOCTFQwru9muBNwGhsHU83DXiGHhKGKLhYOT2pG85lc5nN1U4mqN09Wd6ED0pkMius8HPXu39nNavIHE3II3DeKiFCtZKtifiA9ccS4Q4gLmHIviQZHiaGugPtqOkjbTlROvgurZsoIh37lFekfLlEC7C+2YA9yOfE9AY0kBcrZBmrzTN2ypx3lMB6\\/F2lZ2JvZEh7t7gQreYnXUdXGbvq4pM4fHKgdfhgwYtZoiyR77YK3\\/GNGw=="

When decoding this, it turns out this is an 256bit file. Which leaves me to think it is some kind of SHA256 encoding of the full request.
However, when I try to emulate this, I only manage to generate 32bit hashes, so I would really love to know how a 256bit file like the one above is generated.

A: Have a look at this:
import base64

text = "SkmsMFNubSonX13bhnR9fOaWQ3c+ObXMDJZXJqV1BuUEBXkYLJCtzsQh2HaGpEEKUjN2wlvVK3YKss2O0ElwYXgv0qAERSKNuiWOCTFQwru9muBNwGhsHU83DXiGHhKGKLhYOT2pG85lc5nN1U4mqN09Wd6ED0pkMius8HPXu39nNavIHE3II3DeKiFCtZKtifiA9ccS4Q4gLmHIviQZHiaGugPtqOkjbTlROvgurZsoIh37lFekfLlEC7C+2YA9yOfE9AY0kBcrZBmrzTN2ypx3lMB6\\/F2lZ2JvZEh7t7gQreYnXUdXGbvq4pM4fHKgdfhgwYtZoiyR77YK3\\/GNGw=="

decoded = base64.b64decode(text)
print(len(decoded))  # this 256 bytes (not bits)

reencoded = base64.b64encode(decoded)
reencoded_text = reencoded.decode()  # bytes to string
print(reencoded_text == text)  # this is False!  Because of strange `\\` in text

fixed_text = "SkmsMFNubSonX13bhnR9fOaWQ3c+ObXMDJZXJqV1BuUEBXkYLJCtzsQh2HaGpEEKUjN2wlvVK3YKss2O0ElwYXgv0qAERSKNuiWOCTFQwru9muBNwGhsHU83DXiGHhKGKLhYOT2pG85lc5nN1U4mqN09Wd6ED0pkMius8HPXu39nNavIHE3II3DeKiFCtZKtifiA9ccS4Q4gLmHIviQZHiaGugPtqOkjbTlROvgurZsoIh37lFekfLlEC7C+2YA9yOfE9AY0kBcrZBmrzTN2ypx3lMB6/F2lZ2JvZEh7t7gQreYnXUdXGbvq4pM4fHKgdfhgwYtZoiyR77YK3/GNGw=="

print(reencoded_text == fixed_text)  # this is True

It's unclear why those backslashes are in your source text to begin with. Apparently, someone thought to escape the foreward slashes that follow, even though I don't know of languages where that would be required.
If you remove the superfluous backslashes, the text still decodes and encodes identically.
print(reencoded == base64.b64encode(base64.b64decode(fixed_text)))

That's True as well, so reencoded based on your text is the same as the reencoded version of fixed_text - the backslashes are not needed.
Note: the .decode() on the reencoded is needed because b64encode() encodes a character string into a base64 encoded string of bytes, i.e. a bytes. Since we want to compare it with text, which is a character string, we need to use .decode() to decode the bytes into str - the string will still be the base64 representation of the original string.


text:
Q: Preventing "pasting" (p) from copying selected text to register in Vim What I want is:

*

*Copy some part of text

*Replace some other parts of text with copied part.

What I do is:

*

*Make a selection: v

*Yanking the selection: y

*Making another selection: v

*Paste the yanked text: p
But whenever I paste, it replaces current selection with old yanked selection, but copies the replaced (deleted) selection to register. How to make p just paste and do nothing more?

A: Not very good answer but...
Instead of selecting and pasting (p):

*

*move to beginning of selection to be replaced

*paste

*select unwanted selection

*delete it using "delete to black-hole register" ("_d)

or vice versa, "delete to black-hole register", then paste.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Jquery loop with AJAX, looping through bootstrap modal I am getting data from database, looping trough it and appending to the div in html page. It works until I am looping trough function witch contains bootstrap MODAL. I am passing parameters to function  but every MODAL that was created display first row of my database table. My goal is to loop trough my function(MODAL) and pass different rows of my table, not only the first one.
VARIBLE WITH MY HTML
var table = {
        createTable: function(result) {
            $.each(result, function(i, column) {
                    $("#loopRows").append(
                        '
' + column.ID + '	' +
                        '' + column.Title + '	' +
                        '<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#details">Details</button>+showBookmark.showItemTemplate(column.Title, column.Url, column.User)+	'
                    });
            }
        }

AJAX REQUEST
$(document).ready(function() {
    $.ajax({
        type: "GET",
        url: 'http://localhost:62795/api/bookmarks',
        success: function(result) {
            table.createTable(result);
        }
    });
});

BOOTSTRAP MODAL WITH HTML FORM
var showBookmark = {
    showItemTemplate: function(title, url, user) {
        return '
' +
            '   Title:' + title + '' +
            '   Url:' + url + '' +
            '   User:' + user + '' +
            '
'
    }
}


text:
Q: Converted to comment
Possible Duplicate:
How could this user98776 leave a comment with only 1 rep?

Why was this made a comment? I thought you needed 50 reputation points to make a comment?
None of the DVDs can be read
https://askubuntu.com/privileges/comment


text:
Q: Why these JavaScript functions don't add to this object? I want to write a getter and setter functions for an object based on a Json files. I copied the below code of John Resig's book(Appress Pro JavaScript Techniques) but it doesn't work and these functions don't add to the object.Can you tell me why and what is the right code?
// Create a new user object that accepts an object of properties
function User(properties) {
// Iterate through the properties of the object, and make sure
// that it's properly scoped (as discussed previously)
  for (var i in properties) {
    (function () {
        // Create a new getter for the property
        this["get" + i] = function () {
            return properties[i];
        };

        // Create a new setter for the property
        this["set" + i] = function (val) {
            properties[i] = val;
        };
    })();
  }
}

// Create a new user object instance and pass in an object of
// properties to seed it with
var user = new User({
name: "Bob",
age: 44
});

// Just note that the name property does not exist, as it's private
// within the properties object
//alert( user.name == null );

// However, we're able to access its value using the new getname()
// method, that was dynamically generated
alert(user.getname());

A: You've used a function to create a closure, but you've forgotten to pass i into it. You'll also need a different reference to this inside the function, as the context changes in it to window.
function User(properties) {
    var i, me = this;
    for (i in properties) (function (i) {
        // Create a new getter for the property
        me["get" + i] = function () { // using `me` because `this !== me`
            return properties[i];
        };

        // Create a new setter for the property
        me["set" + i] = function (val) {
            properties[i] = val;
        };
    }(i)); // i passed into function closure
}

A: In your IIFE, this is actually window. You have to specify the context by using Function.prototype.call:
function User(properties) {
    // Iterate through the properties of the object, and make sure
    // that it's properly scoped (as discussed previously)
    for (var i in properties) {
        (function(i) {
            // Create a new getter for the property
            this["get" + i] = function() {
                return properties[i];
            };

            // Create a new setter for the property
            this["set" + i] = function(val) {
                properties[i] = val;
            };
        }).call(this, i);
    }
}

Or keep a reference to it with another variable:
function User(properties) {
    var that = this;

    // Iterate through the properties of the object, and make sure
    // that it's properly scoped (as discussed previously)
    for (var i in properties) {
        (function(i) {
            // Create a new getter for the property
            that["get" + i] = function() {
                return properties[i];
            };

            // Create a new setter for the property
            that["set" + i] = function(val) {
                properties[i] = val;
            };
        })(i);
    }
}

If you were in strict mode, your code would throw an error instead of misleadingly succeeding:
TypeError: Cannot set property 'getname' of undefined


text:
Q: Mysql server not connecting to magento Hi i have my magento running in amazon ec2 linux instance but frequently i get errors stating below mentioned errors
SQLSTATE[HY000] [2003] Can't connect to MySQL server on '127.0.0.1' (111)

Trace:
#0 /var/www/html/trial/lib/Zend/Db/Adapter/Pdo/Mysql.php(96): Zend_Db_Adapter_Pdo_Abstract->_connect()
#1 /var/www/html/trial/lib/Varien/Db/Adapter/Pdo/Mysql.php(320): Zend_Db_Adapter_Pdo_Mysql->_connect()
#2 /var/www/html/trial/lib/Zend/Db/Adapter/Abstract.php(459): Varien_Db_Adapter_Pdo_Mysql->_connect()
#3 /var/www/html/trial/lib/Zend/Db/Adapter/Pdo/Abstract.php(238): Zend_Db_Adapter_Abstract->query('SET NAMES utf8', Array)
#4 /var/www/html/trial/lib/Varien/Db/Adapter/Pdo/Mysql.php(428): Zend_Db_Adapter_Pdo_Abstract->query('SET NAMES utf8', Array)
#5 /var/www/html/trial/app/code/core/Mage/Core/Model/Resource.php(169): Varien_Db_Adapter_Pdo_Mysql->query('SET NAMES utf8')
#6 /var/www/html/trial/app/code/core/Mage/Core/Model/Resource.php(110): Mage_Core_Model_Resource->_newConnection('pdo_mysql', Object(Mage_Core_Model_Config_Element))
#7 /var/www/html/trial/app/code/core/Mage/Core/Model/Resource/Setup.php(141): Mage_Core_Model_Resource->getConnection('core_setup')
#8 /var/www/html/trial/app/code/core/Mage/Core/Model/Resource/Setup.php(234): Mage_Core_Model_Resource_Setup->__construct('core_setup')
#9 /var/www/html/trial/app/code/core/Mage/Core/Model/App.php(417): Mage_Core_Model_Resource_Setup::applyAllUpdates()
#10 /var/www/html/trial/app/code/core/Mage/Core/Model/App.php(343): Mage_Core_Model_App->_initModules()
#11 /var/www/html/trial/app/Mage.php(684): Mage_Core_Model_App->run(Array)
#12 /var/www/html/trial/index.php(87): Mage::run('', 'store')
#13 {main}

But once if i restart my apache and mysql again my site starts working perfectly and after some time the same error occurs initially my site was running in localhost after migrating to amazon linux instance i changed the secure base url and unsecure base url pointing towards my amazon linux instance public ip.
I have tried reindexing data.
so my question is
1.Where do i need to make changes so that my mysql will connect to my public ip instead of localhost(127.0.0.1).
2.what should i do so that this error won't happen again.
Thanks in advance.

A: Is sounds like your MySQL process is dropping. If you're running MySQL and Apache on the same instance and it's running out of memory the MySQL process will be killed.
2 solutions:

*

*Split your web and database nodes (On AWS look at RDS)

*Go for a bigger AWS instance with more memory


text:
Q: $T$-equivariant resolution of coherent sheaf Let $X := \{x_1x_2= 0\} \subset \mathbb{C}^2$ and let $\mathcal{F} := \mathcal{O}_0$ where $0\in X$ is the origin. Let $T = \left\{\begin{pmatrix} t_1 & 0 \\ 0 & t_2\end{pmatrix}\right\}\subset \operatorname{GL}_2$ act on $X$ diagonally.
What is the minimal $T$-equivariant resolution of $\mathcal{F}$?

A: The resolution has the form
$$
\dots \to
\mathcal{O} \oplus \mathcal{O}
\stackrel{\left(\begin{smallmatrix} x_1 & 0 \\ 0 & x_2\end{smallmatrix}\right)}\longrightarrow
\mathcal{O} \oplus \mathcal{O}
\stackrel{\left(\begin{smallmatrix} x_2 & 0 \\ 0 & x_1\end{smallmatrix}\right)}\longrightarrow
\mathcal{O} \oplus \mathcal{O}
\stackrel{\left(\begin{smallmatrix} x_1 & x_2\end{smallmatrix}\right)}\longrightarrow
\mathcal{O} \longrightarrow
\mathcal{F} \longrightarrow
0.
$$
It is obvious that it has a $T$-equivariant structure.


text:
Q: What is the maximum number of rails instances a single 256 MB RAM rackspace cloud server can support? I know it is a vague and ambiguous question.
I want to know just out of curiosity. How many instances of a rails app can I host on server with 256 MB RAM [Cheapest option on Rackspace]?
Assumptions - The app is very simple with 100-200 CRUD operations/day.
            - Database server is on a separate server.

A: I would say one or two.


text:
Q: Handle proper quotation marks in comment Markdown
Possible Duplicate:
Italics markup not working in comments
Problem with markdown and Unicode characters in comments

Mid-word Markdown like *long*word isn't allowed on Stack Exchange. But there seem to be a test to allow things like "*word*" to get "word" (this also works in comments). In questions and answers it is possible to use proper quotation mark characters, like "*word*" ("word"). But this doesn't work in comments and chat.
Could the characters ""'' be also added as punctuation characters in comment Markdown?

A: When I asked about a similar question ( Why do bold links syntax in comments work differently than answer text box? ) about the functioning of markdown in comments, @Jeff mentioned the following:
The rules for bold and italic are stricter in comments; this is by design to
prevent false positives.Remember that comments are a stricter subset of
markdown, what we call "mini-markdown". See the below link

https://stackoverflow.com/editing-help#comment-formatting
I don't know if that helps you but just wanted to let you know. Comments mark down don't work exactly like question and answer in certain cases.

A: You could simply cheat the system a little, and format it using multiple code-blocks, and surround the ones which are desired to be formatted with said formatting:
abcdefghijkl [link]mno
Looks like this in the editor: abc`_`def`_`ghi`[`jkl [link]`](http://test.com/)`mno


text:
Q: TAR or ZIP current directory excluding the generated file I am trying to zip or tar all the files and subdirectories in current directory and save it to the file I am zipping. The problem is that -x shitch does not work - files are being zipped and saved to a random-named file.
zip -r backup.zip ./* -x backup.zip

This is what I tried but the code did not work properly.
Is there any way to do this without saving the archive .. directory and then moving it back to the ./ dir?
Thanks in advance.

A: ./* is expanded by the shell before being sent to the command, so the only way zip will try to include backup.zip is if it exists before running the command.
tar can do it:
$ cd -- "$(mktemp -d)"
$ touch -- $'--$`!*@\a\b\E\f\r\t\v\\\'"\360\240\202\211 \n'
$ tar -czf test.tar.gz ./*
$ ls
--$`!*@???????\'" ?  test.tar.gz
$ tar -tvf test.tar.gz
-rw-rw-r-- user/group      0 2013-06-26 14:38 ./--$`!*@\a\b\033\f\r\t\v\\'" \n

A: Zip will not attempt to zip it's own out file so you don't need to use -x. Assuming backup.zip already exists in the current directory and we try to update the zip:
# zip -r backup.zip ./*
updating: libproxychains4.so (deflated 61%)
updating: README (deflated 55%)
updating: TODO (deflated 17%)
updating: COPYING (deflated 62%)
updating: src/ (stored 0%)
updating: src/proxychains (deflated 65%)
updating: src/core.c (deflated 70%)
updating: src/common.o (deflated 68%)
updating: src/core.o (deflated 66%)
updating: src/main.c (deflated 58%)
updating: src/core.h (deflated 66%)
updating: src/libproxychains.c (deflated 69%)
updating: src/proxyresolv (deflated 30%)
updating: src/main.o (deflated 67%)
updating: src/libproxychains.o (deflated 70%)
updating: src/common.h (deflated 55%)
updating: src/proxychains.conf (deflated 57%)
updating: src/common.c (deflated 62%)
updating: proxychains.lsm (deflated 28%)
updating: configure (deflated 65%)
updating: AUTHORS (deflated 45%)
updating: dist/ (stored 0%)
updating: dist/config.mak (deflated 43%)
updating: ChangeLog (deflated 66%)
updating: config.mak (deflated 37%)
updating: proxychains4 (deflated 62%)
updating: tests/ (stored 0%)
updating: tests/test_getaddrinfo.c (deflated 51%)
updating: Makefile (deflated 58%)

Use -x if you really need to exclude a file from your backup.


text:
Q: Magento data model - "one or more images" field I have created a custom extension in Magento.
I would like to be able to attach one or more images to an item. The clunky way would be to add a bunch of image fields and ignore the empty ones but this is obviously limited and not very tidy.
Question 1) Is there a generic term for this technique? I've tried googling for solutions but haven't found a way to phrase it that doesn't bring up a bunch of unrelated things.
Question 2) Is there a way to do this simply in Magento or will I have to roll my own?

A: I think you need your own.
Maybe you should just create Models which store a list of image names and a sort order along with a foreign key to your current model.
then you could just have a collection of images loaded by the id of you current model and sorted with an order by clause.
Simply use a methods like these
$collection->addAttributeToFilter('foreign_key_column', array('eq' => $foreignKey))
           ->setOrder('sort_order');


text:
Q: How to activate a function on clicking a tab? I have 2 tabs each of them displays different details. On clicking second tab, I have created a button clicking on which will display certain details. But would like to know if there are any method that calls the function directly when the tab is clicked.I tried activate function but it dint work.
        $(function() {
        $( "#tabs" ).tabs({
        activate: function( event, ui ) {
        fn.my_function(); }
        });
        });

Also I was wondering whether using activate function would be a good choice as the function is specific to second tab only.
Here is my code for the tabs :

DEMO

Details

 Code : Code number

Close

          <input type="submit" name="call_function" id="call_function" value="Click for details"       />

 // this is to display the details listed by the       function in the table format.

Close

Any pointers to solve this would be appreciated.

A: Basically you can trigger function for the specific tab by just adding an id to it:

DEMO

...

$("#tab1").click(...);

Another option is to write a proper selector to get first/second/n-th...
 element:
$("#tabs ul li:nth-child(2)").click(...)


text:
Q: Why is this DTD not valid? I've tried validating this DTD using 1-2 validators, however I'm unsure on why it is not valid:
DTD code:
Any help will be appreciated!
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE cars
[
    <!ELEMENT car (maker, model, year, colour, engine, number_of_doors, accessories)>

    <!ELEMENT maker (#PCDATA)>
    <!ELEMENT model (#PCDATA)>
    <!ELEMENT year (#PCDATA)>
    <!ELEMENT colour (#PCDATA)>
    <!ELEMENT engine (number_of_cylinders)>
    <!ELEMENT number_of_doors (#PCDATA)>
    <!ELEMENT accessories (#PCDATA)>

    <!ELEMENT number_of_cylinders (#PCDATA)>

    <!ATTLIST accessories radio (yes|no) #REQUIRED
        air_conditioning (yes|no) #REQUIRED
        power_windows (yes|no) #REQUIRED
        power_steering (yes|no) #REQUIRED
        power_brakes (yes|no) #REQUIRED
    >
]>

A: To make your XML document with an internal DTD subset be valid, make the following changes:

*

*Change the document element from cars to car.

*Build out the XML associated with the given internal subset.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE car
[
<!ELEMENT car (maker, model, year, colour, engine, number_of_doors, accessories)>

<!ELEMENT maker (#PCDATA)>
<!ELEMENT model (#PCDATA)>
<!ELEMENT year (#PCDATA)>
<!ELEMENT colour (#PCDATA)>
<!ELEMENT engine (number_of_cylinders)>
<!ELEMENT number_of_doors (#PCDATA)>
<!ELEMENT accessories (#PCDATA)>

<!ELEMENT number_of_cylinders (#PCDATA)>

<!ATTLIST accessories radio (yes|no) #REQUIRED
    air_conditioning (yes|no) #REQUIRED
    power_windows (yes|no) #REQUIRED
    power_steering (yes|no) #REQUIRED
    power_brakes (yes|no) #REQUIRED>
]>
<car>
    <!-- Finish building out the XML per the internal subset. -->
</car>

A: You can use this validator is the best for DTD https://validator.w3.org/check


text:
Q: Convert Integer or Hexadecimal value to unicode point I`m trying to solve this task :
http://www.codeabbey.com/index/task_view/parity-control
But as output I get lots of question marks in the website and blank spaces in visual studio console.
If I try to print, lets say, 160 as a char (\'u0160') everything works fine, but if I cast int to char I get white space.
I searched the internet and tried some conversions from Hexadecimal to char but they work the same way as casting int to char and I get white space again.
Why I get these question marks, do I have to change the encoding or something? Can I create a unicode point from hexadecimal or int and then just do:
char output = convertedValue;
Here`s my code for the task above:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
using System.Text.RegularExpressions;

class Program
{
    static void Main(string[] args)
    {

        string buffer = Console.ReadLine();
        string[] container = buffer.Split(' ');
        byte[] asciiCodes = new byte[container.Length];

        for (int i = 0; i < container.Length; i++)
        {
            asciiCodes[i] = byte.Parse(container[i]);
        }

        for (int i = 0; i < asciiCodes.Length; i++)
        {
            byte currNumber = asciiCodes[i];
            string binaryRepresent = Convert.ToString(currNumber, 2).PadLeft(8, '0');
            int counter = 0;
            for (int j = 0; j < binaryRepresent.Length; j++)
            {
                if(binaryRepresent[j] == '1')
                {
                    counter++;
                }
            }

            if(counter % 2 == 0)
            {
                char output = Convert.ToChar(currNumber);
                Console.Write(output);
            }

        }
    }
}

A: You are doing everything right except for:
u0160 is represented in hex format, that means 160 hex == 352 decimal
so if you run
Convert.ToChar(352);

you'll get Š.
Whereas Convert.ToChar(160) is resolving unicode symbol u00A0 (A0 hex = 160 dec), that symbol is a "No-break space" and you see a whitespace.
if you need code to convert from hex string and vice versa, here's how to do it:
string s = "00A0";
//to int
int code = int.Parse(s, System.Globalization.NumberStyles.HexNumber);
//back to hex
string unicodeString = char.ConvertFromUtf32(code).ToString();


text:
Q: How to extract adjacant elements in the dom by inner html I would like to extract adjacent DOM elements by searching for innerHtml text. The elements are not children of a wrapping parent. An example will make it easier to understand:

1.

This is the first paragraph..

<button>click</button>

2.

And this is the second...

3.

this is the last paragraph

I would like to find the first element by looking for the inner text of "1." and then extract all its siblings until I reach the first element with the inner text of "2."
And then do it with 2 and 3 and so on. All the elements are siblings. The extract could be moving the elements into an array as plain text for example.
Is it possible to achieve?
Thanks a lot in advance

A: If I understand your question correctly, this could be achieved via the use of the .nextSibling field on DOM nodes.
This would allow you to access the next sibling node to the current node being processed (ie the first p element in your document). You could use this to iterate through all valid siblings, searching for any with innerText matching your the criteria and adding those to a list of extracted nodes like so:

var extracted = [];

/*
Get starting node for search. In this case we'll start
with the first p element
*/
var p = document.querySelector('p');

/*
Iterate through each sibiling of p
*/
do {

  /*
  If this sibling node has innerText that matches the
  number pattern required, add this node to the list of
  extracted nodes
  */
  if(p.innerText && p.innerText.match(/\d+./gi)) {
    extracted.push(p.innerText);
  }

  /*
  Move to next sibling
  */
  p = p.nextSibling;
}
while(p) /* Iterate while sibing is valid */

console.log('Extracted plain text for nodes with number string for innerText:', extracted);

1.

This is the first paragraph..

<button>click</button>

2.

And this is the second...

3.

this is the last paragraph

A: You can check the nextElementSibling with while like the following way:

var arrP = ['1.','2.','3.'];
var allP =  document.querySelectorAll('p');
allP.forEach(function(p){
  if(arrP.includes(p.textContent)){
    var siblings = [];
    elem = p.nextElementSibling;
    while(elem) {
      if (elem.nodeName == 'P' || elem.nodeName == 'SCRIPT') break;
      siblings.push(elem);
      elem = elem.nextElementSibling;
    }
    console.log(siblings);
  }
});

1.

This is the first paragraph..

<button>click</button>

2.

And this is the second...

3.

this is the last but one paragraph

Not.

this is the last paragraph


text:
Q: Magento PHP Cron Issue on Magento 1.9 CE I am using Magento 1.9 CE and am having a cron issue. The Magento cron will not start and the error reports the following:
/home/magento/magento/cron.sh: line 48: /home/magento/magento/cron.php: Permission denied

I am logging in as user 'magento' and have created a crontab -e
*/5 * * * *  sh /home/magento/magento/cron.sh

Because cron.sh is having problems locating the PHP binary, I hard-coded that in the Cron.sh
PHP_BIN=`/opt/remi/php56/root/usr/bin/php`

I found this by performing a 'which php'
My permissions on the cron.sh and cron.php are as follows:
-rw-rw-r--  1 magento magento   2946 Jun 12  2017 cron.php
-rw-rw-r--  1 magento magento   1683 Dec 20 11:45 cron.sh

Still getting the error message in the /var/mail/
 /home/magento/magento/cron.sh: line 48: /home/magento/magento/cron.php: Permission denied

A: wrong permission for sh script.
chmod +x /home/magento/magento/cron.sh

should do the job

A: Looks like your files has no execution rights(just read-write). Try to set execution rights for this files(775 for example). I think it should help with your issue.


text:
Q: Shopify: Iterate and show return button for partial orders on fulfilled items only In Shopify on order.liquid I am trying to add a return button to orders that are only fulfilled. I am having trouble adding this to partial orders that have various fulfillment statuses. Is there a way to access the fulfillment_status on a line item level?
I am able to access values from the order.fulfillment_status but I do not see any values from the line_item.fulfillment_status
{%- if order.fulfillment_status == 'partial' -%}
    {% for order in customer.orders %}
        {% for line_item in order.line_items %}
            {%- if line_item.fulfillment_status == 'fulfilled' -%}
                Return Item
            {%- endif -%}
         {% endfor %}
    {% endfor %}
{%- endif -%}

I would like the return button to show only for fulfilled items on a line item level for partial orders.

A: line_item does not have property fulfillment_status, instead it has fulfillment:
https://help.shopify.com/en/themes/liquid/objects/line_item
https://help.shopify.com/en/themes/liquid/objects/fulfillment
Your if statement for line item should be more like:
{% if line_item.fulfillment.item_count == line_item.quantity %}
So you need something like this:
{%- if order.fulfillment_status == 'partial' -%}
    {% for order in customer.orders %}
        {% for line_item in order.line_items %}
            {% if line_item.fulfillment.item_count == line_item.quantity %}
                Return Item
            {%- endif -%}
         {% endfor %}
    {% endfor %}
{%- endif -%}

give it a shot,
Best of luck


text:
Q: Node-specific component for graphs Is there a name for the set of nodes which can be reached from a given node in a graph, similar to a node-specific component? Or in the words of @mark-s in the comments: the vertex set of the component of that vertex.
Reachbility is not the right term because it is defined as the reachability refers to the ability to get from one vertex to another within a graph, not as a set of vertices that can be reached.
The Python graph library networkx calls it node connected component, but I cannot find any literature using that term
In time-varying graphs the set of vertices which can be reached in a time-respecting manner is called horizon. I am looking for the equivalent for time-aggregated, static graphs.


text:
Q: Notification and AlarmManager I know that this question has been asked several times but I really don't understand why my code doesn't work. I based upon a lot of examples (from stackoverflow answers) to write my code and I need help to understand where is the problem.
The context
The user can, trough preferences, choose a day to be notify.
I get a number from 2 (monday) 3...4...5... to 1 (sunday).
public Calendar getCalendar(){
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.DAY_OF_WEEK,getDayForNotification());
    calendar.set(Calendar.HOUR_OF_DAY, 8);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    calendar.set(Calendar.AM_PM,Calendar.AM);

    return calendar;
}

Then I want to repeat the alarm once a week on the day that the user has chosen.
public void setNotificationDate() {

    alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(this, myAlarmReceiver.class);
    alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);

    DateNotificationPreference dateNotificationPreference = new DateNotificationPreference(this);

    alarmMgr.setRepeating(AlarmManager.RTC, dateNotificationPreference.getCalendar().getTimeInMillis(),AlarmManager.INTERVAL_DAY * 7, alarmIntent);

}

My broadcast receiver
public class myAlarmReceiver extends BroadcastReceiver
{

  @Override
  public void onReceive(Context context, Intent intent)
   {
    Intent service1 = new Intent(context, AlarmService.class);
    context.startService(service1);

   }
}

In my service, I have juste one method :
public void createNotification(){
    final NotificationManager mNotification = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    final Intent launchNotifiactionIntent = new Intent(this, mySilhouette.class);
    final PendingIntent pendingIntent = PendingIntent.getActivity(this,
            0, launchNotifiactionIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    Notification.Builder builder = new Notification.Builder(this)
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(R.drawable.icon_notification)
            .setContentTitle("my notification")
            .setContentText("my first notification")
            .setContentIntent(pendingIntent);

    mNotification.notify(0, builder.build());
}

When I choose the current day, the notification appears at the good time, but when I relaunch the app at 8:05 am for example, I have again a notification. After that, if I choose another day and go back to the activity, I have again a notification...There is something strange and I don't know what can be the problem. I need your help :)
Thanks a lot !
Kmel

A: set() on Calendar does just that: it sets the value. As a result, the date may be in the past, given your existing code.
For example, where I am, right now it is Friday. So, the object returned by Calendar.getInstance() is set for now, which means its day-of-week will be Friday. If you call set() to change that to Tuesday, now you may be setting a date in the past. Similarly, even if you were to set the day-of-week to Friday, it is after 8am where I am, and therefore you would be creating a date that is in the past.
You need to check your calculated Calendar object and see if it is in the past. If it is, add 7 days to move it to the next week's time for the alarm to go off.
Also, note that an RTC alarm will not wake up the device out of sleep mode. That may be fine for your purposes, but I just wanted to make sure that you were aware of this.


text:
Q: Gradients of the NDSolve PDE solution I would like to understand, how to obtain gradients of the PDE solution obtained with NDSolve. To be precise let us consider a Laplace equation from one of the examples:
    Clear[x, y, f];
Needs["NDSolve`FEM`"]
emesh = ToElementMesh[Disk[]];

f = NDSolveValue[{Derivative[0, 2][u][x, y] +
Derivative[2, 0][u][x, y] == 0,
   DirichletCondition[u[x, y] == Sin[x y], True]},
  u, {x, y} ∈ emesh]

This returns the interpolation function which one can plot and integrate:
    NIntegrate[f[x, y], {x, y} ∈ emesh]

(*  1.52794*10^-8  *)

Plot3D[f[x, y], {x, y} ∈ emesh]

This, however, does not work:
  g[x_, y_] := D[f[x, y], x];
Plot3D[g[x, y], {x, y} ∈ emesh]

Since Integrate does not work on this result, only NIntegratedoes, the problem is probably that one needs to apply a numeric derivative.
  What and how?

A: That's an easy one:
g[x_, y_] = D[f[x, y], x];
Plot3D[g[x, y], {x, y} \[Element] emesh]

Note the : in the definition of g :-)


text:
Q: How can I make a jbutton trigger by pressing "Enter" key? Hello I have build a simple GUI game to guess a number between 0-100 and I have a button which the user clicks to check the number. I want the user to be able to press the key enter and execute the action of the button. I have looked around for a solution but cant seemed to find a answer for my problem :/
thank you in advance
package org.eclipse.wb.swt;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.util.Random;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class JGuessinggame {

private JFrame frame;
private JTextField textField;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                JGuessinggame window = new JGuessinggame();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */
public JGuessinggame() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    frame = new JFrame();
    frame.getContentPane().setFont(new Font("Tahoma", Font.PLAIN, 15));
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    JLabel lblWwe = new JLabel("Welcome to the Magic Number Guessing game");
    lblWwe.setFont(new Font("Segoe UI", Font.PLAIN, 15));
    lblWwe.setBounds(56, 11, 333, 44);
    frame.getContentPane().add(lblWwe);

    JLabel lblGuessANumber = new JLabel("Guess a number between 0 - 100");
    lblGuessANumber.setFont(new Font("Tahoma", Font.PLAIN, 14));
    lblGuessANumber.setBounds(100, 66, 215, 14);
    frame.getContentPane().add(lblGuessANumber);

    textField = new JTextField();
    textField.addKeyListener(new KeyAdapter() {

    });
    textField.setBounds(159, 128, 86, 20);
    frame.getContentPane().add(textField);
    textField.setColumns(10);

    JLabel lblAnswer = new JLabel("");
    lblAnswer.setFont(new Font("Tahoma", Font.PLAIN, 14));
    lblAnswer.setBounds(100, 174, 324, 29);
    frame.getContentPane().add(lblAnswer);

    Random ran = new Random();
    int number;
    number = (ran.nextInt(100)+1);

    JButton btnCheck = new JButton("Check!");
    btnCheck.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

        try{

            int guess = Integer.parseInt(textField.getText());

            if(number>guess)
                lblAnswer.setText("try higher!");
            else if(number<guess)
                lblAnswer.setText("try lower!");
            else if(number==guess)

                lblAnswer.setText("you guess correctly! , the magic number was "+number);

            }catch(Exception exc){
            exc.printStackTrace();
            }

        }
    });
    btnCheck.setBounds(159, 214, 89, 23);
    frame.getContentPane().add(btnCheck);

}

}


text:
Q: Realm database difficulties in IOS application I am currently developing an application, and I am facing some problems I can not solve.
I currently have two views:

*

*First view is a tableView representing my Realm objects.

*Second view is for adding objects to my Realm database.

My problem is that, after adding a new object to my Realm database and immediately returning to the first view, sometimes the tableView does not recognize the newly added object but sometimes it does.
I hope this is information enough - ask me questions if needed.
override func viewWillAppear(_ animated: Bool) {
    setupDataForViewTable()

    tableView.delegate = self
    tableView.dataSource = self
    tableView.reloadData()
}

func setupDataForViewTable() {
    let realmm = try! Realm()
    let cryptocurrenciesFromDatabase = realmm.objects(crypto.self)
    for crypto in cryptocurrenciesFromDatabase{
        //For debugging
        if crypto.name.count <= 0{
            continue
        }
        let ROI = 0.0
        let change24h = 0.0
        let totalHolding = Double(crypto.buyingPrice) * Double(crypto.amount)
        cryptoCurrencies.append((name : crypto.name, amount : crypto.amount, ROI : ROI, change24h : change24h, total : totalHolding))
    }
}

Then there is the code from the second view, where i add stuff:
func updateCryptoInRealmDatabase(name : String, buyingPrice : Double, amount : Double){
    DispatchQueue(label: "background").async {
        autoreleasepool {
            let realm = try! Realm()
            let objectToUpdate = realm.objects(crypto.self).filter("name CONTAINS %@", name).first
            try! realm.write {
                objectToUpdate!.buyingPrice = (objectToUpdate!.buyingPrice + buyingPrice) / 2
                objectToUpdate!.amount += amount
            }
        }
    }
}

A: You need to make sure that tableView is updated when you navigate back to the first view. If that view is holding reference to Realm object and second view edited List in that object then it is enough to reload table. If you are holding reference to query of Realm objects then it will be refreshed automatically by Realm after commit update.
You can simply reload the view after it is shown again or register for Realm notifications and update the view as the second view does changes to it.
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    tableView.reloadData()
}

If first view showing (same) Realm object  that second view is editing then data is already up to date. We will get fresh count of related objects here:
func titleTableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return realmObject.relatedObjects.count
}

Update: Fixed refresh need for Realm Result and added link to notifications in Realm documentation.


text:
Q: Google script that triggers copy of a range to another spreadsheet - NOT WORKING for me I have an issue with Google Apps Script that should trigger the copy of a range to another Google spreadsheet. The strange thing here is that the script is perfectly working if started through the Script Editor. But it's not working through the trigger (onEdit).
The script itself is much longer and everything related to data processing within one and the same spreadsheet is triggered successfully. Only the copy of a specific range to another spreadsheet is not working. But as I mentioned, it's working if I run it through the Script Editor.
Please see below a simple representation of my script:
   function onEdit(e){

   var sourceFile1 = SpreadsheetApp.getActiveSpreadsheet();
   var sheet = sourceFile1.getActiveSheet();
   var selectedRange = sheet.getRange(44,1, 1, 29);
   var sourceData = selectedRange.getValues();
   var destinationFile = SpreadsheetApp.openById("    ");
   var destinationSheet = destinationFile.getSheetByName("Orders");
   var lastRow = destinationSheet.getLastRow();
   lastRow = lastRow + 1;
   destinationSheet.getRange(lastRow, 1, 1, 29).setValues(sourceData);
   }

A: *

*In your script, when you run onEdit() with the script editor, it works.

*But when the function is run as the OnEdit trigger, it doesn't work.

*In this situation, you are owner of Spreadsheet and Script.

If my understanding is correct, how about this answer?
I think that in your script, when the OnEdit event is run, an error related to the authorization occurs at var destinationFile = SpreadsheetApp.openById("    ");. When you want to confirm this, please check the execution transcript of script editor after the function is run as the OnEdit trigger.
So as a solution, how about installing the function as the installable Triggers?
Note:

*

*In your case, because the error of authorization occurs, you can install the function name onEdit() as the installable Triggers. But I recommend to modify the function name from onEdit() to other. For example, it is like installed_onEdit().

*

*Because the function of function name of onEdit() is run as a simple trigger, when onEdit() is installed as the installable Triggers, onEdit() run 2 times as the simple trigger and the installable Triggers.

References:

*

*Execution transcript

*Managing triggers manually
If I misunderstood your question and this was not the solution of your issue, I apologize.


text:
Q: Estimating departures in a matrix I'm attempting to estimate how many individuals (unique "id"s) that were in a given zone in a given time step (date), departed that zone in the following time step. Here is a tiny subset of the data:
zone   date            id
802 2007-01-01       453444
803 2007-01-01       407680
803 2007-01-01       415786
804 2007-02-01       407680
802 2007-02-01       453444
802 2007-03-01       415786
804 2007-03-01       407680
802 2007-04-01       415786
802 2007-04-01       407680
804 2007-04-01       453444
801 2007-05-01       453444
804 2007-05-01       407680
804 2007-05-01       415786
804 2007-06-01       453444
801 2007-06-01       415786
804 2007-06-01       407680
803 2007-07-01       407680
803 2007-07-01       453444
804 2007-07-01       415786

So my question is, how can I estimate these departures? I am trying to create a matrix that will look something like below for the number of individuals that departed summed per date/zone. Any help you can offer is very much appreciated.
        zone   2005-07-01   2005-08-01   2005-09-01
1       103          0          1          0
2       106          0          0          3
3       107          0          0          0
4      1603          0          0          0
5      1607          0          0          0
6      2204          0          0          0
7      2206          0          3          1
8      2209          0          0          0
9      3106          0          0          0
10     3804          0          0          0
11     3806          0          0          0

I'm thinking something like a two step function that 1.) iterates through all individual IDs asking if zone[i] in date[t] = zone[i] in date[t+1], and if NOT yield a "1" and store in a matrix (indicating departure); then 2.) summing all the the 1's for each zone/date across all IDs to yield the sum of departures per zone for each time step. Something like that, but having trouble formulating that function

A: New answer:
So, the first step is to group the data by id and zone, and to count the number of departures at each time. This can done with:
all.dates = data.frame(date=unique(zz$date))
n=nrow(all.dates)

bool.list = by(data=zz, INDICES=list(zz$zone, zz$id), FUN=function(x){
  xx = merge(x,all.dates,by=c('date'),all=T)
  xx$id[is.na(xx$id)] = 0
  return(diff(xx$id)<0)
  })

which returns a list indicating the departures:
> bool.list
: 801
: 407680
[1] FALSE FALSE  TRUE FALSE FALSE FALSE
--------------------------------------------------------------------------
: 802
: 407680
[1] FALSE FALSE FALSE  TRUE FALSE FALSE
--------------------------------------------------------------------------
: 803
: 407680
[1]  TRUE FALSE FALSE FALSE FALSE FALSE
--------------------------------------------------------------------------
: 804
: 407680
[1] FALSE  TRUE FALSE FALSE FALSE  TRUE
--------------------------------------------------------------------------
: 801
: 415786
[1] FALSE FALSE FALSE FALSE FALSE  TRUE
--------------------------------------------------------------------------
[...]

This list can easily be converted to a matrix:
tmp = matrix(unlist(bool.list),ncol=nrow(all.dates)-1,byrow=T)
colnames(tmp) = all.dates$date[2:nrow(all.dates)]
rownames(tmp) = rep(rownames(bool.list), length(colnames(bool.list)))

Returning:
> tmp
    2007-02-01 2007-03-01 2007-04-01 2007-05-01 2007-06-01 2007-07-01
801      FALSE      FALSE       TRUE      FALSE      FALSE      FALSE
802      FALSE      FALSE      FALSE       TRUE      FALSE      FALSE
803       TRUE      FALSE      FALSE      FALSE      FALSE      FALSE
804      FALSE       TRUE      FALSE      FALSE      FALSE       TRUE
801      FALSE      FALSE      FALSE      FALSE      FALSE       TRUE
802      FALSE      FALSE      FALSE       TRUE      FALSE      FALSE
803       TRUE      FALSE       TRUE      FALSE      FALSE      FALSE
804      FALSE      FALSE      FALSE      FALSE       TRUE      FALSE
801      FALSE      FALSE      FALSE      FALSE       TRUE      FALSE
802      FALSE       TRUE      FALSE      FALSE      FALSE      FALSE
803      FALSE      FALSE      FALSE      FALSE      FALSE      FALSE
804      FALSE      FALSE      FALSE       TRUE      FALSE       TRUE

The second step is to collapse all rows with the same id and to count the number of TRUE values. This can be done with:
result = aggregate(tmp,list(rownames(tmp)),FUN=sum)

Returning:
> result
  Group.1 2007-02-01 2007-03-01 2007-04-01 2007-05-01 2007-06-01 2007-07-01
1     801          0          0          1          0          1          1
2     802          0          1          0          2          0          0
3     803          2          0          1          0          0          0
4     804          0          1          0          1          1          2

which should be the desired answer.

Old answer:
Here is my best guess, provided that you did not specify how to handle duplicated data:
# we extract all the dates:
# they will define the number of columns of the returned matrix
all.dates = data.frame(date=unique(zz$date))

bool.list = by(data=zz, INDICES=list(zz$id), FUN=function(x){
  if (any(duplicated(x$date))) {
    x = x[!duplicated(x$date),]
  }
  # we complete so we have all dates represented, for each ID and each zone
  xx = merge(x,all.dates,all=T)
  return(diff(xx$zone)==0)
}
)

# we build the matrix from the list vectors
r = matrix(unlist(tst),ncol=nrow(all.dates)-1,nrow=length(names(tst)),byrow=T)

# some cosmetic job
colnames(r) = all.dates$date[2:nrow(all.dates)]
rownames(r) = names(bool.list)

This returns, for your example:
> r
       2007-02-01 2007-03-01 2007-04-01 2007-05-01 2007-06-01 2007-07-01
407680      FALSE      FALSE      FALSE      FALSE       TRUE      FALSE
415786         NA         NA      FALSE       TRUE      FALSE      FALSE
453444       TRUE         NA         NA      FALSE      FALSE      FALSE

You may want to replace the NA with whatever value makes sense to you (TRUE or FALSE)
Notice the part:
  if (any(duplicated(x$date))) {
    x = x[!duplicated(x$date),]
  }

This is where I get rid of the second zone data for the same date and the same id, if duplicated. You may want to modify this to have another way to handling messy data :)


text:
Q: "coffee" command fails silently, how to debug? When using coffee-script this command runs ok on 1 computer but silently fails on another.
coffee --output dir --compile dir
make: *** [js] Error 1

How can I debug? Any flags for verbose output?
npm list -g
/usr/local/lib
├─┬ coffee-script@1.7.1
│ └── mkdirp@0.3.5
├── csso@1.2.15
└── uglify-js@1.3.2

Even coffee --version fails with no output

A: It was a terrible mix of old Ubuntu's/new packages.

*

*Needed to remove node, nodejs packages.

*Install new versions from PPA
sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install python-software-properties python g++ make nodejs

*Reinstall coffee-script: sudo npm install coffee-script -g
Thanks


text:
Q: Use PHP to split a sentence into shorter sentences Is there a certain way I can apply to split a sentence into smaller sentences to perform a databas search. My client want to perform a database search like in this example:
First request: Claimant had an accident in the coffee shop
Second request: Claimant had an accident in the coffee (in case document states it was a bar etc.)
Third request: Claimant had an accident in the
...
Last request: Claimant
I find a lot of topics about splitting sentece by word, but nothing about chunks of words. Any suggestions?

A: You could use explode(" ", $str). Then, you can reconstruct the sentence word by word (except for the words outside that particular iteration).
Something like this (the loops may be off, I've never written PHP before):
for ($x = count($sentence); $x >0; $x--) {
    for($y = 0; $y < $x; $y++) {
      echo $cars[$y];
       echo "
";
   }
   echo "
"
}

A: Simple solution with explode, implode and array_slice functions:
$str = "Claimant had an accident in the coffee shop";
$words = explode(" ", $str);
$count = count($words);

echo implode(" ", array_slice($words, 0, $count)) . "
"; // first request
while (--$count) {
    echo implode(" ", array_slice($words, 0, $count)) . "
";
}

The output:
Claimant had an accident in the coffee shop
Claimant had an accident in the coffee
Claimant had an accident in the
Claimant had an accident in
Claimant had an accident
Claimant had an
Claimant had
Claimant

A: One more option using string functions:
$string = 'Claimant had an accident in the coffee shop';

echo "$string
";  // use the entire string first as first iteration of
                     // the loop will chop off the last word

while ($string = substr($string, 0, strrpos($string, ' '))) {
    echo "$string
";
}

A: You could write a regexp that splits based on punctuation marks.  This example, which splits on periods, question marks, exclamation marks and the end-of-line, should get you started:
$data = 'First request: Claimant lost $500 in the coffee shop.  Second request: (unknown) Claimant had an accident?  Third request: Claimaint went to the hospital!  End of report';

preg_match_all("/\s*(.*?(?:[\.\?\!]|$))/", $data, $matches);
foreach ($matches[1] as $sentence) {
    if (preg_match("/\S/", $sentence) ) {
        print "Sentence: $sentence\n";
    }
}

Results:
Sentence: First request: Claimant lost $500 in the coffee shop.
Sentence: Second request: (unknown) Claimant had an accident?
Sentence: Third request: Claimaint went to the hospital!
Sentence: End of report


text:
Q: Domain Driven Design using Environment Variables for .NET Microservices I'm trying to work with Domain Driven Design, in a .NET 6 project, and I'm trying to wrap my head around the following.
In my previous Big Ball of Mud projects we've typically stored Application configuration variables in environment variables (and/or appsettings.json).
My understanding of DDD is we are shifting the business rules/logic into the Domain Layer to organize it separate to our Application Layer (implementation detail).
I've done training on Pluralsight and also reviewed Microsoft's DDD-orientated microservice (https://learn.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/ddd-oriented-microservice) and Clean Architecture. Its clear that the Domain Layer should be referencing anything in the Application Layer.
To me, using appsettings.json seems to be part of the Application Layer's implementation detail - so my question is, "is it not possible to use appsettings.json with the Domain Layer?"?
I raise this question because I want to allow for certain variables to be defined with appsettings.json, however I also want to be able to use those variables to enforce Guards within my Domain Layer.
For example, I want to define a "user's default session length" in the environment variables, but I also want to enforce that session length in the Domain Layer when creating or updating entities.
I know I can do this in the Application Layer, but it feels wrong to move something that should be tied to Domain Entity into the Application Layer.
Any help or opinions would be appreciated.

A: Broad strokes: the code that figures out what to do with information lives inside the domain layer.  The code that figures out where the information comes from lives outside the domain layer.
So you'll have code outside the domain layer that reads your environment variables, or reads appsettings.json, or whatever, and the values are passed to the domain layer as arguments.
I can think of at least three variations

*

*The domain layer defines an interface for accessing this implementation; the application layer implements that interface, and passes a reference to its implementation to the domain layer

*The domain layer defines a data structure for representing this information, and offers affordances for creating instances of these data structures (ex: a factory method)

*The domain layer defines an interface that accepts this information in some general purpose representation (ex: Strings, ints, arrays of bytes, etc) and hides the details of how that information might be organized into data structures.

A: I always like to ask myself the following questions:

If the users tell you their stories what they want to do with the software, do they really care about that thing? In your example, user's default session length? Is that something they brought up, or is it a technical aspect which arose from your mind?

*

*If they don't care, then it's technical and only part of the Application layer, not the Domain

*If they do care, then it should be part of the domain. The next question to the users then is: "Do you need to configure it by yourself?"

*

*If they say yes, then the session length would be part of an Aggregate and would not be injected via settings, but set by an user interaction with the app

*If they say no, they most likely have a specific default length in mind. Then I would explicitly model this value "hard-wired" in the Domain and don't make it configurable, because it's a definite business rule and must expressed accordingly in the Domain code (maybe a constant in the Aggregate, which needs it).

You can generalize this thinking to every feature you implement. So naturally there should never be a need to configure domain business rules via appsettings.json. Or conversely: Having the need to configure the domain via settings could be a misunderstanding of DDD.
Or you can think about it this way: An Aggregate ensures the transactional consistency of business rules. If you could change values via appsettings.json, what does that mean for the business rules? Without any user interaction, the consistency is defined differently today for all Aggregate instances than yesterday? What does that mean for existing instances, are they now just invalid? Doesn't sound like DDD in my ears.


text:
Q: Why does this nostdlib C++ code segfault when I call a function with a thread local variable? But not with a global var or when I access members? Assembly included. This weekend I tried to get my own small library running without any C libs and the thread local stuff is giving me problems. Below you can see I created a struct called Try1 (because it's my first attempt!) If I set the thread local variable and use it, the code seems to execute fine. If I call a const method on Try1 with a global variable it seems to run fine. Now if I do both, it's not fine. It segfaults despite me being able to access members and running the function with a global variable. The code will print Hello and Hello2 but not Hello3
I suspect the problem is the address of the variable. I tried using an if statement to print the first hello. if ((s64)&t1 > (s64)buf+1024*16) It was true so it means the pointer isn't where I thought it was. Also it isn't -8 as gdb suggest (it's a signed compare and I tried 0 instead of buf)
Assembly under the c++ code. First line is the first call to write
//test.cpp
//clang++ or g++ -std=c++20 -g -fno-rtti -fno-exceptions -fno-stack-protector -fno-asynchronous-unwind-tables -static -nostdlib test.cpp -march=native && ./a.out
#include <immintrin.h>
typedef unsigned long long int u64;

ssize_t my_write(int fd, const void *buf, size_t size) {
    register int64_t rax __asm__ ("rax") = 1;
    register int rdi __asm__ ("rdi") = fd;
    register const void *rsi __asm__ ("rsi") = buf;
    register size_t rdx __asm__ ("rdx") = size;
    __asm__ __volatile__ (
        "syscall"
        : "+r" (rax)
        : "r" (rdi), "r" (rsi), "r" (rdx)
        : "cc", "rcx", "r11", "memory"
    );
    return rax;
}

void my_exit(int exit_status) {
    register int64_t rax __asm__ ("rax") = 60;
    register int rdi __asm__ ("rdi") = exit_status;
    __asm__ __volatile__ (
        "syscall"
        : "+r" (rax)
        : "r" (rdi)
        : "cc", "rcx", "r11", "memory"
    );
}

struct Try1
{
    u64 val;
    constexpr Try1() { val=0; }
    u64 Get() const { return val; }
};

static char buf[1024*8]; //originally mmap but lets reduce code

static __thread u64 sanity_check;
static __thread Try1 t1;
static Try1 global;

extern "C"
int _start()
{
    auto tls_size = 4096*2;
    auto originalFS = _readfsbase_u64();
    _writefsbase_u64((u64)(buf+4096));

    global.val = 1;
    global.Get(); //Executes fine

    sanity_check=6;
    t1.val = 7;

    my_write(1, "Hello\n", sanity_check);
    my_write(1, "Hello2\n", t1.val); //Still fine
    my_write(1, "Hello3\n", t1.Get()); //crash! :/
    my_exit(0);
    return 0;
}

Asm:
4010b4:       e8 47 ff ff ff          call   401000 <_Z8my_writeiPKvm>
4010b9:       64 48 8b 04 25 f8 ff    mov    rax,QWORD PTR fs:0xfffffffffffffff8
4010c0:       ff ff
4010c2:       48 89 c2                mov    rdx,rax
4010c5:       48 8d 05 3b 0f 00 00    lea    rax,[rip+0xf3b]        # 402007 <_ZNK4Try13GetEv+0xeef>
4010cc:       48 89 c6                mov    rsi,rax
4010cf:       bf 01 00 00 00          mov    edi,0x1
4010d4:       e8 27 ff ff ff          call   401000 <_Z8my_writeiPKvm>
4010d9:       64 48 8b 04 25 00 00    mov    rax,QWORD PTR fs:0x0
4010e0:       00 00
4010e2:       48 05 f8 ff ff ff       add    rax,0xfffffffffffffff8
4010e8:       48 89 c7                mov    rdi,rax
4010eb:       e8 28 00 00 00          call   401118 <_ZNK4Try13GetEv>
4010f0:       48 89 c2                mov    rdx,rax
4010f3:       48 8d 05 15 0f 00 00    lea    rax,[rip+0xf15]        # 40200f <_ZNK4Try13GetEv+0xef7>
4010fa:       48 89 c6                mov    rsi,rax
4010fd:       bf 01 00 00 00          mov    edi,0x1
401102:       e8 f9 fe ff ff          call   401000 <_Z8my_writeiPKvm>
401107:       bf 00 00 00 00          mov    edi,0x0
40110c:       e8 12 ff ff ff          call   401023 <_Z7my_exiti>
401111:       b8 00 00 00 00          mov    eax,0x0
401116:       c9                      leave
401117:       c3                      ret

A: The ABI requires that fs:0 contains a pointer with the absolute address of the thread-local storage block, i.e. the value of fsbase.  The compiler needs access to this address to evaluate expressions like &t1, which here it needs in order to compute the this pointer to be passed to Try1::Get().
It's tricky to recover this address on x86-64, since the TLS base address isn't in a convenient general register, but in the hidden fsbase.  It isn't feasible to execute rdfsbase every time we need it (expensive instruction that may not be available) nor worse yet to call arch_prctl, so the easiest solution is to ensure that it's available in memory at a known address.  See this past answer and sections 3.4.2 and 3.4.6 of "ELF Handling for Thread-Local Storage", which is incorporated by reference into the x86-64 ABI.
In your disassembly at 0x4010d9, you can see the compiler trying to load from address fs:0x0 into rax, then adding  -8 (the offset of t1 in the TLS block) and moving the result into rdi as the hidden this argument to Try1::Get().  Obviously since you have zeros at fs:0 instead, the resulting pointer is invalid and you get a crash when Try1::Get()  reads val, which is really this->val.
I would write something like
void *fsbase = buf+4096;
_writefsbase_u64((u64)fsbase);
*(void **)fsbase = fsbase;

(Or memcpy(fsbase, &fsbase, sizeof(void *)) might be more compliant with strict aliasing.)


text:
Q: Multiple monitors at different resolutions I'm running a Dell XPS 13 9350 that has a resolution of 3200x1800, and then I have an external display running 1920x1080, all of a sudden a few months ago, windows and dialogs on the external display suddenly started to appear weirdly.
Dialogs would appear super large and depending on the window, the close/maximize/minimize buttons would get stretched.
Here's a screenshot of my desktops in a vertical stack (1920x1080 is on top)
Note how the chrome window on the top monitor appears to have been cut off at the top of the screen, and how the buttons in the top right have been stretched, and lastly how the chrome window very slightly stretched too far at the bottom underneath the task bar. (You may need to open the image in another tab and zoom in)
Then the image below is the "save file" dialog on the same monitor within Chrome (this problem extends to all dialogs from any application)
And lastly, all my drivers are up to date.
Does anyone have any idea what's going on?

Oversized Dialog:


text:
Q: How to Easily Process IMAP Email in RAILS 6 I am looking for an easy way to parse an IMAP struct that I have read from an exiting email account. Ideally if you could point me to an existing gem that handles imap emails. Everything I find is extremely old.
My app fetches email from an existing, external imap account. I am able to read the email and retrieve it and even to parse it and extract most  of the information I want. However, I am not able to extract the HTML or text body parts easily. Overall, parsing the struct that is returned by the net/imap library is difficult to handle.
All the help articles that I can find on the topic seem VERY old and existing gems have not been updated in many years.
Is there not an easy way, a gem or built in library to handle imap objects? I am also open t rewriting my app to do things easier. My code below is workig fine. The envelopes struct that I receive back is just really awful to work with.
      connection = Net::IMAP.new(server.inbound_server, server.inbound_port, server.inbound_encryption)
      connection.login(server.inbound_user, server.inbound_password)

      connection.examine("INBOX")
      uid_list = connection.search(["FROM", search_term])
      envelopes = connection.fetch(uid_list, "ENVELOPE")


text:
Q: Create a custom search in Entity Symfony2 I'm a newby in Symfony, but I'm trying to develop a small system to my job.
I only have experience in ZF1 and I'm not used to use Doctrine. But I need to create a custom Query for my page, and searching in the internet I discover that when I generate a new Entity, I can create a new one that has the same name + Repository in the class name.
For example, I have a Entity named Schedule and a Repository named ScheduleRepository.
And in the ScheduleRepository that I'm tryong to generate my custom Query.
class ScheduleRepository extends EntityRepository
{
   public function findAll()
   {
      $rsm = new ResultSetMapping();

      # ScheduleType
      $rsm->addEntityResult( "ApplicationBundle\Entity\Schedule", "s" );
      $rsm->addFieldResult( "s", "schedule_id", "id" );
      $rsm->addFieldResult( "s", "usersId", "usersId" );
      $rsm->addFieldResult( "s", "updatedAt", "updatedAt" );
      $rsm->addFieldResult( "s", "start", "createdAt" );
      $rsm->addFieldResult( "s", "finish", "createdAt" );
      $rsm->addFieldResult( "s", "schedulesTypeId", "schedulesTypeId" );

      # User
      $rsm->addJoinedEntityResult( "ApplicationBundle\Entity\User", "u", "s", "users" );
      $rsm->addFieldResult( "u", "users_id", "id" );
      $rsm->addFieldResult( "u", "name", "name" );

      $rsm->addJoinedEntityResult( "ApplicationBundle\Entity\ScheduleType", "st", "s", "scheduleType" );
      $rsm->addFieldResult( "st", "schedule_type_id", "id" );
      $rsm->addFieldResult( "st", "schedule_type_name", "name" );

      # custom SQL
      $sql = "SELECT
               s.id AS schedule_id,
               s.updated_at,
               st.id AS schedule_type_id,
               st.name AS schedule_type_name,
               u.id AS users_id,
               u.name,
               MAX( CASE WHEN s.schedules_type_id = 2 THEN s.created_at END ) AS start,
               MAX( CASE WHEN s.schedules_type_id = 2 THEN s.created_at END ) AS finish
             FROM
               schedules s
             INNER JOIN users u ON u.id = s.users_id
             INNER JOIN schedules_type st ON st.id = s.schedules_type_id
             GROUP BY
               s.users_id,
               DATE_FORMAT( s.created_at, '%Y-%m-%d' )
             ORDER BY
               DATE_FORMAT( s.created_at, '%Y-%m-%d' ) ASC";

      return $this->_em->createNativeQuery( $sql, $rsm )->getResult();
   }

And when I dump the return I receive this:
Schedule {#2187
  -id: 1
  -users: User {#2189
    -id: 1
    -name: "Felipe"
    -email: null
    -password: null
    -active: null
    -createdAt: null
    -updatedAt: null
    #schedule: PersistentCollection {#2190
      -snapshot: []
      -owner: User {#2189}
      -association: array:15 [ …15]
      -em: EntityManager {#2092 …10}
      -backRefFieldName: "users"
      -typeClass: ClassMetadata {#2101 …}
      -isDirty: false
      -initialized: false
      -coll: ArrayCollection {#2191
        -_elements: []
      }
    }
  }
  -scheduleType: ScheduleType {#2180
    -id: 1
    -name: "Entrada"
    #schedule: PersistentCollection {#2181
      -snapshot: []
      -owner: ScheduleType {#2180}
      -association: array:15 [ …15]
      -em: EntityManager {#2092 …10}
      -backRefFieldName: "scheduleType"
      -typeClass: ClassMetadata {#2101 …}
      -isDirty: false
      -initialized: false
      -coll: ArrayCollection {#2182
        -_elements: []
      }
    }
  }
  -createdAt: DateTime {#2188
    +"date": "2015-02-18 19:31:39"
    +"timezone_type": 3
    +"timezone": "UTC"
  }
  -updatedAt: null
}

My questions are:

*

*Why I didn't receive the start and finish alias that I create in my Query?

*Why my updatedAt is null if I have value in that field?

Thank you.
Update
I'm trying what the user [user3749178]:(https://stackoverflow.com/users/3749178/user3749178) said, using this library github.com/mapado/MysqlDoctrineFunctions I generate again the Query, but in DQL, and now I receive an error:
[Syntax Error] line 0, col 73: Error: Unexpected ')'
in this DQL:
SELECT u, s, st, MAX(CASE WHEN s.schedulesTypeId = 2 THEN s.createdAt END) AS start FROM ApplicationBundle:Schedule s JOIN s.users u JOIN s.scheduleType st

A:   $rsm->addFieldResult( "s", "updatedAt", "updatedAt" );
  $rsm->addFieldResult( "s", "start", "createdAt" );
  $rsm->addFieldResult( "s", "finish", "createdAt" );

updatedAt should be updated_at.  Notice also that you have start/finish both mapped to the same field.  I suspect the finish will override the start.  And since you are restricting yourself the mysql then I'd suggest just using camelCase for your aliases to reduce confusion.
It would probably be better to use DQL but I think you are almost there.
DQL only supports the following sql functions: http://doctrine-orm.readthedocs.org/en/latest/reference/dql-doctrine-query-language.html#dql-functions
You can however add your own.
http://symfony.com/doc/current/cookbook/doctrine/common_extensions.html
http://symfony.com/doc/current/cookbook/doctrine/custom_dql_functions.html


text:
Q: Optimizing Firebase query for speed: search Users by city Scenario: I have a Users node which stores their location (city & country). I want to find all users that reside in a particular city. Then per city, I want to filter on roomType and finally sort Users by their score.
Problem: City & Country are string fields, so it will be VERY resource intensive string_comparison query to iterate over all the Users to first match the country & then the city.
What can I do to make this search faster?
One possible approach: Convert the City + Country "location_pair" into a numeric value (say int_val_location_pair). Then do a integer comparison on int_val_location_pair. This will be much faster than doing two string comparisons on country & city. Of course, I will have to store mapping as a separate node.
There aren't that many cities in the world (approx 4,000,000) so I can easily use a 32 bytes integer to represent all cities in the world. Plus realistically, I will get Users from at max 10,000 different cities signed up.
schema can be something like this:
$Users:
    name:
    city:
    country:
    $int_val_location_pair:
    score:
    roomType:
$int_val_location_pair:
    city:
    country:

Question: Is this a good approach??
If yes, I have next concern: At time of registration, when the user fills in country & city, I want to create a new value for int_val_location_pair automatically only IF the location_pair (city & country) does not exist in database.
In this case how to make sure there is no duplication of int_val_location_pair?  Say 10 people are registering all at same time for same location (which does not exists in db). They all query the database & get confirmation that location_pair doesnt exist & so end up creating a new value for int_val_location_pair causing duplicates. How should I avoid this scenario?
Thanks in advance.

A: Why don't you keep a list of users ids for each location in a tree?
usersByLocation
  $country
    $city
      uid1: true
      uid2: true

With that you can simply look up the UIDs for the users in a specific city with:
ref.child("United States").child("San Francisco").on("child_added"...


text:
Q: Is there any danger in allowing direct access to PHP files? I have a bunch of helper files and parsers, some of which are called through AJAX. My understanding is that I can't use .htaccess to block access to those files as it will break AJAX. So my question is: is there actually any harm or danger in allowing direct access to those files? If so, how do I allow AJAX but block users from accessing them?

A: You can use the php  $_SERVER value to validate the ajax requests but if the user use spoofing its not work also if you have perfect validations in your php scripts don't worry about the direct access
  if(isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && ( $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' ) )
    {
        //Your response
    } else {

        //I hate users redirect
    }

A: Ajax is users accessing them, just in a controlled manner.
If the scripts/files can be accessed from Ajax, you can't stop someone from accessing them directly.  You can put roadblocks like looking for certain headers but people can and will find a way around that.
There is no harm or danger in allowing direct access to them as long as your code is secure :)
For example, if you're gonna have Ajax make a call like POST /message/delete?id=1, you'd better make sure the caller has permission to delete the message with ID 1.
Filter and validate all input and put sufficient access checks in place and you should be about as safe as any other website on the internet.

A: To prevent users loading a php file directly in the browser but still allowing ajax requests through and also allowing the file to be included in the document you could try adding the following to the top of the script you wish to protect from direct access.
if ( realpath(__FILE__) == realpath( $_SERVER['SCRIPT_FILENAME'] ) ) {
    header( 'HTTP/1.0 403 Forbidden', TRUE, 403 );
    die( header( 'location:/403/error/Forbidden' ) );/* change to your error page url etc */
}


text:
Q: Pandas Excel groupby/count Hi I'm trying to have my script count the number of times it sees the same words in specified columns with some of those columns having multiple separated by a comma.
For example -
Labels                        Labs
a1, b3                         1
a2                             3
b3                             1

I would want two outputs.
Labels  # of labels
a1           1
b3           2

Labels       Lab1     Lab3
a1            1        0
a2            0        1
b3            2        0

I was trying to use groupby to count but the only output I am getting in excel is below and I am unable to know what they belong to
20
2
1
7
7

I have been playing with this but keep getting the same result shown above
df1 = df.groupby('Labs').count()

A: Keys

*

*Convert the comma-separated string into lists first.

*Use df.explode() to expand the entries.

*Pivoted aggregation (to which concept that group size belongs) can be achieved by df.pivot_table().

Setup
df = pd.read_csv(io.StringIO("""
Labels                        Labs
a1, b3                         1
a2                             3
b3                             1
"""), sep=r"\s{2,}", engine="python")

# split string into list (assume consistent separator pattern)
df["Labels"] = df["Labels"].str.split(", ")

First output:
df.explode("Labels").groupby("Labels").size()

Out[69]:
Labels
a1    1
a2    1
b3    2
dtype: int64

Second output:
df.explode("Labels").pivot_table(index="Labels", columns="Labs", aggfunc="size")\
    .fillna(0).astype(int)

Out[70]:
Labs    1  3
Labels
a1      1  0
a2      0  1
b3      2  0


text:
Q: How to handle generic classes / interfaces in a modular application? I am new to Java and I am coding up a modular application made like this:
*************          *******         ***********
*           *          *     *         *   Data  *
* Front-end * -------- * API * ------- * Handler *
*           *          *     *         *         *
*************          *******         ***********

Essentially, I want to be able to define an API with N classes, and then have a "Data Handler" module deal with storing the objects somewhere (a database, for example), without the front-end needing to know anything of how that is implemented.
So, let's say I have two classes defined in my API: Contract and Company.
I want the front-end to be able to do something like:
myContract = new Contract();
myCompany = new Company();
myContract.setCompany(myCompany);
myContract.save();
myCompany.save();

This way, in the future I could change the way I store the data (the Data Handler module), without changing any code in the front-end.
To do this, I wrote two interfaces for Contract and Company in the API module.
Then, in the data handler module I wrote to classes which implement the two interfaces: DbContract and DbCompany.
Now, I am running into issues because I have defined the getter/setter methods in the Contract interface as:
public interface Contract {
    public Company getCompany();
    public void setCompany(Company company);
}

And implemented them in DbContract as:
public class DbContract implements Contract {
    private DbCompany company;

    @Override
    public Company getCompany() {
        return this.company;
    }

    @Override
    public void setCompany(Company company) {
        this.company = company;
    }
}

However, I am getting class type mismatch errors all over the place...
Am I completely missing the point? How should I actually do this?
Thanks in advance for your help.

A: Change
    private DbCompany company;

To
    private Company company;

And every thing should be sweet.
Otherwise you will need the front end to know what type of company you are dealing with and go generic.
This has not been compiled But something like:
public interface Contract<T extends Company>{
    public T getCompany();
    public void setCompany(T company);
}

public class DbContract implements Contract<DbCompany> {
    private DbCompany company;

    @Override
    public DbCompany getCompany() {
        return this.company;
    }

    @Override
    public void setCompany(DbCompany company) {
        this.company = company;
    }
}

A: myContract = new Contract();

This wouldn't work since you can't create instances of an interface.
You seem to have the right idea, but there also seems to be a misconception on the term "implementation".
If the frontend needs to create instances of those interfaces, it needs to know an implementation or provide its own. On the other hand if the frontend should not know about the implementations at all it should call the backend to create a new instance.
Besides that it might be a better design to make Contract and Company data containers and move the actual logic for saving to a service, e.g. your code would look like this:
class Contract { ... } //as before, but classes not interfaces
class Company { ... } //as before, but classes not interfaces

Creating a new contract:
Contract myContract = new Contract();
Company myCompany = new Company();
myContract.setCompany(myCompany);

contractService.save( myContract ); //assuming this would save the company as well

You could look up the service or let it be injected. For the latter have a look at Spring dependency injection.
Update:
In your comment you state that Company and Contract would be JPA entities and if I understand you correctly you don't want the frontend to have any notion that JPA is being used.
In that case you have two options:

*

*Make your objects plain POJOs and add an XML for the JPA-mapping in the backend. Then you'd treat every instance that is passed from the frontend as a detached entity.

*If you want to use annotations for the mapping and don't want the frontend to know about that you'd need to provide an intermediate layer (called data transfer objects = DTO) that is used by the API. Internally the backend would then translate between entities and DTOs.


text:
Q: how do I add third party app access to my organisation mail in Gmail I wanted to add third party app access to google account and got and error generating app password for third party apps , afterwards I found out we cannot add third party app password in organizational mails link
I tried to find resources to solve this problem but didn't get anything, I still want to add third party app access to organizational mail , is there any walkaround here?


text:
Q: Flashcards with figures I want to make some flashcards of my anatomy notes, i guess i need to use the flashcards class. But then my problem is that i can't have figures/images on the flashcards, it won't compile; It gives the error

" Undefined control sequence"

What am i doing wrong?
\documentclass[avery5388,grid,frame]{flashcards}

\cardfrontstyle[\large\slshape]{headings}
\cardbackstyle{empty}

\begin{document}

\cardfrontfoot{Functional Analysis}

\begin{flashcard}[Definition]{Lever celler}
  \includegraphics[width=.8\linewidth]{billeder/0604}
 \end{flashcard}

\begin{flashcard}[Definition]{Inner Product}

Let $X$ be a complex linear space. An \emph{inner product} on $X$ is
a mapping that associates to each pair of vectors $x$, $y$ a scalar,
denoted $(x,y)$, that satisfies the following properties:

\medskip

\begin{description}
\item [Additivity] $(x+y,z) = (x,z) + (y,z)$,
\item [Homogeneity] $(\alpha \: x, y) = \alpha (x,y)$,
\item [Symmetry] $(x,y) = \overline{(y,x)}$,
\item [Positive Definiteness] $(x,x) > 0$, when $x\neq0$.
\end{description}
\end{flashcard}
    \end{document}

Thanks


text:
Q: Thymeleaf: Neither BindingResult nor plain target object for bean name '#ids' available as request attribute Summary of the problem
I'm trying to create inputs whose name and id are 'workingDay*'(* is a consecutive number).
I faced to the error messages.
It seems that an error happened during parsing "${#ids.next('workingDay')}"
Libraries

*

*JDK: AdoptOpenJDK: 11.0.5

*Spring Framework: 5.2.2.RELEASE

*Thymeleaf Spring: 3.0.11.RELEASE

Error messages
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name '#ids' available as request attribute
    at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:153)
    at org.springframework.web.servlet.support.RequestContext.getBindStatus(RequestContext.java:903)
    at org.thymeleaf.spring5.context.webmvc.SpringWebMvcThymeleafRequestContext.getBindStatus(SpringWebMvcThymeleafRequestContext.java:227)
    at org.thymeleaf.spring5.util.FieldUtils.getBindStatusFromParsedExpression(FieldUtils.java:306)
    at org.thymeleaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:258)
    at org.thymeleaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:227)
    at org.thymeleaf.spring5.processor.AbstractSpringFieldTagProcessor.doProcess(AbstractSpringFieldTagProcessor.java:174)
    at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:74)
    at org.thymeleaf.processor.element.AbstractElementTagProcessor.process(AbstractElementTagProcessor.java:95)
    at org.thymeleaf.util.ProcessorConfigurationUtils$ElementTagProcessorWrapper.process(ProcessorConfigurationUtils.java:633)
    at org.thymeleaf.engine.ProcessorTemplateHandler.handleOpenElement(ProcessorTemplateHandler.java:1314)
    at org.thymeleaf.engine.OpenElementTag.beHandled(OpenElementTag.java:205)
    at org.thymeleaf.engine.Model.process(Model.java:282)
    at org.thymeleaf.engine.Model.process(Model.java:290)
    at org.thymeleaf.engine.IteratedGatheringModelProcessable.processIterationModel(IteratedGatheringModelProcessable.java:367)
    at org.thymeleaf.engine.IteratedGatheringModelProcessable.process(IteratedGatheringModelProcessable.java:221)
    at org.thymeleaf.engine.ProcessorTemplateHandler.handleCloseElement(ProcessorTemplateHandler.java:1640)
    at org.thymeleaf.engine.TemplateHandlerAdapterMarkupHandler.handleCloseElementEnd(TemplateHandlerAdapterMarkupHandler.java:388)
    at org.thymeleaf.templateparser.markup.InlinedOutputExpressionMarkupHandler$InlineMarkupAdapterPreProcessorHandler.handleCloseElementEnd(InlinedOutputExpressionMarkupHandler.java:322)
    at org.thymeleaf.standard.inline.OutputExpressionInlinePreProcessorHandler.handleCloseElementEnd(OutputExpressionInlinePreProcessorHandler.java:220)
    at org.thymeleaf.templateparser.markup.InlinedOutputExpressionMarkupHandler.handleCloseElementEnd(InlinedOutputExpressionMarkupHandler.java:164)
    at org.attoparser.HtmlElement.handleCloseElementEnd(HtmlElement.java:169)
    at org.attoparser.HtmlMarkupHandler.handleCloseElementEnd(HtmlMarkupHandler.java:412)
    at org.attoparser.MarkupEventProcessorHandler.handleCloseElementEnd(MarkupEventProcessorHandler.java:473)
    at org.attoparser.ParsingElementMarkupUtil.parseCloseElement(ParsingElementMarkupUtil.java:201)
    at org.attoparser.MarkupParser.parseBuffer(MarkupParser.java:725)
    at org.attoparser.MarkupParser.parseDocument(MarkupParser.java:301)
    at org.attoparser.MarkupParser.parse(MarkupParser.java:257)
    at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:230)
    at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parseStandalone(AbstractMarkupTemplateParser.java:100)
    at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:666)
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1098)
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1072)
    at org.thymeleaf.spring5.view.ThymeleafView.renderFragment(ThymeleafView.java:362)
    at org.thymeleaf.spring5.view.ThymeleafView.render(ThymeleafView.java:189)
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1373)
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1118)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1057)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:118)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:158)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:158)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:117)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:92)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:77)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1598)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:834)

Thymeleaf Template (From line 30 to line 74)
<form action="#" id="helper_add" method="post" th:object="${helperForm}">

      First Name
      <input type="text" class="form-control" id="inputName" placeholder="First Name" th:field="*{firstName}" th:value="*{firstName}">

      Last Name
      <input type="text" class="form-control" id="inputKana" placeholder="Last Name" th:field="*{lastName}" th:value="*{lastName}">

      Working day 1
      <select class="working-day-body form-control selectpicker" data-style="btn" th:field="${#ids.next('workingDay')}">
        <option value="7">Sun</option>
        <option value="1">Mon</option>
        <option value="2">Tue</option>
        <option value="3">Wed</option>
        <option value="4">Thu</option>
        <option value="5">Fri</option>
        <option value="6">Sat</option>
      </select>

      Working time 1
      <input type="time" class="working-time-from form-control d-inline" th:field="${#ids.next('timeFrom')}" th:value="${#ids.next('timeFrom')}">~
      <input type="time" class="working-time-to form-control d-inline" th:field="${#ids.next('timeTo')}" th:value="${#ids.next('timeTo')}">

      All day
      <input id="chkbox03" name="chkbox01" type="checkbox" class="d-block is-all-day" style="margin:1rem .125rem;">

      Actions

        <button type="button" rel="tooltip" class="btn btn-small btn-success btn-add-line">
          add
        </button>
        <button type="button" rel="tooltip" class="btn btn-small btn-danger btn-delete-line">
          delete
        </button>

the output I want
<form action="#" id="helper_add" method="post" th:object="${helperForm}">

      First Name
      <input type="text" class="form-control" id="inputName" placeholder="First Name" th:field="*{firstName}" th:value="*{firstName}">

      Last Name
      <input type="text" class="form-control" id="inputKana" placeholder="Last Name" th:field="*{lastName}" th:value="*{lastName}">

      Working day 1
      <select class="working-day-body form-control selectpicker" data-style="btn" id="workingDay1" name="workingDay1">
        <option value="7">Sun</option>
        <option value="1">Mon</option>
        <option value="2">Tue</option>
        <option value="3">Wed</option>
        <option value="4">Thu</option>
        <option value="5">Fri</option>
        <option value="6">Sat</option>
      </select>

      Working time 1
      <input type="time" class="working-time-from form-control d-inline" id="timeFrom1" name="timeFrom1" value="(object value)">~
      <input type="time" class="working-time-to form-control d-inline" id="timeTo1" name="timeTo1" value="(object value)">

      All day
      <input id="chkbox03" name="chkbox01" type="checkbox" class="d-block is-all-day" style="margin:1rem .125rem;">

      Actions

        <button type="button" rel="tooltip" class="btn btn-small btn-success btn-add-line">
          add
        </button>
        <button type="button" rel="tooltip" class="btn btn-small btn-danger btn-delete-line">
          delete
        </button>

      Working day 2
      <select class="working-day-body form-control selectpicker" data-style="btn" id="workingDay2" name="workingDay2">
        <option value="7">Sun</option>
        <option value="1">Mon</option>
        <option value="2">Tue</option>
        <option value="3">Wed</option>
        <option value="4">Thu</option>
        <option value="5">Fri</option>
        <option value="6">Sat</option>
      </select>

      Working time 2
      <input type="time" class="working-time-from form-control d-inline" id="timeFrom2" name="timeFrom2" value="(object value)">~
      <input type="time" class="working-time-to form-control d-inline" id="timeTo2" name="timeTo2" value="(object value)">

      All day
      <input id="chkbox03" name="chkbox01" type="checkbox" class="d-block is-all-day" style="margin:1rem .125rem;">

      Actions

        <button type="button" rel="tooltip" class="btn btn-small btn-success btn-add-line">
          add
        </button>
        <button type="button" rel="tooltip" class="btn btn-small btn-danger btn-delete-line">
          delete
        </button>

      Working day 3
      <select class="working-day-body form-control selectpicker" data-style="btn" id="workingDay3" name="workingDay3">
        <option value="7">Sun</option>
        <option value="1">Mon</option>
        <option value="2">Tue</option>
        <option value="3">Wed</option>
        <option value="4">Thu</option>
        <option value="5">Fri</option>
        <option value="6">Sat</option>
      </select>

      Working time 3
      <input type="time" class="working-time-from form-control d-inline" id="timeFrom3" name="timeFrom3" value="(object value)">~
      <input type="time" class="working-time-to form-control d-inline" id="timeTo3" name="timeTo3" value="(object value)">

      All day
      <input id="chkbox03" name="chkbox01" type="checkbox" class="d-block is-all-day" style="margin:1rem .125rem;">

      Actions

        <button type="button" rel="tooltip" class="btn btn-small btn-success btn-add-line">
          add
        </button>
        <button type="button" rel="tooltip" class="btn btn-small btn-danger btn-delete-line">
          delete
        </button>

A: I succeeded in gaining the output what I wanted. I changed the template as below.
th:for
replacing #ids.next('*') with ${'*' + i}".
th:field and th:value
replacing #ids.next('*') with *{__${'*' + i}__}>.