text:
Q: Using xpath to extract a list of values Is there a way that I can extract data so it will be output as follows?
Color, Cognac, Shoe Size, 12, 10994
Color, Cognac, Shoe Size, 13, 10995

The values inside any tags can be dynamic, so selectors must use tag names.
There will be a dynamic number of SKUs.
I'm able to extract individual values e.g
//SKUs/Attributes/name/text() .. Color
//SKUs/Attributes/Values/values/text() .. Cognac

But the dynamic nature of the number of SKUs+Attributes is challenging.
XML ..
<?xml version="1.0" encoding="UTF-8"?>

<root>
  <SKUs>
    <Attributes>
      <Values>
        <values>Cognac</values>
      </Values>
      <name>Color</name>
    </Attributes>
    <Attributes>
      <Values>
        <values>12</values>
      </Values>
      <name>Shoe Size</name>
    </Attributes>
    <SKUUniqueID>10994</SKUUniqueID>
  </SKUs>
  <SKUs>
    <Attributes>
      <Values>
        <values>Cognac</values>
      </Values>
      <name>Color</name>
    </Attributes>
    <Attributes>
      <Values>
        <values>13</values>
      </Values>
      <name>Shoe Size</name>
    </Attributes>
    <SKUUniqueID>10995</SKUUniqueID>
  </SKUs>
</root>

A: This is how you could do using java.
you need to count the SKU's first and iterate on them
import java.io.FileInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class XPathExample {

    public static void main(String[] args) throws Exception {
        /*
         * disclaimer - code from http://viralpatel.net/blogs/java-xml-xpath-tutorial-parse-xml/
         */
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document xmlDocument = builder.parse(new FileInputStream(
                "//path//to//sample.xml"));
        XPath xPath =  XPathFactory.newInstance().newXPath();

        NodeList skus = (NodeList) xPath.compile("//SKUs").evaluate(xmlDocument, XPathConstants.NODESET);
        for(int i=1;i<skus.getLength()+1;i++) {
            String t1 = xPath.compile("//SKUs["+i+"]/Attributes[1]/name[1]").evaluate(xmlDocument);
            String t2 = xPath.compile("//SKUs["+i+"]/Attributes[1]/Values/identifier[1]").evaluate(xmlDocument);
            String t3 = xPath.compile("//SKUs["+i+"]/Attributes[2]/name[1]").evaluate(xmlDocument);
            String t4 = xPath.compile("//SKUs["+i+"]/Attributes[2]/Values/identifier[1]").evaluate(xmlDocument);
            String id = xPath.compile("//SKUs["+i+"]/SKUUniqueID").evaluate(xmlDocument);
            System.out.println(t1+","+t2+","+t3+","+t4+","+id);
        }
    }
}

also notice that it's not clear in your xml where the values come from because they may come from different places.


text:
Q: JavaScript: To the other page I made this PHP chatbox which supports some JavaScript code.
I have these 'images' which if you click them make special codes inside the textfield. e.g:

redpajama_set_name: RedPajamaStackExchange


text:
Q: JScript confirm infinite loop? var setOfCats = {}; //an object
while (r = true) //testing to see if r is true
{
  var i = 0;
  setOfCats.i = prompt ("What's your cat's name?", ""); //index object elements
  alert ("Congratulations! Your cat has been added to the directory.");
  var r = confirm ("Would you like to add another cat?"); //if r is true, then the loop should continue. if false, the loop should end.
  i++
}

However, the loop does not end. I've been pondering this problem, with futile attempts, for the last 30 minutes. Any ideas?

A: Your comment is incorrect.
r = true doesn't test whether r is true; it assigns r to become true.
You need to compare the variable using the === operator.
Or you can just write while(r), since r itself is already true.

A: while (r = true)

You're setting r to true each loop iteration.  You want while (r == true), or just while (r).

A: For clarity, r and setOfCats should be set outside the while declaration:
var setOfCats = [];
var r = true;

while (r) {
    setOfCats.push( prompt ("What's your cat's name?", "") );
    alert ("Congratulations! Your cat has been added to the directory.");
    r = confirm ("Would you like to add another cat?");
}

A: You are re-assigning the value of r to true upon each iteration of the while expression.  Therefore, it will always override the value.
You should do the while test with:
while(r === true)

or more idiomatic:
while(r)

This should work:
var setOfCats = {}; //an object
var r = true;
while(r) //testing to see if r is true
{
    var i = 0;
    setOfCats.i = prompt ("What's your cat's name?", ""); //index object elements
    alert ("Congratulations! Your cat has been added to the directory.");
    r = confirm ("Would you like to add another cat?"); //if r is true, then the loop should continue. if false, the loop should end.
    i++
}


text:
Q: Include a TeX file in a section I want to include a document in one of my section. For example,
\section{Introduction}
We are blablabla.....

\section{Our Previous Document: Document 1}
\include{Document1.tex}

Unfortunately, when I tried to build it, I couldn't see the document (document1) in my section. Can anyone help me?


text:
Q: Can SQL Server index a text string by delimiter? I need to store content keyed by strings, so a database table of key/value pairs, essentially. The keys, however, will be of a hierarchical format, like this:
foo.bar.baz

They'll have multiple categories, delimited by dots.  The above value is in a category called "baz" which is in a parent category called "bar" which is in a parent category called "foo."
How can I index this in such a way that it's rapidly searchable for different permutations of the key/dot combo? For example, I want to be able to very quick find everything that starts
foo

Or
foo.bar

Yes, I could do a LIKE query, but I never need find anything like:
fo

So that seems like a waste to me.
Is there any way that SQL would index all permutation of a string delimited by the dots?  So, in the above case we have:
foo
foo.bar
foo.bar.baz

Is there any type of index that would facilitate searching like that?
Edit
I will never need to search backwards or from the middle.  My searches will always begin from the front of the string:
foo.bar

Never:
bar.baz

A: SQL Server can't really index substrings, no. If you only ever want to search on the first string, this will work fine, and will perform an index seek (depending on other query semantics of course):
WHERE col LIKE 'foo.%';
-- or
WHERE col LIKE 'foo.bar.%';

However when you start needing to search for bar or baz following any leading string, you will need to search on the substring:
WHERE col LIKE '%.bar.%';
-- or
WHERE PATINDEX('%.bar.%', col) > 0;

This won't work well with regular B-tree indexes, and I don't think Full-Text Search will be much help either, because of the special characters (periods) - but you should try it out if this is a requirement.
In general, storing data this way smells wrong to me. Seems to me that you should either have separate columns instead of jamming all the data into one column, or using a more relational EAV design.

A: Its appears to be a work for CTE!
create TableA(
id int identity,
parentid int null,
name varchar(50)
)

for a (fixed) two level its easy
select t2.name, t1.name
from tableA t1
join tableA t2 on t2.id = t1.parentid
where t2.name = 'father'

To find that kind of hierarchical values for a most general case you ill need some kind of recursion in self-join table by using a CTE.
http://msdn.microsoft.com/pt-br/library/ms175972.aspx


text:
Q: Android .properties file with variable holding different values based on the current build variant I have a .property file which at the moment is like this:
com.myapp.token = myGenericString
What I would like to have is to have different values for different build variants. Something like:
if (BuildConfig == Release) {
    com.myapp.token = myReleaseString
} else {
    com.myapp.token = myOtherString
}

I'm new to Android so I'm not even sure it's possible.
Any suggestions? Thanks!

A: .properties do not support that, but you can do this with string resources, for example:
app/src/main/res/values/strings.xml and app/src/debug/res/values/strings.xml
one does not even have to differ in code then, the resource location is internally being changed.


text:
Q: Flutter - Dialog start new Activity I am developing an app that is counting points, after the teams have been created. After the teams are created, an AlertDialog pops up and displays the names. Then it should be possible to click on a button to open a new activity. That activity should not be connected to the previous activity. Does anybody has an idea, how this could be done?
Here is the code-snippet of the dialog activity:
import 'dart:math';
import 'package:flutter/material.dart';

import 'punktezaehler.dart';

class Team_Dialog extends StatefulWidget{

  final List<String> team_namen;

  Team_Dialog(this.team_namen);

  @override
  State<StatefulWidget> createState() => new _TeamDialogState(team_namen);

}

class _TeamDialogState extends State<Team_Dialog>{

  final List<String> team_namen;
  _TeamDialogState(this.team_namen);

  @override
  Widget build(BuildContext context) {
    return new AlertDialog(
      content: new SingleChildScrollView(
        child: new ListBody(
            children: List.generate(1, (index){
              return Column(
                children: <Widget>[
                  new Row(
                    children: <Widget>[
                      Text("Team 1: ", style: TextStyle(fontFamily: "Roboto")),
                      Text(team_namen[0] + " und " + team_namen[1])
                    ],
                  ),
                  new Row(
                    children: <Widget>[
                      Text("Team 2: "),
                      Text(team_namen[2] + " und " + team_namen[3])
                    ],
                  )
                ],
              );
            })
        ),
      ),
      actions: <Widget>[
        new FlatButton(
            color: Colors.red,
            splashColor: Colors.red[900],
            onPressed: (){
              Navigator.of(context).pop();
            },
            child: new Text("Abort", style: TextStyle(color: Colors.white),)
        ),
        new IconButton(
            icon: Icon(Icons.shuffle),
            onPressed: (){
              shuffle(team_namen);
              setState(() {
              });
            }
        ),
        new FlatButton(
            color: Colors.green,
            splashColor: Colors.green[800],
            onPressed: () => , //After click it should start new Activity
            child: new Text("Start Game", style: TextStyle(color:  Colors.white))
        )
      ],
    );
  }

  List shuffle(List items) {
    var random = new Random();

    for (var i = items.length - 1; i > 0; i--) {

      var n = random.nextInt(i + 1);

      var temp = items[i];
      items[i] = items[n];
      items[n] = temp;
    }

    return items;
  }

}

It would be awesome if someone has an idea :D

A: Actually when you are talking about Flutter think about pages, not activities.  It should be something like :
Navigator.push(context,
   MaterialPageRoute(builder: (context) => SecondScreen()),);

SecondScreen is another widget with its own  Widget build(BuildContext context) method where you will declare what to have on this page.
In case you want to return back, you can do it with:
 Navigator.pop(context);

Source documentation
You can also use named routes for navigation. Example:
MaterialApp(
  // Start the app with the "/" named route. In our case, the app will start
  // on the FirstScreen Widget
  initialRoute: '/',
  routes: {
    // When we navigate to the "/" route, build the FirstScreen Widget
    '/': (context) => FirstScreen(),
    // When we navigate to the "/second" route, build the SecondScreen Widget
    '/second': (context) => SecondScreen(),
  },
);

And something like:
Navigator.pushNamed(context, '/second');

Documentation

