Q: Setting border for checkable QListWidgetItem I have added some check-able QListWidgetItem and I have challenge setting the border color for the checkboxes. setForeground function only sets the color of the checkbox text.
Any suggestion please.
This is my sample code creating the check-able QListWidgetItems:
    watch_list = ["Protesters", "Local news staff", "Techfluencers"]
    for category in watch_list:
        self.checkBox = QtWidgets.QListWidgetItem(category)
        self.checkBox.setFlags(self.checkBox.flags() | QtCore.Qt.ItemIsUserCheckable)
        self.checkBox.setCheckState(QtCore.Qt.Unchecked)
        self.checkBox.setForeground(QtGui.QColor('#FFFFFF'))
        self.watchListslistWidget.addItem(self.checkBox)

I have tried
     self.watchListslistWidget.setStyleSheet("""
                                            QListWidget::item {
                                                 border:1px #FFFFFF
                                            }
                                        """)

But it sets the all background of the QListWidget to white.

A: You can use a delegate:
from PyQt5 import QtCore, QtGui, QtWidgets

class CheckBoxDelegate(QtWidgets.QStyledItemDelegate):
    def initStyleOption(self, option, index):
        super().initStyleOption(option, index)
        option.palette.setBrush(QtGui.QPalette.Button, QtGui.QColor("red"))

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.watchListslistWidget = QtWidgets.QListWidget()
        self.setCentralWidget(self.watchListslistWidget)

        watch_list = ["Protesters", "Local news staff", "Techfluencers"]
        for category in watch_list:
            checkBox = QtWidgets.QListWidgetItem(category)
            checkBox.setFlags(checkBox.flags() | QtCore.Qt.ItemIsUserCheckable)
            checkBox.setCheckState(QtCore.Qt.Unchecked)
            self.watchListslistWidget.addItem(checkBox)

        delegate = CheckBoxDelegate(self.watchListslistWidget)
        self.watchListslistWidget.setItemDelegate(delegate)

def main():
    import sys

    app = QtWidgets.QApplication(sys.argv)

    w = MainWindow()
    w.show()

    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

A: I got it working by using indicator as follows:
self.watchListslistWidget.setStyleSheet("""
                                       QListWidget::indicator{
                                            border: 1px solid white;
                                       }
                                       """)


Q: display json data that contains html I have the following json
[{
  "date": "2011",
  "content": "
Hello world?
"
},
{
  "date": "2012",
  "content": "
Hello again
"
}]

my controller has
public function index() {
  $data['json'] = json_decode(file_get_contents('location_of_json_file.json'));
  return view('index', $data);
}

my view has
@foreach ($json as $a)
  {{ $a->content }}
@endforeach

but what i get is
<p>Hello world?</p>

<p><strong>Hello again</strong></p>

how can i make it parse the html code instead of displaying the syntax? i've tried htmlentities and html_entity_decode. i tried to json_encode in different place of the code, i'm lost. please help.

A: The Blade output tags changed between Laravel 4 and Laravel 5.  You're looking for:
{!! $a->content !!}

In Laravel 4, {{ $data }} would echo data as is, whereas {{{ $data }}} would echo data after running it through htmlentities.
However, Laravel 5 has changed it so that {{ $data }} will echo data after running it through htmlentities, and the new syntax {!! $data !!} will echo data as is.
Documentation here.

A: In Laravel 5, by default {{ ... }} will escape the output using htmlentities. To output raw HTML that get's interpreted use {!! ... !!}:
@foreach ($json as $a)
    {!! $a->content !!}
@endforeach

Here's a comparison between the different echo brackets and how to change them


Q: WPF: Making child elements' MinWidth/MinHeight constrain the Window I have a WPF Window that contains a UserControl with a MinWidth and MinHeight. How can I prevent the user from resizing the Window down to a point where that UserControl's minimum size is violated?
Here's a simplified version of a Window I'm working on. My real app's UserControl is replaced here by a Border:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <DockPanel>
    <StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal">
      <Button Content="OK"/>
      <Button Content="Cancel"/>
    </StackPanel>
    <Border BorderBrush="Green" BorderThickness="10"
            MinWidth="200" MinHeight="150"/>
  </DockPanel>
</Window>

If I shrink the window small enough, the Border's right and bottom edges are cut off. I want to prevent the window from getting that small -- I want my window's minimum size to be exactly the point at which the Border is at its minimum size. Some frameworks (like the Delphi VCL) automatically aggregate child controls' minimum sizes up to the window; I expected WPF to do the same, but clearly it does not.
I could always explicitly set the Window's MinWidth and MinHeight, but to calculate those correctly, I would have to factor in the Buttons' ActualHeight, which would mean waiting for at least one layout pass (or calling Measure manually). Messy.
Is there any better way to keep the Window from resizing too small for its content?

A: The simplest way I've found is to tell the Window to size to its content:
<Window ... SizeToContent="WidthAndHeight" ...>

and then, once it's done sizing (which will take the child elements' MinWidth and MinHeight into account), run some code that sets MinWidth and MinHeight to the window's ActualWidth and ActualHeight. It's also a good idea to turn SizeToContent back off at this point, lest the window resize when its content changes.
The next question is, where to put this code? I finally settled on OnSourceInitialized:
protected override void OnSourceInitialized(EventArgs e)
{
    base.OnSourceInitialized(e);
    MinWidth = ActualWidth;
    MinHeight = ActualHeight;
    ClearValue(SizeToContentProperty);
}

I also tried the Loaded event, but in my case, that was too soon -- Loaded happens before databindings have been evaluated, and I had databindings that affected my layout (a Label with a binding for its Content -- its size changed after the binding took effect). Moving the code into OnSourceInitialized, which fires after databinding, corrected the problem.
(There were also other events that fired after binding, but before the window was shown -- SizeChanged and LayoutUpdated -- but they both fire multiple times as the window is shown, and again later if the user resizes the window; OnSourceInitialized only fires once, which I consider ideal.)

A: Have you tried using an ElementName style binding from the Window to the UserControl at hand? It seems like it would be feasible to bind the Window's MinWidth/Height to those of the Button. Still not pretty, but it shouldn't require extra passes once the binding is in place and will adapt if you change the values on the Button.


Q: Form that has a date picker input. And I’m sending my data to the database using nodejs My problem is: when I set the data type of my date picker to just “date” my data makes it to the database(even though it’s not the current date), BUT when I set the data type of my date picker to “datetime-local” it doesn’t make it, instead it’s just giving me an error.

*

*Date picker image
    <form action="/formdata" method="POST"class="row g-12 needs-validation" novalidate>

                     End Shift

 <input name="datepicker" id="datepicker"
                        class="form-
                       control" type="datetime-local" required>

*This is how I'm adding the data to the database (SQL Server)

    class forms {
        constructor(datepicker,site,line,units){

            this.d = datepicker;
            this.s = site;
            this.l = line;
            this.u = units;
        }

    }

    app.use(bodyParser.urlencoded({ extended: true}));
    app.use(bodyParser.json());

    //make directory static
    app.use(express.static(__dirname + '/public'));

    //we getting the home.html page
    app.get("/",(req,res)=>{
        res.sendFile(__dirname+"/public/home.html");
    });

    //creating a route for form data
    app.post("/formdata",(req,res)=>{
        const userDetails = new
         forms(req.body.datepicker,req.body.site,req.body.line,req.body.units);

        //Requesting database
        var request = new sql.Request();

        // let datetime =userDetails.d ;
        console.log(userDetails.d);

        const date = moment(userDetails.d).format('YYYY-MM-DD HH:mm:ss');

        // Insert data into the database
        let mssql = (`INSERT INTO DataEntry(Date,TimeStamp,Line,Units,Site)
           Values(${date},'25114','${userDetails.l}','${userDetails.u}','${userDetails.s}');`);

           request.query(mssql,function (err, data) {
               if (err) throw err;
               console.log("User data is successfully inserted");
          });
            res.sendFile(__dirname+"/public/home.html");
    });

    //Listern to port 3002
    app.listen(port,(e)=>{
        if(e) throw e;
        console.log("html page provided");
    });

*This is the error I'm getting

originalError: Error: Incorrect syntax near '11'.

*This is the date format on my database

Databasecolums and data format

*And this is how the date appears in my database when when the date picker datatype is set to "datetime-local".

Date entry to the database
As you can see things look pretty broken, please help me figure out this problem.


Q: .bash_profile permission denied I'm trying to make one of my first projects published with github but I'm having trouble testing the build locally.
I'm following the steps here:
https://jekyllrb.com/docs/installation/macos/
and I am stuck on the following command line runs:
echo "source $(brew --prefix)/opt/chruby/share/chruby/chruby.sh" >> ~/.bash_profile
echo "source $(brew --prefix)/opt/chruby/share/chruby/auto.sh" >> ~/.bash_profile
echo "chruby ruby-3.1.2" >> ~/.bash_profile # run 'chruby' to see actual version

Each time I run the first one, I get the following error:
-bash: /Users/account/.bash_profile: Permission denied
This is all very new to me and honestly I have no clue what I'm doing when it comes to the console. I am on MacOS Monetory and my shell is bash. Any help would be really appreciated!

A: Something has corrupted or changed ownership to root your .bash_profile script.
Open Terminal.app and do these:

*

*mv -f ~/.bash_profile ~/.bash_profile

*cp ~/.bash_profile.old ~/.bash_profile
These commands show not produce errors.
Now try to re-run your scripts to append to .bash_profile.


Q: IE10 anchor tag z-index issue In IE 10, I have a relatively positioned wrapper div with some content (an image / text). Inside of that div is an absolutely positioned anchor tag which is positioned to "cover" the entire wrapper div. It has a z-index set. So the entire area inside the wrapper div should be clickable. However, only the areas in the wrapper div that don't have content are clickable. The entire wrapper div is clickable in all other browsers except for IE 10. Here is a fiddle: http://jsfiddle.net/NUyhF/3/. Help?

