Q: How to structure BEM modifiers with nested elements in SASS SASS + BEM is pretty much a match made in heaven most of the time, but a common struggle of mine is understand how to best define BEM modifiers on an element that affects it's child elements while using SASS parent selectors.
I have the following component defined in SASS using BEM style syntax:
.card {
  background-color: #FFF;

  &__value {
    font-size: 2em;
    color: #000;
  }
}

This works well because of SASS's parent selector. It keeps relevant code organized and self-contained.
But when I need to add a modifier that alters a child element using a parent selector, the idea quickly falls apart:
.card {
  padding: 2em;

  &__value {
    font-size: 1.5em;
    color: #000;
  }

  &--big {
    padding: 2.5em;

    &__value {          // Is this going to work?
      font-size: 3em;
    }
  }
}

Nope. It generates this:
.card {
  padding: 2em;
}
.card__value {
  font-size: 1.5em;
  color: #000;
}
.card--big {
  padding: 2.5em;
}
.card--big__value {  // Wrong
  font-size: 3em;
}

It would make more sense to somehow get this selector:
.card--big .card__value {
  font-size: 3em;
}

The reason for this, is so you can simply add a modifier to the top level element and have it affect any or all of the child elements.
I've tried a couple approaches:
Use two structures
.card {
  padding: 2em;

  &__value {
    font-size: 1.5em;
    color: #000;
  }
}

.card--big {
  padding: 2.5em;

  &__value {
    font-size: 3em;
  }
}

This works (especially in this simplified demonstration) but in a more complicated set of components with many modifiers this can be a potential pain to maintain and keep bug free. Also, it would nice to continue to use SASS parent selectors if possible.
Use a variable for the element
.card {
  $component: &;  // Set the variable here

  padding: 2em;

  &__value {
    font-size: 1.5em;
    color: #000;
  }

  &--big {
    padding: 2.5em;

    #{$component}__value {  // Use it here
      font-size: 3em;
    }
  }
}

This works well. But it seems kind of silly to have to define the element as a variable. Maybe it's the only real way to do this... I'm not sure. Are there better options to how to structure this?

A: Why not just do this?
.card {
  padding: 2em;

  &__value {
    font-size: 1.5em;
    color: #000;
  }

  &--big {
    padding: 2.5em;
  }

  &--big &__value {
    font-size: 3em;
  }
}

A: You can split up the modifiers in a different structure, but nested within the .card selector, like this:
.card {
  padding: 2em;

  &__value {
    font-size: 1.5em;
    color: #000;
  }

  &--big {
    padding: 2.5em;
  }

  &--big &__value {
    padding: 2.5em;
  }
}

Which will in turn produce this:
.card {
  padding: 2em;
}
.card__value {
  font-size: 1.5em;
  color: #000;
}
.card--big {
  padding: 2.5em;
}
.card--big .card__value {
  padding: 2.5em;
}

I think this is an almost perfect way, although its not perfectly nested
I hope this was a help!

A: I just found a much better way to achieve this with sass, by using a variable to store the value of the parent selector you can use it at any level of nesting!
For example here I am storing the .card selector in the $this variable, and reusing it like this #{$this}
So this code
.card {
  padding: 2em;

  &__value {
    font-size: 1.5em;
    color: #000;
  }
  $this: &;

  &--big {
    padding: 2.5em;

    #{$this}__value {
      font-size: 3em;
    }
  }
}

will compile to
.card {
  padding: 2em;
}
.card__value {
  font-size: 1.5em;
  color: #000;
}
.card--big {
  padding: 2.5em;
}
.card--big .card__value {
  font-size: 3em;
}

This answer was inspired by this article on css-tricks. Thanks to Sergey Kovalenko

A: There is another pattern you could use here.
This will:
 - separate actual card modifier from its elements' modifiers
 - will keep the modified styles within the same elements' selector so you don't need to scroll your code up and down to see what is being modified
 - will prevent more specific rules from appearing above less specific rules, if that's your thing
Here's an example:
// scss
.card {
  $component: &;

  padding: 2em;

  &--big {
    padding: 2.5em;
  }

  &__value {
    font-size: 1.5em;
    color: #000;

    #{$component}--big & {
      font-size: 3em;
    }
  }
}

/* css */
.card {
  padding: 2em;
}
.card--big {
  padding: 2.5em;
}
.card__value {
  font-size: 1.5em;
  color: #000;
}
.card--big .card__value {
  font-size: 3em;
}