A: It's not a good practice to use Navigator.push() or Navigator.pushNamed() and then remove the back button. Because the page that you are leaving from will remain in the pages stack.
What you actually should use is Navigator.pushReplacement() if you don't want the user to be able to go back to the previous page.
And if you are doing it from a dialog, you should pop the dialog first and then push the next page.


text:
Q: How can one IIS6 .NET app appear as subsite of another? SiteA.com and siteB.com are .NET 2.0 apps on IIS6.  SiteA uses SSL.
Can I set things up so siteA.com/train gets people to siteB.com?
Are there multiple ways to do this?  How would a good way be configured?

A: Go to MyComputer, right+mouse+click and chose Manage.  Go to IIS/Websites and open up your sitename.com website.. navigate to the directory sitename.com/train.  right+mouse+click on the train folder and chose "properties". Under the "directory" property click "create".  I think that's what you're looking for.

A: You can't have a subdirectory of a site point to the root, and you can't have two site instances with the same domain name- the DNS record for www.sitename.com points to exactly one IP address.  I think you'd be better off with something like http://train.sitename.com.

A: Actually you can have two site instances with the same domain, one could work with www.domain.com and the other to only work on domain.com. DNS can distinguish between the two.


text:
Q: Compute the pdf $p(y) = \int_{CP^{N-1}} \delta \left( \frac{1-\bar \xi_{N-1} \xi_{N-1}}{1+ \xi^\dagger \xi} - y\right)d\mu_{CP^{N-1}} (\xi,\bar\xi)$ I am trying to determine the pdf of $Y = \langle{\psi}|Z^{\otimes n}|\psi\rangle$ when $|\psi\rangle$ is sampled randomly wrt the Haar measure. Let $\xi = [\xi_1, \dots,\xi_{N-1}]^T \in \mathbb{C}^{N-1}, (N = 2^n)$ and represent
$$|\psi\rangle = \frac{[1, \xi_1, \dots, \xi_{N-1}]^T}{1+\xi^\dagger \xi}$$
with the Fubini Study measure
$$ d\mu_{CP^{N-1}} (\xi,\bar\xi) = \frac{(N-1)!}{\pi^{N-1}} \frac{\prod_{k=1}^{N-1} d\xi_k d\bar\xi_k}{(1+\xi^\dagger \xi)^N}$$
The pdf is $$p(y) = \int_{CP^{N-1}} \delta \left( \frac{1-\bar \xi_{N-1} \xi_{N-1}}{1+ \xi^\dagger \xi} - y\right)d\mu_{CP^{N-1}} (\xi,\bar\xi)$$
Is there any elementary way to evaluate the integral?


text:
Q: serviceWorker is a unresovled variable in Intellij when i try to write my service worker i get the error  unresolved variable
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./service-worker.js').then(function
(registration) {
    console.log("SW reg", registration);

}).catch(function (err) {
    console.log("SW failed", err);

})

}

how do I fix it ?

A: Please try 2017.3 EAP - it's not an issue there, as it bundles Typescript stubs for most popular JavaScript APIs:


text:
Q: How to sort a mock object in python? I am mocking the path attribute of an object that is used for sorting. However, trying to sort objects fails:
    def __lt__(self, other: RealObject) -> bool:
        """Sort based on path."""
>       return self.path < other.path
E       TypeError: '<' not supported between instances of 'MagicMock' and 'MagicMock'

So I tried extending MagicMock, but it still fails:
class MockPath(MagicMock):
    def __init__(self, name: Optional[str] = None, *args, **kw) -> None:
        super().__init__(*args, **kw)
        self.name = name or str(random.randint(1, 10000))

    def __lt__(self, other) -> bool:
        return self.name < other.name

    def __lt__(self, other: RealObject) -> bool:
        """Sort based on path."""
>       return self.path < other.path
E       TypeError: '<' not supported between instances of 'MockPath' and 'MockPath'

How can I allow the mocked objects to sort? It's not important what they sort to, I just don't want it to fail.


text:
Q: Tagged structures casting rules I was playing around with toy tuple implementations and eventually stuck with how get function works.
Consider this simple example
#include <iostream>
#include <utility>

template <size_t Tag, typename ValueType>
struct TagedValue { ValueType value; };

struct Test : TagedValue<0, int>, TagedValue<1, std::string>, TagedValue<2, double> {};

template <size_t Idx, typename T>
auto& get(Test& test) {
    ((TagedValue<Idx, T>&)(test)).value;
}

template <size_t Idx, typename T>
auto& get_impl(TagedValue<Idx, T>& tagged_value) {
    return tagged_value.value;
}

template <size_t Idx>
auto& get_2(Test& test) {
    return get_impl<Idx>(test);
}

int main()
{
    Test test;
    get_2<0>(test);
    get<0>(test);
}

I get this error:
<source>: In function 'int main()':
<source>:29:16: error: no matching function for call to 'get<0>(Test&)'
   29 |     get<0>(test);
      |                ^