Here is some text

.wrapper { position : relative; width: 500px; height: 300px; }
.wrapper a { position: absolute; top: 0px; width: 500px; height: 300px; z-index: 2; }

A: It is now semantically correct to wrap block level elements in an anchor tag (using the html5 doctype).  I would suggest amending your markup to this.
HTML

Here is some text

A: I have found this to be an annoying trait of IE for some time, to solve it I had to make a transparent image and use it as the background of the anchor tag:
background:url(transparent1x1.gif) repeat;

http://jsfiddle.net/NUyhF/6/


Q: Multiprocessing pool.imap with large chunksize is skipping processing some records in iterable I am processing a list of string using multiprocessing pool.imap() with passing chunksize. My list length is 1821 and process in imap is 4. I was trying to give almost equal number of chunk size to each process so set chunk size as 455. Also tried with 500. But this makes my imap to skip some of the records.
Skipping was not so random too as it is ordered list. Once I changed the chunk size to 200, imap started sending all the records to my target function.
Can some one explain why the chunksize > 450 is causing issue here, while as per documentation it should be divided 1821/4  = 455 or 456 rec in each process ideally.
Also note , in my function I am using that string and running some steps which takes few seconds for each. While for testing I tried  to writing the string only in file inside target function and even then it was skipping some records.
  def process_init(self,l):
        global process_lock
        process_lock = l

  def _run_multiprocess(self,num_process,input_list,target_func,chunk):
        l = mp.Lock()
        with mp.Pool(processes=(num_process),initializer=self.process_init, initargs=(l,)) as p:
            start = time.time()
            async_result  = p.imap(target_func, input_list,chunksize =chunk)

            p.close()
            p.join()
            print("Completed the multiprocess")
            end = time.time()
            print('total time (s)= ' + str(end-start))

chunksize = 500
self._run_multiprocess(4,iterator_source,self._process_data,chunksize)

def _process_data(self,well_name):

        with open("MultiProcessMethod_RecordReceived.csv","a") as openfile:
            process_lock.acquire()
            openfile.write( "\t" +well_name.upper() + "\n")
            openfile.flush()
            process_lock.release()


Q: Unable to choose order of buttons in UIAlertController I was under the impression that if the normal action is a destructive action and the other is a cancel action in their UIAlertController that the destructive one should be on the left and the cancel should be on the right.
If the normal action is not destructive, then the normal action should be on the right and the cancel should be on the left.
That said, I have the following:
var confirmLeaveAlert = UIAlertController(title: "Leave", message: "Are you sure you want to leave?", preferredStyle: .Alert)

let leaveAction = UIAlertAction(title: "Leave", style: .Destructive, handler: {
        (alert: UIAlertAction!) in

        //Handle leave

    }
)

let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)

confirmLeaveAlert.addAction(leaveAction)
confirmLeaveAlert.addAction(cancelAction)

self.presentViewController(confirmLeaveAlert, animated: true, completion: nil)

I was under the impression that if I add the leaveAction first, then the cancelAction that the leaveAction would be the button on the left. This was not the case. I tried adding the buttons in the opposite order as well and it also resulted in the buttons being added in the same order.
Am I wrong? Is there no way to achieve this?

A: My solution to this was to use the .Default style instead of .Cancel for the cancelAction.

A: Since iOS9 there is a preferredAction property on UIAlertController. It places action on right side. From docs:

When you specify a preferred action, the alert controller highlights the text of that action to give it emphasis. (If the alert also contains a cancel button, the preferred action receives the highlighting instead of the cancel button.)
The action object you assign to this property must have already been added to the alert controller’s list of actions. Assigning an object to this property before adding it with the addAction: method is a programmer error.


Q: ASP.NET custom HttpHandler in IIS 7, 7.5 My web.config is setup as following. My handler lives in an assembly called TestProject.Custom. I am calling this handler via jQuery post, works great in VS 2010 (of course!) but when I push it out to IIS 7.5 or IIS 7, it throws 404 about not being able to find TestHandler.ashx. Not sure what I am missing.
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />

<handlers>
  <add name="TestHandler"
       verb="*" preCondition="integratedMode"
       path="TestProject.Custom.HttpHandlers.TestHandler.ashx"
       type="TestProject.Custom.HttpHandlers.TestHandler, TestProject.Custom"/>

</handlers>

Edit: I am calling this handler with jQuery and the handler is behind forms authentication (which I don't think is the problem):
jQuery(function () {
    jQuery.ajax({
        type: "POST",
        url: "TestHandler.ashx",
        data: { "test_data": "some test data" }
    });
});

A: I think the "path" attribute should be "TestHandler.ashx" instead of its current value. It must match the URL you use in jQuery. Otherwise, 404 is expected.

A: 404 usually means a problem with the registration, basically it just can't find something to handle the request that came in.
Inside of the add node, try adding the following attribute at the end: resourceType="Unspecified"
That tells IIS not to look for a physical file when it sees the request for the ashx.  I think that's causing the 404


Q: org.apache.catalina.LifecycleException: Failed to start component i am getting this error when starting my tomcat server with my application.
I don't really understand it but if i "clean" in eclipse a few times or if i stop start the tomcat server a few times it somehow works, but then it happens over again if i stop.
any ideas?

WARNING: [SetContextPropertiesRule]{Context} Setting property 'source' to 'org.eclipse.jst.j2ee.server:datalinx-backend' did not find a matching property.
May 27, 2014 11:23:36 AM org.apache.catalina.loader.WebappClassLoader validateJarFile
INFO: validateJarFile(D:\Applications\STS\vfabric-tc-server-developer- 2.9.2.RELEASE\base-instance\wtpwebapps\datalinx-backend\WEB-INF\lib\javax.el-api-2.2.4.jar)    - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/el/Expression.class
May 27, 2014 11:23:36 AM org.apache.catalina.loader.WebappClassLoader validateJarFile
INFO: validateJarFile(D:\Applications\STS\vfabric-tc-server-developer-2.9.2.RELEASE\base-instance\wtpwebapps\datalinx-backend\WEB-INF\lib\javax.servlet-api-3.0.1.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class
May 27, 2014 11:23:36 AM org.apache.catalina.loader.WebappClassLoader validateJarFile
INFO: validateJarFile(D:\Applications\STS\vfabric-tc-server-developer-2.9.2.RELEASE\base-instance\wtpwebapps\datalinx-backend\WEB-INF\lib\tomcat-embed-core-7.0.52.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class      May 27, 2014 11:23:36 AM org.apache.catalina.loader.WebappClassLoader validateJarFile
INFO: validateJarFile(D:\Applications\STS\vfabric-tc-server-developer-2.9.2.RELEASE\base-instance\wtpwebapps\datalinx-backend\WEB-INF\lib\tomcat-embed-el-7.0.52.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/el/Expression.class
May 27, 2014 11:23:39 AM org.apache.catalina.core.ContainerBase addChildInternal
SEVERE: ContainerBase.addChild: start:
org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/backend]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:657)
at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1637)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
Caused by: java.lang.IllegalStateException: Unable to complete the scan for annotations for web application [/backend] due to a StackOverflowError. Possible root causes include a too low setting for -Xss and illegal cyclic inheritance dependencies. The class hierarchy being processed was [org.bouncycastle.asn1.ASN1EncodableVector->org.bouncycastle.asn1.DEREncodableVector->org.bouncycastle.asn1.ASN1EncodableVector]
at org.apache.catalina.startup.ContextConfig.checkHandlesTypes(ContextConfig.java:2179)
at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:2126)
at org.apache.catalina.startup.ContextConfig.processAnnotationsJar(ContextConfig.java:2001)
at org.apache.catalina.startup.ContextConfig.processAnnotationsUrl(ContextConfig.java:1967)
at org.apache.catalina.startup.ContextConfig.processAnnotations(ContextConfig.java:1952)
at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1326)
at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:878)
at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:369)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5269)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 11 more

 May 27, 2014 11:23:39 AM org.apache.catalina.startup.HostConfig deployDescriptor
 SEVERE: Error deploying configuration descriptor D:\Applications\STS\vfabric-tc-server-developer-2.9.2.RELEASE\base-instance\conf\Catalina\localhost\backend.xml
 java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/backend]]
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:904)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:657)
at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1637)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)

  May 27, 2014 11:23:39 AM org.apache.catalina.startup.HostConfig deployDirectory

A: First of all, that looks like Pivotal's tc Server rather than Apache Tomcat. tc Server is based on Apache Tomcat but they are not exactlt the same and it always helps to provide the most accurrate information you can.
There is something seriously wrong with your dependencies. Tomcat is detecting the following class heirarchy:
org.bouncycastle.asn1.ASN1EncodableVector
 ->org.bouncycastle.asn1.DEREncodableVector
  ->org.bouncycastle.asn1.ASN1EncodableVector
This is a cyclic dependency. In Java it is illegal for A to extend B if B extends A.
Cleaning out your dependencies and ensuring you are using only using one version of the bouncy castle JAR should fix this.
If the problem persists and can be reproduced on a clean install of the latest stable Tomcat 7 release then please do open a bug against Apache Tomcat and provide the web application that demonstrates the issue.


Q: Connectionless UDP vs connection-oriented TCP over an open connection If a TCP connection is established between a client and server, is sending data faster on this connection-oriented route compared to a connectionless given there is less header info in the packets? So a TCP connection is opened and bytes sent down the open connection as and when required.  Or would UDP still be a better choice via a connectionless route where each packet contains the destination address?
Is sending packets via an established TCP connection (after all hand shaking has been done) a method to be faster than UDP?