A: You can do this by adding ONE character, no variables or mixins are needed.
&--big { becomes &--big & {:
.card {
  padding: 2em;

  &__value {
    font-size: 1.5em;
    color: #000;
  }

  &--big & {
    padding: 2.5em;

    &__value {          // Is this going to work? (yes!)
      font-size: 3em;
    }
  }
}

A: Going through the same issue I've build a library called Superbem which is basically a set of SCSS mixins that help you write BEM declarative way. Take a look:
@include block(card) {
    padding: 2em;

    @include element(value) {
        font-size: 1.5em;
        color: #000;
    }

    @include modifier(big) {
        padding: 2.5em;

        @include element(value) {
            font-size: 3em;
        }
    }
}

Gives you:
.card, .card--big {
    padding: 2em;
}

.card__value {
    font-size: 1.5em;
    color: #000;
}

.card--big {
    padding: 2.5em;
}

.card--big .card__value {
    font-size: 3em;
}

Hope you'll find this useful!

A: Your solution looks quite fine but you may also try @at-root.

A: .card {
  padding: 2em;

  &__value {
    font-size: 1.5em;
    color: #000;
  }

  &--big {
    padding: 2.5em;

    &__value {          // Is this going to work?
      font-size: 3em;
    }
  }
}

You can achieve the result You wanted by the following :
.card {
  padding: 2em;

  &__value {
    font-size: 1.5em;
    color: #000;
  }

  &--big {
    padding: 2.5em;

    .card {
       &__value {          // this would work
          font-size: 3em;
       }
    }
  }
}


Q: How to using JPQL to join two tables I made employee table and position table.Every Employees have one position.I want join two table ,but I don't know how to write code.
Employee.java
@Table(name = "employees")
@NamedQueries({
        @NamedQuery(name = "getAllEmployees", query = "SELECT e FROM Employee AS e ORDER BY e.emp_id DESC")
})
@Entity
public class Employee {
    @Id
    @Column(name = "emp_id", length = 8)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer emp_id;

    @Column(name = "emp_name", length = 20, nullable = false)
    private String emp_name;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinTable(name = "position", joinColumns = {
            @JoinColumn(name = "emp_id", referencedColumnName = "emp_id") }, inverseJoinColumns = {
                    @JoinColumn(name = "pos_id", referencedColumnName = "pos_id") })
    private Position pos;

    ～setter/getter～

Position.java
@Table(name = "position")

@Entity
public class Position {
    @Id
    @Column(name = "pos_id")
    private Integer pos_id;

    @Column(name = "pos_name", length = 30, nullable = false)
    private String pos_name;

    @OneToOne(mappedBy = "pos")
    private Employee employee;

    ～setter/getter～

A: Employee.java
@Entity
public class Employee {
    @Id
    @Column(name = "emp_id", length = 8)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer emp_id;

    @Column(name = "emp_name", length = 20, nullable = false)
    private String emp_name;

    @ManyToOne
    private Position position;

Position.java
@Entity
public class Position {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int pos_id;

    @Column(name = "pos_name", length = 16)
    private String pos_name;

    @OneToMany(mappedBy = "position")
    private List<Employee> employees;

Thank you.I can join two tables!


Q: Compatibility View and its importance I have just finished the layout for my website, and it is working perfectly fine in all browsers (Opera, Safari, Chrome, IE 7, 8, 9, 10 (both), and several others) - but this time around, the Compatibility View button in the address bar of IE 10 is appearing. This has not happened for a very long time and it's really annoying me.
I don't want the Compatibility View button to display at all. It sends a bad message to viewers/visitors. In this case, I have tested my whole site on different computers all running different browsers and different versions of browsers and I have not noticed a single problem.
Why is the Compatibility View button appearing if there are no issues?
Here's the problem, and like I said, everything works fine - except for when I turn ON Compatibility View in IE 10. When I turn it ON, the only things in my entire website I can see is my logo, and a little image in the top right corner of the page (but they're positioned exactly where I wanted them). What gives?
There's nothing wrong with the code - seriously. i've had it validated several times, all AJAX stuff works like a charm, and I really tried so hard to find a problem and I even intentionally tried to mess it up but it's working really well. The positioning of everything is spot on.
So what's the deal with this Compatibility View junk? Why is it there - on a website that does not have any issues? And, most importantly, is it important that I make sure my website works well while in Compatibility View even though it works perfectly when it's off and even though it works perfectly in all the major browsers - and then some?

A: First and foremost, you can force IE not to display the Compatibility View button simply by adding this to your page head:
<meta http-equiv="X-UA-Compatible" content="IE=edge">

As for your other questions:

Why is the Compatibility View button appearing if there are no issues?

So what's the deal with this Compatibility View junk? Why is it there - on a website that does not have any issues?

It's there in case a site, typically one that was written many years ago, fails to work in a newer version of IE, to allow users to view or IE to display it in a legacy rendering mode where it will hopefully work better.
Additionally, it's there by default because legacy sites will not even have the meta tag above to begin with. In order for the button to display when viewing existing sites without having to update their code, it's only logical to make it an opt-out feature instead, by having the developer add it to new code to tell newer versions of IE to hide the button when it's not needed.

And, most importantly, is it important that I make sure my website works well while in Compatibility View even though it works perfectly when it's off and even though it works perfectly in all the major browsers - and then some?

Compatibility View is meant for websites that were specifically designed for legacy browsers, and as such, depend on legacy rendering quirks not present in more recent browsers which may cause "problems" in those more recent browsers.
Without seeing your site, we won't be able to determine why it works in IE7 and IE10 in IE7 mode but not Compatibility View, but if it works well in newer versions of IE, you do not need to ensure that it works well in Compatibility View. Using the meta tag above to hide the button when it's not necessary will suffice.

A: Can you provide us a link to your site? I always use
<!DOCTYPE html>

on the first line of the HTML document. This is a universal switch to the latest rendering mode in all modern browsers. Use BoltClock's solution to hide a compatible view button in IE's address bar. I would prefer a HTTP header rather than HTML meta tag, because the meta tag causes parser switch and reset.


Q: Make my jQuery accordion responsive I have created this jQuery accordion and want to make it responsive on smaller screens. I know there is a way to make this responsive using CSS media query but I am wondering if there is a better way of making it responsive using JS. I am also hoping that the tabs sit on top of each other on smaller screens. Can anyone please help me.
Also please feel free to suggest anything that could improve this code.

$(document).ready(function(){

 var tabButton = ".allContainer .tabsList .tab-wrapper .tabButton";
 var tabButtonCurrent = ".allContainer .tabsList .tab-wrapper > .curr";
 var tabContent = ".allContainer .tabsList .tab-content .curr";
    var tabContentParent = ".allContainer .tabsList .tab-content";

 $(tabButton).on('click', function(){

  $(tabButtonCurrent).removeClass('curr');
  $(this).addClass('curr');

  var panelId = $(this).attr('rel');

  $(tabContent).hide(500, showClickedSlider);

  function showClickedSlider(){
  $(this).removeClass('curr');

  $(panelId).show(500, function(){
  $(this).addClass('curr');
  });
  }
 });
});
.tabList {
    width:100%;
}
.tab-wrapper {
    float:left;
    margin-right:10px;
    background-color:olivedrab;
    height:200px;
}
.tabButton {
 float:left;
 margin-right:1%;
    min-width: 50px;
    height:200px;
 background-color:orange;
 cursor:pointer;
}
.tab-content {
    overflow:hidden;
    float:left;
    width:70%;
}
.tab-content > div {
    display: none;
 width:350px;
}
.tab-content .curr {
    display: block !important;
}

tab1

content 01

tab2

content 02

tab3

content 03


Q: How do I filter based on dict contents in a DictField on a model using the Django-MongoDB Engine? Given the models:
class Post(models.Model):
    datas = ListField(EmbeddedModelField('Comment'),blank=True)
    data = DictField()

class Comment(models.Model):
    name = models.CharField(max_length=255)
    date = DateField(blank=True, null=True)

If we set the data variable to:
{'key':'value'}

Is there a way to filter for Posts with key=='value'?
As an alternative, what about with embedded documents?  Is there a way to filter for a Post that has an author with the name 'Ralph'?
It seems like this must be possible, or else this ORM is far too limiting to be useful, which seems unlikely.

A: I recommend trying it out for yourself, but the comment in the code

 #TODO/XXX: Remove as_lookup_value() once we have a cleaner solution
        # for dot-notation queries

suggests that it does. I've ever only really used lists.

A: You can filter for a Post that has an author named "Ralph" using raw queries:
Post.objects.raw_query({'author.name': "Ralph"})


Q: Double quotes in a string C# I'm trying to read through a file and look for this tag
    ,
,
i've read a bunch and everyone tells me to use @""" or \" to accept the double quotes in the middle of the string, but what it does is turns my string into this.
 and it still doesn't work because thats not how it is in the file. examples:
string tblName = "
";
string tblName = "
";

Nothing seems to work. It just addes the \ into the string and i can't replace it because it removes the quotes. Any suggestions?
Thanks
 string tblName = "
";

         try
    {
        // Only get files that begin with the letter "c."
        string[] dirs = Directory.GetFiles(@"C:\Users\dylan.stewart\Desktop\Testing\", "*.ism");
        //Console.WriteLine("The number of files starting with c is {0}.", dirs.Length);
        foreach (string dir in dirs)
        {
            foreach( string line in File.ReadLines(dir))
            if(line.Contains(tblName))
            {
                Console.WriteLine(dir);
            }

            //Console.WriteLine(dir);
        }
    }

A: The above methods for adding " into a string are correct. The issue with my OP is i was searching for a specific amount of white space before the tag. I removed the spaces and used the mentioned methods and it is now working properly. Thanks for the help!

A: string tblName = "
";

should work since the plus sign concatenate

A: It should be either
string tblName = @"
";

or
string tblName = "
";

No need for concatenation. Also what do you mean "it still doesn't work"? Just try Console.Write() and you'll see it ok. If you mean the backslashes are visible while inspecting in debugger then it's supposed to be that way
B


Q: Looping over  with FileReader only displays last image in grid of divs I am trying to create a HTML form that allows the user to upload up to 5 images. After the user selects the images (from the filesystem using <input multiple>) I'd like to display them in 5 divs (ID'ed from #contactImage0 to #contactImage4).
To achieve this I loop over the selected images using vanilla JS and set them as background-image in the corresponding div. The problem is that only the last image in a selection actually shows up. All other divs stay empty.
After debugging a bit I found out that for all but the last image reader.result returns "" but I can't figure out why as the "image" variable I pass to reader.readAsDataURL() seems to be valid.
Why is that and how do I fix it?
HTML:

<input id="upload" type="file" onchange="LoadImage(this)" name="image" accept="image/*" multiple>

JavaScript:
function LoadImage(input){

            if (input.files.length > 5){
                alert("You may only select a maximum of 5 images!");
                // TODO: Remove selected images
                return;
            }
            var i;
            for (i = 0; i < input.files.length; i++){
                var image = input.files[i]
                var imageDiv = 'contactImage' + i.toString();
                var element = document.getElementById(imageDiv);
                var reader = new FileReader();
                reader.onloadend = function(){
                    element.style.backgroundImage = "url(" + reader.result + ")"; // <-- RETURNS EMPTY STRING (EXCEPT FOR LAST IMAGE)
                }
                if(image){
                    reader.readAsDataURL(image);
                    }else{
                    }
            }
        }

CSS (Shouldn't be the cause of the problem but you never know):
.imagePreview{
    margin: .5em;
    display: inline-block;
    width: calc(100% - 1em);
    height: 80px;
    background-color: #fff;
    background-image:url('');
    background-size:cover;
    background-position: center;
}

A: See https://dzone.com/articles/why-does-javascript-loop-only-use-last-value
Solution 1 - Creating a new function setElementBackground
for (i = 0; i < input.files.length; i++) {
  setElementBackground(input.files[i], i);
}

function setElementBackground(file, i) {
  var image = file;
  var imageDiv = "contactImage" + i.toString();
  var element = document.getElementById(imageDiv);
  var reader = new FileReader();
  reader.onloadend = function() {
    element.style.backgroundImage = "url(" + reader.result + ")";
  };
  if (image) {
    reader.readAsDataURL(image);
  }
}

Solution 2 - Using Another Closure inside for loop
for (i = 0; i < input.files.length; i++) {
  (function() {
    var count = i;
    var image = input.files[count];
    var imageDiv = "contactImage" + count.toString();
    var element = document.getElementById(imageDiv);
    var reader = new FileReader();
    reader.onloadend = function() {
      element.style.backgroundImage = "url(" + reader.result + ")";
    };
    if (image) {
      reader.readAsDataURL(image);
    }
  })();
}


Q: MinGW DLL project compatability with linux I've recently created a DLL project using the MinGW (4.8.1) compiler through the CodeBlocks IDE, and in the debugging output folder I have: my ".dll" ("AttribRdr.dll" in this case) file with an Export Definition File and finally a ".a" file ("libAttribRdr.a" in this case).
According to my knowledge, the programs built for Linux/Unix based operating systems use libraries in the ".a" format. My question is: can I use that ".a" file, generated by MinGW on my Windows system, on my Linux system without having to change the library's code or to re-compile? Obiously I would have to change the code of the program using the ".a" library, but otherwise can I use that ".a" file as-is?
I'm asking this because I know MinGW aims to be a "cross-platform" C++ compiler and if I can use the generated ".a" file on Linux systems without having to re-compile it would reduce my workload drastically.

A: To use libraries (or executables) built on Windows in Linux environment you need to cross-compile your code. GCC is capable of cross compilation - so you can research the topic, there is plenty of information.


Q: Javascript Download remote picture in background In my project, I need to implement an Image viewer to display pictures stored on the server on an HTML Page (thumbnail first and on click on the thumbnail display the full screen picture).
Currently, the server is providing me an URL (ex: https://testsrv/getImage?id=0) which is sending back the picture to the browser (Servlet sending a File to an OutputStream). For the moment, I'm just adding an a href hyperlink to download the picture that's ok.
but If I want to improve this, I would need to download the pictures (thumbnail and full size picture) in background while opening the html page to show the thumbnail on the screen.
I assume I would need to download the picture by using AJAX in background and store the pictures in a local temporary folder but if you have some examples to provide me that would be very helpful...
EDIT1:
I finally found a way thanks to the comments based on the onload service:
            var image = document.images[0];
        var downloadingImage = new Image();
        downloadingImage.onload = function(){
            image.src = this.src;
            document.getElementById("img_ref").setAttribute('href', "../../../testSRV/GetPhoto?id="+id_attach);
            console.log('preloaded');
        };
        downloadingImage.src = "../../../testSRV/GetPhoto?id="+id_attach;


Q: Turn on All ec2(+ future created ec2) 'termination protection' Using Lambda Im trying to turn on 'termination protection' for all ec2.
(termination protection doesn't work to spot instance, so i want to add skip condition not to make an error for spot instance.)
I saw a code like below, however the code doesn't work.
import json
import boto3
def lambda_handler(event, context):
  client = boto3.client('ec2')
  ec2_regions = [region['RegionName'] for region in client.describe_regions()['Regions']]
  for region in ec2_regions:
     client = boto3.client('ec2', region_name=region)
     conn = boto3.resource('ec2',region_name=region)
     instances = conn.instances.filter()
     for instance in instances:
       if instance.state["Name"] == "running":
       #print instance.id # , instance.instance_type, region)
        terminate_protection=client.describe_instance_attribute(InstanceId =instance.id,Attribute = 'disableApiTermination')
        protection_value=(terminate_protection['DisableApiTermination']['Value'])
        if protection_value == False:
          client.modify_instance_attribute(InstanceId=instance.id,Attribute="disableApiTermination",Value= "True" )

Summary,,,
I want to turn on 'Termination protection' for all EC2 which is running(not spot instance).
The region should be ap-northeast-2.
Could you help me to fix this code to running appropriatly?

A: if you want to skip the spot instance all you need to do this is figure out which one is spot instance.
You need to use describe_instances api and then  using if-else condition, request_id is empty its a spot instance, if not then its not a spot instance
import boto3
ec2 = boto3.resource('ec2')
instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}]) #add filter of your own choice
for instance in instances:
   if instance.spot_instance_request_id:
     # logic to skip termination ( spot instance )
   else:
     # logic to terminate ( not spot instance )

You can refer a similar question on this -> https://stackoverflow.com/a/45604396/13126651
docs for describe_instances


Q: Using `if-case` format in boolean assignment in Swift? If I have the following enum defined:
enum CardRank {
  case number(Int)
  case jack
  case queen
  case king
  case ace
}

I know I can use an if-let to check if it's a number:
let cardRank = CardRank.number(5)
if case .number = cardRank {
  // is a number
} else {
  // something else
}

Instead of using an if statement, though, I want to assign the boolean result of "is this a number" to a variable.
E.g. something like this:
let isNumber = (case .number = cardRank)

However, this gives me the compiler error:
error: expected expression in list of expressions
let isNumber = (case .number = cardRank)
                ^

Is there a similar 1-line syntax to get this kind of assignment to work?
The closest I got was this, but it's pretty messy:
let isNumber: Bool = { if case .number = cardRank { return true } else { return false } }()

I know I can implement the Equatable protocol on my enum, and then do the following:
let isAce = cardRank == .ace

But I'm looking for a solution that doesn't require needing to conform to the Equatable protocol.

A: Add it as a property on the enum:
extension CardRank {
    var isNumber: Bool {
        switch self {
        case .number: return true
        default: return false
        }
    }
}

let isNumber = cardRank.isNumber


Q: What is the best way to implement this SQL query? I have a PRODUCTS table, and each product can have multiple attributes so I have an ATTRIBUTES table, and another table called ATTRIBPRODUCTS which sits in the middle.  The attributes are grouped into classes (type, brand, material, colour, etc), so people might want a product of a particular type, from a certain brand.
PRODUCTS
product_id
product_name

ATTRIBUTES
attribute_id
attribute_name
attribute_class

ATTRIBPRODUCTS
attribute_id
product_id

When someone is looking for a product they can select one or many of the attributes.  The problem I'm having is returning a single product that has multiple attributes.  This should be really simple I know but SQL really isn't my thing and past a certain point I get a bit lost in the logic.  The problem is I'm trying to check each attribute class separately so I want to end up with something like:
SELECT DISTINCT products.product_id
FROM         attribproducts
INNER JOIN products ON attribproducts.product_id = products.product_id
WHERE     (attribproducts.attribute_id IN (9,10,11)
AND        attribproducts.attribute_id IN (60,61))

I've used IN to separate the blocks of attributes of different classes, so I end up with the products which are of certain types, but also of certain brands.  From the results I've had it seems to be that AND between the IN statements that's causing the problem.
Can anyone help a little?  I don't have the luxury of completely refactoring the database unfortunately, there is a lot more to it than this bit, so any suggestions how to work with what I have will be gratefully received.

A: Take a look at the answers to the question SQL: Many-To-Many table AND query. It's the exact same problem. Cletus gave there 2 possible solutions, none of which very trivial (but then again, there simply is no trivial solution).

A: SELECT DISTINCT products.product_id
FROM products p
INNER JOIN attribproducts ptype on p.product_id = ptype.product_id
INNER JOIN attribproducts pbrand on p.product_id = pbrand.product_id
WHERE ptype.attribute_id IN (9,10,11)
    AND pbrand.attribute_id IN (60,61)

A: Try this:
select * from products p, attribproducts a1, attribproducts a2
  where p.product_id = a1.product_id
    and p.product_id = a2.product_id
    and a1.attribute_id in (9,10,11)
    and a2.attribute_id in (60,61);

A: This will return no rows because you're only counting rows that have a number that's (either 9, 10, 11) AND (either 60, 61).
Because those sets don't intersect, you'll get no rows.
If you use OR instead, it'll give products with attributes that are in the set 9, 10, 11, 60, 61, which isn't what you want either, although you'll then get multiple rows for each product.
You could use that select as an subquery in a GROUP BY statement, grouping by the quantity of products, and order that grouping by the number of shared attributes. That will give you the highest matches first.
Alternatively (as another answer shows), you could join with a new copy of the table for each attribute set, giving you only those products that match all attribute sets.

A: It sounds like you have a data schema that is GREAT for storage but terrible for selecting/reporting. When you have a data structure of OBJECT, ATTRIBUTE, OBJECT-ATTRIBUTE and OBJECT-ATTRIBUTE-VALUE you can store many objects with many different attributes per object. This is sometime referred to as "Vertical Storage".
However, when you want to retrieve a list of objects with all of their attributes values, it is an variable number of joins you have to make. It is much easier to retrieve data when it is stored horizonatally (Defined columns of data)
I have run into this scenario several times. Since you cannot change the existing data structure. My suggest would be to write a "layer" of tables on top. Dynamically create a table for each object/product you have. Then dynamically create static columns in those new tables for each attribute. Pretty much you need to "flatten" your vertically stored attribute/values into static columns. Convert from a vertical architecture into a horizontal ones.
Use the "flattened" tables for reporting, and use the vertical tables for storage.
If you need sample code or more details, just ask me.
I hope this is clear. I have not had much coffee yet :)
Thanks,
  - Mark

A: You can use multiple inner joins -- I think this would work:
select distinct product_id
from products p
inner join attribproducts a1 on a1.product_id=p.product_id
inner join attribproducts a2 on a1.product_id=p.product_id
where a1.attribute_id in (9,10,11)
  and a2.attribute_id in (60,61)


Q: Send requests to a website from an iOS app I was wondering if there's a way to send requests to a website, directly from an iOS app, for example, I type my username and password in two inputbox and then I just tap a "login" button on the iPhone, sending the credentials to a website. Can it be done?

A: You can send requests to a website from an iOS application. You're probably looking to perform a HTTP action.
There is a great guide by the Spring development team which guides you through the process of using RESTful services on iOS, this includes Posting data to a web service.
RESTful services also allow you the create, retrieve, update and delete data from a webservice too using a variety of HTTP calls.


Q: Laravel - Redirect user after login to specific page I want to redirect the user to the edit.blade page when they login for the first time. for this I made this code, but it doesn't work and i have no idea what the problem is. Can someone help me.
this is the code that I have now:
// This section is the only change
if ($this->guard()->validate($this->credentials($request))) {
    $user = $this->guard()->getLastAttempted();
    // Make sure the user is active
    if ($user->verified && $this->attemptLogin($request)) {
        if ($user->first_time_login == true || $user->first_time_login == 1) {
            $this->redirectTo = '/users/edit';
            $user->first_time_login = false;
            $user->save();
        }
        return $this->sendLoginResponse($request);
    }
}

everything works except this line:
if ($user->first_time_login == true || $user->first_time_login == 1) {
    $this->redirectTo = '/users/edit';
}

A: You could do this with the redirectTo property or the authenticated method:
redirectTo property: docs

If the redirect path needs custom generation logic you may define a
  redirectTo method instead of a redirectTo property:

protected function redirectTo()
{
    $user = Auth::user();

    if($user->first_time_login){
        $user->first_time_login = false;
        $user->save();

        return '/users/edit';
    }else{
        return '/home';
    }
}

authenticated method:
protected function authenticated(Request $request, $user)
{
    if ($user->first_time_login) {
        $url = '/users/edit';
        $user->first_time_login = false;
        $user->save();
    } else {
        $url = $this->redirectTo;
    }

    return redirect($url);
}

A: I have found the problem, i had to add return redirect()->to('/users/edit'); on the bottom of the auth function that $this->redirrectTo is the default if the user has not already navigated to a different authed route.
My code now looks like this:
if ($user->first_time_login == true || $user->first_time_login == 1) {
                $this->redirectTo = '/users/edit';
                $user->first_time_login = false;
                $user->save();
                return redirect()->to('/users/edit');
            }


Q: String formula for linear models I'm trying to create a string formula with the independent variables that are significant within my linear model, though I'm finding it difficult trying to include the + at the end of each variable.
I have tried:
as.formula(sprintf("encounter ~  %s",
                   names(tbest$model)[-1]))

However, this only gives the first variable:
encounter ~ open_shrubland

Warning message:
Using formula(x) is deprecated when x is a character vector of length > 1.
Consider formula(paste(x, collapse = " ")) instead.

How would I include all of them such that: encounter ~ X1 + X2 + X3 ..., also, can this be made functional, such that if I wanted to remove a variable, I would only have to do my.formula[-3] to remove it?
list of variable names:
c("open_shrubland", "Appalachian_Mountains", "Boreal_Hardwood_Transition",
"Central_Hardwoods", "Piedmont", "wetland", "Badlands_And_Prairies",
"Peninsular_Florida", "Central_Mixed_Grass_Prairie", "water",
"New_England_Mid_Atlantic_Coast", "grassland", "mixed_forest",
"cropland", "Oaks_And_Prairies", "Eastern_Tallgrass_Prairie",
"evergreen_needleleaf", "year", "pland_change", "evergreen_broadleaf",
"Southeastern_Coastal_Plain", "Prairie_Potholes", "Shortgrass_Prairie",
"urban", "Prairie_Hardwood_Transition", "Lower_Great_Lakes_St.Lawrence_Plain",
"mosaic", "Mississippi_Alluvial_Valley", "deciduous_broadleaf",
"deciduous_needleleaf", "barren")

A: Using reformulate will be helpful.
reformulate(names(tbest$model)[-1], 'encounter')

If the list of variable names are in x :
reformulate(x, 'encounter')

encounter ~ open_shrubland + Appalachian_Mountains + Boreal_Hardwood_Transition +
    Central_Hardwoods + Piedmont + wetland + Badlands_And_Prairies +
    Peninsular_Florida + Central_Mixed_Grass_Prairie + water +
    New_England_Mid_Atlantic_Coast + grassland + mixed_forest +
    cropland + Oaks_And_Prairies + Eastern_Tallgrass_Prairie +
    evergreen_needleleaf + year + pland_change + evergreen_broadleaf +
    Southeastern_Coastal_Plain + Prairie_Potholes + Shortgrass_Prairie +
    urban + Prairie_Hardwood_Transition + Lower_Great_Lakes_St.Lawrence_Plain +
    mosaic + Mississippi_Alluvial_Valley + deciduous_broadleaf +
    deciduous_needleleaf + barren

A: We can create a formula with paste
as.formula(paste('encounter~', paste(names(tbtest$model)[-1], collapse = "+")))


Q: VBScript, purpose of colon? What is the purpose of the colon?
e. g.:
Dim objConn : Set objConn = OpenConnection()`

Is the colon used to combine the two statements into one line? I just want to be sure.

A: Yes this is correct.  In VB style languages, including VBScript, the colon is an end of statement token.  It allows you to place several statements on the same line.

A: What you have stated is correct. The purpose of the colon is to combine 2 otherwise separate lines into a single line. It works on most statements, but not all.

A: Yes, the code would work exactly the same on two lines; the colon's just a statement separator.

A: You can put two (or more) lines of code in one line.  It's most often used, as in your example, to declare and set a variable on one line.
Think of it like a semicolon in every other language, except optional.


Q: jasmine-expect cannot find jest, jasmine v2.x, or jasmine v1.x I'm trying unit test with jasmine-expect. However I keep getting the error:

jasmine-expect cannot find jest, jasmine v2.x, or jasmine v1.x

I have installed the latest version of jasmine. What am I missing?
package.json
{
  "name": "js",
  "version": "1.0.0",
  "description": "",
  "main": "Person.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "add-matchers": "^0.4.0",
    "babel-cli": "^6.22.2",
    "babel-core": "^6.22.1",
    "babel-loader": "^6.2.10",
    "babel-preset-es2015": "^6.22.0",
    "babel-preset-react": "^6.22.0",
    "jasmine": "^2.5.3",
    "jasmine-expect": "^3.6.0",
    "jest": "^18.1.0",
    "webpack": "^2.2.1"
  },
  "dependencies": {
    "deep-freeze": "0.0.1"
  }
}

My Code:
'use strict';
import expect from 'jasmine-expect';

console.log('It is working...');

Error Message:

A: I have switched to the mjackson expect library. It seems to be working fine. Thanks.

A: Please see https://github.com/JamieMason/Jasmine-Matchers/tree/master/examples/jest for a working example of jasmine-expect with jest, thanks.


Q: 'failed to lookup address information' error is displayed on executing selenium test using Gecko driver on Mac OS I am having tuff time on executing Selenium test in Mac OS using Gecko driver. I am using Firefox 56.
Here is the code which i have used to initialize web driver.
System.setProperty("webdriver.gecko.driver", "/Users/<username>/Documents/Tools/geckodriver");
DesiredCapabilities capabilities=DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
WebDriver driver = new FirefoxDriver(capabilities);

Now, when i execute a test, it seems Gecko driver is initialized but below mentioned error is displayed and the browser is not being initialized.
1507662170977   geckodriver INFO    geckodriver 0.19.0
1507662170983   geckodriver INFO    Listening on 127.0.0.1:42748
FAILED CONFIGURATION: @BeforeClass initializeDriver
org.openqa.selenium.WebDriverException: failed to lookup address information: nodename nor servname provided, or not known
Build info: version: '3.6.0', revision: '6fbf3ec767', time: '2017-09-27T15:28:36.4Z'
System info: host: '<username>s-MacBook-Pro.local', ip: '192.168.1.2', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.12.6', java.version: '1.8.0_144'
Driver info: driver.version: FirefoxDriver
remote stacktrace: stack backtrace:
   0:        0x10d96ca8e - backtrace::backtrace::trace::h69682bcb53decaf6
   1:        0x10d96cacc - backtrace::capture::Backtrace::new::hdc9d731a957304a6
   2:        0x10d8ce8e3 - webdriver::error::WebDriverError::new::h4c6ae7c4aac049c6
   3:        0x10d8cf352 - _$LT$webdriver..error..WebDriverError$u20$as$u20$core..convert..From$LT$std..io..error..Error$GT$$GT$::from::ha068e680ab4e1954
   4:        0x10d8a221e - geckodriver::marionette::MarionetteHandler::create_connection::hc09196342b760e35
   5:        0x10d8847d4 - _$LT$webdriver..server..Dispatcher$LT$T$C$$u20$U$GT$$GT$::run::hfda25a6dc0b512aa
   6:        0x10d85c645 - std::sys_common::backtrace::__rust_begin_short_backtrace::h95009c1d3a320838
   7:        0x10d86411d - std::panicking::try::do_call::h8c5f07f1fc714fb2
   8:        0x10da1d9cc - __rust_maybe_catch_panic
   9:        0x10d879f55 - _$LT$F$u20$as$u20$alloc..boxed..FnBox$LT$A$GT$$GT$::call_box::h6a96e09ff4d37bff
  10:        0x10da19c3b - std::sys::imp::thread::Thread::new::thread_start::h823686b907c11c46
  11:     0x7fffdf79f93a - _pthread_body
  12:     0x7fffdf79f886 - _pthread_start

Your solution would be appreciated.

A: Apparently there is an issue with the JDK and OSX where the hostname does not recognize localhost.
The solution is to add localhost to /etc/hosts

A: You need to pass the capabilities to the driver:
WebDriver driver = new FirefoxDriver(capabilities);


Q: TensorFlow Probability: how to do sample weighting with log_prob loss function? I'm using TensorFlow probability to train a model whose output is a tfp.distributions.Independent object for probabilistic regression. My problem is that I'm unsure how to implement sample weighting in the negative log likelihood (NLL) loss function.
I have the following loss function which I believe does not use the sample_weight third argument:
class NLL(tf.keras.losses.Loss):
    ''' Custom keras loss/metric for negative log likelihood '''

    def __call__(self, y_true, y_pred, sample_weight=None):
        return -y_pred.log_prob(y_true)

With standard TensorFlow loss functions and a dataset containing (X, y, sample_weight) tuples, the use of sample_weight in the loss reductions summations is handled under the hood. How can I make the sum in y_pred.log_prob use the weights in the sample_weight tensor?

A: I found a solution to my problem as posted in this GitHub issue.
My problem was caused by the fact that my model outputs a tfp.Independent distribution, which means the log_prob is returned as a scalar sum over individual log_probs for each element of the tensor. This prevents weighting individual elements of the loss function. You can get the underlying tensor of log_prob values by accessing the .distribution attribute of the tfp.Independent object - this underlying distribution object treats each element of the loss as an independent random variable, rather than a single random variable with multiple values. By writing a loss function that inherits from tf.keras.losses.Loss, the resulting weighted tensor is implicitly reduced, returning the weighted mean of log_prob values rather than the sum, e.g.:
class NLL(tf.keras.losses.Loss):
    ''' Custom keras loss/metric for weighted negative log likelihood '''

    def __call__(self, y_true, y_pred, sample_weight=None):

        # This tensor is implicitly reduced by TensorFlow
        #     by taking the mean over all weighted elements
        return -y_pred.distribution.log_prob(y_true) * sample_weight


Q: BoxFit.cover does not work with CachedNetworkImage plus PhotoView In this scenario I can not make to work the fit property with BoxFit.cover.
There is always borders on screen. How can I do it?
Scaffold(
  appBar: AppBar(),
  body: CachedNetworkImage(
    height: double.infinity,
    width: double.infinity,
    fit: BoxFit.cover, // does not work
    imageUrl: _imageUrl,
    imageBuilder: (context, imageProvider) => PhotoView(
      imageProvider: imageProvider,
    ),
  ),
);

A:        Container(
        child: CachedNetworkImage(
          imageUrl: _imageUrl,
          imageBuilder: (context, imageProvider)=>PhotoView(
            minScale: 1.0,
            imageProvider: imageProvider,
          ),
        ),
      ),

A: For the future searchers, there is an another solution which seems perfectly fits the desired behaviour.
https://stackoverflow.com/a/58200356/5829191

A: This work for me. Since I have a Container with the same borderRadius as the Catched Image. Without the BoxDecoration it failed med too!
    Container( decoration: BoxDecoration(borderRadius:
BorderRadius.circular(10),),child:CachedNetworkImage(imageUrl: ("UrlToImage"),imageBuilder: (context, imageProvider) => Container(decoration: BoxDecoration(borderRadius: BorderRadius.circular(10),image: DecorationImage(image: imageProvider,
                                            fit: BoxFit.cover,
                                            )),),placeholder: (context, url) => CircularProgressIndicator(),errorWidget: (context, url, error) => Image.asset("PathToImage")
                                  ),


Q: Awful looking custom transition I have a problem with custom transition between controllers. I have two view controllers. First is a table view controller and initiate controller is the second one. It has a button on it's top left corner which, when it is pressed, first navigation controller is called. There should be slide animation, but from left to right, not from right to left. I made my own transition but when the button is pressed, transition looks very awful. Transition code:
CATransition *transition = [CATransition animation];
transition.duration = 0.45;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault];
transition.type = kCATransitionFromLeft;
[transition setType:kCATransitionPush];
transition.subtype = kCATransitionFromLeft;
transition.delegate = self;
[self.navigationController.view.layer addAnimation:transition forKey:nil];
[self.navigationController pushViewController:controller animated:NO];

This is a screenshot, how the transition looks like:


Q: put part of the method which returns null in other method The method storeData works fine, but I am trying to put a part of my method in another method samePosition to minimize it, but I have the problem that some of its part returns null.
I put it in the other method names samePosition with return values Integer but then I received this error message:

This method must return a result of type Integer

How can I solve this problem?
storeData method before minimization:
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response storeData(Data data) {

    String macD = data.getMac();
    int routeD = data.getRoute();
    float latD = data.getLatitude();
    float longD = data.getLongitude();

    // Add the lat and Long to the ArrayList.
    latLongList.add(new LatLong(latD, longD));

////////////I want to put this part in seperate method "samePosition" //////////////
    int size = latLongList.size();
    if (size > 1) {
        ArrayList<Double> array = new ArrayList<>();

        for (int i = 0; i < latLongList.size() - 1; i++) {
            LatLong last = latLongList.get(latLongList.size() - 1);

            double distance = haversineDistance(latLongList.get(i), last);
            array.add(distance);

        }

        ArrayList<Double> distanceRange = new ArrayList<>();

        for (int j = 0; j < array.size(); j++) {

            // Store request in the circumcircle of 4 meter into ArrayList.
            if (array.get(j) < 4) {

                distanceRange.add(array.get(j));
            }
        }

        if (distanceRange.size() == 0) {
            processData(macD, routeD, latD, longD);
        } else {
            return null;
        }

    } else {

        processData(macD, routeD, latD, longD);
    }
//////////////////////until here/////////////////////////
    return Response.status(201).build();
}

Edit:
storeData:
public Response storeData(Data data) {

        String macD = data.getMac();
        int routeD = data.getRoute();
        float latD = data.getLatitude();
        float longD = data.getLongitude();

        // Add the lat and Long to the ArrayList.
        latLongList.add(new LatLong(latD, longD));

        System.out.println("latLondList size: " + latLongList.size());

         int valueReturned =   samePosition(macD, routeD, latD, longD);

        if (valueReturned == -1) {
            return null;
            } else {
                return Response.status(201).build();
            }
    }

samePosition method:
private int samePosition(String macD, int routeD, float latD, float longD) {
        int size = latLongList.size();
        if (size > 1) {
            ArrayList<Double> array = new ArrayList<>();

            for (int i = 0; i < latLongList.size() - 1; i++) {
                LatLong last = latLongList.get(latLongList.size() - 1);

                double distance = haversineDistance(latLongList.get(i), last);
                array.add(distance);

            }

            ArrayList<Double> distanceRange = new ArrayList<>();

            for (int j = 0; j < array.size(); j++) {

                // Store request in the circumcircle of 4 meter into ArrayList.
                if (array.get(j) < 4) {

                    distanceRange.add(array.get(j));
                }
            }

            if (distanceRange.size() == 0) {
                processData(macD, routeD, latD, longD);
            } else {
                return -1;
            }

        } else {

            processData(macD, routeD, latD, longD);
        }
    }

A: Instead of returning null you could return -1 and then check for the value you return being -1.
if (valueReturned == -1) {
return null;
} else {
    //continue with method
}

The samePosition() method should return always an integer:
private int samePosition(String macD, int routeD, float latD, float longD) {
    int size = latLongList.size();
    if (size > 1) {
        ArrayList<Double> array = new ArrayList<>();

        for (int i = 0; i < latLongList.size() - 1; i++) {
            LatLong last = latLongList.get(latLongList.size() - 1);

            double distance = haversineDistance(latLongList.get(i), last);
            array.add(distance);

        }

        ArrayList<Double> distanceRange = new ArrayList<>();

        for (int j = 0; j < array.size(); j++) {

            // Store request in the circumcircle of 4 meter into ArrayList.
            if (array.get(j) < 4) {

                distanceRange.add(array.get(j));
            }
        }

        if (distanceRange.size() == 0) {
            processData(macD, routeD, latD, longD);
            return 0;
        } else {
            return -1;
        }

    } else {
        processData(macD, routeD, latD, longD);
            return 0;
    }
}

A: Check the below and modify as needed. Instead of returning 201 as response in all the cases I preferred to return different status code based on whether you processed the data or not.
In your earlier code, the code segment you are trying to extract is returning null from one point and nothing from last else where you are calling processData(..).
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response storeData(Data data) {
  ..
  int status = samePosition(..);
  return Response.status(status).build();
}

private int samePosition(..) {
  int status = 201;
  if() {
    ...
    if (distanceRange.size() == 0) {
      processData(macD, routeD, latD, longD);
    } else {
      status = <Preferred HTTP status code to return for not processing>;
    }
  } else {

  }
  return status;
}


Q: UICollectionViewCompositionLayout with auto-sizing cells containing a fixed ratio UIImageView The goal is to configure a UICollectionViewCompositionalLayout for full-width cells which contain a fixed-aspect ratio UIImageView (plus some other views underneath including variable height UILabels and UIStackViews) and have the cells properly auto-size. My naive attempt doesn't work and I can't figure out why. The simple case I present here gives me a bunch of constraint errors at runtime.
I cribbed the code from this answer, but it looks pretty straightforward:
    override func viewDidLoad() {
        super.viewDidLoad()

        let size = NSCollectionLayoutSize(
            widthDimension: NSCollectionLayoutDimension.fractionalWidth(1),
            heightDimension: NSCollectionLayoutDimension.estimated(100)
        )
        let item = NSCollectionLayoutItem(layoutSize: size)
        let group = NSCollectionLayoutGroup.horizontal(layoutSize: size, subitem: item, count: 1)

        let section = NSCollectionLayoutSection(group: group)
        section.interGroupSpacing = 10

        let layout = UICollectionViewCompositionalLayout(section: section)

        collectionView.collectionViewLayout = layout
    }

And the constraints look like this:

And as soon as I scroll, I get these constraint errors:
2021-01-21 20:29:18.311491+0100 CompositionalLayoutDynamicHeight[96399:2597528] [LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want.
    Try this:
        (1) look at each constraint and try to figure out which you don't expect;
        (2) find the code that added the unwanted constraint or constraints and fix it.
(
    "<NSLayoutConstraint:0x6000020a82d0 UIImageView:0x138818600.width == 1.33333*UIImageView:0x138818600.height   (active)>",
    "<NSLayoutConstraint:0x6000020a8460 V:|-(0)-[UIImageView:0x138818600]   (active, names: '|':UIView:0x13881c4d0 )>",
    "<NSLayoutConstraint:0x6000020a84b0 H:[UIImageView:0x138818600]-(0)-|   (active, names: '|':UIView:0x13881c4d0 )>",
    "<NSLayoutConstraint:0x6000020a8500 V:[UIImageView:0x138818600]-(0)-|   (active, names: '|':UIView:0x13881c4d0 )>",
    "<NSLayoutConstraint:0x6000020a8550 H:|-(0)-[UIImageView:0x138818600]   (active, names: '|':UIView:0x13881c4d0 )>",
    "<NSLayoutConstraint:0x6000020a85a0 'UIIBSystemGenerated' CompositionalLayoutDynamicHeight.CollectionViewCell:0x13881c280.leading == UIView:0x13881c4d0.leading   (active)>",
    "<NSLayoutConstraint:0x6000020a85f0 'UIIBSystemGenerated' H:[UIView:0x13881c4d0]-(0)-|   (active, names: '|':CompositionalLayoutDynamicHeight.CollectionViewCell:0x13881c280 )>",
    "<NSLayoutConstraint:0x6000020a8640 'UIIBSystemGenerated' CompositionalLayoutDynamicHeight.CollectionViewCell:0x13881c280.top == UIView:0x13881c4d0.top   (active)>",
    "<NSLayoutConstraint:0x6000020a8690 'UIIBSystemGenerated' V:[UIView:0x13881c4d0]-(0)-|   (active, names: '|':CompositionalLayoutDynamicHeight.CollectionViewCell:0x13881c280 )>",
    "<NSLayoutConstraint:0x6000020a60d0 'UIView-Encapsulated-Layout-Height' CompositionalLayoutDynamicHeight.CollectionViewCell:0x13881c280.height == 292.667   (active)>",
    "<NSLayoutConstraint:0x6000020a6120 'UIView-Encapsulated-Layout-Width' CompositionalLayoutDynamicHeight.CollectionViewCell:0x13881c280.width == 390   (active)>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x6000020a82d0 UIImageView:0x138818600.width == 1.33333*UIImageView:0x138818600.height   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful.

It seems that AutoLayout is creating that UIView-Encapsulated-Layout-Height constraint which is conflicting with the aspect ratio constraint—but why isn't it just resizing to fit it?

A: Auto-layout makes multiple "passes" when laying out the UI elements for Collection views (and Table views).
Frequently, particularly when using variable-sized cell content, auto-layout will throw warnings as it walks its way through the constraints.
Probably the easiest way to get rid of that warning is to give your Aspect Ratio constraint a Priority of less-than Required.
If you set it to Default High (750), that tells auto-layout it's allowed to "break" it without throwing the warning (but it will still be applied).

A: I had the same issue on a horizontal slider with dynamic item widths. I found the solution in my case which looks like a bug to me.
There are two functions to create a NSCollectionLayoutGroup. Using the other one fixed it for me.
This breaks my constraints:
let group = NSCollectionLayoutGroup.horizontal(layoutSize: size, subitem: item, count: 1)

This doesnt:
let group = NSCollectionLayoutGroup.horizontal(layoutSize: size, subitems: [item])


Q: has anyone undergone certification of PCI-DSS using general purpose HSM (and not payshield)? can we utilise a general purpose HSM for EMV related work ? like ARQC/ARPC ? PCI guidelines do not specifically prohibit general purpose HSM from being used. There are certain constraints (e.g. disallow trnslation of ISO Type 0 to Type 1), etc.
But im generally curious - has anyone passed certification of a EMV switch using a general purpose HSM ?
Here's why I think it is possible:
ISO 9564 and TR-31 standards mandate that a few common things like

b) It must prevent the determination of key length for variable length
keys.
c) It must ensure that the key can only be used for a specific
algorithm (such as TDES or AES, but not both).
d) It must ensure a modified key or key block can be rejected prior to use, regardless of the utility of the key after modification. Modification includes changing any bits of the key, as well as the reordering or manipulation of individual single DES keys within a TDES key block

In forthcoming TR-31 regulations, I see that AWS KMS is compliant at the "at-rest integrity checks" using stuff like  EncryptionContext and Policy Constraints
so im generally wondering what prevents us from using KMS for this purpose ?


Q: Performing a WHERE - IN query in CouchDB I would like to query for a list of particular documents with one call to CouchDB.
With SQL I would do something like
SELECT *
FROM database.table
WHERE database.table.id
IN (2,4,56);

What is a recipe for doing this in CouchDB by either _id or another field?

A: You need to use views keys query parameter to get records with keys in specified set.
function(doc){
    emit(doc.table.id, null);
}

And then
GET /db/_design/ddoc_name/_view/by_table_id?keys=[2,4,56]

To retrieve document content in same time just add include_docs=True query parameter to your request.
UPD: Probably, you might be interested to retrieve documents by this reference ids (2,4,56). By default CouchDB views "maps" emitted keys with documents they belongs to. To tweak this behaviour you could use linked documents trick:
function(doc){
    emit(doc.table.id, {'_id': doc.table.id});
}

And now request
GET /db/_design/ddoc_name/_view/by_table_id?keys=[2,4,56]&include_docs=True

will return rows with id field that points to document that holds 2,4 and 56 keys and doc one that contains referenced document content.

A: In CouchDB Bulk document APi is used for this:
curl -d '{"keys":["2","4", "56"]}' -X POST http://127.0.0.1:5984/foo/_all_docs?include_docs=true

http://wiki.apache.org/couchdb/HTTP_Bulk_Document_API


Q: Qt SDK download for MingW I´m looking for Qt SDK for windows that uses MingW as the compiler. Unfortunately, on the official download sites, I can only find the one that uses MSVC. Or just the library instead of the whole SDK.
Can anybody tell me where I can find the version I am looking for, or explain what I should do if I download QT library, QT creator and MingW seperately?

A: Here you can find pre-release builds using MinGW 4.7.
http://releases.qt-project.org/digia/5.0.1/latest/
They work well with the MinGW builds distributed here:
http://sourceforge.net/projects/mingwbuilds/
The Qt builds come with Qt Creator, so you can install it and should be good to go after setting up your kits.

A: You can find binaries here:
http://qt-project.org/forums/viewthread/23002/
But then you ought to reconfigure installation manual or you may use this utility.
Some guy from Digia promised MinGW builds by the end of January, so you can wait instead.


Q: How to add into map in range loop package main

import (
    "fmt"
)

func main() {
    m := make(map[int]int, 4)
    m[1] = 0
    m[2] = 0
    for k, _ := range m {
        i := 10 + k
        m[i] = 0
    }
    fmt.Println(m)
    fmt.Println("len:", len(m))
}

This code returns: 8 or 10 or 6 as length of map after loop.
Video is here, playgroud here.
I see that new added elements go into range, but can't explain why this loop stops randomly?

A: Spec: For statements:

The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next. If a map entry that has not yet been reached is removed during iteration, the corresponding iteration value will not be produced. If a map entry is created during iteration, that entry may be produced during the iteration or may be skipped. The choice may vary for each entry created and from one iteration to the next. If the map is nil, the number of iterations is 0.

The spec states that if you add entries to the map you are ranging over, the elements you add may or may not be visited by the loop, and moreover, which is visited is not even deterministic (may change when doing it again).

A: You are modifying map you are iterating over. This is the cause.


Q: IOS Charts Labels not centered to data points. Charts Library I am currently using IOS Charts to for a line chart.
This is the link to it: Link
It is horribly documented and I am having trouble centering my X-Axis labels to the plots on my chart.
I have already enabled granularity and set it to 1. - This ensures the labels do not get repeated
Here is what my chart looks like now:

Here is what I want it to look like:
I know the spacing of the points is different, but my main focus is how to get the labels centered to the correct data points.
My Code:
`import UIKit
import Charts
class ReviewDetailVC: UIViewController, ChartViewDelegate {
@IBOutlet weak var chartView: LineChartView!

var yValues =  [Double]()
var months = [String]()
var xValues = [String]()
let red = UIColor(hue: 0.9639, saturation: 0.62, brightness: 0.93, alpha: 1.0)
let black = UIColor(red:0.29, green:0.29, blue:0.29, alpha:1.0)
let grey = UIColor(red:0.81, green:0.81, blue:0.81, alpha:1.0)

let avenirDemi =  UIFont(name: "AvenirNext-DemiBold", size: 14)
override func viewDidLoad() {
    super.viewDidLoad()

    chartView.delegate = self
    // Chart Ui Settings
    chartView.xAxis.axisMinimum = 1
    chartView.leftAxis.axisMaximum = 5
    chartView.leftAxis.axisMinimum = 0.0
    chartView.chartDescription?.text = ""
    chartView.xAxis.labelPosition = .bottom
    chartView.legend.enabled = false
    chartView.scaleYEnabled = false
    chartView.scaleXEnabled = true
    chartView.doubleTapToZoomEnabled = false
    chartView.highlighter = nil
    chartView.rightAxis.enabled = false
    chartView.xAxis.drawGridLinesEnabled = false
    chartView.dragEnabled = true
    chartView.scaleXEnabled = false
    chartView.scaleYEnabled = false
    chartView.zoom(scaleX: 4, scaleY: 1, x: 0, y: CGFloat(AxisDependency.left.rawValue))
    chartView.xAxis.labelFont = avenirDemi!
    chartView.xAxis.labelTextColor = grey
    chartView.leftAxis.labelFont = avenirDemi!
    chartView.leftAxis.labelTextColor = black
    chartView.xAxis.axisLineWidth = 0
    chartView.leftAxis.axisLineWidth = 0
    //chartView.xAxis.avoidFirstLastClippingEnabled = true
    chartView.xAxis.granularityEnabled = true
    chartView.xAxis.granularity = 1
    chartView.leftAxis.gridColor = grey
    chartView.leftAxis.gridLineDashLengths = [4]
    chartView.leftAxis.gridLineWidth = 1.5
    chartView.xAxis.centerAxisLabelsEnabled = true
    chartView.noDataText = "This person has not reviewed your business."

    //**MARK:: DATA SHIT

    let sales = DataGenerator.data()

    xValues = ["MAR 10"," MAR 15", "APR 7", "APR 8", "APR 15", "APR 30", "MAY 14", "MAY 21","MAY 31", "MAY 31"]
    yValues = [4,2,4,5,3,4,2,4,5]

    var salesEntries = [ChartDataEntry]()

    var salesMonths = [String]()

    var i = 0

    for sale in sales {
        // Create single chart data entry and append it to the array
        let saleEntry = ChartDataEntry(x: Double(i), y: sale.value)
        salesEntries.append(saleEntry)

        // Append the month to the array
        salesMonths.append(sale.date)

        i += 1
    }

    // Create bar chart data set containing salesEntries
    let chartDataSet = LineChartDataSet(values: salesEntries, label: "Profit")

    // Create bar chart data with data set and array with values for x axis

    let chartData = LineChartData(dataSets: [chartDataSet])

    //setChart(dataPoints: xValues, values: yValues)

    //let formatter = CustomLabelsAxisValueFormatter(miniTime: 0.0)
    //formatter.labels = xValues
    chartView.xAxis.valueFormatter = CustomLabelsAxisValueFormatter(miniTime: 0.0)

    //**MARK:: END DATA SHIT

    chartDataSet.colors = [red]
    chartDataSet.drawCirclesEnabled = true
    chartDataSet.circleRadius = 16
    chartDataSet.circleColors = [red]
    chartDataSet.circleHoleRadius = 12
    chartDataSet.circleHoleColor = UIColor.white
    chartDataSet.lineWidth = 4
    chartDataSet.drawValuesEnabled = false

    chartView.animate(yAxisDuration: 1)

    chartView.setVisibleXRangeMaximum(4)

    // Set bar chart data
        chartView.data = chartData
   setChart(dataPoints: xValues, values: yValues)

}

func setChart(dataPoints: [String], values: [Double]) {
    chartView.noDataText = "You need to provide data for the chart."

    var dataEntries: [ChartDataEntry] = []

    for i in 0..<dataPoints.count {
        let dataEntry = ChartDataEntry(x: Double(i), y: values[i])
        dataEntries.append(dataEntry)
    }

    let chartDataSet = LineChartDataSet(values: dataEntries, label: "")
    let chartData = LineChartData(dataSets: [chartDataSet])

    chartDataSet.colors = [red]
    chartDataSet.drawCirclesEnabled = true
    chartDataSet.circleRadius = 16
    chartDataSet.circleColors = [red]
    chartDataSet.circleHoleRadius = 12
    chartDataSet.circleHoleColor = UIColor.white
    chartDataSet.lineWidth = 4

    chartView.data = chartData

}

        }`

A: You can change your setChart method to this:
 func setChart(dataPoints: [String], values: [Double]) {
    chartView.noDataText = "You need to provide data for the chart."

    var dataEntries: [ChartDataEntry] = []

    for i in 0..<dataPoints.count {
        let dataEntry = ChartDataEntry(x: Double(i)+0.5, y: values[i])
        dataEntries.append(dataEntry)
    }

    let chartDataSet = LineChartDataSet(values: dataEntries, label: "")
    let chartData = LineChartData(dataSets: [chartDataSet])

    chartDataSet.colors = [red]
    chartDataSet.drawCirclesEnabled = true
    chartDataSet.circleRadius = 16
    chartDataSet.circleColors = [red]
    chartDataSet.circleHoleRadius = 12
    chartDataSet.circleHoleColor = UIColor.white
    chartDataSet.lineWidth = 4

    chartView.data = chartData

}

Result:
update:
chartView.xAxis.axisMinimum = 0.0 //I changed this from 1 to 0
let xvalues = ["MAR 10"," MAR 15", "APR 7", "APR 8", "APR 15", "APR 30", "MAY 14", "MAY 21","MAY 31", "MAY 31"]

chartView.xAxis.valueFormatter = IndexAxisValueFormatter(values: xvalues)

class MyIndexFormatter: IndexAxisValueFormatter {

open override func stringForValue(_ value: Double, axis: AxisBase?) -> String
{
        return "\(value)"
}

}


Q: Error when trying to push code to nexus maven I have found out that in order to add my code to my nexus repo I have to use mvn deploy
When ran I get this error:
https://hastebin.com/wikisohuni.pas
I have searhced ALL over stackoverflow and online guides, but NOTHING has worked!
settings.xml:
<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <mirrors>
    <mirror>
      <id>nexus</id>
      <mirrorOf>*</mirrorOf>
      <url>http://192.168.0.145/nexus/content/groups/public</url>
    </mirror>
  </mirrors>
  <proxies></proxies>
  <pluginGroups>
    <pluginGroup>org.codehaus.modello</pluginGroup>
  </pluginGroups>
  <profiles>
    <profile>
      <id>nexus</id>
      <!--Enable snapshots for the built in central repo to direct -->
      <!--all requests to nexus via the mirror -->
      <repositories>
        <repository>
          <id>central</id>
          <url>http://central</url>
          <releases><enabled>true</enabled></releases>
          <snapshots><enabled>true</enabled></snapshots>
        </repository>
      </repositories>
      <pluginRepositories>
        <pluginRepository>
          <id>central</id>
          <url>http://central</url>
          <releases><enabled>true</enabled></releases>
          <snapshots><enabled>true</enabled></snapshots>
        </pluginRepository>
      </pluginRepositories>
    </profile>
  </profiles>
  <activeProfiles>
    <activeProfile>nexus</activeProfile>
  </activeProfiles>
  <servers>
    <server>
      <id>nexus</id>
      <username>admin</username>
      <password>removed</password>
    </server>
  </servers>
</settings>

My pom can be found at: https://github.com/PhanaticGames/PhanaticSpigotCore/blob/master/pom.xml
EDIT: I edited my settings a bit and got that error to go away, however, I now get this error: https://hastebin.com/ohukowohud.sql
However, these are what run my jar. I am making a central API for other plugins ran by these jars.


Q: unicorn: do I need to disconnect from database in before_fork block? There is a comment that explains why you don't need to (and shouldn't) disconnect from DB and Redis in before_fork:

By disconnecting in before_fork, you are closing the connection at the parent process every time you spawn a child, which is only needed once - you're beating a dead horse. Connection handling is a child's concern (after_fork) rather than a parent's concern (before_fork).
ActiveRecord's connection pool is now keyed by Process.pid, so it's always safe to call ActiveRecord::Base.establish_connection in after_fork - the connection will never be shared with the parent, no need to disconnect at the master anyway.
On Unicorn, the master process is a singleton and can be used in many ways - spawn a thread and run EventMachine loop inside it to run scheduled / background jobs, etc. And there it's useful to keep the AR connection open. Only main thread will be inherited to a child (on linux systems at least) so it's safe to have threads.

Is that true?

A: It definitely isn't required, but I prefer to do it anyway - we run a ton of application servers and if we didn't disconnect the master process from the DB we'd be holding a lot of connections open for no reason.


Q: How to Set A Methods For A Class In Vue.js you know that we can use on events for a class in JQuery.
for instance
$(".example").click(function(){
//the process
})

I am new on Vue.js and I am working on methods in vue.js
Vue use v-on attr to set a method for a element. But I dont want to define attr for all elements whichs use same function.
For Example

Menu 1

Menu 1

Menu 2

You must saw, I used v-on attr for all li elements. For li elements it is not problem, I can solve it v-repeat but for some cases, I have to set same function for lots of divs or form. I want to set a class for a function and set a method for the class.
Is there any solution for it?

A: David's answer is good. But if you don't want to use Jquery, you can use document.querySelectorAll instead of $(this.el).find("li") and then add the click handlers with addEventListener in the directive.
Having said that, you don't have to add event listeners to all the elements in a directive (even though a directive might be the best solution for this). Another approach would be to do what you suggest, put the handlers on the parent elements, and then implement some logic depending on which element the function was called from. Example:
https://jsfiddle.net/q7xcbuxd/33/

Menu 1 item 1

Menu 2 item 1

Menu 2 item 2

Menu 2 item 3

    lots

    of

    items

var vue = new Vue({
    el: '#app',

    methods: {
        Menu: function(id){
            console.log('You invoked function Menu' + id + ' ' +
                        'by clicking on ' + event.path[0].innerHTML + ' ' +
                        'which is of type ' + event.srcElement.nodeName + '.\n' +
                        'The parent element\'s class name is \'' + event.srcElement.parentElement.className + '\' ' +
                        'which is of type ' + event.srcElement.parentElement.nodeName + '.');
        }
    }
});

A: I would write a directive for
 and
 that adds click handlers for all
 children.
Something like:
Vue.directive('menu', {
    bind: function () {
        $(this.el).find("li").on("click", function (event) {
            this.menu_click(event);
        });
    },
    update: function (value) {
        this.menu_click = value;
    },
    unbind: function () {
        $(this.el).find("li").off("click", this.menu_click);
    }
})

And use it like this:

Menu 1

Menu 1

Menu 2


Q: How to deploy Angular cli 7 app on Azure using Visual Studio code? I created an Angular app using angular-cli(node 8.12) and build it:
npm install -g @angular/cli7

ng new my-app

ng build --prod  //inside folder

i connect my visual studio code to my azure account then i create the service app and then just right click on my project and select Publish Web App then select my dist folder and deploy it.
VS say that all is completed and i see my dist folder but if i browse there i see the default page.
how can I solve this?


Q: vc++ 6.0 testing an unlicensed Activex ctrl by dlg application I am using vc++ 6.0. I Have made an unlicensed activex ctrl application from app wizard (MFC activeX ctrl wizard for generating random drawing). When I am testing this Activex by ActiveX control test container,  all functions are working fine, but when I am testing it with dialog application, On calling any method of ActiveX it is giving error debug assertion failed.
Program ......
File: winocc.cpp;
line: 345
I am making an object of this ActiveX ctrl wrapper class in my testing dialog application and then calling method defined in this ActiveX ctrl.
My code:
CNewSquiggleAcX m_ClNewSquigg;
CFileDialog m_ldFile(TRUE);
    // Show the File open dialog and capture the result
    if(m_ldFile.DoModal()== IDOK)
    {
        CString m_sResults;
        m_sResults = m_ldFile.GetFileName();
        //m_ClNewSquigg.GetSquiggleLength();
        m_ClNewSquigg.LoadDrawing(m_sResults); // Error comes in this line
                                                          calling any activex function
    }

Please help me thanks in advance

A: The control needs to be instanciated. If you placed it on a dialog template then opening the dialog will create the control. The other approach is to call the CreateControl method, which you can find in the h file of the control's wrapper class.


Q: Refreshing the Cursor from SQLiteCursorLoader My project uses the SQLiteCursorLoader library from commonsguy to load data from a database into a ListView. Among that data is a simple boolean (as so far as SQLite supports booleans... that is, a number that only ever is 0 or 1) that tells the state of a checkbox. If I change the state of a checkbox in a list and then scroll the item off the list, the list item returns to the state it has when the cursor was passed in, despite the fact that the underlying database has changed. If I change the state of a bunch of checkboxes and then activate the list's MultiChoiceMode, all the items displayed will revert back to the state they were in when the cursor was originally passed in, despite the fact that the underlying database has changed.
Is there a way to refresh the cursor? Cursor.requery() is deprecated, and I don't want to have to create a new Cursor each time a checkbox is checked, which happens a lot. I'm also unsure of how calling restartLoader() several times would work, performance-wise, especially since I use onLoadFinish() to perform some animations.

A:
Is there a way to refresh the cursor?

Call restartLoader() to have it reload the data.

I don't want to have to create a new Cursor each time a checkbox is checked, which happens a lot

Used properly, a ListView maintains the checked state for you. You would do this via android:choiceMode="multipleChoice" and row Views that implement Checkable. The objective is to not modify the database until the user has indicated they are done messing with the checklist by one means or another (e.g., "Save" action bar item).

I'm also unsure of how calling restartLoader() several times would work, performance-wise, especially since I use onLoadFinish() to perform some animations.

Don't call it several times. Ideally, call it zero times, by not updating the database until the user is done, at which point you are probably transitioning to some other portion of your UI. Or, call it just once per requested database I/O (e.g., at the point of clicking "Save"). Or, switch from using a CursorAdapter to something else, such as an ArrayAdapter on a set of POJOs you populate from the Cursor, so that the in-memory representation is modifiable in addition to being separately persistable.


Q: UIButton not working on the first tap I made a custom switch to turn on and off sound effects in my game Optic Combat, but for some reason the button that when tapped, animates the switch moving to a different position, is not working on the first tap. Subsequent taps work, just not the first one.
In the IBAction for the button I have:
- (IBAction)theSwitch:(id)sender {
NSUserDefaults *toggle = [NSUserDefaults standardUserDefaults];

if (_toggle == 1) {

    [UIView animateWithDuration:0.3 animations:^{
        audioToggle.frame = CGRectMake(985.0f, 59.0f, audioToggle.frame.size.width, audioToggle.frame.size.height);
    }];

    _toggle ++;
    [toggle setInteger:_toggle forKey:@"toggleState"];
    [toggle synchronize];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"audioOn"];

}

else {

    [UIView animateWithDuration:0.3 animations:^{
        audioToggle.frame = CGRectMake(924.0f, 59.0f, audioToggle.frame.size.width, audioToggle.frame.size.height);
    }];

    _toggle --;
    [toggle setInteger:_toggle forKey:@"toggleState"];
    [toggle synchronize];
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"audioOn"];

}
}

And in the viewDidLoad, checking the state of the switch and adjusting it to show the correct position (on or off):
- (void)viewDidLoad
{
[super viewDidLoad];

if ([[NSUserDefaults standardUserDefaults] boolForKey:@"audioOn"]) {
    [audioToggle setFrame:CGRectMake(924.0f, 59.0f, audioToggle.frame.size.width, audioToggle.frame.size.height)];
    _toggle = 2;
}
else {
    [audioToggle setFrame:CGRectMake(985.0f, 59.0f, audioToggle.frame.size.width, audioToggle.frame.size.height)];
    _toggle = 1;
}

Edit: I used this to solve my problem, in the IBAction for the button:
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"audioOn"]) {
    [UIView animateWithDuration:0.3 animations:^{
    audioToggle.frame = CGRectMake(985.0f, 59.0f, audioToggle.frame.size.width, audioToggle.frame.size.height);
    }];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"audioOn"];
}
else {
    [UIView animateWithDuration:0.3 animations:^{
    audioToggle.frame = CGRectMake(924.0f, 59.0f, audioToggle.frame.size.width, audioToggle.frame.size.height);
    }];
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"audioOn"];
}

A: In your viewDidLoad
 if _toggle = 2;
 frame = CGRectMake(924.0f, 59.0f, audioToggle.frame.size.width, audioToggle.frame.size.height)

and
if _toggle = 1;
 frame = CGRectMake(985.0f, 59.0f, audioToggle.frame.size.width, audioToggle.frame.size.height)

But in your buttonAction it is different. Interchange in viewDidLoad if buttonAction is correct.

A: I suspect Anusha got it. But I also suspect you would easily have found it yourself if you'd chosen a slightly different style. The toggle is either on or off, in other words a perfect match for a boolean. If you had a BOOL named swicthedOn you'd have checks reading if (switchedOn) which would improve readability a lot.
Something like this perhaps:
- (IBAction)theSwitch:(id)sender { // Not using the sender for anything (?)
    NSUserDefaults *toggle = [NSUserDefaults standardUserDefaults];
    BOOL audioOn = NO;
    float toggleX = 924.0f;

    if (_switchIsOn) {
        toggleX = 985.0f;
        audioOn = NO; // not strictly necessary but improves readability
    }
    else {
        toggleX = 924.0f; // not strictly necessary but improves readability
        audioOn = YES;
    }

    _switchIsOn = audioOn;
    [UIView animateWithDuration:0.3 animations:^{
        audioToggle.frame = CGRectMake(toggleX, 59.0f, audioToggle.frame.size.width, audioToggle.frame.size.height);
    }];

    [toggle setBool:_switchIsOn forKey:@"toggleState"];
    [toggle synchronize];
    [[NSUserDefaults standardUserDefaults] setBool:audioOn forKey:@"audioOn"]; // Not being synchronized
}

Yes, I refactored it (and probably introduced a couple of new bugs). Sorry, couldn't help myself...


Q: What's the path to global node_modules folder in Travis CI I need to pass the path for the node_modules global installation folder to the mink-zombie-driver, but I can't find anywhere in the docs what's the path for it.
MinkExtension requires you to pass the node_modules folder in the configuration file for Behat.


Q: Column-image hover text Hello everybody out there reading my question :)
I am currently working on website with a "Masonry-lookalike" home screen.
There are 4x4 images with 2 different sizes and 1 image in every column is hidden.
So far it went pretty good but now I am stuck on the text-effect when hovering one of the images.
When the cursor is hovering over an image, a small text-box should appear on the bottom of it.

*

*How do i get them one above the other without ruining the Masonry?

*Where do i place the Text in the html code?
Sorry for my English, its not the best since I am from Austria ;)
HTML:
<!DOCTYPE html>

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

    <meta charset="utf-8">

CSS:
body {
    margin: 0;
    padding: 0;
}
#img-container {
    width: 1200px;
    margin: 0 auto;
    font-size: 0;
}
#content {
    column-count: 4;
    column-gap: 10px;
}
#content li img {
    margin-bottom: 10px;
    width: 100%;
    display: block;
}
/* ---------------------  HOVER EFFECTS  --------------------- */

.img_a:hover {
    opacity: 0.5;
}
.img_b:hover {
    opacity: 0.5;
}
.img_c:hover {
    opacity: 0.5;
}

I will append some zip.-file with .css .html and images.
Link to Dropbox

A: The following writeup might help you:
http://geekgirllife.com/place-text-over-images-on-hover-without-javascript/
It is one of the simplest methods I came across. Place the div tag containing text right below the img tag.


Q: AS3 undefined property stageVideos I have an AS3 Mobile AIR project targeting iOS and Android. For some reason when I try to access stageVideos i.e. stage.stageVideos[0]...there is NO stageVideos property available on stage?? Very strange as I've done it before. My app is using Starling and Features UI framework, and my class is extending Screen. I'm fairly new to both frameworks but have been AS veteren. Thanks!

A: Should be hardware problem. When StageVideo is not available on particular device stage.stageVideos property is empty, so to make sure you should make check like this.
var stageVideo:StageVideo;

if ( stage.stageVideos.length >= 1 ) {
    stageVideo = stage.stageVideos[0];
}

or register  StageVideoAvailabilityEvent on stage
stage.addEventListener(StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY, stageVideoChange);

private function stageVideoChange(e:StageVideoAvailabilityEvent):void
{
    if(e.availability == AVAILABLE)
    {
         // (stage.stageVideos.length >= 1) is TRUE so we can use stageVideo[0]
    }
    else
    {
         // StageVideo become unavailable for example after going from fullscreen
         // back to wmode=normal, wmode=opaque, or wmode=transparent
    }
}

Of course second approach is more acceptable because you are notified every time StageVideo becomes available or negative. Note if stage video is available at the moment of registering Listener on StageVideoAvailabilityEvent then listener function (stageVideoChange) is called immediately.

A: Turns out Starling runs on Stage3D on TOP of the actual flash display stage. So in order to do this, you need to hide the Starling Stage3D first:
Starling.current.stage3D.visible = false

Then you can access and show...etc stageVideos and add to the flash display stage:
_stageVideo = Starling.current.nativeStage.stageVideos[0];

So basically, the native flash display stage is on the Starling.current.nativeStage property, however, can not be visible unless you first hide the Starling.current.stage3D FIRST.
Thanks for the responses! Hope this helps anyone else with the same problem.


Q: regex breaks when I use a colon(:) I just started working with elastic search. By started working I mean I have to query an already running elastic database.  Is there a good documentation of the regex they follow. I know about the one on their official site, but its not very helpful.
The more specific problem is that I want to query for lines of the sort:
10:02:37:623421|0098-TSOT {TRANSITION} {ID} {1619245525} {securityID} {} {fromStatus} {NOT_PRESENT} {toStatus} {WAITING}
or
01:01:36:832516|0058-CT {ADD} {0} {3137TTDR7} {23} {COM} {New} {0} {0} {52} {1}
and more of a similar structure. I don't want a generalized regex. If possible, could someone give me a regex expression for each of these that would run with elastic?
I noticed that it matches if the regexp matches with a substring too when I ran with:
query = {"query":
             {"regexp":
                  {
                      "message": "[0-9]{2}"
                  }
              },
         "sort":
             [
                 {"@timestamp":"asc"}
             ]
         }

But it wont match anything if I use:
query = {"query":
             {"regexp":
                  {
                      "message": "[0-9]{2}:.*"
                  }
              },
         "sort":
             [
                 {"@timestamp":"asc"}
             ]
         }

I want to write regex that are more specific and that are different for the two examples given near the top.

A: turns out my message is present in the tokenized form instead of the raw form, and : is one of the default delimiters of the tokenizer, in elastic. And as a reason, I can't use regexp query on the whole message because it matches it with each token individually.


Q: How to add groups to asp.net dropdownlist control? I have to implement groups in asp.net dropdownlist.
eg: I have a classname as dropdownlist group and students in the class as its options.
How can I implement this using  JqueryUI Multiselect.


Q: Select-Object with output from 2 cmdlets Suppose I have the following PowerShell script:
Get-WmiObject -Class Win32_Service |
Select DisplayName,@{Name="PID";Expression={$_.ProcessID}} |
Get-Process |
Select Name,CPU

This will:
Line 1: Get all services on the local machine
Line 2: Create a new object with the DisplayName and PID.
Line 3: Call Get-Process for information about each of the services.
Line 4: Create a new object with the Process Name and CPU usage.
However, in Line 4 I want to also have the DisplayName that I obtained in Line 2 - is this possible?

A: One way to do this is to output a custom object after collecting the properties you want. Example:
Get-WmiObject -Class Win32_Service | foreach-object {
  $displayName = $_.DisplayName
  $processID = $_.ProcessID
  $process = Get-Process -Id $processID
  new-object PSObject -property @{
    "DisplayName" = $displayName
    "Name" = $process.Name
    "CPU" = $process.CPU
  }
}

A: A couple of other ways to achieve this:
Add a note property to the object returned by Get-Process:
Get-WmiObject -Class Win32_Service |
Select DisplayName,@{Name="PID";Expression={$_.ProcessID}} |
% {
    $displayName = $_.DisplayName;
    $gp = Get-Process;
    $gp | Add-Member -type NoteProperty -name DisplayName -value $displayName;
    Write-Output $gp
} |
Select DisplayName, Name,CPU

Set a script scoped variable at one point in the pipeline, and use it at a later point in the pipeline:
Get-WmiObject -Class Win32_Service |
Select @{n='DisplayName';e={($script:displayName =  $_.DisplayName)}},
       @{Name="PID";Expression={$_.ProcessID}} |
Get-Process |
Select @{n='DisplayName';e={$script:displayName}}, Name,CPU

A: Using a pipelinevariable:
Get-CimInstance -ClassName Win32_Service -PipelineVariable service |
Select @{Name="PID";Expression={$_.ProcessID}} |
Get-Process |
Select Name,CPU,@{Name='DisplayName';Expression={$service.DisplayName}}


Q: How to insert a existing json data into new object? I have a json data is in this form
[ { id: '1', name: 'Plant Director', parentJobID: -1 },
  { id: '19', name: 'Operations Director', parentJobID: 1 },
  { id: '16',
    name: 'Financial planning and costs Manager',
    parentJobID: 19 },
  { id: '14', name: 'Cost Analyst', parentJobID: 16 },
  { id: '15', name: 'Head of Costs', parentJobID: 16 },
  { id: '17', name: 'Manufacturing Manager', parentJobID: 19 },
  { id: '2', name: 'Head of Security', parentJobID: 17 },
  { id: '3', name: 'Asistente Ejecutiva', parentJobID: 2 },
  { id: '8', name: 'Jefe de Mantenimiento', parentJobID: 2 },
  { id: '27',
    name: 'Jefe Aseguramiento de Calidad',
    parentJobID: 2 },
  { id: '28', name: 'Jefe Seguridad Alimentaria', parentJobID: 27 },
  { id: '33', name: 'Operario Fabricación A (2)', parentJobID: 28 },
  { id: '34', name: 'Operario Fabricación B (2)', parentJobID: 28 },
  { id: '29',
    name: 'Especialista Aseguramiento de Calidad',
    parentJobID: 27 },
  { id: '30',
    name: 'Especialista en Microbiología',
    parentJobID: 27 },
  { id: '31',
    name: 'Especialista en Evaluación Sensorial',
    parentJobID: 27 },
  { id: '32',
    name: 'Técnico Aseguramiento de Calidad',
    parentJobID: 27 },
  { id: '4', name: 'Production Manager', parentJobID: 17 },
  { id: '5', name: 'Head of Maintenance', parentJobID: 17 },
  { id: '6', name: 'Quality Control Manager', parentJobID: 17 },
  { id: '7', name: 'Técnico Medio Ambiente', parentJobID: 6 },
  { id: '23',
    name: 'Quality Control Technician 1',
    parentJobID: 6 },
  { id: '25', name: 'Operario Fabricación B', parentJobID: 23 },
  { id: '26', name: 'Operario Fabricación D', parentJobID: 23 },
  { id: '24',
    name: 'Quality Control Technician 2',
    parentJobID: 6 },
  { id: '9', name: 'Warehouse Manager', parentJobID: 17 },
  { id: '10', name: 'Head of Planning', parentJobID: 17 },
  { id: '20', name: 'Operario Mtto A (2)', parentJobID: 10 },
  { id: '11',
    name: 'Head of Continuous Improvement',
    parentJobID: 17 },
  { id: '21', name: 'Operario Servicios A (2)', parentJobID: 11 },
  { id: '12', name: 'Head of Supplies', parentJobID: 17 },
  { id: '13', name: 'Process Manager', parentJobID: 17 },
  { id: '18', name: 'IT Manager', parentJobID: 17 },
  { id: '35', name: '[ LINEA DE PRODUCCION ]', parentJobID: 1 },
  { id: '22', name: 'Extrusion Area', parentJobID: -1 } ]

then i change it into hierarchy form like:
[ { id: '1',
    name: 'Plant Director',
    parentJobID: -1,
    children: [ [Object], [Object] ] },
  { id: '22',
    name: 'Extrusion Area',
    parentJobID: -1,
    children: [] } ]

i want to show like this
  http://www.jqueryscript.net/demo/jQuery-Plugin-To-Create-Checkbox-Tree-View-highchecktree/
but in this they used item label which is not in my response  i need to change the josn in this form

 item:{
                id: '1',
                label: 'Plant Director',
                checked: false
            },
            children: [{
               item:{
                    id: '19',
                    label: 'Operations Director',
                    checked: false
                }
            },{
               item:{
                    id: '35',
                    label: '[ LINEA DE PRODUCCION ]',
                    checked: false
                }
            }
            }]


Q: TypeError: Cannot interpret feed_dict key as Tensor, need to understand sessions and graphs I'm new to tensorflow and posting this using mobile. I actually wanted the session to alive so used the following way of coding. However,  in one place I can see Placeholder node existing,  but error comes up saying the node doesn't exist. I doubt on the same graph being used.
class Model(object):

    def __init__(self, model_path):
        self.sess = tf.Session()
        self.graph = tf.Graph()
        self.graph_def = tf.GraphDef()

        with open(model_path, "rb") as f:
            self.graph_def.ParseFromString(f.read())

        with tf.Graph().as_default() as self.graph:
            tf.import_graph_def(self.graph_def)

        self.input_operation = self.graph.get_operation_by_name('import/Placeholder')
        self.output_operation = self.graph.get_operation_by_name('import/final_result')

    def predict(self, images):
        dims_expander = tf.expand_dims(images, 0)
        resized = tf.image.resize_bilinear(dims_expander, [299, 299])
        normalized = tf.divide(tf.subtract(resized, [0]), [255])
        print(normalized)
        for op in self.graph.get_operations():
            print(op.name)
            results = self.sess.run(self.output_operation.outputs[0], {self.input_operation.outputs[0]: self.sess.run(normalized)})
        results = np.squeeze(results)
        top_k = results.argsort()[-5:][::-1]
        labels = ['1','0']
        print(labels[top_k[0]], results[top_k[0]])

And then making an object.
model = Model('identification_model.pb').predict(img_from_openCV)

The following is the output error including the print statement that printed the first node to be import/Placeholder
Tensor("truediv_13:0", shape=(1, 299, 299, 3), dtype=float32)
import/Placeholder
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
   1091             subfeed_t = self.graph.as_graph_element(
-> 1092                 subfeed, allow_tensor=True, allow_operation=False)
   1093           except Exception as e:

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py in as_graph_element(self, obj, allow_tensor, allow_operation)
   3489     with self._lock:
-> 3490       return self._as_graph_element_locked(obj, allow_tensor, allow_operation)
   3491

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py in _as_graph_element_locked(self, obj, allow_tensor, allow_operation)
   3568       if obj.graph is not self:
-> 3569         raise ValueError("Tensor %s is not an element of this graph." % obj)
   3570       return obj

ValueError: Tensor Tensor("import/Placeholder:0", shape=(?, 299, 299, 3), dtype=float32) is not an element of this graph.

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)

----> 1 model = Model('identification_model.pb').predict(img)

     32         for op in self.graph.get_operations():
     33             print(op.name)
---> 34             results = self.sess.run(self.output_operation.outputs[0], {self.input_operation.outputs[0]: self.sess.run(normalized)})
     35         results = np.squeeze(results)
     36         top_k = results.argsort()[-5:][::-1]

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in run(self, fetches, feed_dict, options, run_metadata)
    927     try:
    928       result = self._run(None, fetches, feed_dict, options_ptr,
--> 929                          run_metadata_ptr)
    930       if run_metadata:
    931         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
   1093           except Exception as e:
   1094             raise TypeError(
-> 1095                 'Cannot interpret feed_dict key as Tensor: ' + e.args[0])
   1096
   1097           if isinstance(subfeed_val, ops.Tensor):

TypeError: Cannot interpret feed_dict key as Tensor: Tensor Tensor("import/Placeholder:0", shape=(?, 299, 299, 3), dtype=float32) is not an element of this graph.

A: When you create the session, the default graph is launched by default, which does not contain the operations you are looking for (they are all in self.graph). You should do something like this:
with tf.Session(self.graph) as sess:
    sess.run(...)

Now, sess will have access to self.input_operation and self.output_operation. In your code, this means you should create the session after you create self.graph. By the way, most of the time it is more convenient to just use the default graph (exactly to avoid problems like these). May be this post will also help you in this regard.