<source>:10:7: note: candidate: 'template<long unsigned int Idx, class T> auto& get(Test&)'
   10 | auto& get(Test& test) {
      |       ^~~
<source>:10:7: note:   template argument deduction/substitution failed:
<source>:29:16: note:   couldn't deduce template parameter 'T'
   29 |     get<0>(test);
      |                ^

I do have couple of questions:

*

*Basically why get_2 works and get doesn't compile. To me it looks like get_2 does exactly what I'm trying to do inside get

*Does deducing T for get_2 take O(1) time, if yes how is it possible? Does compiler store some kind of map internally?

A: When you call a function template then all template arguments must either be specified explicitly or be deduced from the function arguments. When you call
get<0>(test);

Then Idx is 0, but there is no way for the compiler to know what T is supposed to be. The parameter is just Test, and T cannot be deduced from that.


text:
Q: TDD with C#, issue with writing tests with mock I'm moving first steps in TDD (I'm studying "Professional Test-Driven Development with C#" by Bender and McWherter).
I'm trying to write my first application with TDD: I assume to have a DataService class for manage persistence. I wrote two tests that pass, but I think I've not got the point.
This is my first test, I assume that I can instantiate a Transaction, whatever it means in the DataService
public void Begin_a_transaction_should_returns_true_when_is_all_ok()
{
    Mock<IDataLayer> dataLayer = new Mock<IDataLayer>();
    DataService sut = new DataService(dataLayer.Object);

    bool expected = true;
    dataLayer.Setup(dl => dl.BeginTransaction()).Returns(expected);

    bool actual = sut.BeginTransaction();

    Assert.AreEqual(expected, actual);
}

According to TDD now I wrote the classes, no issues with this
public class DataService
{
    private IDataLayer _dataLayer;

    public DataService(IDataLayer dataLayer)
    {
        this._dataLayer = dataLayer;
    }

    public bool BeginTransaction()
    {
        return _dataLayer.BeginTransaction();
    }
}

Now I want to write second test: BeginTransaction should fail if transaction already exists, and I demand this to IDataLayer
[Test]
public void Begin_a_transaction_should_throws_exception_if_transaction_already_exists()
{
    Mock<IDataLayer> dataLayer = new Mock<IDataLayer>();
    DataService sut = new DataService(dataLayer.Object);

    dataLayer.Setup(dl => dl.BeginTransaction()).Throws(new Exception("Transaction already exists"));

    Assert.Throws<Exception>(() => sut.BeginTransaction());
}

And now the point: tests pass without writing any line of code, because I've mocked the BeginTransaction to throw an Exception.
That can be OK because I'll test it in the implementation of IDataLayer tests, but if I mock all, DataService tests are useful?

A: I would say this happens because you're testing the behavior of a class that does not have any behavior other than wrapping the IDataLayer - anything that happens in the wrapped class is simply passed on to the outside. The same thing that you are describing happens for the case when the method returns true although it's less obvious.
To make your example more meaningful you could add some behavior that is dependent on the result of IDataLayer's BeginTransaction(), like;
Implementation
public class DataService
{
    public DataService(IDataLayer dataLayer, IBookRepository bookRepository)
    {
        _dataLayer = dataLayer;
        _bookRepository = bookRepository;
    }

    public void StoreBookInfo(string data)
    {
        if (_dataLayer.BeginTransaction())
            _bookRepository.StoreBookInfo(data);
        else
            throw new SomeException();
    }
}

Test
[Test]
public void Should_store_book_info_if_transaction_can_be_started()
{
    Mock<IDataLayer> dataLayer = new Mock<IDataLayer>();
    Mock<IBookRepository> bookRepository = new Mock<IBookRepository>();

    dataLayer.Setup(dl => dl.BeginTransaction()).Returns(true);
    bookRepository.Setup(x => x.StoreBookInfo(It.IsAny<string>()));

    DataService sut = new DataService(dataLayer.Object, bookRepository.Object);

    sut.StoreBookInfo("SomeValue");

    bookRepository.Verify(x => x.StoreBookInfo(It.IsAny<string>()));
}

[Test]
public void Should_throw_exception_if_transaction_cannot_be_started()
{
    Mock<IDataLayer> dataLayer = new Mock<IDataLayer>();
    Mock<IBookRepository> bookRepository = new Mock<IBookRepository>();

    dataLayer.Setup(dl => dl.BeginTransaction()).Returns(false);

    DataService sut = new DataService(dataLayer.Object, bookRepository.Object);

    Assert.Throws<SomeException>(() => sut.StoreBookInfo("someValue"));
}

A: Exposing internals just for the sake of tests generally is not good practice. In your case _transaction is made protected so that decorator could do changes to it's internal state. I'd better suggest to mimic behavior of a client.
    [Test]
    public void Begin_a_transaction_should_throws_exception_if_transaction_already_exists()
    {
        Mock<IDataLayer> dataLayer = new Mock<IDataLayer>();
        DataService sut = new DataService(dataLayer.Object);

        sut.BeginTransaction();

        Assert.Throws<Exception>(() => sut.BeginTransaction());
    }

A: Well, I reviewed my code in this way.
public class DataService
    {
        private IDataLayer _dataLayer;
        protected object _transaction;

        public DataService(IDataLayer dataLayer)
        {
            this._dataLayer = dataLayer;
        }

        public bool BeginTransaction()
        {
            if (_transaction != null)
                throw new Exception("Transaction already exists");

            _transaction = _dataLayer.BeginTransaction();

            return true;
        }
    }

Than I use a decorator pattern in test class
internal class DataServiceDecorator : DataService
        {
            public DataServiceDecorator(IDataLayer dataLayer) : base(dataLayer)
            { }

            public void InjectTransactionObject(object transaction)
            {
                this._transaction = transaction;
            }
        }

So I'm able to write this test
[Test]
        public void Begin_a_transaction_should_throws_exception_if_transaction_already_exists()
        {
            Mock<IDataLayer> dataLayer = new Mock<IDataLayer>();
            DataServiceDecorator sut = new DataServiceDecorator(dataLayer.Object);

            sut.InjectTransactionObject(new object());

            Assert.Throws<Exception>(() => sut.BeginTransaction());
        }

What do you think about this?


text:
Q: The datagrid not showing the child element of xml file I am doing task of loading online xml file into datagrid, I done it but in xml file there is child nodes such as,
        <quantity>-54</quantity>
        <weight>1.000</weight>
        <categories>
            <category>Cradles & Holders</category>
            <category>iPhone & iPod Accessories</category>
            <category>FM Transmitters</category>
        </categories>

The datagrid showing the <quantity>,<weight> as a column and its data, but truncate  node and also not showing the data also.
My question is that how I add them or manage the child node to show in datagrid.


text:
Q: datetimepicker error submitting form I'm trying to use a jquery datetimepicker.
And I have some trouble when I submit the form:

This value is not valid. : Unable to reverse value for property path "debut": Date parsing failed: U_PARSE_ERROR

Here is my form:
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('debut', 'datetime', array(
            'widget' => 'single_text',
            'label' => 'Debut',
            'html5' => false,
            'format' => 'dd/MM/yyyy H:m'
        ))
  //...

And the javascript is:
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.4/build/jquery.datetimepicker.full.min.js"></script>

<script>

    $(document).ready(function () {
        $( '#mybundle_evenement_debut' ).datetimepicker({
            startDate: new Date(),
            format: 'd/m/y H:i',
            autoclose: true,

        });
    });
</script>

How would you fix this?


text:
Q: Handling events using ResourceChangeListener AEM 6.3 Can someone please help me in understanding how to implement a ResourceChangeListener and handle events using osgi R6 annotations?
I saw a similar post with no answer.AEM 6.3 - Creating Event handler using OSGi R6 annotations

A: The code snippet below registers a ResourceChangeListener with OSGI R6 annotations. The comments inline have the explanation.
import java.util.List;
import org.apache.sling.api.resource.observation.ResourceChange;
import org.apache.sling.api.resource.observation.ResourceChangeListener;
import org.osgi.service.component.annotations.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(
    service = ResourceChangeListener.class,
    property = {
        // filter the notifications by path in the repo. Can be array and supports globs
        ResourceChangeListener.PATHS+"="+"/content",
        //The type of change you want to listen to.
        //Possible values at https://sling.apache.org/apidocs/sling9/org/apache/sling/api/resource/observation/ResourceChange.ChangeType.html.
        ResourceChangeListener.CHANGES+"="+"ADDED",
        ResourceChangeListener.CHANGES+"="+"REMOVED",
        ResourceChangeListener.CHANGES+"="+"CHANGED"

        //PS: If you want to declare multiple values for a prop, you repeat it in OSGI R6 annotations.
        //https://stackoverflow.com/questions/41243873/osgi-r6-service-component-annotations-property-list#answer-41248826
    }
)
public class SampleResourceChangeListener implements ResourceChangeListener{ // Use ExternalResourceChangeListener to listen for changes that happen in a different node
  public static final Logger LOGGER = LoggerFactory.getLogger(SampleResourceChangeListener.class);

  //This method will be called with paths and types of change that occurred
  //The task in this should be fast. In case it takes more time, trigger a sling job from here.
  //The listener can be blacklisted if it's slow [it does for event handler, should be same for ResourceListener IMHO]
  @Override
  public void onChange(List<ResourceChange> list) {
    list.forEach((change) -> {
      LOGGER.info(change.getPath());
      LOGGER.info(change.getType().toString());
      //the methods to identify the property that changed are deprecated.
    });
  }
}

Some reference implementations within Sling

*

*https://github.com/apache/sling-org-apache-sling-discovery-commons/blob/4f7d7ca3224239d52798cc8418ec8283f5eddc9e/src/main/java/org/apache/sling/discovery/commons/providers/spi/base/IdMapService.java

*https://github.com/apache/sling-org-apache-sling-scripting-java/blob/89c28859a7df17a40eaaf2c26ee2433c98830204/src/main/java/org/apache/sling/scripting/java/impl/JavaScriptEngineFactory.java


text:
Q: Using Scala Akka framework for blocking CLI calls I'm relatively new to Akka & Scala, but I would like to use Akka as a generic framework to pull together information from various web tools, and cli commands.
I understand the general principal that in an Actor model, it is highly desirable not to have the actors block.  And in the case of the http requests, there are async http clients (such as Spray) that means that I can handle the requests asynchronously within the Actor framework.
However, I'm unsure what is the best approach when combining actors with existing blocking API calls such as the scala ProcessBuilder/ProcessIO libraries.  In terms of issuing these CLI commands I expect a relatively small amount of concurrency, e.g. perhaps executing a max of 10 concurrent CLI invocations on a 12 core machine.
Is it better to have a single actor managing these CLI commands, farming the actual work off to Futures that are created as needed?  Or would it be cleaner just to maintain a set of separate actors backed by a PinnedDispatcher?  Or something else?

A: From the Akka documentation ( http://doc.akka.io/docs/akka/snapshot/general/actor-systems.html#Blocking_Needs_Careful_Management ):
"
Blocking Needs Careful Management
In some cases it is unavoidable to do blocking operations, i.e. to put a thread to sleep for an indeterminate time, waiting for an external event to occur. Examples are legacy RDBMS drivers or messaging APIs, and the underlying reason in typically that (network) I/O occurs under the covers. When facing this, you may be tempted to just wrap the blocking call inside a Future and work with that instead, but this strategy is too simple: you are quite likely to find bottle-necks or run out of memory or threads when the application runs under increased load.
The non-exhaustive list of adequate solutions to the "blocking problem" includes the following suggestions:

*

*Do the blocking call within an actor (or a set of actors managed by a router [Java, Scala]), making sure to configure a thread pool which is either dedicated for this purpose or sufficiently sized.

*Do the blocking call within a Future, ensuring an upper bound on the number of such calls at any point in time (submitting an unbounded number of tasks of this nature will exhaust your memory or thread limits).

*Do the blocking call within a Future, providing a thread pool with an upper limit on the number of threads which is appropriate for the hardware on which the application runs.
Dedicate a single thread to manage a set of blocking resources (e.g. a NIO selector driving multiple channels) and dispatch events as they occur as actor messages.

The first possibility is especially well-suited for resources which are single-threaded in nature, like database handles which traditionally can only execute one outstanding query at a time and use internal synchronization to ensure this. A common pattern is to create a router for N actors, each of which wraps a single DB connection and handles queries as sent to the router. The number N must then be tuned for maximum throughput, which will vary depending on which DBMS is deployed on what hardware."


text:
Q: Backbone: properties in ECMAScript 6 I'm searching for a good ECMAScript 6 equivalent of the following Backbone code:
var MyModel = Backbone.Model.extend({});

var MyCollection = Backbone.Collection.extend({
    model: MyModel
});

This pattern is widely used in Backbone models, views and collections. Can I do better than the code below (e.g. by creating a method named "model")?
export class MyModel extends Backbone.Model {}

export class MyCollection extends Backbone.Collection {
    constructor() {
        super({model: MyModel});
    }
}

A: I'd use a getter:
export class MyModel extends Backbone.Model {}

export class MyCollection extends Backbone.Collection {
  get model() {
    return MyModel;
  }
}

A: Of course, just don't use the class keyword:
var MyModel = Backbone.Model.extend({});

var MyCollection = Backbone.Collection.extend({
    model: MyModel
});

This code is actually more reusable than the ECMAScript 6 equivalent you wrote. The ECMAScript 6 is actually worse than the original one.
You have to understand that in JavaScript objects can exist without classes and that feature is extremely important.
Here is what Douglas Crockford wrote on prototypal inheritance back in 2008: http://javascript.crockford.com/prototypal.html


text:
Q: How to run a piece of javascript when you select a dropdown option? I have a select with loads of options. (Code below shortened for sake of example).
I want it to set the value of the input textfield "hoh" to "10" when you click/select all dropdown options, except one, that should set it to 50.
I imagined something like this would work, but its not. What am I doing wrong here?
<select>
    <option onselect="document.getElementById('hoh').value = '50'">Hey</option>
    <option onselect="document.getElementById('hoh').value = '10'">Ho</option>
    <option onselect="document.getElementById('hoh').value = '10'">Lo</option>
    ....
</select>

<input type="text" id="hoh" value="10">

A: Something like this should work:
<script>
function myFunc(val) {
    if (val == '50') {
        document.getElementById('hoh').value = val;
    } else {
        document.getElementById('hoh').value = '10';
    }
}
</script>

<select onchange="myFunc(this.value)">
    <option value="1">one</option>
    <option value="2">two</option>
    <option value="50">fifty</option>
</select>

http://jsfiddle.net/isherwood/LH57d/3

A: The onselect event refers to selecting (or highlighting) text. To trigger an action when a dropbox selection changes, use the onchange event trigger for the <select> element.
E.g. Since you didn't already set the value attribute of your option tags.
<select id="myselect" onchange="myFunction()">
    <option value="50">Hey</option>
    <option value="10">Ho</option>
    <option value="10">Lo</option>
    ....
</select>

and somewhere inside of a <script> tag (presumably in your HTML header) you define your javascript function.
<script type="text/javascript>

function myFunction() {
   var dropbox = document.getElementById('myselect');
   document.getElementById('hoh').value = dropbox[dropbox.selectedIndex].value;
}

</script>

I'm not sure it's wise to repeat the same value among different options in a droplist, but you could expand on this to implement the result other ways, such as if the sole option which will have value 50 is in a certain position, you could compare the selectedIndex to that position.

A: Try this code
var inp = document.getElementById('hoh');
sel.onchange = function(){
    var v = this.value;
    if( v !== '50'){
         v = '10';
    }
    inp.value = v;
};

A: you could add an onchange event trigger to the select, and use the value of an option to show in the textbox
see http://jsfiddle.net/Icepickle/5g5pg/ here
<select onchange="setValue(this, 'hoh')">
    <option>-- select --</option>
    <option value="10">Test</option>
    <option value="50">Test 2</option>
</select>
<input type="text" id="hoh" />

with function setValue as
function setValue(source, target) {
    var tg = document.getElementById(target);
    if (!tg) {
        alert('No target element found');
        return;
    }
    if (source.selectedIndex <= 0) {
        tg.value = '';
        return;
    }
    var opt = source.options[source.selectedIndex];
    tg.value = opt.value;
}


text:
Q: Angular 5 accessing the fields that is enclosing the Observable Hi Angular and Typescript gurus,
I have been exploring how to make an Observable to be Asynchronous.
Somebody did advice to try this link:
https://medium.com/@benlesh/rxjs-observable-interop-with-promises-and-async-await-bebb05306875
And I am facing 2 problems with this example:
- How to access the fields of the class enclosing the Observable
- How do I do .next(), .error() or .complete for the observer
Here is a sample/pseudo class
import { Observable, Subscription } from 'rxjs/Rx';

export class TestComponent {

    private isRunning: boolean = false;

    construct() {
       this.createObservable()
         .subscribe(
            data => {
               console.log("observable sent: " + data);
            }
            ,error => {
               console.log("observable had an error:");
               console.log(error);
            }
         );

       console.log("If the observable above is asynchronous this will be executed before the observable ends...");

       //for some random event here terminate the observable
       while(Math.floor(Math.random() * 10000) != 6073){ }
       this.isRunning = false;
    }

    private createObservable():Observable<string> {
        this.isRunning = true;
        var obs: Observable<string> = Observable.defer(async function() {
           while(this.isRunning) { //accessing this.isRunning here is an error
             console.log("Observable is still running");
             setTimeout(() => { }, 2000);
             //main logic of the observable goes here...
           }

           //for some event I want to do a
           //observer.next("test string");

           //if an error occurs I want to do a
           //observer.error()

           //after some time... I will need to a
           //observer.complete()
        });

        return obs;
     }

}

Follow-up question, is this a proper way to make an asynchronous observable manually?
Or probably, do I have the right mindset that every observable is asynchronous.
Because when I was creating the same class here but the Observable object/class is based on "import { Observable } from '../../node_modules/rxjs';" it wasn't running asynchronously.

By the way, my example above is based on This one is based on import { Observable } from 'rxjs/Rx';

Your expertise is very much appreciated.

many thanks

Artanis.


text:
Q: SSRS report: unrelated list of values appears when empty date/time parameter is clicked I have SSRS reports with date/time parameters which work fine.
Strange thing happens when I click date/time parameter's box while it's empty: dropdown list of unrelated text lines appears below the clicked box. Here's how it looks:

It appears in all reports with date/time parameters. In each report the values that appear are different.
In the Development Studio while previewing a report it doesn't happen at all.
The parameters are defined as usual in very simple manner.
Google search didn't help. :(
Can anyone give me a hint, please, what is it and how to get rid of it? SSRS version: 14.0.1016.232, MVS version 2015.

A: I looks to me like it could be the contents of your browsers 'type-ahead' or 'auto-complete' history.
The field name probably has the same name as another field that you've input data into, in the past.
Try using another browser and if that's OK trying clearing your browser history. If you are using Chrome it's part of the "Autofill" data.
You could follow this guide to removing specific entries if that's better in your scenario.
https://osxdaily.com/2018/07/20/how-delete-chrome-autofill-suggetsions


text:
Q: Change member identifier of a type during runtime in C++ Is it possible to change the name/identifier of a member of a user defined type during runtime, so that something like the following would be possible.
file.json: "{name: "Peter", nums: [10, 13, 1]}"
JSONDocument d("file.json"); // Parses JSON File
d.name.key = "other_key";
d.other_key = "Alfred";
d.writeToFile("file.json");

file.json: "{other_key: "Alfred", nums: [10, 13, 1]}"

A: No, you cannot create members at runtime in C++.


text:
Q: Laravel Event Broadcast not work with pusher I used pusher for my project. I configure broadcasting as per laravel docs. When I fired my event pusher does not work for me. But when I send data from pusher console then pusher receive this data.
I also try vinkla/pusher. Its work fine but laravel event broadcasting not work.
Please help me.
Here is my TestEvent.php code
namespace Factum\Events;

use Factum\Events\Event;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class TestEvent implements ShouldBroadcast
{
    use SerializesModels;

    public $text;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($text)
    {
        $this->text = $text;
    }

    /**
     * Get the channels the event should be broadcast on.
     *
     * @return array
     */
    public function broadcastOn()
    {
        return ['test-channel'];
    }
}

A: 1/ you should clear cache
php artisan config:cache

php artisan config:clear

php artisan route:cache

php artisan route:clear

php artisan optimize --force

2/ and try this for push a message
2.1/ include : use Pusher\Laravel\Facades\Pusher;
2.2/ inside route add :
Pusher::trigger('adevChannel', 'EventAdev', ['message' => $message]);

or
   event(EventAdev($message) );

A: I encountered a similar problem and went step by step and fixed the issues.
I will assume you are running Laravel 5.3.
Here is a step by step walkthrough that might be helpful:

*

*Check your config file. In config\broadcasting.php:
'connections' => [
   'pusher' => [
     'driver' => 'pusher',
     'key' => env('PUSHER_KEY'),
     'secret' => env('PUSHER_SECRET'),
     'app_id' => env('PUSHER_ID'),
     'options' => [
                         'cluster' => 'eu',
                         'encrypted' => true,
                      // 'host' => 'api-eu.pusher.com'
                      // 'debug' => true,
                  ],
    ],
],

*Create a route for testing in your web.php file:
Route::get('/broadcast', function() {
    event(new \Factum\Events\TestEvent('Sent from my Laravel application'));

    return 'ok';
});

*In your TestEvent.php event file you should add this method in order to specify your event name:
/**
  * The event's broadcast name.
  *
  * @return string
  */
public function broadcastAs()
{
    return 'my_event';
}

*Open your Pusher dashboard and go to debug console.
Keep the page open so you can notice if you got a successful request from your application.

*Start or restart your queue worker. This step can make or break everything. If you are using Mysql tables for queues I will assume that you already set up your "jobs" and "failed_jobs" database tables necessary for the queues.
Another important element is the worker - the queue processor.
Without an active worker running to process your queue, the jobs (TestEvent) will "remain" in the jobs table, meaning the jobs are pending and nothing will happen further until an active worker starts processing the queue.
You can start the worker like this:
www@yourmachine# PHP artisan queue:work --tries=3

*Now that you have everything in order to make a call on "http://your-app.laravel/broadcast" and check your pusher debug console for a response.
Optional step:
If something is still missing, you can debug your app interaction with Pusher like so:
In your testing route try doing this:
Route::get('/broadcast', function() {

    // New Pusher instance with our config data
    $pusher = new \Pusher(
        config('broadcasting.connections.pusher.key'),
        config('broadcasting.connections.pusher.secret'),
        config('broadcasting.connections.pusher.app_id'),
        config('broadcasting.connections.pusher.options')
    );

    // Enable pusher logging - I used an anonymous class and the Monolog
    $pusher->set_logger(new class {
           public function log($msg)
           {
                 \Log::info($msg);
           }
    });

    // Your data that you would like to send to Pusher
    $data = ['text' => 'hello world from Laravel 5.3'];

    // Sending the data to channel: "test_channel" with "my_event" event
    $pusher->trigger( 'test_channel', 'my_event', $data);

    return 'ok';
});

I hope it will work for you too!
Have a good time coding! ;)


text:
Q: Create Memory Device Context... for a bitmap, not a device (not display) I'm probably thinking about this all wrong, so please let me start by stating the goal: I want to compare two images by XORing them together, then save (not display) the result as a file. Actually, I want to then average all the bit values to get a percentage match, but that part isn't hard.
So BitBlt (remember BitBlt?) has a ROP called SRCINVERT that does exactly this. And screamingly fast. Works a treat. But... it wants a source and destination DC (Device Context) to work with... you can SelectObject a bitmap into those DC's, but you must have the DC's.
Making DC's is easy with CreateCompatibleDC(0); or even CreateDC(L"DISPLAY", NULL, NULL, NULL); but... those are based on the pixel depth, size, etc... of the current hardware display. {EDIT: Nop, CreateCompatibleDC(0); gets everything from the bitmap selected into it, I just wasn't actually using it.} And I don't care about that, I want to work with the pixel depth, etc... of the files I'm loading the bitmaps from. In fact, this is a command line program; it will never have a window. EDIT: But because the DC is for the actual screen, when using CreateDC(L"DISPLAY", NULL, NULL, NULL), I see the image on the display (overwriting the desktop) before it is saved out to a file.
Am I stuck? Do I have to find another graphics library to do my XOR function? Or is there a way to use BitBlt? More generally, is there a way to do GDI or GDIPlus type stuff with DC's that don't exist on the current system? Wouldn't that be a really useful thing to be able to do for programs that process image files without necessarily displaying the result?