A: I suggest you read a little bit more about this topic.
just as a quick answer. TCP makes sure that all the packages are delivered. So if one is dropped for whatever reason. The sender will continue sending it until the receiver gets it. However, UDP sends a packet and just forgets it, so you might loose some of the packets. As a result of this, UDP sends less number of packets over network.
This is why they use UDP for videos because first loosing small amount of data is not a big deal plus even if the sender sends it again it is too late for receiver to use it, so UDP is better. In contrast, you don't want your online banking be over UDP!
Edit: Remember, the speed of sending packets for both UDP and TCP is almost same, and depends on the network! However, after handshake is done in TCP, still receiver needs to send the acks, and sender has to wait for ack before sending new batch of data, so still would be a little slower.

A: In general, TCP is marginally slower, despite less header info, because the packets must arrive in order, and, in fact, must arrive.  In a UDP situation, there is no checking of either.


Q: How to have few options as checked in the entity/choice type in symfony I want to render the choice type from entity and its working fine. I want to few options to be checked by default when the form is rendered. For e.g. I have 10 options out of it only 3 options to be checked by default and when it persisted and in edit page whatever is saved to database should be rendered not the default 3 items. In the below title is fieldname
->add('attendee', EntityType::class, [
    'label' => 'Select any information you would like to
    require per Attendee:',
    'multiple' => true,
    'expanded' => true,
    'required' => true,
    'class' => 'AppBundle\\Entity\\Registrant',
    'choice_label' => 'title',
  ])

A: if you have saved some values, then symfony will select the values in the form itself. You don't need to preselect them. You need in your form type the method "configureOptions" like this:
    public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'AppBundle\Entity\MyClass'
    ));
}

If it is not working anyway, post more code.


Q: phonegap Google Analytics plugin for android returns class not found when i call one of the methods Good evening,
I am currently developing an application for android using phonegap  and sencha touch 1.1.
I am having trouble with the GoogleAnalyticsTracker plugin for Android. I followed all the instructions on github on how to import the necessery code for the plugin to work but I am having trouble with initialization.
In my plugins.xml I have added the following line:
< plugin name="Analytics" value="com.phonegap.plugins.analytics.GoogleAnalyticsTracker" />
As indicated in the readme.md file in github. I also added the GoogleAnalyticsTracker.java file inside com/phonegap/plugins/analytics and referenced the js file in my html... every thing seems to work fine except the part where I call the start method with my account id... The method returns the failure callback with error 'Class not found'. any ideas why phonegap cannot find the class specified in the xml?
if you need more info on this please do not hesitate to ask.
Thank you in advance!
PS. i am using phonegap 1.4.1
-L_Sonic

A: I took a look at the src and I see that the PhoneGap.exec calls in analytics.js does not match the plugin name. You have two ways to fix this.

*

*In plugins.xml make the plugin line:
<plugin name="GoogleAnalyticsTracker" value="com.phonegap.plugins.analytics.GoogleAnalyticsTracker"/>

*Or in analytics.js replace all instances of 'GoogleAnalyticsTracker' with 'Analytics'
This is a bug in the way the code is setup in github. You should message the author to get them to fix it.

A: Rather than using the PhoneGap plugin, I would recommend using the Google Analytics SDK for tracking usage of application developed using PhoneGap or any web based mobile app.
Ensure that you respect your users privacy and dont send any other data to Google Analytics.
Besides you should also adhere to Google Analytics privacy policy.
Heres how to do it.
http://www.the4thdimension.net/2011/11/using-google-analytics-with-html5-or.html


Q: XLSX Writer Python- 3 Color Scale with Number as Midpoint I'm trying to conditional formatting in XLSX writer with a 3 color scale with a 0 midpoint value in the middle.  I want all negative values to scale from red (lowest number) to yellow (when the value is zero) and all positive numbers to scale from yellow (at zero) to green (at the highest).
The scaling gets all messed up when I try the following..
Something that would look like the following in Excel:

I can figure out how to do a 3 color scale in XLSX writer, but there doesnt seem to be an option (I can see) for midpoint being a number:
worksheet.conditional_format('G2:G83', {'type': '3_color_scale',
                                     'min_color': "red",
                                     'mid_color': "yellow",
                                     'max_color': "green"})

I then tried to break it down with a criteria with one format applied to values above zero and one below zero
worksheet.conditional_format('G2:G83', {'type': '2_color_scale',
                                    'criteria': '<',
                                    'value': 0,
                                    'min_color': "red",
                                    'max_color': "yellow"})

worksheet.conditional_format('G2:G83', {'type': '2_color_scale',
                                    'criteria': '>',
                                    'value': 0,
                                     'min_color': "yellow",
                                     'max_color': "green"})

But that doesn't seem to work either - if anybody has any ideas.. please let me know.. would really appreciate it.
Complete sample code:
import xlsxwriter

workbook = xlsxwriter.Workbook('conditional_format.xlsx')
worksheet1 = workbook.add_worksheet()

# Add a format. Light red fill with dark red text.
format1 = workbook.add_format({'bg_color': '#FFC7CE',
                           'font_color': '#9C0006'})

# Add a format. Green fill with dark green text.
format2 = workbook.add_format({'bg_color': '#C6EFCE',
                           'font_color': '#006100'})

# Some sample data to run the conditional formatting against.
data = [
[34, 72, -38, 30, 75, 48, 75, 66, 84, 86],
[-6, -24, 1, -84, 54, 62, 60, 3, 26, 59],
[-28, 0, 0, 13, -85, 93, 93, 22, 5, 14],
[27, -71, -40, 17, 18, 79, 90, 93, 29, 47],
[0, 25, -33, -23, 0, 1, 59, 79, 47, 36],
[-24, 100, 20, 88, 29, 33, 38, 54, 54, 88],
[6, -57, -88, 0, 10, 26, 37, 7, 41, 48],
[-52, 78, 1, -96, 26, -45, 47, 33, 96, 36],
[60, -54, -81, 66, 81, 90, 80, 93, 12, 55],
[-70, 5, 46, 14, 71, -19, 66, 36, 41, 21],

]
for row, row_data in enumerate(data):
    worksheet1.write_row(row + 2, 1, row_data)

worksheet1.conditional_format('B2:B12', {'type': '2_color_scale',
                                    'criteria': '<',
                                    'value': 0,
                                    'min_color': "red",
                                    'max_color': "yellow"})

worksheet1.conditional_format('C2:C12', {'type': '2_color_scale',
                                    'criteria': '>',
                                    'value': 0,
                                     'min_color': "yellow",
                                     'max_color': "green"})

worksheet1.conditional_format('C2:C12', {'type': '2_color_scale',
                                    'criteria': '<',
                                    'value': 0,
                                     'min_color': "red",
                                     'max_color': "yellow"})

worksheet1.conditional_format('D2:D12', {'type': '3_color_scale',
                                     'min_color': "red",
                                     'mid_color': "yellow",
                                     'max_color': "green"})

workbook.close()
writer.save()

This is what I get:

As you can see, column B (the first column) has no green
Column C has no red
Column D has 0 as green
Any ideas how to do the 3 step scaling with zero in the middle?
Thanks

A:
I can figure out how to do a 3 color scale in XLSX writer, but there doesnt seem to be an option (I can see) for midpoint being a number:

You can use the min_type, mid_type and max_type parameters to set the following types:
min        (for min_type only)
num
percent
percentile
formula
max        (for max_type only)

See Conditional Format Options
So in your case it should be something like.
worksheet1.conditional_format('D2:D12', {'type': '3_color_scale',
                                         'min_color': "red",
                                         'mid_color': "yellow",
                                         'max_color': "green",
                                         'mid_type': "num"})

However, I'm not sure if that will fix your overall problem. Maybe add that to your example and if it doesn't work then open a second question.
One thing that you will have to figure out is how to do what you want in Excel first. After that it is generally easier to figure out what is required in XlsxWriter.

A: I know this is an old question but I just ran into this problem and figured out how to solve it.
Below is a copy of a utility function I wrote for my work. The main thing is that the min, mid and max types ALL need to be 'num' and they need to specify values for these points.
If you only set the mid type to 'num' and value to 0 then the 3 color scale will still use min and max for the end points. This means that if the contents of the column are all on one side of the pivot point the coloring will in effect disregard the pivot.
from xlsxwriter.utility import xl_col_to_name as index_to_col

MIN_MIN_FORMAT_VALUE = -500
MAX_MAX_FORMAT_VALUE = 500

def conditional_color_column(
        worksheet, df, column_name, min_format_value=None, pivot_value=0, max_format_value=None):
    """
    Do a 3 color conditional format on the column.

    The default behavior for the min and max values is to take the min and max values of each column, unless said value
    is greater than or less than the pivot value respectively at which point the values MIN_MIN_FORMAT_VALUE and
    MAX_MAX_FORMAT_VALUE are used. Also, if the min and max vales are less than or greater than respectively of
    MIN_MIN_FORMAT_VALUE and MAX_MAX_FORMAT_VALUE then the latter will be used

    :param worksheet: The worksheet on which to do the conditional formatting
    :param df: The DataFrame that was used to create the worksheet
    :param column_name: The column to format
    :param min_format_value: The value below which all cells will have the same red color
    :param pivot_value: The pivot point, values less than this number will gradient to red, values greater will gradient to green
    :param max_format_value: The value above which all cells will have the same green color
    :return: Nothing
    """
    column = df[column_name]
    min_value = min(column)
    max_value = max(column)

    last_column = len(df.index)+1
    column_index = df.columns.get_loc(column_name)
    excel_column = index_to_col(column_index)
    column_to_format = f'{excel_column}2:{excel_column}{last_column}'

    if min_format_value is None:
        min_format_value = max(min_value, MIN_MIN_FORMAT_VALUE)\
            if min_value < pivot_value else MIN_MIN_FORMAT_VALUE

    if max_format_value is None:
        max_format_value = min(max_value, MAX_MAX_FORMAT_VALUE)\
            if max_value > pivot_value else MAX_MAX_FORMAT_VALUE

    color_format = {
        'type': '3_color_scale',
        'min_type': 'num',
        'min_value': min_format_value,
        'mid_type': 'num',
        'mid_value': pivot_value,
        'max_type': 'num',
        'max_value': max_format_value
    }
    worksheet.conditional_format(column_to_format, color_format)