A: Once you select a bitmap into a memory context, its bit depth/pixel size will be taken over by the ones from the bitmap.

A: nevermind... silly boy... I was using CreateDC(L"DISPLAY", NULL, NULL, NULL); to make the destination DC and when I tried  CreateCompatibleDC(0); I must have only changed the source DC... Oops.  CreateCompatibleDC(0); works a treat.
https://github.com/JamesNewton/WinBitBltImageCompare


text:
Q: How to call a datable in the parent form from the child form using C# Winforms? I tried to create an instance using ParentForm class or Parent class but unable to get the data table already created in the parent form. Please find the below sample of code in the parent form which I'm trying to get from my child form.
    private void ParentForm_Load(object sender, EventArgs e)
    {
        try
        {
            BLGridsToControls objBL = new BLGridsToControls();
            dgMainGrid.DataSource = objBL.GetCity();
        }
        catch
        {
            throw;
        }

Note : objBL.GetCity returns a data table

A: You can pass the dataTable to the child form by creating a constructor that accepts a DataTable as a parameter, and then calling that constructor.
E.g.
var childForm = new ChildForm(dgMainGrid.DataSource);
childForm.ShowDialog();

and in ChildForm:
DataTable myDataSource { get; set; }

ChildForm(DataTable myDataTable)
{
     // do something with myDataTable, such as put it into a property for later use,
     myDataSource = myDataTable;
}

A: Another option is to pass a reference to the parent form into the child form via the Show() command itself.  The reference can be accessed in the child form via the .Owner property; just cast it back to the parent form type.
So in the Parent form:
private void button1_Click(object sender, EventArgs e)
{
    // in the parent form, pass a reference to the Show() command:
    SomeChildForm scf = new SomeChildForm();
    scf.Show(this); // <-- pass in the parent (this) via Show()
}

Over in the Child form:
private void Foo()
{
    // in the child form, cast the .Owner property to the parent form type:
    BLGridsToControls objBL = (BLGridsToControls)this.Owner;
    dgMainGrid.DataSource = objBL.GetCity();
}


text:
Q: Apache reverse proxy couchpotato, nzbget, and sonarr, alternate http and https port I am having issues setting up a reverse proxy with ssl enable and also Apache authentication. I have att uverse and for some odd reason they have port 443 forwarded by default to the dvr box. I would like to use an alternative standard port other than 80 and also another encrypted port other than 443. I have limited knowledge when it comes to Apache. But can do all right with the right guidance. I use Ubuntu server 14.04.4. Thanks

A: There's not a second 'official' SSL port. 443 is the universal standard.
That said, you can send encrypted data from any port, so long as the application using said port, is sending encrypted data.
Try changing the reverse proxy to use a different port (one not commonly used, such as 8991) and then forward the new Port number.
Also good reference for seeing commonly used ports: https://en.m.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers
Apache reference for  SSL setup:
https://httpd.apache.org/docs/2.4/ssl/ssl_howto.html


text:
Q: Entity Framework: How to query (LINQ) for data ->child-> 4 grandchildren I have 4 classes like that:
Organization1:
    Contact 1:
        Phones:
            phone1
            phone2
        Addresses:
            address1
            address2
        Bankdata:
            bankdata1
            bankdata2
    Contact 2:
        Phones:
            phone1
            phone2
        Addresses:
            address1
            address2
        Bankdata:
            bankdata1
            bankdata2
    Contact 3:
        Phones:
            phone1
            phone2
        Addresses:
            address1
            address2
        Bankdata:
            bankdata1
            bankdata2
Organization 2:
... and so on...

In order to grab the list of Organizations with all its contacts and each contact including JUST the phone1 (where main == true), address1 and bankdata1 I have written the following inside Entity Framework a query:
...
    public class ContactManagementRepository : IContactManagementRepository
    {
        public IEnumerable<Organization> getAllOrganizations()
        {
            return _context.Organizations
                                .OrderBy(o => o.organizationName)
                                .Include(o => o.Contacts)
                                .ToList();
        }
...

But I just get ONE Organization, and no contacts.
A tried a second attempt like this:
    public class ContactManagementRepository : IContactManagementRepository
    {
        public IEnumerable<Organization> getAllOrganizations()
        {
            return _context.Organizations.ToList();
        }
...

It returns all the organizations, but not data under the tree (contact->phones, etc)
A third attempt (very bad for performance) was to get ALL the organizations and loop through using getorganizationsbyID and get the info of each one like this:
...
        public Organization GetOrganizationById(Guid Id)
        {
            return _context.Organizations
                .Include(o => o.Contacts)
                .ThenInclude(c => c.Phone.main == true)
                .Where(o => o.Id == Id)
                .FirstOrDefault();
        }
...

But it just get the organization with JUST ONE CONTACT (the first one) and not phones, address or bankdata. The method "ThenInclude" does not accept a second call. It means accept just one child under contact, but not several children.
Here are my model classes:
Organization class:
public class Organization
{
        public Organization() { }

        private Organization(DateTime dateCreated)
        {
            this.dateCreated = DateTime.Now;
            Contacts = new List<Contact>();
        }

        public Guid Id { get; set; }
        public DateTime dateCreated { get; set; }
        public string organizationName { get; set; }
        public string organizationType { get; set; }
        public string web { get; set; }

        // Contacts
        public ICollection<Contact> Contacts { get; set; }
}

Contact class:
public class Contact
{
    public Contact() { }

    private Contact(DateTime dateCreated)
    {
            this.dateCreated = DateTime.Now;
            Phones = new List<Phone>();
            Addresses = new List<Address>();
            Bankdatas = new List<Bankdata>();
    }

    public Guid Id { get; set; }
    public DateTime dateCreated { get; set; }
    public string firstName { get; set; }
    public string lastName { get; set; }
    public string email { get; set; }

    public Guid OrganizationId { get; set; }
    [ForeignKey("OrganizationId")]
    public virtual Organization Organization { get; set; }

    public virtual ICollection<Phone> Phones { get; set; }
    public virtual ICollection<Address> Addresses { get; set; }
    public virtual ICollection<Bankdata> Bankdatas { get; set; }
}

Phone class (same structure for addresses and bankdata)
public class Phone
{
        public Guid Id { get; set; }
        public DateTime dateCreated { get; set; }
        public string phone { get; set; }
        public bool main { get; set; }

        // Foreign Key for Contacts
        public Guid ContactId { get; set; }

        //Related Organization entity
        [ForeignKey("ContactId")]
        public virtual Contact Contact { get; set; }
}

Database is created with the PK and FK in correctly in place (code-first)
And now I am lost. Does anybody could help with this?
How do I query (LINQ) for organization -> child -> 4 grandchildren ?
I have read literally dozens of threads here and follow tutorials in Udemy and Pluralsight without success.

EDIT
@ Hadi Hassan
I followed your instructions, I created new classes OrganizationDTO, ContactDTO, AddressDTO, PhoneDTO and BankdataDTO.
I created the DTO for Bank, Phone and address because even if  am sure just one is main (there is a radio button at the front end) I still will need the whole list when I get the contactsdetails.html. It will allows me to make searches by country-code and so on.
I have changed, as per your advice, but it dd not even compile. I get error telling:
*DbSet<Organization>ContactManagement.Context.Organizations {get; set;}
Cannot assign method group to an implicitly-typed variable.*

I have decided to test changing the Context class like this:
DBSet. So I changes all DBset properties with the suffix DTO. Like this:
public DbSet<OrganizationDTO> OrganizationsDTO { get; set; }
public DbSet<ContactDTO> ContactsDTO { get; set; }
public DbSet<BankdataDTO> BankdatasDTO { get; set; }
public DbSet<AddressDTO> AddressesDTO { get; set; }
public DbSet<PhoneDTO> PhonesDTO { get; set; }

But the I have got copilations error everywhere.

A: Best way to get your data is by relying on the DTO
so your code will appear like this
public class OrganizationDTO
{
   public OrganizationDTO()
   {
       Contacts = new List<ContactDTO>();
   }
   public Guid Id{get;set;}
   public string Name{get; set;}
   // other needed properties goes here

   public IList<ContactDTO> Contacts{get;set;}
}
public class ContactDTO
{
   public ContactDTO
   {
       Phones = new List<PhoneDTO>();
       Addresses = new List<AddressDTO>();
       Banks = new List<BankDTO>();
   }
   public Guid Id{get;set;}
   public string FirstName{get;set;}
   public string LastName {get;set;}
   // other required properties goes here

   public IList<PhoneDTO> Phones {get;set;}
   public IList<BankDTO> Banks{get;set;}
   public IList<AddressDTO> Addresses{get;set;}
}
public class PhoneDTO
{
   public Guid Id{get;set;}
   public string Phone{get;set;}
}
public class AddressDTO
{
   public Guid Id{get;set;}
   public string Description{get;set;}
}
public class BankDTO
{
   public Guid Id{get;set;}
   public string Name{get;set;}
}

Your query then will look like
var query = _context.Organizations
                    .Select t=> new OrganizationDTO{
                       Id = t.Id,
                       Name = t.organizationName,
                       Contacts = t.Contacts.Select(c => new ContactDTO{
                          Id = c.Id,
                          FirstName = c.firstName,
                          LastName = c.lastName,
                          Phones = c.Phones.Where(p=>p.Main).Select(p=>new PhoneDTO{Id = p.Id, Phone= p.phone}),
                          Banks = c.Banks.Where(p=>p.Main).Select(p=>new BankDTO{Id = p.Id, Name= p.BankName}),
                          Addresses = c.Addressess.Where(p=>p.Main).Select(p=>new AddressDTO{Id = p.Id, Description= p.Description}),
                       })
                    }).OrderBy(t=>t.Name);

Implementing the DTO will provide many advantages for your data

*

*Avoid Circular references

*Return the required data and not all the object (Data Projection)

*Allows you to combine many objects together to appear in same result, for example, in the solution I returned object BankDTO and PhoneDTO and AddressDTO which allows your to return list of object from these entities, but if you are sure that only one phone, bank , address is main, then you can instead define these data as properties in the class ContactDTO and by this you combined 4 entities data in one result.

Your ContactDTO will become as
public class ContactDTO
{
     public Guid Id{get;set;}
     public string FirstName{get;set;}
     public string LastName{get;set;}
     public string Phone{get;set;}
     public string Bank{get;set;}
     public string Address{get;set;}
}

and your code will be like
var query = _context.Organizations
                    .Select t=> new OrganizationDTO{
                       Id = t.Id,
                       Name = t.organizationName,
                       Contacts = t.Contacts.Select(c => new ContactDTO{
                          Id = c.Id,
                          FirstName = c.firstName,
                          LastName = c.lastName,
                          Phone = c.Phones.Where(p=>p.Main).Select(p=>p.phone).FirstOrDefault(),
                          Bank = c.Banks.Where(p=>p.Main).Select(p=>p.Name).FirstOrDefault(),
                          Address = c.Addressess.Where(p=>p.Main).Select(p=>p.Discreption).FirstOrDefault(),
                       })
                    }).OrderBy(t=>t.Name);

and in case you want to get the phone as object and not list, may be you want to get the benefit of the phone Id, you can instead of IList<PhoneDTO> to define directly PhoneDTO.
Hope this will help you


text:
Q: javascript bind method parameters I saw examples of 2 types of bind calls. first kind is:
    const book = {
      title: 'Brave New World',
      author: 'Aldous Huxley',
    }

    function summary() {
      console.log(`${this.title} was written by ${this.author}.`)
    }

    const braveNewWorldSummary = summary.bind(book)

now "this" in summary is now bond to the "book" object
the second kind is:
  function utilizationUpdate(chart, data) {....}

  function utilizationInit(component, btnGroup, data){
        ....
        var myChart = new Chart(ctx, {....}
        $(btnGroup).on("change", function() {
                    ...
                    fetch('{% url 'api_utilization' fac.fac_id %}?measure=' + measure + '&{{ request.GET.urlencode() }}' )
                    .then(status)
                    .then(json)
                    .then(utilizationUpdate.bind(this, myChart));
                }
            });
        }

"chart" in utilizationUpdate() is now bond to myChart.
Why in first bind() example, "this" is not an argument to be passed? but it is specified in the second bind() example?

A: The first argument passed to bind is the this value and the other arguments are the additional arguments to the function. In the first case, it only sets the this value, while in the second case, it sets both the this value and the first argument. However, it is likely that the this value wasn't truly needed, so null could have been passed too.


text:
Q: Change information in a sqlite3 table using keyword arguments as a function input, how can I do this in Python? The keyword arguments are idx, name and
passwd. to update the record with index 3 to the name 'Brian', the method is called as
update(idx=3, name='Brian'). The method returns False if the parameter idx is absent. also the password may be present and the record with the index is updated with the given values
for the fields.
I've tried something like this, but get a str object not callable error, I've attempted to look at other scripts here, but I keep getting errors.
def update(self, **kwargs):
    ''' keyword arguments are idx, name and password.
     For example, to update the record with index 3 to
     the name 'Brian', the method is called as
     update(idx=3, name='Brian'). The method returns
     False if the parameter idx is absent. In addition
     to name, also the passwd may be present and the record
     with the index is updated with the given values
     for the fields. The method update returns True if the
     updates succeeded, or False otherwise.'''

    if 'idx' in kwargs:

        query = 'UPDATE players set name = ?, password = ? WHERE idx = ?' (kwargs['name'], kwargs['password'],kwargs['idx'])

        self.cr.execute(query)

        self.db.commit()

        print('records updated')

        return True

    else:

        print('records failed to update')

        return False

A: You can't put the argument with the query like you've done:
query = 'UPDATE players set name = ?, password = ? WHERE idx = ?' (kwargs['name'], kwargs['password'],kwargs['idx'])

Python will think you're trying to call that string literal like it was a function.
Instead, pass the args when you execute the query, because the execute()  method is what actually stuffs your values into the SQL statement.
query = 'UPDATE players set name = ?, password = ? WHERE idx = ?'
self.cr.execute(query, (kwargs['name'], kwargs['password'], kwargs['idx']))

A better approach is to use named placeholders; then you can just pass in kwargs instead of having to dig out the fields you want:
query = 'UPDATE players set name = :name, password = :password WHERE idx = :idx'
self.cr.execute(query, kwargs)

To answer the question from your comment, you can dynamically create the query based on the fields for which you have values by iterating over the dictionary:
assert "idx" in kwargs   # idx is a required field
query = "UPDATE players SET"
for field in kwargs:
    if field != "idx":
        query += " {f} = :{f},".format(f=field)
query = query.strip(",")   # strip off unneeded comma after last field
query += " WHERE idx = :idx"
self.cr.execute(query, kwargs)

Or as a single statement:
query = "UPDATE players SET " + ", ".join(f + " = :" + f
         for f in kwargs if f != "idx") + " WHERE idx = :idx"


text:
Q: aesimc instruction gives incorrect result I'm trying to implement AES cryptography using the AES machine instructions (basing it on Intel's white paper) available on my Sandy Bridge. Unfortunately, I've come to a halt in the phase of generating the round keys for decryption. Specifically, the instruction aesimc (applying the Inverse Mix Columns operation) returns an incorrect result.
In their paper they have an example:

So with input:
48 69 28 53 68 61 79 29 5B 47 75 65 72 6F 6E 5D

I get the following using _mm_aesimc_si128():
2D BF F9 31 99 CD 3A 37 B7 C7 81 FD 7D E0 3D 8E

It should have returned:
62 7A 6F 66 44 B1 09 C8 2B 18 33 0A 81 C3 B3 E5

Not the same result. Why is this the case?
If you want to reproduce it, I tested it with the code below (remember the arguments -maes -msse4 when compiling):
#include <wmmintrin.h>
#include <iostream>
using namespace std;

void print_m128i(__m128i data) {
  unsigned char *ptr = (unsigned char*) &data;
  for (int i = 0; i < 16; i++) {
    int val = (int) ptr[i];
    if (val < 0xF) {
      cout << "0";
    }
    cout << uppercase << hex << val << " ";
  }
  cout << endl;
}

int main() {
  unsigned char *data = (unsigned char*)
    "\x48\x69\x28\x53\x68\x61\x79\x29\x5B\x47\x75\x65\x72\x6F\x6E\x5D";
  __m128i num = _mm_loadu_si128((__m128i*) data);
  __m128i num2 = _mm_aesimc_si128(num);
  print_m128i(num2);
  return 0;
}

EDIT: The example in Intel's white paper was wrong. As Hans suggested, my chip is little-endian so byte-swapping is necessary - to and fro.