Q: multi-select with search ability in angularjs I started angularjs two weeks ago. I should make a multi select input with search ability.
What I made has 2 problems that I can't fix.
first when I search for "a" it won't filter correctly to only show "a" but the other work fine
second it has a bug when I select "a" to "d" and then deselect from "a" to "d" the last 2 won't delete and the second time that I do this it get's worse.

*

*please try to edit my own code if possible because I'm not good at reading other people's code

appreciate any help

var app = angular.module("myApp", []);

app.controller("myCtrl", function ($scope, $http) {

 $scope.selectEnable = false;
 $scope.selectedItems = [];

 $scope.openSelect = function () {
  $scope.selectEnable = !$scope.selectEnable;
 };

 $scope.itemChecked = function (data) {

  data.flag = !data.flag;
  var selected = $scope.datas.indexOf(data);
  var x = $scope.selectedItems.indexOf(data);
  if ((data.flag == true) && (x == -1)) {
   $scope.selectedItems.push(data.item);
  } else {
   $scope.selectedItems.splice(selected, 1);
  }
 };

 $scope.datas = [
  {
   "item": "a",
   /*"category": "x",*/
   "flag": false
  },
  {
   "item": "b",
   /*"category": "y",*/
   "flag": false
  },
  {
   "item": "c",
   /*"category": "x",*/
   "flag": false
  },
  {
   "item": "d",
   /*"category": "y",*/
   "flag": false
  }
 ];

});
ul li {
 list-style: none;
 text-align: center;
}

#category {
 text-align: center;
 background: #ddd;
}

#listContainer {
 width: 20%;
}

span {
 cursor: pointer;
}
<!DOCTYPE html>

 <meta charset="UTF-8">
 <title>Document</title>

 <link rel="stylesheet" href="stylesheet/style.css">

 <input type="text" ng-click="openSelect()">

{{selectedItems.toString()}}

  <input type="text" id="searchField" ng-model="searchField">

     <input type="checkbox" ng-change="itemChecked(data)" name="select" ng-model="selectedItems">
     {{data.item}}

A: Follow these steps:
1- Change your itemChecked function to this
$scope.itemChecked = function(data) {
    var selected = $scope.selectedItems.findIndex(function(itm) {
      return itm == data.item
    });
    if (selected == -1) {
      $scope.selectedItems.push(data.item);
    } else {
      $scope.selectedItems.splice(selected, 1);
    }

    };

2- Add an array for showing data after any filtering. Also add a function which filter your data according to input text:
$scope.filter = function() {
    if (!$scope.searchField) {
      $scope.data2Show = angular.copy($scope.data);
    } else {
      $scope.data2Show = [];
      $scope.data.map(function(itm) {
        if (itm.item.indexOf($scope.searchField) != -1) {
          $scope.data2Show.push(itm);
        }
      });
    }
  };

  $scope.data2Show = [];

Use this array to show items in list:

3- Write a function to check if an item is selected or not and use:
$scope.isChecked = function (data) {
    var selected = $scope.selectedItems.findIndex(function(itm) {
      return itm == data.item;
    });
    if (selected == -1) {
      return false;
    } else {
      return true;
    }
  }

And usage in html :
<input type="checkbox" ng-change="itemChecked(data)" name="select" ng-model="selectedItems" ng-checked="isChecked(data)">

4- Change checkbox ngModels from selectedItems to data.flag
ng-model="data.flag"

Final code:

var app = angular.module("myApp", []);

app.controller("myCtrl", function($scope, $http) {
  $scope.selectEnable = false;
  $scope.selectedItems = [];

  $scope.openSelect = function() {
    $scope.selectEnable = !$scope.selectEnable;
  };

  $scope.itemChecked = function(data) {
    var selected = $scope.selectedItems.findIndex(function(itm) {
      return itm == data.item;
    });
    if (selected == -1) {
      $scope.selectedItems.push(data.item);
    } else {
      $scope.selectedItems.splice(selected, 1);
    }
  };

  $scope.filter = function() {
    if (!$scope.searchField) {
      $scope.data2Show = angular.copy($scope.data);
    } else {
      $scope.data2Show = [];
      $scope.data.map(function(itm) {
        if (itm.item.indexOf($scope.searchField) != -1) {
          $scope.data2Show.push(itm);
        }
      });
    }
  };

  $scope.isChecked = function(data) {
    var selected = $scope.selectedItems.findIndex(function(itm) {
      return itm == data.item;
    });
    if (selected == -1) {
      return false;
    } else {
      return true;
    }
  }

  $scope.data2Show = [];

  $scope.data = [{
      item: "a",
      /*"category": "x",*/
      flag: false
    },
    {
      item: "b",
      /*"category": "y",*/
      flag: false
    },
    {
      item: "c",
      /*"category": "x",*/
      flag: false
    },
    {
      item: "d",
      /*"category": "y",*/
      flag: false
    }
  ];

  $scope.filter();
});
ul li {
  list-style: none;
  text-align: center;
}

#category {
  text-align: center;
  background: #ddd;
}

#listContainer {
  width: 20%;
}

span {
  cursor: pointer;
}

  <meta charset="UTF-8">
  <title>Document</title>

  <link rel="stylesheet" href="stylesheet/style.css">

  <input type="text" ng-click="openSelect()">

{{selectedItems.toString()}}

    <input type="text" id="searchField" ng-model="searchField" ng-change="filter()">

          <input type="checkbox" ng-change="itemChecked(data)" name="select" ng-model="data.flag" ng-checked="isChecked(data)"> {{data.item}}

There are some prepared directives for multi-selecting. for example this one Angular-strap selects


Q: AngularJS : Seqential Promise chain Function one passes value to two and then two passes value to three. Any of these functions could take any amount of time to return data. How can I make them wait for value instead of rushing ahead and printing undefined.
var deferred = $q.defer();

var one = function (msg) {
  $timeout(function () {
    console.log(msg);
    return "pass this to two";
  }, 2000);
};

var two = function (msg) {
  console.log(msg);
  return "pass this to three";
};

var three = function (msg) {
  console.log(msg);
};

deferred.promise
  .then(one)
  .then(two)
  .then(three);

deferred.resolve("pass this to one");

A: You need to return a promise from every function that does something asynchronous.
In your case, your one function returns undefined, while it would need to return the promise that you created for the "pass this to two" value after the timeout:
function one (msg) {
  return $timeout(function () {
//^^^^^^
    console.log(msg);
    return "pass this to two";
  }, 2000);
}

Btw, instead of using var deferred = $q.defer();, the chain is better written as:
one("pass this to one")
  .then(two)
  .then(three);


Q: Angular dynamic form, sub-components not updating top level form As the title suggests, I've created a dynamic form using a mix of tutorials I've read.
I have a parent component which creates a empty form group which I then (try) to populate with sub-groups via child components. These components are passed a reference to the parent form, and the child component then creates its own formgroup and attempts to bind this to the parent.
The form model should then look like the following:
FormGroup
-- FormGroup1
---- FormControl1
---- FormControl2
-- FormGroup2
---- FormControl3
---- FormControl4
However, even thought the lower level form controls all render, the parent form doesn't seem to know they exist. My issue seems like it might be related to Angular 2: How to link form elements across a dynamically created components? but I was unable to figure out what he actually did to fix his issue.
Any thoughts?
See https://stackblitz.com/edit/angular-imi6j6?file=app%2Fapp.component.html for what I'm doing.

A: Wow... I just figured it out.
I was trying to add my subgroups to the parent via just assigning properties, but I should have been using FormGroup.addControl(new <FormGroup>).
Works perfectly now.


Q: type 'ObjectId' is not a subtype of type 'String' of 'value' I am trying to insert a document into my Mongo Database using the package mongo_dart
  var db = await Db.create(MONGO_CONN_STRING);
  await db.open();
  var coll = db.collection('reports');
  await coll.insertOne({
    "username": "Tom",
    "action": "test",
    "dateTime": "today",
  });

Runtime error on line 4
Unhandled Exception: type 'ObjectId' is not a subtype of type 'String' of 'value'

Is it an issue with the package or is something wrong with my code?

A: try this one
var db = await Db.create(MONGO_CONN_STRING);
  await db.open();
  var coll = db.collection('reports');
  await coll.insertOne({
    "username": "Tom",
    "action": "test",
    "dateTime": "today",
  }).toList();

A: Are you using the latest version of the package?
I think your problem is related to this issue in the GitHub Repo of the package but it is closed at Jul 25, 2015.

A: The error is arising because you declared variables db and (collection name) outside the static connect() async function; declare them inside the function.
  var db = await Db.create(MONGO_CONN_STRING);
  await db.open();
  var coll = db.collection('reports');
  await coll.insertOne({
    "username": "Tom",
    "action": "test",
    "dateTime": "today",
  });

static connect() async {
var db = await Db.create(MONGO_CONN_STRING);
  await db.open();
  var coll = db.collection('reports');
  await coll.insertOne({
    "username": "Tom",
    "action": "test",
   "dateTime": "today",
  });
}


Q: How to change permission of a kvm-qemu serial console output log I have a virtual machine with this config to redirect serial console log to another file:
<devices>
   ...
   <console type="pty">
       <target type="sclp"/>
       <log file="/home/nptusk/serial-console.log" append="on"/>
   </console>
</devices>

For automation reasons I want the log to have the permission other than root:root. What can I do to achieve this without using chown afterwards, in other words the log file when generated already has my desired user and group.

A: Kvm deamon is running on root.Otherwise it changes its uid,there is no way to change owner.But you can change its permssion to 665 or 664 so that you can access it,or change its ACL for more security


Q: How load Partial View with JavaScript In my view I have JavaScript to load a partial view.

@using (Html.BeginForm(@MyChoise, "Corr_Exit"))
{
    @Html.AntiForgeryToken()

                    etc...........

I'd load this partial between
 tag

But my code doesn't work. Why?
Someone can help me please?

A: I have used load ajax for this
$('#AREA_PARTIAL_VIEW').load('@Url.Action("Insert_Partial_View","Customers")');


Q: Ansible ec2_vpc_route_table playbook error was: 'dict object' has no attribute subnet I have a previously working piece of Ansible that I've inherited for a previous contractor, and I'm getting an error message that doesn't lead me in the right direction. I have tried searching for a few days now, with no joy, and my colleagues can't figure it out either.
The Ansible in question is :-
- name: Routes | Set up NAT-protected route table
  ec2_vpc_route_table:
    vpc_id: "{{ ec2_vpc_net_reg.vpc.id }}"
    region: "{{ vpc_region }}"
    tags:
      Name: "Internal {{ item.subnet_id }}"
    subnets:
      - "{{ az_to_private_sub[public_subnets_to_az[item.subnet_id]] }}"
      - "{{ az_to_private_data_sub[public_subnets_to_az[item.subnet_id]] }}"
    routes:
      - dest: 0.0.0.0/0
        gateway_id: "{{ item.nat_gateway_id }}"
  loop: "{{ existing_nat_gateways.result|flatten(levels=1) }}"
  #with_items: "{{ existing_nat_gateways.result }}"
  register: nat_route_table
  retry: 2
  delay: 10

And the error message is :-
fatal: [localhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute u'subnet-0facefaceface9'\n\nThe error appears to have been in '/cup/core-kubernetes-linux/ansible/roles/aws_vpc/tasks/routes.yml': line 62, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: Routes | Set up NAT-protected route table\n  ^ here\n"}

I have tried adding extra debug, for az_to_private_sub and public_subnet_to_az, and these look OK. I've tried reading the docs
Can anyone suggest where I should look next?
Thanks!

A: After speaking to a different colleague, they pointed out that the version which works uses Ansible 2.5.5 and I was trying with 2.5.1 also the boto python libraries need to be using the correct version.


Q: Interesting behaviour with infix notation One sometimes try to get away from your girlfriend by hiding behind your computer screen. However, I find that Scala is sometimes exactly like my girl...
This prints the intersection between two lists:
  val boys = List(Person("John"), Person("Kim"), Person("Joe"), Person("Piet"), Person("Alex"))

  val girls = List(Person("Jana"), Person("Alex"), Person("Sally"), Person("Kim"))

  println("Unisex names: " + boys.intersect(girls))

This prints absolutely nothing:
  val boys = List(Person("John"), Person("Kim"), Person("Joe"), Person("Piet"), Person("Alex"))

  val girls = List(Person("Jana"), Person("Alex"), Person("Sally"), Person("Kim"))

  println("Unisex names: " + boys intersect girls)

There are no compiler warnings and the statement prints absolutely nothing to the console. Could someone please explain gently (I have a hangover), why this is so.

A: It gets desugared to this:
println("Unisex names: ".+(boys).intersect(girls))

then according to the -Xprint:typer compiler option it gets rewritten like this:
println(augmentString("Unisex names: ".+(boys.toString)).intersect[Any](girls))

where augmentString is an implicit conversion from type String to StringOps, which provides the intersect method.


Q: iPhone SDK:NSScanner crashing randomly I have an application that scans text from a website in order to get the information and put it into my application. So in this case I'm retrieveing the number of notifications that the user has on facebook. Everything works fine except that the application crashes randomly. This is the code I have for searching for the number inside the text:
   NSScanner *theScanner = [NSScanner scannerWithString:facebookTextF];
NSScanner *theScanner2 = [NSScanner scannerWithString:facebookTextFa];

[theScanner scanUpToString:@"Notifications" intoString:&facebookTextFa] ;
[theScanner scanUpToString:@"\n" intoString:&facebookTextF] ;
NSString *NotificationsValue;
if ([facebookTextF isEqualToString:@"Notifications"]) {
    NotificationsValue = @"0";
    NSLog(@"%@", NotificationsValue);

       } else {
    [theScanner2 scanUpToString:@"Notifications" intoString:nil] ;
    [theScanner2 setScanLocation:([theScanner2 scanLocation] + 13)];
    [theScanner2 scanUpToString:@"\n" intoString:&facebookTextFa] ;

               NSLog(@"%@", facebookTextFa);

                    }

This code works well but just randomly crashes. Here is the crash log I get:
iphone[654:907] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSConcreteScanner setScanLocation:]: Range or index out of bounds'

* First throw call stack:
(0x3361b6c3 0x398b397f 0x3361b5e5 0x34d2632f 0x25147 0x34dbf78b 0x335f09ff 0x335f06b1 0x335ef321 0x3356239d 0x33562229 0x39fad31b 0x3402b8f9 0x22267 0x22208)
libc++abi.dylib: terminate called throwing an exception
This crash occurs randomly no matter what. For example if I leave it running for a while, after 7 minutes is just randomly crashes. Not sure what is wrong.
Thank you for looking. IF you need any more information please let me know.

A: You are getting that error message because (apparently) the string sometimes doesn't have the word "Notifications", so the theScanner2 sets its scan location to the end of the string. Then, when you try to set the scan location 13 characters ahead, it's past the end of the string, and you get an out of range error.

A: Trying to setScanLocation in NSScanner which is out of bound means the end of the string and beyond which doesnot exists by  setting scan location


Q: Parser for Pipfiles (get a list of all packages used in a Pipfile) Is there any parser out there for reading in a Pipfile and returning a list of all packages used in the Pipfile?
If not, how would one go about this? I was thinking a regular expression could do the job, but I am not sufficiently acquainted with the structure of Pipfiles to confirm that is the case.

A: first install pipfile    pip install pipfile.
then just use the parser it provides
from pipfile import  Pipfile
parsed = Pipfile.load(filename=pipfile_path)


Q: Bash Regex to print out the matched string only? Im trying to read a file line by line and trying to match few strings,and im not able to echo the matched line using "$?" im not sure which "$" function to use. can anyone help? i dont want using grep, thanks in advance.
#!/usr/bin/bash
while read EachLine
    do
    if [[ "$EachLine =~ ^Pass: [0-9]\{1,\}" ]]
        then
    echo "$?"
    fi
    done < zoix.progress-N0
exit

A: If you just want to put out the lines that match your pattern in a file, have you tried the following:
grep -E "^Pass: [0-9]+" zoix.progress-N0


Q: hibernate validator, json schema generation and using common constraints We use Spring MVC, Jackson for json, Hibernate ORM. We need to add front end validations. I came across hibernate validator.
We have a set of Domain classes [DO classes] annotated with JPA.
We have another set of POJO classes [DTO classes] annotated for Json binding.
We want to implement infrastructure that does the following:

*

*DTO classes refer to the DO class constraints [where applicable] so that the truth is one place.

*Generate json schema , again by reusing the JPA annotations.

*Validate input to the rest calls.

For example, instead of the following:
PersonDTO{
  @NotNull
    @Size(min=2, max=60)
    private String firstName;
}

How about:
PersonDTO{
   @MapsTo(com.xyz.domain.PersonDO.firstName.Size) // referring to the JPA annotation
   private String firstName;
}

And then, a custom validator figures out the constraints to uphold by looking at the JPA annotation.
Is the strategy I outlined a typical approach? Any feedback or opinions is appreciated. Can you point me to relevant any articles?
Thank you.

A: There is no out-of-the-box functionality for copying constraints from one model to another in Hibernate Validator, but you could implement it yourself using existing APIs.
More specifically, there is an API for retrieving constraint metadata (standardized by Bean Validation) and an API for dynamically putting constraints to your types at runtime (provided by Hibernate Validator). You could use the former to read the constraints of your domain model and drive the creation of equivalent constraints on your DTO model using the latter. For that you'd of course need a strategy for matching corresponding types and properties of your source and target model.


Q: C++ A multiple inheritance pproblem with pure virtual functions I have produced a minimal example to replicate the problem I am seeing with a more complex class hierarchy structure:
#include <string>
#include <iostream>

class A
{
protected:

    virtual
    ~A() = 0;

};

inline
A::~A() {}

class B : public A
{
public:

    virtual
    ~B()
    {
    }

    std::string B_str;
};

class BB : public A
{
public:

    virtual
    ~BB()
    {
    }

    std::string BB_str;
};

class C : public A
{
protected:

    virtual
    ~C()
    {
    }

    virtual
    void Print() const = 0;
};

class D : public B, public BB, public C
{
public:

    virtual
    ~D()
    {
    }
};

class E : public C
{
public:

    void Print() const
    {
        std::cout << "E" << std::endl;
    }
};

class F : public E, public D
{
public:

    void Print_Different() const
    {
        std::cout << "Different to E" << std::endl;
    }

};

int main()
{

    F f_inst;

    return 0;
}

Compiling with g++ --std=c++11 main.cpp produces the error:
error: cannot declare variable ‘f_inst’ to be of abstract type ‘F’

    F f_inst;

note:   because the following virtual functions are pure within ‘F’:

    class F : public E, public D
          ^
note:   virtual void C::Print() const

    void Print() const = 0;
         ^

So the compiler thinks that Print() is pure virtual.
But, I have specified what Print() should be in class E.
So, I've misunderstood some of the rules of inheritance.
What is my misunderstanding, and how can I correct this problem?
Note: It will compile if I remove the inheritance : public D from class F.

A: Currently your F is derived from C in two different ways. This means that an F object has two separate C bases, and so there are two instances of C::Print().
You only override the one coming via E currently.
To solve this you must take one of the following options:

*

*Also override the one coming via D, either by implementing D::Print() or F::Print()

*Make Print non-pure

*Use virtual inheritance so that there is only a single C base.

For the latter option, the syntax adjustments would be:
class E : virtual public C

and
class D : public B, public BB, virtual public C

This means that D and E will both have the same C instance as their parent, and so the override E::Print() overrides the function for all classes 'downstream' of that C.
For more information , look up "diamond inheritance problem".  See also Multiple inheritance FAQ


Q: Recording Xero check payments via payments endpoint - will they automatically match bank statement? I'm trying to work around the Xero API's lack of support for payment via checks.
If I use the payments endpoint to create and apply new payments to existing invoices, and as part of the PUT add the check number to the reference field, does anyone know if that will be automatically matched when the check is cashed and shows up in our bank statement feed? I can't find Xero's internal reconciliation rules detailed anywhere.
Our issue is that we write about 2k checks per month and many have the same amounts, so we rely on the check number to match and reconcile. Currently Xero automatically matches 95%+ of our checks to bank statement lines we get via our bank feed. My concern is that without a check number linked to the API-created payment, Xero won't match checks to the correct bank statement items, and then we've got 2,000 payments that have to each be reconciled by manual searches for the reference number.
I've imported a test CSV bank rec file and that matched 3 of 3 test payments, but need to explore this more using identical amounts. In the demo company I could create 1,000 bill payments, apply 1,000 payments to them, and import 1,000 statement lines and see how the reconciliation screen looks, but wanted to see if someone already knew the answer!
(I believe we'll also lose the ability to quickly search payments via the check register but we may have to accept that. We send our check list to an outside printing/mailing firm so don't actually need to print the checks in Xero.)


Q: convert Json object to java object: The logic I have a json weather API that forecasts five days every three hours. I put part of the json with two forcasts since it is too long and repetitive:
{

    "cod": "200",
    "message": 0.4194,
    "city": {
        "id": 1851632,
        "name": "Shuzenji",
        "coord": {
            "lon": 138.933334,
            "lat": 34.966671
        },
        "country": "JP",
        "population": 0
    },
    "cnt": 40,
    "list": [
        {
            "dt": 1399950000,
            "main": {
                "temp": 287.82,
                "temp_min": 287.82,
                "temp_max": 287.82,
                "pressure": 923.74,
                "sea_level": 1018.93,
                "grnd_level": 923.74,
                "humidity": 100,
                "temp_kf": 0
            },
            "weather": [
                {
                    "id": 501,
                    "main": "Rain",
                    "description": "moderate rain",
                    "icon": "10d"
                }
            ],
            "clouds": {
                "all": 92
            },
            "wind": {
                "speed": 0.51,
                "deg": 226.005
            },
            "rain": {
                "3h": 6
            },
            "sys": {
                "pod": "d"
            },
            "dt_txt": "2014-05-13 03:00:00"
        },
        {
            "dt": 1399960800,
            "main": {
                "temp": 291.36,
                "temp_min": 291.358,
                "temp_max": 291.36,
                "pressure": 921.65,
                "sea_level": 1016.09,
                "grnd_level": 921.65,
                "humidity": 87,
                "temp_kf": 0
            },
            "weather": [
                {
                    "id": 500,
                    "main": "Rain",
                    "description": "light rain",
                    "icon": "10d"
                }
            ],
            "clouds": {
                "all": 20
            },
            "wind": {
                "speed": 0.87,
                "deg": 12.0018
            },
            "rain": {
                "3h": 0.5
            },
            "sys": {
                "pod": "d"
            },
            "dt_txt": "2014-05-13 06:00:00"
        },

My problem is that I do not understand the logic of making java objects. I used jsongen for generating the java objects, but it seems it does not give me the right objects.
by jsongen my java object classes are:
public class Jweather {

        private Number cod;
        private Number message;
        private City city;
        private Number cnt;
        private myList list;
                   ...
                 }

public class City{
    private Coord coord;
    private String country;
    private Number id;
    private String name;
    private Number population;
            ...
           }

public class Coord{
    private Number lat;
    private Number lon;
            ...
           }

public class myList{

    List list = new ArrayList();
    private Number clouds;
    private Number deg;
    private Number dt;
    private Number humidity;
    private Number pressure;
    private Number speed;
    private Temp temp;
    private List weather;
              ...
            }

public class Temp{
    private Number day;
    private Number eve;
    private Number max;
    private Number min;
    private Number morn;
    private Number night;
           ...
         }

public class Weather{
    private City city;
    private Number cnt;
    private String cod;
    private List list;
    private Number message;
            ...
         }

I think myList, temp, weather classes are wrong. Am I write or wrong?
I think list.java should contain dt, main, weather, clouds, wind, rain, sys and dt_txt
and I also need a main.java class including: temp, temp_min, temp_max, pressure, sea_level, grnd_level, humidity and temp_kf
and a cloud.java class including: all
and wind class including: speed, deg
and rain class including:3h
and a sys class including: pob
Any help would be highly appreciated.

A: Based on the JSON you pasted in, I agree that the generated classes don't look correct. For example, morn does not seem to appear in the JSON at all. Did you paste in the entire JSON content that was used to generate the classes?
What are you using to serialize/deserialize the JSON? Jackson is a common framework with which to do that. You would need to define mappers from the beans that store the deserialized JSON to the POJO beans.
I've not used it myself (I use Jackson and create the JSON and POJO beans myself), but based on the json gen doc, it appears that it's intended to generate the JSON-bean side of things. So you would still need to (at least potentially) define your POJO beans (unless they happened to map 100%, which seems unlikely for a variety of reasons, from different JSON property names versus POJO field names, etc.).


Q: NuGet Packages claiming to not be correctly installed I have a project that references
WindowsAzure.ServiceBus

However, when I rebuild the project, I get the error:

1>C:\Users\xyz\documents\visual studio
  2017\Projects\MyProject\Class.cs(1,17,1,27): error
  CS0234: The type or namespace name 'ServiceBus' does not exist in the
  namespace 'Microsoft' (are you missing an assembly reference?)
1>C:\Users\xyz\documents\visual studio
  2017\Projects\MyProject\Class.cs(12,24,12,38): error
  CS0246: The type or namespace name 'EventHubClient' could not be found
  (are you missing a using directive or an assembly reference?)

I've removed and restored the packages directory for the solution, but to no avail.  I've tried re-installing the NuGet packages:
Update-Package -reinstall

Which claimed to successfully restore the package.  I can Build the project successfully, but a Rebuild fails.  Issuing an MSBuild in the command prompt also fails.
Just to alay any theories that there's no using statement, Class.cs:
using Microsoft.ServiceBus.Messaging;

I'm at a loss to how to progress with this; can anyone offer any ideas where to go next?

A: Posting for the points :) (I love them)
Other thing that comes to my mind is to Upgrade your .NET Framework version. If nuget dll was build for higher .NET runtime, there is just a Warning message printed in Output window and Error window stays clear. But Build fails.


Q: How to sync light to the current song with Raspberry Pi? I want to make an LED attached to my Raspberry Pi blink in sync with the music playing on the Raspberry.
The problem is that I don't know how to get the current level of volume of the track which is in line audio. How can I do this?
I use Raspbian.


Q: Wrapping long text into a container, causes overflow Flutter I'm creating a notification center for my application, and it contains a bit of long strings for the title and the body, and it always causes overflow, I've tried using Expanded widgets, and these following stack over flow questions: Question 1, Question 2 But I cannot apply it to my code, here is what it looks like right now:

I get the text from my firebase cloud firestore, and I'm outputting the texts using a listview.
The title text is this: "Allen Indefenzo has rescinded consent for you to access his/her data"
The body text is this : "He/she has removed all your access and you will no longer be able to view / change his data, to have access again ask for the user to give you his/her special code again."
Here is my code:
Container(
        color: Colors.white,
        child: StreamBuilder(
          stream: db
              .collection('users')
              .document(userData.userID)
              .collection('notifications')
              .snapshots(),
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            if (!snapshot.hasData) {
              return Center(
                child: CircularProgressIndicator(),
              );
            }
            if (snapshot.data.documents.length != 0) {
              return ListView.builder(
                itemCount: snapshot.data.documents.length,
                itemBuilder: (BuildContext context, int index) {
                  return Container(
                    child: Row(
                      children: <Widget>[
                        Container(
                          height: 150,
                          width: 100,
                          child: Image(
                            image: NetworkImage(
                                snapshot.data.documents[index]['dpURL']), fit: BoxFit.contain,
                          ),
                        ),
                        Column(
                          children: <Widget>[
                            Container(
                              height: 50,
                              width: MediaQuery.of(context).size.width * 0.8,
                              child:
                                  Text(snapshot.data.documents[index]['title']),
                            ),
                            Container(
                              height: 50,
                              width: MediaQuery.of(context).size.width * 0.8,
                              child:
                                  Text(snapshot.data.documents[index]['body']),
                            ),
                          ],
                        ),
                      ],
                    ),
                  );
                },
              );
            }
          },
        ),
      ),

Any help is appreciated and if you can explain it would be amazing! Thank you so much!

A: try to wrap your Column inside Expanded,
 Container(
              child: Row(
                children: <Widget>[
                  Container(
                    height: 150,
                    width: 100,
                    child: Image(
                      image: NetworkImage(
                          'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcQLBtBU3nUOK7osT41ZsQhP4VBV7fd9euqXvXVKQH0Q7bl4txeD'),
                      fit: BoxFit.contain,
                    ),
                  ),
                  Expanded(
                    child: Column(
                      children: <Widget>[
                        Text(
                            'Reallly looooooooooooooooooooooooooooooong textttttttttttttttttttttttttttttttttttttttttttttttt'),
                        Text(
                            'Reallly looooooooooooooooooooooooooooooong textttttttttttttttttttttttttttttttttttttttttttttttt'),
                      ],
                    ),
                  ),
                ],
              ),
            );

output:

Additionally if you want to limit lines of Text use,
  Text(
'Reallly looooooooooooooooooooooooooooooongtextttttttttttttttttttttttttttttttttttttttttttttttt',
    maxLines: 2,
    overflow: TextOverflow.ellipsis,
                        ),

Output:

A: Just wrap your column inside expanded widget
Expanded(child:
               Column(
                          children: <Widget>[
                            Container(
                              height: 50,
                              width: MediaQuery.of(context).size.width * 0.8,
                              child:
                                  Text(snapshot.data.documents[index]['title']),
                            ),
                            Container(
                              height: 50,
                              width: MediaQuery.of(context).size.width * 0.8,
                              child:
                                  Text(snapshot.data.documents[index]['body']),
                            ),
                          ],
      ),
),

Expanded widget is useful when you want to fill all the remaining space when a column or row widget have 2 or more child widgets. so wrapping a child inside an expanded widget will fill up the remaining space accordingly.

A: return Container(child: Row(
                            children: <Widget>[
                              Container(
                                height: 150,
                                width: 100,
                                child: Image(
                                  image: NetworkImage(snapshot.data.documents[index]['dpURL']), fit: BoxFit.contain,
                                ),
                              ),
                             new Expanded(
                                child: Column(
                                  children: <Widget>[
                                    Padding(
                                      padding: const EdgeInsets.all(8.0),
                                      child: TitleText(
                                        text:snapshot.data.documents[index]['title'] ,
                                        maxLine: 5,
                                      ),
                                    ),
                                    Container(
                                      height: 50,
                                      width: MediaQuery.of(context).size.width * 0.8,
                                      child: TitleText(
                                          text:snapshot.data.documents[index]['body']),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        );


Q: How to insert an image in the linear layout? I just wanted to insert an image in linear layout similar to this
Can anyone help me with this???

A: You are probably looking for ImageButton since your picture shows something similar to that.
Alternatively, take a look at ImageView

A: set layout's orientation to horizontal, then add 4 images in xml, one after another, add ids like image1, image2 etc, then call them in your onCreate like ImageView image
ImageView image1 = (ImageView) findViewById(R.id.image1)

and so on, then you can either set "src" attribute in yoru xml or say image1.setImageBitmap or any other method available in ImageView class to set the image you want from your res/drawable/

A: you can use ImageButton in horizontal LinearLayout
make background of the ImageButton @null
then put the margins between them


Q: How could I implement a trap to indicate ASP.Net Session expiry I need to create a user login/logout/Session expiry tracking page(ASP.Net)..
It is obvious that I can invoke my tracking page when user logs in and logs out..
How do I detect session expirey ?

A: Your most obvious way in a stateful app is to assume that any hit on a non-login page without being logged in implies that the session has expired.

A: use the Session_End event in Global.asax. Keep in mind this event does not fires when sessions are persisted outside of the process (in SQL for example)


Q: CSS3 Animation not working on chrome or safari I'm trying to get a simple css3 animation to work. Till now it works fine in Firefox, but not in Chrome or Safari.
I added @-webkit-keyframes so it should work on all browsers (maybe not in IE).
This is my css:
.myFace {
        display: block;
        width: 266px;
        height: 266px;
        background: url(http://cl.ly/image/443k292m2C24/face2x.png) no-repeat 0 0;}
.myFace:hover {
    animation: threesixty 1s;
    -webkit-animation: threesixty 1s; /* Safari and Chrome */
}
@keyframes threesixty {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}
@-webkit-keyframes threesixty {
    0% {transform: rotate(0deg);}
    100% {transform: rotate(360deg);}
}

This is what i'm trying to do -
http://jsfiddle.net/dansku/JTcxH/4/

A: I believe that's because inside your keyframes, you're using transform:, which will work for IE10, Firefox and Opera, but haven't also got the webkit equivalent - specifically -webkit-transform which will work for Chrome and Safari.
@keyframes threesixty {
  0% {
    transform: rotate(0deg);
    -webkit-rotate(0deg);
    -ms-transform:rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
    -webkit-rotate(360deg);
    -ms-transform:rotate(360deg);
  }
}
@-webkit-keyframes threesixty {
  0% {
    transform: rotate(0deg);
    -webkit-rotate(0deg);
    -ms-rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
    -webkit-rotate(360deg);
    -ms-rotate(360deg);
  }
}

You should also include the -ms- prefix as I've shown above, for versions of IE before 10.

A: From the MDN article on transforms:
Webkit browsers (Chrome, Safari) still needs the -webkit prefix for transforms, while Firefox, as of version 16, does not.
This code should do the job for you:
@keyframes threesixty {
  0% {
    transform: rotate(0deg);
    -webkit-transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
    -webkit-transform: rotate(360deg); }
  }
@-webkit-keyframes threesixty {
  0% {
    transform: rotate(0deg);
    -webkit-transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
    -webkit-transform: rotate(360deg);
  }
}

For Opera and IE9+ support, use -o and -ms prefixes respectively. (IE10 does not require the prefix)


Q: Website images overlapping(Shopify) I am using shopify and added a section using my own html into it. I added the picture of the lipstick, the face and the one under those that is being overlapped by one of the products from the 'featured products' section that comes built into the theme.  I was wondering how I would be able to fix this? Do I need to go in and fix something with liquid?
I have solved this issue by using a table in html instead; Ive provided my solution for future readers.
HTML

A: Add padding to the photographs. Padding (e.g. of 10px) will add a 10px white space on all sides (unless you specify padding-top or padding-bottom etc.. which you can do if you prefer. ) You could also add a margin to the container. A negative margin-top will  shift the appearance of the position of the container upwards, likewise it can be applied to the photographs as well. (Positive or negative)
Hope this helps
Rachel


Q: Response to preflight request doesn't pass access control check with Angular 2 I am trying to connect to an API using Angular 2. I am unable to connect to it as it is giving me a OPTIONS error as well as:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 500.
I have the Google Chrome plugin as well as the headers. Here is the code
map.service.ts
import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class MapService {

    private headers = new Headers();
    constructor(private http: Http) { }

    getMarkers() {
        this.headers.append("Access-Control-Allow-Origin", '*');
        this.headers.append("Access-Control-Allow-Methods", 'GET, POST, PATCH, PUT, DELETE, OPTIONS');
        this.headers.append("Access-Control-Allow-Headers", 'Origin, Content-Type, X-Auth-Token');
        this.headers.append("Authorization", 'Bearer ' + 'mysecretcode');
        return this.http.get('https://api.yelp.com/v3/businesses/search?location=suo&limit=50', { headers: this.headers})
            .map(response => response.json());
    }

}

map.component.ts
import { Component } from '@angular/core';
import { OnInit } from '@angular/core';

import { Marker } from '../../models/map/marker';
import { MapService } from '../../services/map/map.service';
import {Observable} from 'rxjs/Rx';
import {Http, Response, Headers } from '@angular/http';

@Component({
    moduleId: module.id,
    selector: 'map-view',
    templateUrl: 'map.component.html',
    styleUrls: ['map.component.css'],
})

export class MapComponent {

    marker: Object;

    constructor(mapService: MapService) {
        mapService.getMarkers()
            .subscribe(
                marker => this.marker = marker,
                error => console.error('Error: ' + error),
                () => console.log('Completed!')
            );
    }

I understand that this is most likely a problem with CORS. Is this something i can do to fix or is this on yelps end?
EDIT:
Here is one of the errors:
Error: Response with status: 0  for URL: null(anonymous function) @ map.component.ts:24SafeSubscriber.__tryOrUnsub @ Subscriber.ts:238SafeSubscriber.error @ Subscriber.ts:202Subscriber._error @ Subscriber.ts:139Subscriber.error @ Subscriber.ts:109Subscriber._error @ Subscriber.ts:139Subscriber.error @ Subscriber.ts:109onError @ http.umd.js:1186ZoneDelegate.invokeTask @ zone.js:262onInvokeTask @ core.umd.js:7768ZoneDelegate.invokeTask @ zone.js:261Zone.runTask @ zone.js:151ZoneTask.invoke @ zone.js:332

A: The reason for pre-flight failing is a standard problem with CORS:
How does Access-Control-Allow-Origin header work?
It is fixed by having server to set correct Access-Control-Allow-Origin.
However, the root cause of your problem could be in misconfiguration of your server or your client, since 500 is the server internal error. So it might not be accessing intended server code, but some generic handler in apache or whatever is hosting the service. Most of the generic error handlers dont provide CORS support as default.
Note, if you are using REST API, 500 is not a code you should see in a successful API use scenario. It means that the server is not capable of handling the request properly.
Maybe this link would have relevant information:
EXCEPTION: Response with status: 0 for URL: null in angular2


Q: How to scrape latitude longitude from java script I am fairly new to BeautifulSoup4 and am having trouble extracting latitude and longitude values out of javascript. The file is quite long and I have to prepare data frame from all the latitude longitudes
The Java script file will have strings like these:
var marker_9795626cfd584471ab4406d756a00baf = L.marker([19.041691972000024, 72.85052482000003],{}).addTo(feature_group_ad623471194f451d9f1cf7fc718747c5);

The marker id, here, would be - 9795626cfd584471ab4406d756a00baf
The latitude would be - 19.041691972000024
And the longitude would be - 72.85052482000003
How to extract marker id, latitude and longitude out of the strings using BeautifulSoup.

A: if all you need is to isolate those 2 numbers from that string try this:
def parse(text):
   return [float(i) for i in text.split('[', 1)[1].split(']', 1)[0].split(', ')]

long_lat = parse(your_string_var)

EDIT:
oh and to get the id something like this should do:
def parse2(text):
   return text.split('_', 1)[1].split(' ', 1)[0]

id = parse2(your_string_var)

A: This is Javasascript script, so BeautifulSoup won't execute/parse it. You can use re module to get the information.
For example:
import re
txt = '''var marker_9795626cfd584471ab4406d756a00baf = L.marker([19.041691972000024, 72.85052482000003],{}).addTo(feature_group_ad623471194f451d9f1cf7fc718747c5);'''

marker_id, lat, lon = re.search(r'marker_([a-f\d]+).*?\[(.*?), (.*?)\]', txt).groups()

print(marker_id)
print(lat)
print(lon)

Prints:
9795626cfd584471ab4406d756a00baf
19.041691972000024
72.85052482000003

EDIT: To parse the variables from file, you can use this script:
import re

with open('<YOUR FILE>', 'r') as f_in:
    for line in f_in:
        m = re.search(r'marker_([a-f\d]+).*?\[(.*?), (.*?)\]', line)
        if m:
            marker_id, lat, lon = m.groups()
            print(marker_id, lat, lon)

EDIT2: New version:
import re

with open('<YOUR FILE>', 'r') as f_in:
    data = f_in.read()

for marker_id, lat, lon in re.findall(r'marker_([a-fA-F\d]+).*?\[(.*?),\s*(.*?)\]', data):
    print(marker_id, lat, lon)


Q: Sphinx MVA sql_attr_multi results always on first field in FACET Query I am trying to achieve a filter in Sphinx so that I can filter out the results from two MVA attributes (what I need is a double condition, but since MVA is only 2 fields..) from the same joined table, but whatever I do, It seems that I keep getting the same results since there is always a match on the first field in the multi attribute?
Maybe there's another solutions but I can't seem to find out how to get my desired result, I got to simplify 4 tables: PRODUCT, CATEGORY, PRICE and POSITION.
Data set-up
Below a sample of the data structure:
PRODUCT
+------+-------------+-----------------+---------------+
|  ID  | CATEGORY_ID | MANUFACTURER_ID |     TITLE     |
+------+-------------+-----------------+---------------+
| 1000 |        1000 |            1000 | Apple iPhone  |
| 1001 |        1000 |            1000 | Apple iPad    |
| 1002 |        1000 |            1000 | Apple iPod    |
| 1003 |        1001 |            1001 | Do not show   |
+------+-------------+-----------------+---------------+

CATEGORY
+------+-------+
|  ID  | TITLE |
+------+-------+
| 1000 | Apple |
| 1001 | Other |
+------+-------+

PRICE
+------+--------+---------+
|  ID  | USERID |  PRICE  |
+------+--------+---------+
| 1000 |   1000 |  359.00 |
| 1001 |   1001 | 1058.30 |
| 1002 |   1002 | 1078.00 |
| 1003 |   1003 | 1160.45 |
| 1004 |   1004 | 1180.00 |
| 1005 |   1000 | 1190.00 |
| 1006 |   1000 |  228.76 |
+------+--------+---------+

POSITION
+------+------------+--------+------+
|  ID  | PRODUCT_ID | USERID | RANK |
+------+------------+--------+------+
| 1000 |       1000 |   1000 |    1 |
| 1001 |       1001 |   1001 |    1 |
| 1002 |       1001 |   1002 |    2 |
| 1003 |       1001 |   1003 |    3 |
| 1004 |       1001 |   1004 |    4 |
| 1005 |       1001 |   1000 |    5 |
| 1006 |       1002 |   1000 |    1 |
+------+------------+--------+------+

Sphinx Set-up:
source product
{
        type                            = mysql

        sql_host                        = localhost
        sql_user                        = ...
        sql_pass                        = ...
        sql_db                          = ...

        sql_query_pre                   = SET NAMES utf8
        sql_query                       = SELECT P.ID AS ID, C.ID AS SEARCH_CAT_ID, P.CATEGORY_ID, P.MANUFACTURER_ID, P.TITLE AS TITLE_SORT FROM CATEGORY C, PRODUCT P WHERE P.CATEGORY_ID=C.ID
        sql_attr_uint                   = CATEGORY_ID
        sql_attr_uint                   = MANUFACTURER_ID
        sql_attr_string                 = TITLE_SORT
        sql_attr_multi                  = uint POS_RANK from query; SELECT PRODUCT_ID, RANK FROM POSITION
        sql_attr_multi                  = uint POS_USERID from query; SELECT PRODUCT_ID, USERID FROM POSITION
}
index product
{
        source                   = product
        path                     = ...
        docinfo                  = extern
        min_word_len             = 1
}

MySQL Dump:
CREATE TABLE IF NOT EXISTS `CATEGORY` (
  `ID` int(11) NOT NULL,
  `TITLE` varchar(255) NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `CATEGORY` (`ID`, `TITLE`) VALUES
(1000, 'Apple'),
(1001, 'Other');

CREATE TABLE IF NOT EXISTS `POSITION` (
  `ID` int(11) NOT NULL,
  `PRODUCT_ID` int(11) NOT NULL,
  `USERID` int(11) NOT NULL,
  `RANK` int(11) NOT NULL,
  PRIMARY KEY (`ID`),
  KEY `USERID` (`USERID`),
  KEY `PRODUCT_ID` (`PRODUCT_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `POSITION` (`ID`, `PRODUCT_ID`, `USERID`, `RANK`) VALUES
(1000, 1000, 1000, 1),
(1001, 1001, 1001, 1),
(1002, 1001, 1002, 2),
(1003, 1001, 1003, 3),
(1004, 1001, 1004, 4),
(1005, 1001, 1000, 5),
(1006, 1002, 1000, 1);

CREATE TABLE IF NOT EXISTS `PRICE` (
  `ID` int(11) NOT NULL,
  `USERID` int(11) NOT NULL,
  `PRICE` decimal(9,2) NOT NULL,
  PRIMARY KEY (`ID`),
  KEY `USERID` (`USERID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `PRICE` (`ID`, `USERID`, `PRICE`) VALUES
(1000, 1000, '359.00'),
(1001, 1001, '1058.30'),
(1002, 1002, '1078.00'),
(1003, 1003, '1160.45'),
(1004, 1004, '1180.00'),
(1005, 1000, '1190.00'),
(1006, 1000, '228.76');

CREATE TABLE IF NOT EXISTS `PRODUCT` (
  `ID` int(11) NOT NULL,
  `CATEGORY_ID` int(11) NOT NULL,
  `MANUFACTURER_ID` int(11) NOT NULL,
  `TITLE` varchar(255) NOT NULL,
  PRIMARY KEY (`ID`),
  KEY `CATEGORY_ID` (`CATEGORY_ID`),
  KEY `MANUFACTURER_ID` (`MANUFACTURER_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `PRODUCT` (`ID`, `CATEGORY_ID`, `MANUFACTURER_ID`, `TITLE`) VALUES
(1000, 1000, 1000, 'Apple iPhone'),
(1001, 1000, 1000, 'Apple iPad'),
(1002, 1000, 1000, 'Apple iPod'),
(1003, 1001, 1001, 'Do not show');

ALTER TABLE `POSITION`
  ADD CONSTRAINT `POSITION_ibfk_1` FOREIGN KEY (`PRODUCT_ID`) REFERENCES `POSITION` (`ID`) ON DELETE CASCADE;

ALTER TABLE `PRODUCT`
  ADD CONSTRAINT `PRODUCT_ibfk_1` FOREIGN KEY (`CATEGORY_ID`) REFERENCES `CATEGORY` (`ID`) ON DELETE CASCADE;

Test 1
SphinxQL Query for filter USERID:
SELECT ID FROM product WHERE MATCH('1000') AND POS_USERID IN (1000) ORDER BY WEIGHT() DESC LIMIT 0,20 FACET POS_RANK LIMIT 5;

Result for USERID (first set seems OK this time, second returns everything):
+------+
|  id  |
+------+
| 1000 |
| 1001 |
| 1002 |
+------+

+----------+----------+
| pos_rank | count(*) |
+----------+----------+
|        5 |        1 |
|        4 |        1 |
|        3 |        1 |
|        2 |        1 |
|        1 |        3 |
+----------+----------+

What I expected:

*

*Product ID (1000,1001,1002)

*Position Rank (1 with count 3, 5 with count 1)

Test 2
SphinxQL Query for filter USERID 1000 and RANK 5:
SELECT ID FROM product WHERE MATCH('1000') AND POS_USERID IN (1000) AND POS_RANK IN (5) ORDER BY WEIGHT() DESC LIMIT 0,20 FACET POS_RANK LIMIT 5;

Result for USERID and RANK (first set seems OK this time, second returns everything):
+------+
|  id  |
+------+
| 1001 |
+------+

+----------+----------+
| pos_rank | count(*) |
+----------+----------+
|        5 |        1 |
|        4 |        1 |
|        3 |        1 |
|        2 |        1 |
|        1 |        1 |
+----------+----------+

What I expected:

*

*Product ID (1001)

*Position Rank (5 with count 1)

Test 3
SphinxQL Query for filter USERID 1000 and RANK 4:
SELECT ID FROM product WHERE MATCH('1000') AND POS_USERID IN (1000) AND POS_RANK IN (4) ORDER BY WEIGHT() DESC LIMIT 0,20 FACET POS_RANK LIMIT 5;

Result for USERID and RANK (first stil returns product, second returns everything):
+------+
|  id  |
+------+
| 1001 |
+------+

+----------+----------+
| pos_rank | count(*) |
+----------+----------+
|        5 |        1 |
|        4 |        1 |
|        3 |        1 |
|        2 |        1 |
|        1 |        1 |
+----------+----------+

What I expected:

*

*Product ID (empty set)

*Position Rank (empty set)

I hope you guys understand what I am trying to achieve and can help me out?