A: The bytes are backwards.  You want 0x5d to be the least significant byte, it has to come first.  This is a little-endian chip.  In VS, use Debug + Windows + Registers, right-click + tick SSE to see the register values.


text:
Q: In for loop, I want to get array every time #include<stdio.h>
#include<time.h>

int main(void)
{
srand(time(NULL));
int answer;
int treatment = rand() % 4;
printf("###발모제 찾기###\n\n");

int cntShowBottle = 0;
int prevCntShowBottle = 0;

for (int i = 1; i <=3; i++)
{
    int bottle[4] = { 0, 0, 0, 0 };
    int* ptr = bottle;
    do {
        cntShowBottle = rand() % 2 + 2;
    } while (cntShowBottle == prevCntShowBottle);
    prevCntShowBottle == cntShowBottle;

    int isincluded = 0;
    printf(" %d 번째 시도 : ", i);

        for (int j = 0; j < cntShowBottle; j++)
        {
            int randBottle = rand() % 4;

            if (bottle[randBottle] == 0)
            {
                bottle[randBottle] = 1;
                if (randBottle == treatment)
                {
                    isincluded = 1;
                }
            }
            else
            {
                j--;
            }
        }

I want to get different array 'bottle[]' every time like {0,1,1,0},{1,1,1,0},{1,1,0,1} without duplication.. I think it needs (do while) and (pointer), but I don't know how to coding.


text:
Q: NGINX with Gunicorn: error 502 bad gateway I'm trying to run a web application with a SSL certificate on port 443.
To do so, I'm using Nginx as web server and Gunicorn as application server (running a Flask project).
I'm using a socket as proxy pass but I keep getting 502 bad gateway.
Here is my command with which I launch Gunicorn (works fine until I remove the port from the URL):
   gunicorn --workers 4 --bind unix:webapp.sock -m 007 --certfile "/etc/ssl/certs/domain.chained.crt" --keyfile "/etc/ssl/certs/domain.key" 'wsgi:app'

And this is my nginx.conf:
    # For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;

pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
    access_log /var/log/nginx/access.log;
    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    types_hash_max_size 4096;
    client_body_timeout 999;
    client_header_timeout 999;
    keepalive_timeout 999;
    fastcgi_buffers 8 16k;
    fastcgi_buffer_size 32k;
    fastcgi_connect_timeout 999;
    fastcgi_send_timeout 999;
    fastcgi_read_timeout 999;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    server {
        listen       80;
        listen       [::]:80;
        server_name  _;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        error_page 404 /404.html;
        location = /404.html {
        }

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
        }
    }

# Settings for a TLS enabled server.
#
#    server {
#        listen       443 ssl http2;
#        listen       [::]:443 ssl http2;
#        server_name  _;
#        root         /usr/share/nginx/html;
#
#        ssl_certificate "/etc/pki/nginx/server.crt";
#        ssl_certificate_key "/etc/pki/nginx/private/server.key";
#        ssl_session_cache shared:SSL:1m;
#        ssl_session_timeout  10m;
#        ssl_ciphers HIGH:!aNULL:!MD5;
#        ssl_prefer_server_ciphers on;
#
#        # Load configuration files for the default server block.
#        include /etc/nginx/default.d/*.conf;
#
#        error_page 404 /404.html;
#            location = /40x.html {
#        }
#
#        error_page 500 502 503 504 /50x.html;
#            location = /50x.html {
#        }
#    }
    include /etc/nginx/sites-enabled/*.conf;
    server_names_hash_bucket_size 64;
}

And my web application conf in the sites-available folder:
server {
        listen 443 ssl;
        server_name domain www.domain;
        ssl_certificate /etc/ssl/certs/domain.chained.crt;
        ssl_certificate_key /etc/ssl/certs/domain.key;

        location / {
            proxy_set_header Host $http_host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_pass http://unix:/path/to/sock/webapp.sock;
        }
}

This conf has been symbolically linked.
I have no idea why this is not working, as Nginx is not even logging anything!
I tried multiple things but I keep gateway the 502 error.
Does anyone have any idea? Thanks in advance


text:
Q: Convert float64 numpy array to floats not in scientific notation I currently have a numpy array of float64s:
[ -2.75090260e-08   3.11586226e-08   1.86128266e-08  -1.01560789e-07 ]

which I would like to print as for an excel spreadsheet import:
[ -.0000000275090260   .0000000311586226   .0000000186128266   -.000000101560789 ]

I've tried messing about with precision settings, but each number has its own mantissa and exponent.
Note that these output numbers can be considered a string if that makes the process easier, as they are going into a text file for excel.

A: You want to print the numbers in decimal format with 16 digits precision? How about this?
a = [-2.75090260e-08, 3.11586226e-08, 1.86128266e-08, -1.01560789e-07]
print map(lambda x: "{0:.16f}".format(x), a)

This prints
['-0.0000000275090260', '0.0000000311586226', '0.0000000186128266', '-0.0000001015607890']

Update:
You don't even need the lambda. Using
map("{0:.16f}".format, a)

works just as well. Thanks @JaminSore for pointing that out.

A: Note that you also have the option of:
numpy.round(_array, _decimalPrecision)


text:
Q: Java 14 javax.net.ssl.SSLException occurs only on some computers with identical cacerts files I have a Java 14 application where some computers throw a javax.net.ssl.SSLHandshakeException or javax.net.ssl.SSLException when trying to access https://nomads.ncep.noaa.gov/cgi-bin/filter_gfs_1p00.pl. It works fine for me, and all computers are using the same Windows 10 jre (that I built with jlink) and the same cacerts that came from OpenJDK 14. As I do not have the issue, I am unable to reproduce and debug. I have tried getting a user to replacing the cacerts on one of the computers, and it made no difference. Also, pasting the same URL direct into Chrome works. I have not tried exporting the cert from Windows and reimporting into cacerts, as my cacerts works and I don't see how that would make a difference, unless every cacerts is computer specific which does not appear to be the case from the modification date.
Any ideas on what could be causing this, and why Java is throwing the exception.

A: SOLVED. The particular users had not updated the jre, only the jar file and it was missing the jdk.crypto module.


text:
Q: AngularJS is not updating dynamic scope variable in http post success I'm trying to get data from database and assign it to a dynamic scope variable with a function but it doesn't assign the data to the dynamic variable at first attempt. Can anyone help?
This is my dynamicScope function;
$scope.dynamicScope= function(name, data){
  var modelScope = $parse(name);
  modelScope.assign($rootScope, data);
};

and here is postService function;
$scope.postService = function(scopeName, sentData){
    $http.post($scope.serviceLink, sentData)
            .success(function (data, status) {
              console.log("Fetched data: " + data);
              $scope.dynamicScope(scopeName, data);
            })
            .error(function (errData, status) {
               console.log("Error: "+errData);
            });
};

When I call postService as
$scope.postService("userInfo", loginData);

It prints data from the postService but it gives an error when I want to print it after the previous line like here console.log($scope.userInfo[0].user_name); it says $scope.userInfo is undefined. But it fetches previous data in the second attempt. Thanks in advance.

A: Return the $http promise to the function:
$scope.postService = function(scopeName, sentData){
    ͟r͟e͟t͟u͟r͟n͟ $http.post($scope.serviceLink, sentData)
            .then(function (response) {
              var data = response.data;
              console.log("Fetched data: " + data);
              $scope.dynamicScope(scopeName, data);
              return response.data;
            })
            .catch(function (response) {
               var errData = response.data;
               console.log("Error: "+errData);
               throw response;
            });
};

Then use that promise to delay the console.log:
var promise = $scope.postService("userInfo", loginData);
promise.then(function(data) {
    console.log(data);
    console.log($scope.userInfo[0].user_name);
});


text:
Q: Bash forked for loop with while loop control I have a for loop that will cycle through all the files in a directory. I want to run a process on each file (in this example echo file name and sleep 5). However I want to be able to run this 5 files at a time (in the background with &). The problem is I can't figure out how to iterate $f within the while loop so that I don't end up processing the same file five times instead of five different files at the same time.
#!/bin/bash

maxjobs=5

for f in `ls /home/user/`
do
 jobsrunning=0
  while [ $jobsrunning -lt $maxjobs ]
  do
    echo "Converting file"$f
    sleep 5 & #wait for 5 seconds
    jobsrunning=$((jobsrunning + 1))
    echo $jobsrunning
  done
wait
done

A: You really just need to reset jobsrunning, and I don't think you need the inner loop at all. It's just a condition.
#!/bin/bash

maxjobs=5
jobsrunning=0
for f in /home/user/*; do
    if (( jobsrunning >= maxjobs )); then
        wait
        jobsrunning=0
    fi
    echo "converting"
    sleep 5 & # wait for how many seconds?
    (( jobsrunning++ ))
    echo "$jobsrunning"
done
wait

That said, this sounds like a job for parallel.


text:
Q: Design database where each field needs to have a checkbox I got into a problem designing a database where I have a table, where every field needs to be validated by a human.
for example:

*

*name

*number

*ID card number

Each one of these fields need to be validated (kind of a checkbox).
which one is the correct approach here? have boolean fields in the same tablet or a different table with each field as boolean?

A: If the data has to be persisted between collection and verification, and each value can be accepted or rejected individually then there has to be a _verified column to match each _value column.
These verification columns are information about the thing to which they refer as much as the name and ID are so belong in the same logical entity type. Whether they go in the same physical table is a separate matter. If split this would be considered a vertical partitioning of the logical entity. There are good reasons to do that and good reasons not to.
If split the design and queries are more complicated. Likely response time will be fractionally better, though, since each table will be narrower. Both these can be swamped or mitigated by many other implementation details such as views or covering indexes.
Generally I'd keep a single table until proven otherwise.


text:
Q: Render table rows without binding for performance I'm using Angular 1.4. It's commonly known that ng-repeat can have some performance issues when rendering a large number of rows for things like tables. But I was wondering if there was an optimal way of using ng-repeat or some alternative iteration to simply render an array of data I have, for a table.
I don't need any binding, as it's just outputting data for a report. I've tried some suggestions like one-time binding, but it still takes a good amount of time (10 seconds or more for 1000 records or so). Other non-Angular methods I've tried are pre-rendering the HTML on the backend, and then returning the HTML instead of the data array. And I had a custom directive that just added that HTML to the element. This was less than a second for even 2000 rows (obviously since I didn't use Angular).
But it would be nice if I could accomplish the same thing in Angular, or even do something similar in the controller on the Angular side. Any input would be appreciated.

A: You can use one-way binding for this:

{{ ::item.name }}

Note that you have to add the :: syntax to each entry in the repeater.
I'm not sure how complex your logic is, but 10 seconds for 1000 rows sounds absurd.


text:
Q: Linearity in the vector triple product I am trying to understand the vector triple product:
$$x\times(y\times z).$$
As the vector triple product of $x$, $y$ and $z$ lies in the plane $(y \times z)$ the vector $x\times(y\times z)$ can be written as a linear combination of the vectors $\pm y$ and $\pm z$.
In the passage from the link below, can anyone please explain this sentence

"As the left-hand side is a linear-function of $x$ so is the right-hand side and this means that $\alpha$ and $\beta$ are linear scalar valued functions of $x$".

Please show how the left-hand side is a linear function of $x$. What does linearity in vectors mean? Can anyone please explain in a bit of detail. Is there an online reference I can refer to?
Also, what does linear scalar valued functions of $x$ mean? Please explain Theorem $4.2.5$ here. To my understanding, this function changes a vector into a scalar. What does it mean to say $f : \mathbb{R}^3\to \mathbb{R}$ is linear. Please give examples.

A: Let $V$ and $W$ be real vector spaces. A function $f : V \to W$ is linear if

*

*$f(v_1 + v_2) = f(v_1) + f(v_2)$ for every $v_1, v_2 \in V$, and

*$f(cv) = cf(v)$ for every $c \in \mathbb{R}$ and $v \in V$.

Saying that the expression $x\times(y\times z)$ is linear in $x$ means that for fixed $y, z \in \mathbb{R}^3$, the function $f : \mathbb{R}^3 \to \mathbb{R}$ given by $f(x) = x\times(y\times z)$ is linear. That is,

*

*$(x_1 + x_2)\times(y\times z) = x_1\times(y\times z) + x_2\times (y\times z)$ for all $x_1, x_2 \in \mathbb{R}^3$, and

*$(cx)\times (y\times z) = c(x\times(y\times z))$ for all $c \in \mathbb{R}$ and $x \in \mathbb{R}^3$.

Both of these properties follow from whatever definition of cross product you are using.
A linear scalar valued function is a linear function $f : V \to \mathbb{R}$; i.e. a linear function which takes values in the scalars.
In the case of Theorem $4.2.5$, $V = \mathbb{R}^3$ and the claim is that for any linear scalar valued function $f : \mathbb{R}^3 \to \mathbb{R}$, there is some $a \in \mathbb{R}$ such that $f(x) = x\cdot a$; i.e. every linear function $f : \mathbb{R}^3 \to \mathbb{R}$ is just given by the dot product with a fixed vector.
Example: You can check that that the function $f : \mathbb{R}^3\to\mathbb{R}$ given by $f(x_1, x_2, x_3) = 6x_3-x_1$ is linear. So by Theorem $4.2.5$, there is some vector $a \in \mathbb{R}^3$ such that $6x_3-x_1 = x\cdot a$; in this case, $a = (-1, 0, 6)$.


text:
Q: Getting GPS data from Twilio Photo I'm building a app that allows users to text in there photos to a twilio phone number which stores the photo on an AWS server.
However it appears the end photo is modified both in resolution and redacted exif data.
Does anyone know is this something Twilio is doing and can hopefully be switched off or is this happening during transit somehow?
I've tested from multiple phone models / os's and the results always seem the same which makes me think it twilio.
Maybe there is a better way to extract GPS data from a texted photo???


text:
Q: Django: collectstatic raises OSError: [Errno 39] Directory not empty: (ckeditor) Suddenly, I can't do collectstatic.
python manage.py collectstatic

Type 'yes' to continue, or 'no' to cancel: yes
Found another file with the destination path 'admin/js/jquery.init.js'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path.
Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/home/django/maklerienv36/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "/home/django/maklerienv36/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/django/maklerienv36/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/django/maklerienv36/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute
    output = self.handle(*args, **options)
  File "/home/django/maklerienv36/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 189, in handle
    collected = self.collect()
  File "/home/django/maklerienv36/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 114, in collect
    handler(path, prefixed_path, storage)
  File "/home/django/maklerienv36/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 344, in copy_file
    if not self.delete_file(path, prefixed_path, source_storage):
  File "/home/django/maklerienv36/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 294, in delete_file
    self.storage.delete(prefixed_path)
  File "/home/django/maklerienv36/lib/python3.6/site-packages/django/core/files/storage.py", line 299, in delete
    os.rmdir(name)
OSError: [Errno 39] Directory not empty: '/home/django/makleri/static/ckeditor'

I tried to delete whole static folder and rerun collectstatic but it didn't help. Do you know how to make it work?
It works on my PC, this is a server.

A: I had a similar problem with collectstatic. For me, the following helped:

python3 manage.py collectstatic --clear

According to the django docs:

--clear, -c
Clear the existing files before trying to copy or link the original file.

The problem is that self.delete_file(path, prefixed_path, source_storage) does not work on non-empty directories. -rf would help, but django's collectstatic.py does not use it.


text:
Q: pgAdmin4: What username do I select? So I have installed PostgreSQL on my new macOS via Homebrew, but instead of doing all the work via CLI like I prefer, I want to use pgAdmin4 to make it easier for demonstration purposes for a less technical crowd.
For creating a server in pgAdmin4 where I am trying to make a connection, do I use the default PostgreSQL username that comes with doing an install with Homebrew or do I use the same username for accessing my laptop?

A: The fact that the Homebrew system has you log in to the PostgreSQL server using postgres username seems to be of no relevance, you will have to use the Username in pgAdmin4 of whatever results you get from doing a whoami on your terminal.


text:
Q: Doing manual navigation well with page objects I'm fairly new to Protractor and E2E testing, but I've spent a few days researching, setting up page objects, and creating test suites, and one thing I'm wondering about is how to create good manual navigation between page objects and the actual pages.
Let's say I have some parts on my site that can navigate to other parts of it; the page object for one of them could look something like this:
var SomePartPage = function() {
    this.btnPopUp = // button for opening some pop up
    ...
    this.openPopUp = function() {
        this.btnPopUp.click();
        return popUpPage;
    };
};

I'm following the guideline that returning page objects is a good thing, and I'm assuming the promise returned by calling click() will be resolved before returning (as per WebDriverJS' control flow).
But I have a setup in my test where I want to verify that this navigation takes place correctly, and sometimes it works and sometimes it doesn't. So I'm assuming it's because my pop up isn't always fully loaded by the time I want to interact with it (i.e. by the time openPopUp() has returned).
Are my assumptions correct? And if so, how do I deal with this? I can use manual timers and promises of course, but I'd rather have some promise that gets resolved automatically when my pop up is fully loaded.

A: Actually I don't think the return will wait for the click();
I think you should do something similar:
browser.wait(this.btnPopUp.click(), timeout)


text:
Q: Get value from nested array in jQuery? Here is the array. This is the response of ajax.
Array
(
    [vehicle] => Array
        (
            [reg] => 142D9488
            [make] => Skoda
            [model] => Octavia
            [version] => COM AMB 1.6tdi 105HP 4DR
            [body] => Estate
            [doors] => 4
            [reg_date] => 2014-07-31
            [engine_cc] => 1598
            [colour] => Black
            [fuel] => Diesel
            [transmission] => M
            [no_of_owners] => 4
            [tax_class] => P
            [tax_expiry_date] => 2020-09-30
            [NCT_expiry_date] => 2020-07-30
            [co2_emissions] => 99
            [last_date_of_sale] => 2019-10-21
        )

)

How can I get the value of 'make' key in jQuery?


text:
Q: How to optimize MySQL query (group and order) Hey all, I've got a query in need of optimizing. It works but its a dog, performance wise.
It reads like this:
SELECT  *
FROM    (
        SELECT  *
        FROM    views
        WHERE   user_id = '1'
        ORDER BY
                page DESC
        ) v
GROUP BY
        v.session

I'm tracking views to different pages, and I want to know the highest page per session, in order to know how far they've clicked through (they're required to view every page all the way to the end) in any given session.
Basically what I'm trying to do is ORDER the results before the GROUP. Which the above achieves, at significant cost.
Anyone who can slap me over the head with how to do this? Thanks guys!
Update:
The Explain:
"1" "PRIMARY"   "<derived2>"    "ALL"   \N  \N  \N  \N  "3545"  "Using temporary; Using filesort"

"2" "DERIVED"   "views" "index" \N  "page"  "5" \N  "196168"    "Using where"

The schema:
ID       int(8) unsigned  (NULL)     NO      PRI     (NULL)   auto_increment  select,insert,update,references
page     int(8)           (NULL)     YES     MUL     (NULL)                   select,insert,update,references
user_id  int(8)           (NULL)     YES             (NULL)                   select,insert,update,references
session  int(8)           (NULL)     YES             (NULL)                   select,insert,update,references
created  datetime         (NULL)     NO                                       select,insert,update,references

Index Info:
views            0  PRIMARY              1  ID           A               196008    (NULL)  (NULL)          BTREE

views            1  page                 1  page         A                  259    (NULL)  (NULL)  YES     BTREE

A:
I'm tracking views to different pages, and I want to know the highest page per session, in order to know how far they've clicked through (they're required to view every page all the way to the end) in any given session.

Ordering before grouping is a highly unreliable way to do this.
MySQL extends GROUP BY syntax: you can use ungrouped and unaggregated fields in SELECT and ORDER BY clauses.
In this case, a random value of page is output per each session.
Documentation explicitly states that you should never make any assumptions on which value exactly will it be:

Do not use this feature if the columns you omit from the GROUP BY part are not constant in the group. The server is free to return any value from the group, so the results are indeterminate unless all values are the same.

However, in practice, the values from the first row scanned are returned.
Since you are using an ORDER BY page DESC in your subquery, this row happens to be the rows with a maximal page per session.
You shouldn't rely on it, since this behaviour is undocumented and if some other row will be returned in next version, it will not be considered a bug.
But you don't even have to do such nasty tricks.
Just use aggregate functions:
SELECT  MAX(page)
FROM    views
WHERE   user_id = '1'
GROUP BY
        session

This is documented and clean way to do what you want.
Create a composite index on (user_id, session, page) for the query to run faster.
If you need all columns from your table, not only the aggregated ones, use this syntax:
SELECT  v.*
FROM    (
        SELECT  DISTINCT user_id, session
        FROM    views
        ) vo
JOIN    views v
ON      v.id =
        (
        SELECT  id
        FROM    views vi
        WHERE   vi.user_id = vo.user_id
                AND vi.session = vo.session
        ORDER BY
                page DESC
        LIMIT 1
        )

This assumes that id is a PRIMARY KEY on views.

A: I think your subquery is unnecessary. You would receive the same results from this much simpler (and faster) query:
SELECT *
FROM views
WHERE user_id = '1'
GROUP BY session
ORDER BY page DESC

Also, you should have an index on every field you're either grouping, ordering or "where-ing" by. In this case, you need an index on user_id, session and page.

A: I would suggest a composite (multi-column) index on user_id, page.  That assumes the inner query is the slow part.

A: The problem is the subselect. SELECT * FROM (SELECT * FROM)
You should be using a join. What data type is your 'page' field?


text:
Q: htaccess send 404 status on multiple 404 redirects I have the following rules in my .htaccess file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} ^/en-us/
Rewriterule ^(.*) /en-us/error-404/ [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
Rewriterule ^(.*) /error-404/ [L]

And it's working fine. When there are requests starts with /en-us/, I can see the content of /en-us/error-404/ page and in all other cases I see the content of /error-404/ page. However, the status code received from the server is 200 OK.
Is it possible to send 404 Not Found in both cases?

A: You can use if/elseif/else conditions to use different ErrorDocument directives: (available in Apache 2.4+)
<If "%{REQUEST_URI} =~ m#^/en-us/#">
   ErrorDocument 404 /en-us/error-404/
</If>
<Else>
   ErrorDocument 404 /error-404/
</Else>


text:
Q: How to import from React-Select CDN with React and Babel? I've created a react application following the steps on the React Website, but I'm having issues utilizing the React-Select Library (particularly the Select Component).
I can only use cdn files to load dependencies, including the React-Select cdn file located on cdnjs
https://cdnjs.cloudflare.com/ajax/libs/react-select/2.1.2/react-select.js

I'm getting the following error with my react-app:
ReferenceError: Select is not defined[Learn More]

See below for my script and here for my codepen

      <meta charset="utf-8">

      <title>Using React Select CDN</title>

I've also tried the following which throws the same error

      <meta charset="utf-8">

      <title>Using React Select CDN</title>

How can I get React-Select to work? Perhaps

A: It looks for the latest react-select you need to add the latest dependencies -
Codepen


text:
Q: Make virtual host, htaccess or php.ini or http.conf or etc? I want to make a blog system.
A popular blog address looks like
blogname.sitename.com.
I think that this address should redirect to something like
sitename.com/index.php?user=blogname.
Because is not logical that make a subdomain for every blog.
Is that correct?
So, I write this code for .htaccess:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{HTTP_HOST} !^(www|mail).mydomain.com$ [NC]
RewriteCond %{HTTP_HOST} !^(www|mail).mydomain.com$ [NC]
RewriteCond %{HTTP_HOST} ^(www\.)?([a-z0-9-]+).mydomain.com$ [NC]
RewriteRule ^(.*)/$ ?option=user&id=$2 [R=301,L]

But it does not work.
I guess that I should do some configuration another where.
Where is the configuration source?
What is the configuration?

A: use $2 instead of %2
RewriteRule ^(.*)/$ /index.php?user=$2 [R=301,L]


text:
Q: How do I place a comma between each character in a string with PHP?
Possible Duplicate:
seperate with commas

$following_user_id .= $row['following_user_id'];

leads to
44443344330

can you seperate each with comma, but I don't want a comma on the last one, if anyone could do this for me I would apreciate it very much


text:
Q: htaccess mod rewrite rule to over-ride cakephp controller I have a site running cakephp and also a wordpress site together in the same root directory. I have the following issue. Wordpress is served requests first such that a url for the homepage will be routed through wordpress' index. Now our cakephp code includes a list of controllers that manage some special features of our site. We have a rewrite rule that looks as followed RewriteCond %{REQUEST_URI} !^/users. This allows urls like www.example_site.com/users to hit our cakephp framework instead of generating a 404 error when wordpress cannot find this page.
This rule bypasses the wordpress routing so that the request can be sent to cakephp. We are using a similar rule for each of our cakephp controllers. The issue is that we used to have a wordpress plugin that had a users page. This users page appended arguments to the url as followed www.example_site.com/users/some_dudes_username. Some links to these user pages are still indexed by google or in peoples bookmarks, so what is happening is the rewrite rule we wrote causes these to bypass wordpress (instead of 404ing there like it used to) and instead they hit cakephp and 404 there. I am thinking through how to make it so that any of our cakephp user controller functions are correctly redirected to (there are only a few so white-listing seems like the way to go), but any other request to the user controller for actions that will not exist like www.example_site.com/users/some_dudes_username would redirect to our FAQ page. I have the following white-list code which seems to work, but I cannot figure out how to correctly redirect everything else:
RewriteCond %{REQUEST_URI} !^/admin/users
RewriteCond %{REQUEST_URI} !^/users/login
RewriteCond %{REQUEST_URI} !^/users/admin_login
RewriteCond %{REQUEST_URI} !^/users/logout
RewriteCond %{REQUEST_URI} !^/users/admin_logout
RewriteCond %{REQUEST_URI} !^/users/admin_index

# Then I need a rewrite rule to take everyone else to the FAQ page.

Thank you to anyone that can help.

A: I am not sure I totally understand your issue, but it sounds like you need a RewriteRule like this:
RewriteRule ^/users/.*$ /URI/to/faq.html [R]

This rule should be right after your RewriteCond since the conditions only apply to the rule right after them.
Hope this helps.


text:
Q: How to set tabs line width in vim? I have two vertical split windows. I wish to set my tabs line to the width of the first window only, so the newly opened tabs would not overlaps over the second window.
Is there a way to do that?

A: You can probably manipulate the tabline (see :h setting-tabline) option to achieve your goal but… the tabline already has a very limited usefulness when your reach a dozen tabs because of the available width so it will be even less useful if you reduce it by 50% or more.
What would be the point of that behavior? What would be its benefit? What is your ultimate goal?

A: You need to write a function that provides a custom tabline, and install it into the 'tabline' setting. (Note that this won't apply to GVIM with its graphical tabline.)
The help at :help setting-tabline has a functioning example that emulates the default tabline. You need to manipulate that to limit the width to that of the first window, which you can retrieve with winwidth(1). To make your tabline also correctly deal with double-width characters, the newish strdisplaywidth() function may be of use.
You see, it's doable, but I doubt that the effort warrants the benefit (which I fail to see).


text:
Q: Inverse limit of locally compact groups If $(G_i,\varphi_i)$ is a inverse system of Hausdorff locally compact groups, then $\varprojlim G_i $ is locally compact?
I have looked for information about it, or any additional condition for the conclusion holds.
I don't know if I added the condition that $G_i$ are compact for almost everywhere it's enough.
Thanks you all for any suggestion or any counterexample

A: This is unfortunately false.
We can write an infinite dimensional $\mathbb{R}$ vector space as an inverse limit of finite dimensional $\mathbb{R}$ vector spaces (see here, or PaulFrost's comment below). Now since finite dimensional vector spaces are locally compact, but infinite dimensional spaces aren't (see here, for instance), we see inverse limits cannot preserve local compactness.
You ask about additional conditions to make the conclusion hold, such as the condition that the $G_n$s are "compact almost everywhere":
If we replace local compactness by compactness, then the theorem becomes true (because of Tychonoff's theorem). In fact, if all but finitely many of the $G_n$s are compact, and the remaining finitely many are merely locally compact, then the inverse limit is locally compact (so a version of your "almost everywhere" criterion works!).
To see why, recall $\varprojlim G_n$ is a certain (closed) subgroup of $\prod G_n$. Since the product of finitely many locally compact spaces is locally compact (see here, say), we see $\prod G_n$ is still locally compact, and thus $\varprojlim G_n$, which is a closed subspace, is locally compact too (see here).

I hope this helps ^_^


text:
Q: Linearity of expectations - must prove by induction? I was reviewing linearity of expectations in my textbook and saw the following statement (see arrow in picture).
I understand how the theorem can be proved for multiple random variables using induction, but was wondering: is it necessary to use induction? It seems to me that it's fairly easy to generalize the proof for two random variables for multiple random variables without needing to go through the steps of induction. Asking because I saw another source also saying that linearity of expectation for multiple random variables can be proved by induction. Just wanted to make sure I'm not missing any subleties here. Screenshot here

A: The thing is you are interested in demonstrating the proposed property for every natural number.
If you restrict your proof to some $n\in\mathbb{N}$, you cannot conclude it holds for every $n\in\mathbb{N}$.
That is why the proof by induction is important.