text:
Q: bootstrap not loading on a specific url in my spring boot project iam using bootstrap in my project,
to do that iam including it and jquery in my pom.xml, and i add
 href="webjars/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"
 src="webjars/jquery/1.9.1/jquery.min.js"
 script src="webjars/bootstrap/3.3.6/js/bootstrap.min.js"

in my jsp, and all of them seem to run bootstrap fine, only one, which is at directory "/student/{Cid}", just wont load bootstrap, it looks like plane html with no css.
here is my student controller:
@Controller
@RequestMapping(value = "/student")
public class StudentController {

@Autowired
private StudentDao dao;

@RequestMapping(method = RequestMethod.GET)
public String showStudentPage(ModelMap model, HttpServletRequest request) {
    String UserID = SecurityContextHolder.getContext().getAuthentication().getName();

    Student currentStudent = dao.getStudent(Integer.parseInt(UserID));
    model.put("name", currentStudent.getName());
    ArrayList<CourseMark> list =  dao.getStudentCourses(currentStudent.getId());
    model.put("StudentCourse",list);

    return "studentPage";
}
@RequestMapping(method = RequestMethod.POST)
public String test(@RequestParam String Cid) {
    return "redirect:/student/"+Cid;
}

@RequestMapping(value = "/{Cid}", method = RequestMethod.GET)
public String showMarkDetails(ModelMap model,@PathVariable String Cid) {
    String UserID = SecurityContextHolder.getContext().getAuthentication().getName();

    List<Float> marks = dao.getCourseMarks(Cid);
    CourseMark CM=dao.getStudentCourse(Integer.parseInt(UserID),Cid);

    double max = Collections.max(marks);
    double min = Collections.min(marks);
    double avg = marks.stream().mapToDouble(d -> d).sum() / marks.size();
    Collections.sort(marks);
    double mid = marks.size() % 2 != 0 ? marks.get(marks.size() / 2) :
            (marks.get(marks.size() / 2) + marks.get(marks.size() / 2 - 1)) / 2;
    model.put("ID",Cid);
    model.put("Mark",CM.getMark());
    model.put("min",String.format("%.1f",min));
    model.put("max",String.format("%.1f",max));
    model.put("avg",String.format("%.1f",avg));
    model.put("mid",String.format("%.1f",mid));
    model.put("Cname",CM.getCourseName());

    return "markDetails";
}

}

my pom :
   <?xml version="1.0" encoding="UTF-8"?>
<project 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 https://maven.apache.org/xsd/maven-
 4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.7</version>
        <relativePath/>
    </parent>
    <groupId>com.gradingSystem</groupId>
    <artifactId>spring-grading-system</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>spring-grading-system</name>
    <description>part 3 of the webApp assignment</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
            <version>2.5.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.taglibs</groupId>
            <artifactId>taglibs-standard-spec</artifactId>
            <version>1.2.5</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.3.6</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>1.9.1</version>
        </dependency>
        <dependency>
        <groupId>org.apache.taglibs</groupId>
        <artifactId>taglibs-standard-impl</artifactId>
        <version>1.2.5</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

the jsp im trying to use bootstrap on :

    <title>Details of ${Cname}</title>
    <link href="webjars/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">

Details of ${Cname}

                  ID
                  Your Mark
                  Course Minimum
                  Course Maximum
                  Course average
                  Course median

                ${ID}
                ${Mark}
                ${min}
                ${max}
                ${avg}
                ${mid}

    <form action="/student" method="GET">
        <input type="submit" value="Back" class="btn btn-primary" style="width: 100px;">
    </form>

i cant figure out what the problem is
ive tried turning off security and it didnt work.
the bootstrap seems to run everywhere else. but when i get into that url, it just wont load.

A: it was because im using a relative path, my solution was to add"../" to the start of the link and it fixed it !
href="../webjars/bootstrap/5.0.2/css/bootstrap.min.css" rel="stylesheet"
thanks to @HopeyOne


text:
Q: Text Field cuts off first emoji when typing I have a text field that sizes to the amount of text it has. It looks fine when you are not typing, but when you begin typing it shifts the emojis to the left and causes the first emoji to be cut off (it works fine with text).
I am not doing any manual resizing, just using sizeToFit().
Code:
override func viewDidLoad() {
    super.viewDidLoad()
    let emojiTextField = UITextField.makeEmojiTextField()
    emojiTextField.delegate = self

    view.addSubview(emojiTextField)
    emojiTextField.anchorCenterSuperview()
}

class EmojiTextField: UITextField {
    override var textInputMode: UITextInputMode? {
        for mode in UITextInputMode.activeInputModes {
            if mode.primaryLanguage == "emoji" {
                return mode
            }
        }
        return nil
    }
}

extension UITextField {
        static func makeEmojiTextField() -> EmojiTextField {
            let tf = EmojiTextField()
            tf.placeholder = ""
            tf.font = UIFont.systemFont(ofSize: 64)
            tf.borderStyle = UITextField.BorderStyle.none
            tf.autocorrectionType = UITextAutocorrectionType.no
            tf.returnKeyType = UIReturnKeyType.done
            tf.contentVerticalAlignment = UIControl.ContentVerticalAlignment.center
            tf.backgroundColor = .green
            return tf
        }
    }

extension UIView {
    public func anchorCenterXToSuperview(constant: CGFloat = 0) {
        translatesAutoresizingMaskIntoConstraints = false
        if let anchor = superview?.centerXAnchor {
            centerXAnchor.constraint(equalTo: anchor, constant: constant).isActive = true
        }
    }

    public func anchorCenterYToSuperview(constant: CGFloat = 0) {
        translatesAutoresizingMaskIntoConstraints = false
        if let anchor = superview?.centerYAnchor {
            centerYAnchor.constraint(equalTo: anchor, constant: constant).isActive = true
        }
    }

    public func anchorCenterSuperview() {
        anchorCenterXToSuperview()
        anchorCenterYToSuperview()
    }
}

Emojis fit fine when not typing:

First emoji is cut off when typing:

A: Have you set any constraints to your text field?
if not try adding it to stack view and I believe it should work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: CSS/JS: Is it possible to make a div (with a background image) have a diagonal border rather than a square one Consider the following fiddle: http://jsfiddle.net/xNSm2/
In this scenario I've got a div with a background-image of a triangle. I also have a div underneath it.
I need both of those divs to be clickable.
I cannot have the red div sit on top of the green div. Red must be underneath.
The only solution I can think of is to have the green div have a diagonal border, rather than a square one. Is this possible?


text:
Q: ReactJS - {this.props.children} is undefined I have seen many post related this argument but i'm not able to understand why {this.props.children} is undefined in my application (i'm really new to ReactJS)
Starting with App.js that is my main component i have this:
import React, {Component} from 'react';
import Dashboard from './layouts/Dashboard';

class App extends Component {
    render() {
        return(

                <Dashboard />

        );
    }
}

So, Dashboard.js have to code to render a top bar and a left-side bar, the "dynamic" content will go on the center (and this is where i have placed {this.props.children})
Dashboard.js

render() {
    return(

            <-- this is the dynamic content -->

                {this.props.children}

    );
}

The router right now is very simple:
<Route component={App}>
    <Route path='/' component={Home} />
</Route>

I have omitted the code related to Home.js, but this is a simple div that print in statyc way "Hello World"
Dashboard component is renderd but no "Hello World" is placed in the part where i have {this.props.children}

A: You can't access the children of your component through this.props.children. this.props.children designates the children being passed onto you by the owner:
var App = React.createClass({
  componentDidMount: function() {
    // This doesn't refer to the `span`s! It refers to the children between
    // last line's `<App></App>`, which are undefined.
    console.log(this.props.children);
  },

  render: function() {
    return

;
  }
});

ReactDOM.render(<App></App>, mountNode);

To access your own subcomponents (the spans), place refs on them https://facebook.github.io/react/docs/more-about-refs.html

A: You have to pass children to Dashboard:
class App extends Component {
    render() {
        return(

                <Dashboard>{this.props.children}</Dashboard>

        );
    }
}

A: Dashboard has no children.
Change <Dashboard /> to <Dashboard>{this.props.children}</Dashboard> in App.js so  your Dashboard component can have access to the component you pass through the Route.

A: You can check if children exists in your Dashboard.js
render() {
  return
{this.props.children !== undefined && this.props.children}

}


text:
Q: Plain C - Array pointers I have structure to hold pointer to array of input numbers. When I create matrix I also create default data array. As I suppose the m.data = data; means that m.data pointer points at first element of the array. When I print data right after alocation everything seems ok. But when I print them after in the main function the result is different.
Why does output differs(commented sections)?
#include <stdio.h>
#include <stdlib.h>

typedef struct matrix {
    int *data;
    int rows;
} Matrix;

//Create Matrix
extern Matrix create_matrix(int size)
{
    int data[size * size];

    int i = 0;
    for(i = 0; i < size * size; i++)
    {
        data[i] = 0;
    }

    Matrix m;
    m.data = data;

    for(i = 0; i < size * size; i++)
    {
        printf("%d\n",*(m.data + i)); //<--- m.data {0,0 ..... ,0,0,0}

    }

    m.rows = size;
    return m;
};

extern void supply_row_data(Matrix m, int row, int* data)
{
    int i = 0;
    for(i = 0; i < m.rows; i++)
    {
        m.data[i] = data[i];
    }
};

int main(){
    int size = 4;
    Matrix m = create_matrix(size);

    int i = 0;
    int *j = m.data;

    for(i = 0; i < size * size; i++)
    {
            //*(j + i) = i;

        printf("%d\n", *(j + i));
    }
    getch();
}

A: int data[size * size];

This is a local variable (array) to the function create_matrix It goes out of scope when the function terminates.
m.data = data;

This does not copy the data in the variable data to the data in the variable m.data but rather sets the pointer m.data to the beginning of the array data. When the function returns, the Matrix returned contains what is called a dangling pointer: a pointer to data that no longer exists.
Use the advice from @RSahu to fix this.

A: That's not how you can copy the data from an array in C.
You need to:

*

*Allocate memory for the data.
m.data = malloc(sizeof(int)*size*size);

*Copy the data one element at a time or using memcpy.
memcpy(m.data, data, sizeof(int)*size*size);

*Make sure you deallocate the memory allocated to hold the matrix data.
free(m.data);

A: You should avoid using pointer to local data once function return address of array is no loger valid try to allocate array in following way
int* allocate_vector(size_t elem, int value){
   int* vec = (int *) calloc(elem, sizeof(int));
   int i = 0;
   for( ; i < elem; i++){
      *(vec + i) = value;
   }
   return vec;
}


text:
Q: Prove a function is one-to-one and onto I need some help proving the following function is one-to-one and onto for $\mathbb{N} \times \mathbb{N} \rightarrow \mathbb{N}$.
$F(i, j) = {i + j - 1 \choose 2} + j$
I know you guys like to see some attempt at a problem but I honestly have no idea where to start. A naive attempt simply making $F(i, j) = F(n, m)$ seems like it will have way too many cases to prove and I'm not even sure if that will prove 1-1. Is the best approach to define some sort of function and show it is invertible?

A: You could start by listing the function values out in a grid.  You might see something like the following:
$$
\begin{array}{cccccccccc}
 1 & 3 & 6 & 10 & 15 & 21 & 28 & 36 & 45 & 55 \\
 2 & 5 & 9 & 14 & 20 & 27 & 35 & 44 & 54 & 65 \\
 4 & 8 & 13 & 19 & 26 & 34 & 43 & 53 & 64 & 76 \\
 7 & 12 & 18 & 25 & 33 & 42 & 52 & 63 & 75 & 88 \\
 11 & 17 & 24 & 32 & 41 & 51 & 62 & 74 & 87 & 101 \\
 16 & 23 & 31 & 40 & 50 & 61 & 73 & 86 & 100 & 115 \\
 22 & 30 & 39 & 49 & 60 & 72 & 85 & 99 & 114 & 130 \\
 29 & 38 & 48 & 59 & 71 & 84 & 98 & 113 & 129 & 146 \\
 37 & 47 & 58 & 70 & 83 & 97 & 112 & 128 & 145 & 163 \\
 46 & 57 & 69 & 82 & 96 & 111 & 127 & 144 & 162 & 181 \\
\end{array}
$$
Now, can you explain that?  One hint might be to look up triangular numbers.

A: I would like to point out I love Mark's answer. Triangular numbers are these ones. and they are of the form $\binom{n+1}{2}$

A: Surjectivity of  $F(i, j) = {i + j - 1 \choose 2} + j$.
Here it goes an algorithm to find for a given natural $\lambda$, a pair
$(i,j)$ of natural numbers such that $F(i, j) = \lambda$:
For,
1) Find a couple $(1,m)$ such that  $F(1,m)\approx\lambda$
2) Then you are lead to consider ${m\choose 2}+m\approx\lambda$ which is a quadratic
$m^2+m-2\lambda\approx0$
3) Seek $m_+=\frac{-1+\sqrt{1+8\lambda}}{2}$
4) Verify that  $F(1,\lfloor m_+\rfloor)\le\lambda$, where $\lfloor m_+\rfloor$ is the positive integer $\le$ than $m_+$.
5)  Take $r=\lambda-F(1,\lfloor m_+\rfloor)$
6) Then $F(\lfloor m_+\rfloor+2-r,r)=\lambda$
Check the next exemplification:

Do you need $i,j\in{\Bbb{N}}$ such that $F(i,j)=308$?

-- Find the greatest solution for $m^2+m-616=0$:
-- this is $m_+=\frac{-1+\sqrt{1+2464}}{2}=24.3243...$
-- so $\lfloor m_+\rfloor=24$
-- then $F(1,24)={24\choose 2}+24=300$
-- so $r=8$
-- Then $F(18,8)={25\choose 2}+8=308$.
Injectivity of  $F(i, j) = {i + j - 1 \choose 2} + j$.
(Pending)


text:
Q: jQuery selector from $.get()? I have some code to fetch data using $.get(), and that pulls the entire page in HTML fine.
How do I go about using selectors on that get data and pulling certain data from elements as I would using $('.someclass') in a normal page?

A: It is just text until you insert it into the DOM somehow. You could have a hidden DIV and do:
$('#myhiddendiv').html( data_from_get );

and then search the descendants of #myhiddendiv.

A: If you can use plugin then you can use the following like jQuery.load() does.
/************************************************
jquery.get-enhanced plugin v0.10
Author: www.benbarnett.net || @benpbarnett

Copyright (c) 2011 Ben Barnett
Licensed under the MIT license
http://www.opensource.org/licenses/mit-license.php
*************************************************/
(function(b,j){b.get=function(a,c,d,e){var f=a.indexOf(" ");if(f>=0){var k=a.slice(f,a.length);a=a.slice(0,f)}else return j.apply(this,arguments);if(b.isFunction(c)){e=e||d;d=c;c=null}var l=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi;return b.ajax({type:"GET",url:a,data:c,success:function(h,g){var i="";if(g==="success"||g==="notmodified")i=b("<div>").append(h.replace(l,"")).find(k).html();d&&d.apply(this,[i,g,h])},dataType:e})}})(jQuery,jQuery.get);

You can use like this:
// use space    VV and add class or id which you want to get
$.get( "url.html .someclass", function( data ) {
    $( ".where_to_insert_data" ).html( data );
});

A: say if your GET response data in variable like this response then you can find any selector in it using this
$(response).find('selector');

hope it helps


text:
Q: HTML background image flashing I am trying to create a website and the login page will have a background that has a series of 10 or so images that gradually fade in and fade out at intervals of a few seconds. For some reason, when the images change, there is a brief split second where I notice a flash with the background color (white in my case). I am assuming it is because the images are taking a long time on loading in real time, given that these are extremely good quality images on the order of 3-6 MB each. When everything is done loading, it appears to transition more smoothly.
I have the following code:
    <!DOCTYPE html>
<HTML lang="en">
<HEAD>
  <TITLE>Troubleshoot</TITLE>
  <META charset="utf-8">
  <SCRIPT src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></SCRIPT>
  <SCRIPT type="text/javascript">
    $(document).ready(function () {
      let imgs = ['joshua-sortino-498896-unsplash.jpg', 'theodor-lundqvist-438530-unsplash.jpg', 'cristian-moscoso-1924-unsplash.jpg', 'nathan-dumlao-576639-unsplash.jpg', 'anthony-delanoix-575672-unsplash.jpg', 'karim-manjra-702188-unsplash.jpg', 'jay-dantinne-499958-unsplash.jpg', 'jeremy-bishop-346050-unsplash.jpg', 'robert-tudor-704838-unsplash.jpg', 'john-towner-126926-unsplash.jpg', 'bady-qb-751603-unsplash.jpg', 'caleb-miller-738108-unsplash.jpg', 'christopher-czermak-705859-unsplash.jpg', 'jonathan-gallegos-727409-unsplash.jpg', 'justin-lane-753659-unsplash.jpg', 'michael-liao-725983-unsplash.jpg', 'raphael-nogueira-559166-unsplash.jpg', 'robin-noguier-572033-unsplash.jpg', 'sorasak-252182-unsplash.jpg', 'usukhbayar-gankhuyag-726907-unsplash.jpg'];
      $(function () {
          let i = 0;
          setInterval(function () {
              i++;
              if (i == imgs.length) {
                  i = 0;
              }
                  $('body').css('background-image', 'url(../images/backgrounds/' + imgs[i] + ')');
          }, 5000);
      });
    });
  </SCRIPT>
  <STYLE>
  body {
      background-image: url('../images/backgrounds/sorasak-252182-unsplash.jpg');
      background-repeat: no-repeat;
      background-attachment: fixed;
      background-position: center;
      background-size: cover;
      opacity: 1.0;
      transition: background 4s cubic-bezier(0.4, 0, 1, 1);
  }
  </STYLE>
</HEAD>
<BODY>
</BODY>
</HTML>

Is there a better way of accomplishing this background fading effect than what I currently have here? Any suggestions or tips to make this better? Thanks a ton!

A: You can preload images so they are ready to go when they eventually need to transition.
function preloader() {
    if (document.images) {
        var img1 = new Image();
        var img2 = new Image();
        var img3 = new Image();

        img1.src = "http://domain.tld/path/to/image-001.gif";
        img2.src = "http://domain.tld/path/to/image-002.gif";
        img3.src = "http://domain.tld/path/to/image-003.gif";
    }
}
function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}
addLoadEvent(preloader);

A: Other option is a unique image with all backgrounds and you change the range displayed in css with "#bg{clip: top, right, bottom, left;}". Problem: your bg can have a long time load.
Preload is good idea! But with all background in one image you can any (or part of) image when you to open page.
Preload Problem: with preloader your bg will display only after loaded all imagens!
Soluction for preload problem: You can a array that control how image has loaded and change btw images.
function nextBg(){
if(this.currentImage < this.arrayLoadedImagens.length)
  this.currentImege++
else
  this.currentImage = 0;
}


text:
Q: If $n>1$ is odd, show that $n$ divides an element of $\{2^1-1, 2^2-1, \cdots , 2^{n-1}-1\}$ Consider the numbers: $\{2^1-1, 2^2-1, \cdots , 2^{n-1}-1\}$
Let $n$ be an odd number $> 1$.
Show that it's not possible for each of the numbers in the above set to leave a different remainder among $\{1,2,3,....,n-1\}$
Now my solution goes as follows:
$\phi(n)<n$ and so $n\mid 2^{\phi(n)}-1$, thus contradicting the statement.
But I want a solution/proof using Combinatorics and contradiction.

A: We have to prove that $2^a\cong 1$ holds for at least one $a\in\{1,2,\dots,n-1\}$.
Suppose not, then by the pidgeonhole principle (we are assuming $2^a$ never takes on $0$ or $1$ for $a\in\{1,2,\dots,n-1\}$) there is $1\leq b<c\leq n$ so that $2^b\equiv 2^c\bmod n$. We conclude $2^{c-b}\equiv 1 \bmod n$.


text:
Q: recursive iteration through python dictionary from mongo This is the document I currently have in MongoDB.
{
"name":"food",
"core":{
    "group":{
         "carbs":{
            "abbreviation": "Cs"
            "USA":{
                "breakfast":"potatoes",
                "dinner":"pasta"
            },
            "europe":{
                "breakfast":"something",
                "dinner":"something big"
            }
        },
         "abbreviation": "Ds"
         "dessert":{
             "USA":{
                 "breakfast":"potatoes and eggs",
                 "dinner":"pasta"
        },
         "europe":{
                 "breakfast":"something small",
                 "dinner":"hello"
        }
    },
        "abbreviation": "Vs"
        "veggies":{
                        "USA":{
                                "breakfast":"broccoli",
                                "dinner":"salad"
                        },
                        "europe":{
                                "breakfast":"cheese",
                                "dinner":"asparagus"
                        }
                 }
            }
      }
 }

I extract the data from mongo with the following lines of code.
data = collection.foodie.find({"name":"food"}, {"name":False, '_id':False})
def recursee(d):
    for k, v in d.items():
        if isinstance(v,dict):
            print recursee(d)
        else:
            print "{0} : {1}".format(k,v)

However, when i run the recursee function, it fails to print group : carbs, group : dessert, or group : veggies.  Instead i get the below output.
breakfast : something big
dinner : something
None
abbreviation : Cs
breakfast : potatoes
dinner : pasta
None
None
breakfast : something small
dinner : hello
None
abbreviation : Ds
breakfast : potatoes and eggs
dinner : pasta
None
None
breakfast : cheese
dinner : asparagus
None
abbreviation : Vs
breakfast : broccoli
dinner : salad

Am i skipping something in my recursion that is bypassing printing the group and corresponding value?

A: From docs:

The return statement returns with a value from a function. return without an expression argument returns None. Falling off the end of a function also returns None.

Because your recursee has no return statement, i.e. it implicitly returns None, so next statement
print recursee(d)

executes recursee with d object as an argument and prints function output (which is None)
Try
def recursee(d):
    for k, v in d.items():
        if isinstance(v, dict):
            print "{0} :".format(k)
            recursee(v)
        else:
            print "{0} : {1}".format(k, v)


text:
Q: Remove gap between images in a flex box [Duplicate]
answer here Image inside div has extra space below the image
I display some images with different sizes along multiple rows.
Example here
But there are gaps between the rows. I've tried a lot, but couldn't find why.

      <Album :info="topAlbum" :width="layoutConfig[i].width"/>

And in Album.vue

And css:
.muralBox {
  margin: auto;
  max-width: 400px;
  min-width: 400px;
}
.wrapper {
  background: #1f1c2c;
  display: flex;
  flex-wrap: wrap;
}

A: I'm not sure if this is exactly what you wanted since I can't see how you styled them, but I just gave images 100% height and width and that basically did it in a codepen.
CodePen link
    .albums img{
      height: 100%;
      width: 100%;
     }


text:
Q: Why the following cannot compile? String s = new String({'h','e','l','l','o'});

I received the error:

1  Invalid expression term '{'

I thought {'h','e','l','l','o'} should be a character array, why did it fail to compile?

A: I think you mean:
String s = new String(new[] {'h','e','l','l','o'});

The code you had before was not initializing an array correctly. Check out the MSDN article on implicitly typed arrays for more info.
You could also explicitly specify the type of the array:
String s = new String(new char[] {'h','e','l','l','o'});

A: Try something like this:
String s = new String(new char [] {'h','e','l','l','o'});


text:
Q: Updating table based on date field without using loops with sql I have the following script I created to update a schedule table in Microsoft SQL Server. The primary key field is a date time and are individual dates on the calendar. The Employees are scheduled for 7 consecutive days and I need to alternate between 2 employees for seven days at a time going from each Monday through Sunday to the end of the year. I created the following script using loops and am looking for a way to accomplish it without using loops. Thanks!
DECLARE @z_start INT
DECLARE @z_date DATETIME

SET @z_date = '03/07/16'

WHILE(@z_date < '12/31/16')
BEGIN
    SET @z_start = 0

    WHILE(@z_start < 7) BEGIN
        UPDATE EmployeeOnCall
        SET employeeName = 'Jones, Jim'
        WHERE deptID = 25 AND weekDay = @z_date

        SET @z_date = DATEADD(dd, 1, @z_date)
        SET @z_start = @z_start + 1
    END

    SET @z_start = 0

    WHILE(@z_start < 7) BEGIN
        UPDATE EmployeeOnCall
        SET employeeName = 'Penton, Andy'
        WHERE deptID = 25 AND weekDay = @z_date

        SET @z_date = DATEADD(dd, 1, @z_date)
        SET @z_start = @z_start + 1
    END
END;

A: You could do this using DATEPART and a CTE.  Here's the relevant part:
;with wkNum as (
    SELECT weekDay, EmployeeName, deptID, (DATEPART(wk, weekDay) / 2) % 2 as period
    FROM EmployeeOnCall
)
UPDATE wkNum
SET employeename = CASE WHEN wkNum.period = 0 THEN 'Jones, Jim' ELSE 'Penton, Andy' END

The idea is to determine what week of the year it is, divide that by 2, and then modulo it by the number of employees you're dealing with.
And here's a test script:
DECLARE @test TABLE (weekDay datetime, employeename varchar(50), deptID int);

DEClARE @startdate datetime = '2016-02-16';
declare @enddate datetime = '2016-12-31';

;with
 N0 as (SELECT 1 as n UNION ALL SELECT 1)
,N1 as (SELECT 1 as n FROM N0 t1, N0 t2)
,N2 as (SELECT 1 as n FROM N1 t1, N1 t2)
,N3 as (SELECT 1 as n FROM N2 t1, N2 t2)
,N4 as (SELECT 1 as n FROM N3 t1, N3 t2)
,N5 as (SELECT 1 as n FROM N4 t1, N4 t2)
,N6 as (SELECT 1 as n FROM N5 t1, N5 t2)
,nums as (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as num FROM N6)
INSERT @test (weekDay, deptID)
SELECT DATEADD(day,num-1,@startdate) as thedate, 25
FROM nums
WHERE num <= DATEDIFF(day,@startdate,@enddate) + 1

;with wkNum as (
SELECT weekDay, EmployeeName, deptID, (DATEPART(wk, weekDay) / 2) % 2 as period FROM @test
)
UPDATE wkNum
SET employeename = CASE WHEN wkNum.period = 0 THEN 'Jones, Jim' ELSE 'Penton, Andy' END

SELECT * FROM @test

If you have a table of employees to pull from it might be expanded like so:
DECLARE @emps TABLE (Name varchar(100));

INSERT @emps VALUES ('Dan'), ('Joe'), ('Asdf')

UPDATE eoc
SET employeename = emp.Name
FROM EmployeeOnCall eoc
INNER JOIN (SELECT ROW_NUMBER() OVER(ORDER BY Name) rn, Name FROM @emps) emp
ON ((DATEPART(wk, weekDay) / 2) % (SELECT COUNT(*) FROM @emps)) + 1 = emp.rn

A: The best approach is to populated persisted Calendar table. Fill it with list of days that covers for the start 10 years, mark each day as workday or weekend day, append any columns you need. And simply join it, filter by edge dates you got.Your case does not demonstrate why you mentioned 7-days intervals. 7 days means every day. Let's say you have @startdate and @enddata variables. Let's generate date list and join it with destination table.
declare
  @startdate  datetime = '20150612',
  @enddate    datetime = '20160122',
  @period_len int

set @period_len = datediff(dd, @startdate, @enddate)

;with cteCounter as
(
  select top (@period_len)
    ROW_NUMBER() OVER(ORDER BY c.object_id) as counter
  from sys.columns c
  cross join sys.columns cc
  order by counter
),
cteCalendar as
(
  select c.counter, dateadd(dd, c.counter-1, @startdate) as calendar_date
  from cteCalendar c
  order by calendar_date
)
UPDATE e SET
  employeeName = 'Jones, Jim'
FROM EmployeeOnCall e
inner join cteCalendar c on c.calendar_date = e.weekDay
WHERE e.deptID = 25


text:
Q: I would like to effect the TextView from the json data I get from httpurlconnection //[(START)File:ThirdActivity.java] -->
package com.example.caleb.splash_screen;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.io.IOException;
import java.io.OutputStream;

public class ThirdActivity extends AppCompatActivity {
  //public String  text = "https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoItem.txt";

    public TextView text;

    private void writeStream(OutputStream out){
        String output = "Hello world";

       // out.write(output.getBytes());
        //out.flush();
    }

    /*private String readStream(InputStream is) {
        try {`enter code here`
            ByteArrayOutputStream bo = new ByteArrayOutputStream();
            int i = is.read();
            while(i != -1) {
                bo.write(i);
                i = is.read();
            }
            return bo.toString();
        } catch (IOException e) {
            return "";
        }
    }*/

    //[(START) readStream -->
    private String readStream(InputStream in) throws IOException {
    BufferedReader bin = new BufferedReader(new InputStreamReader(in));
    //temporary
        try {
            StringBuilder sb = new StringBuilder();
            String inputLine;
            while ((inputLine = bin.readLine()) != null) {
                sb.append(inputLine);
            }
            return sb.toString();

        } finally {

        }
    }
    //[(END) readStream -->

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_third2);

        text = (TextView)findViewById(R.id.textView);

        new JSONTask().execute("https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoItem.txt");

    }

}
//[(END)File:ThirdActivity] -->

//[(START)File:JSONTask] -->

package com.example.caleb.splash_screen;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v4.widget.TextViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by Caleb on 12/17/2017.
 */

public class JSONTask extends AsyncTask<String,String,String> {

//final TextView txt = (TextView)findViewById(R.id.textView);
    private Context context;

    public JSONTask(Activity ThirdActivity) {
        context = ThirdActivity;
    }

@Override
    protected String doInBackground(String... params) {
        BufferedReader reader = null;
        HttpURLConnection urlConnection = null;
        //{(START)] Working Connection:ALERT! Error within code will cause crash -->
        try {
            URL url = new URL(params[0]);
            Log.w("testing", "test");
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(false);
            urlConnection.connect();
            //urlConnection.setChunkedStreamingMode(0);
            //OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
            //writeStream(out);
            /*int a = urlConnection.getResponseCode();
            String b = String.valueOf(a);
            Log.e(b, "yesssssssssssssssss");*/

            InputStream in = urlConnection.getInputStream();
            //InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            reader = new BufferedReader(new InputStreamReader(in));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            /*String data = readStream(in);
            /*final TextView textView = (TextView) findViewById(R.id.textView);
            textView.setText("hello");
            */

            return buffer.toString();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            throw new RuntimeException(e);

        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //{(END)] Working Connection -->
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        TextView text = (TextView) ((AppCompatActivity) context).findViewById(R.id.textView);
        text.setText(result);

    }

}
//[(END)File:JSONTask] -->

/Desired Effect/

Blockquote

I would like to pull data from the json file that the url points to and change the TextView within the UI called textView. I don't understand how to access the findviewbyid within the AsyncTask. I've looked all throughout the internet and couldn't find anything :( Any suggestions are greatly appreciated!!

A: try weak reference to get textview in asynctask
//call async task
new JSONTask(yourTextView).execute();

//in your async task
  private final WeakReference<TextView> textViewReference;

    public JSONTask (TextView textView){
         textViewReference = new WeakReference<TextView>( textView);
    }

    @Override
    protected void onPostExecute() {

            TextView textView = textViewReference.get();
            //set values to text view

    }

A: I'm using OkHttp to do the same task in my apps

*

*HTTP/2 support allows all requests to the same host to share a socket.

*Connection pooling reduces request latency (if HTTP/2 isn't available).

*Transparent GZIP shrinks download sizes.

*Response caching avoids the network completely for repeat requests.
Add this dependency
implementation 'com.squareup.okhttp3:okhttp:3.9.1'

Then create/code a new Class named OkHttpHandler
class OkHttpHandler extends AsyncTask<String, String, String> {

        OkHttpClient client = new OkHttpClient();
        private volatile String data;

        public String getResult() {
            return data;
        }

        @Override
        protected String doInBackground(String... params) {

            try {
                Request.Builder builder = new Request.Builder();
                builder.url(params[0]);
                Request request = builder.build();

                Response response = client.newCall(request).execute();
                return response.body().string();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            data = s;
        }
    }
}

and use it like this way
String str = new OkHttpHandler().execute("http://www.<TEST>.com/json").get();

I also suggest to check whether Wi-fi-Connected/Bluetooth-Connected or PhoneData-Enabled is false if true/else, Proceed to your code


text:
Q: Promises and pagination in AngularJS I have a list of events that I'm trying to ng-repeat over. I'm also using UI-Bootstrap to create pagination off of those events. When I hard code that event data into my controller, I am able to display and flip through them no problem. However, when I try to grab that data from a service using promises, my code breaks. I have a feeling it's because I'm not writing my promise correctly (I'm new at them) so when the page loads that data hasn't yet been returned yet.
Here is my controller:
App.controller("EventsController", ['$scope', 'EventsService',       function($scope, EventsService) {
  $scope.events = [];
  $scope.itemsPerPage = 5; //items to show per page
  $scope.currentPage = 1;  //what page to start on

  EventsService.getEvents()
    .then(function(data) {
      $scope.events = data;
    }, function(error) {
     console.log(error);
  });

  $scope.totalItems = $scope.events.length;

 //determines total # of pages
 $scope.pageCount = function () {
  return Math.ceil($scope.events.length / $scope.itemsPerPage);
 };

$scope.$watch('currentPage + itemsPerPage', function() {
  var begin = (($scope.currentPage - 1) * $scope.itemsPerPage),
  end = begin + $scope.itemsPerPage;
  $scope.filteredEvents = $scope.events.slice(begin, end);
  });
}]);

And my service:
App.factory("EventsService", function($http) {
  return {
    getEvents : function() {
      return $http.get("/../../../test_event_data.json")
      .then(function(response) {
        if(typeof response.data === 'object') {
          return response.data;
        } else {
          return $q.reject(response.data);
        }
      }, function(response) {
          return $q.reject(response.data);
      });
    }
  }
});

And my view:

Filter Results

All

Events

Offerings

Upcoming Events&Offerings

{{event.title}}

{{event.location}}

{{event.time}}

{{event.description}}

    <pagination total-items="totalItems" items-per-page="itemsPerPage" ng-model="currentPage" ng-change="pageChanged()"></pagination>

Finally, a sample of the data I'm trying to return:
[{"id":1,"title":"massa quis augue luctus tincidunt   nulla","location":"Little Fleur","time":"8:33 AM","description":"rhoncus mauris enim leo rhoncus sed vestibulum sit amet cursus id","offering":true},
{"id":2,"title":"sapien ut nunc vestibulum ante","location":"Leroy","time":"6:07 PM","description":"vestibulum proin eu mi nulla ac enim in tempor turpis nec euismod scelerisque quam turpis adipiscing lorem vitae","offering":false},
{"id":3,"title":"sagittis nam congue risus semper porta volutpat","location":"Waubesa","time":"4:13 AM","description":"nisi at nibh in hac habitasse platea dictumst aliquam augue","offering":false},
{"id":4,"title":"consequat ut nulla sed","location":"Dahle","time":"2:08 AM","description":"ligula pellentesque ultrices phasellus id sapien in sapien iaculis congue vivamus metus","offering":false}]

A: Solved it:
Turns out I needed to put the logic all inside of the getEvents function. So:
EventsService.getEvents()
.then(function(data) {
  $scope.events = data;
  $scope.pageCount = function () {
    return Math.ceil($scope.events.length / $scope.itemsPerPage);
  };
  $scope.totalItems = $scope.events.length;
  $scope.$watch('currentPage + itemsPerPage', function() {
    var begin = (($scope.currentPage - 1) * $scope.itemsPerPage),
      end = begin + $scope.itemsPerPage;
    $scope.filteredEvents = $scope.events.slice(begin, end);
  });
}, function(error) {
  console.log(error);
});

A: This should also do the trick:
App.controller("EventsController", ['$scope', 'EventsService',       function($scope, EventsService) {
$scope.events = [];
$scope.itemsPerPage = 5; //items to show per page
$scope.currentPage = 1;  //what page to start on

EventsService.getEvents()
.then(function(data) {
    angular.forEach(data, function(value){
       $scope.events.push(value);
     });
 }, function(error) {
     console.log(error);
 });

$scope.pageCount = function () {
   return Math.ceil($scope.events.length / $scope.itemsPerPage);
 };


text:
Q: "The angriest Obama became with Clinton concerned" I read the following sentence from the NYT, and am not sure how this structure works, grammatically or idiomatically:

The angriest Obama became with Clinton, Landler says, concerned the Arab Spring and the uprising in Egypt's Tahrir Square.

I guess it supposed to be "The angriest Obama became with Clinton when the issue was concerned with the Arab Spring and the uprising in Egypt's Tahrir."
With the original sentence, I am confused exactly what is being modified by "concerned." And I am not sure if "concerned" is a proper way to say instead of "concerned with (the subject)."
I already asked the same question on wordreference.com, but I would like to get more help if possible.(http://forum.wordreference.com/threads/the-angriest-someone-became-with-someone-concerned.3178342/#post-16083750)
Thank you in advance:)

A: The angriest Obama became with Clinton /referred to/had to do with/was about/was related to/ the Arab Spring and the uprising in Egypt's Tahrir Square.

*

*concern - To have to do with or relate to: an article that concerns the plight of homeless people.

A: Concerned isn't modifying anything, because it isn't an adjective here.  It is the past tense of the verb concern.
The subject of that verb is Obama's anger.  It's not all of his anger, of course, but just his anger towards Clinton, further limited to that part of his anger with the greatest magnitude (or perhaps the anger at that moment when its magnitude was greatest).  That is, "the angriest."
The sentence isn't quite logical; it's trying to express a lot of ideas in a very few words, and it's easy to get tangled up in a situation like that.  A more logical rewrite might therefore be:

Obama's greatest anger towards Clinton, Landler says, concerned the Arab Spring and the uprising in Egypt's Tahrir Square.

Perhaps one problem with that sentence is that great has been moving away from its original sense of large.

A: This really is not a grammatically correct sentence, though it is perhaps excused a little given that it is a description of what someone said, which is to say the NYT correctly reported a grammatically incorrect sentence by the original speaker.
You can argue that it is an elipsis:

The angriest [moment] Obama [had] with Clinton concerned...

But to argue this one mast also change the verb too, and I have not come up with a suitable ellipsis that would go with "became".
Nevertheless, this sentence is the intended meaning.


text:
Q: Powershell Get File Shares Into Array I am trying to get a list of folders shared on a file server, and put them into an array. This is the code I have at the moment:
$FileServer = "ServerName"

[array]$FileServerShares = gwmi win32_Share -ComputerName $FileServer |
  Where-Object {$_.type -eq '0'} |
  Where {$_.name -notlike "*$*"}

Write-Host $FileServerShares

This outputs the folders that are shared (excluding the $ shares too), but the output puts them all into one long variable on one line.
How do I put this into an array with each record on a new line?
Update:
For those that are interested, I used the accepted answer and it worked great. I was actually after the "Name" instance of each folder, and so used code like this:
$FileServer = "ServerName"

$FileServerSharesFullName = gwmi win32_Share -ComputerName $FileServer |
Where-Object {$_.type -eq '0'} |
Where {$_.name -notlike "*$*"} # This excludes the "dollar shares" from being selected

$FileServerShares = $FileServerSharesFullName.name | % {$_.ToString()}

So each name of the folders that are shared in now in an array in $FileServerShares.

A: $FileServerShares already is an array (even without the [array] specifier):
PS> $FileServerShares.getType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

For some reason, when an array of share objects is converted to a string, each share is put on the same line. I don't know why that is, but what you could do is convert the share objects to strings so that you have an array of strings. String arrays do get converted to multiline strings.
$FileServer = "ServerName"

$FileServerShares = gwmi win32_Share -ComputerName $FileServer |
  Where-Object {$_.type -eq '0'} |
  Where {$_.name -notlike "*$*"} |
  % { $_.ToString() }

Write-Host $FileServerShares


text:
Q: Как получить анимацию svg объекта, который связан через js с другим svg объектом, задавая анимацию только второму? Имеется две линии. Правый конец черной line1 можно передвигать мышкой. При этом координаты конца зеленой линии line2 зависят от line1 через функцию moveline2.
Далее добавил анимацию первой линии по клику на красный круг. При этом line1 анимируется, а функция moveline2, которая также пускается по этому событию срабатывает один раз и все. Вторая линия остается без анимации, хотя функционально связана с анимированной первой.
Понятно, что по мере того, как идет анимация должны генерироваться какие-то события по которым можно пускать перерисовку второй линии, но как это сделать?
Как заставить двигаться все объекты функционально связанные с единственным, на котором висит анимация?
Использую библиотеку svg.js но, видимо, это не принципиально.
Документация по библиотеке https://svgdotjs.github.io

var paper = SVG('draw').size('100%', '100%');

var line1 = paper.line(0, 100, 300, 100).stroke({
  width: 5
}).style({
  cursor: 'pointer'
});

var line2 = paper.line(0, 200, 100, 200).stroke({
  width: 5
}).attr({
  stroke: 'green'
});

var circle = paper.circle(30).move(50, 50).fill('red').style({
  cursor: 'pointer'
});

//перемещение конца line1 примерно под курсор)
function move(event) {
  line1.attr({
    x2: event.pageX,
    y2: event.pageY
  })

  moveline2()

  //ловим событие перемещения мышки на холсте
  paper.mousemove(function(event) {
    line1.attr({
      x2: event.pageX,
      y2: event.pageY
    })

    moveline2()
  })

  paper.mouseup(function() {
    paper.mousemove(null)
  })
}

//функциональная зависимость координат второй линии от первой (любая)
function moveline2() {
  var x = line1.attr('x2');
  var y = line1.attr('y2');

  line2.attr({
    x2: x / 2,
    y2: (x + y) / 2
  })
}

//устанвка функциина нажатие ЛКМ над line1
line1.on('mousedown', move)

//анимация по клику
circle.click(function() {
  line1.animate().attr({
    x2: 300,
    y2: 400
  })
  moveline2()
})
#draw {
  width: 400px;
  height: 400px;
  border: 2px solid silver
}
<!DOCTYPE html>

  <title>Пример</title>

A: Для выполнения собственной функции в течение анимации нужно использовать функции during/duringAll

var paper = SVG('draw').size('100%', '100%');

var line1 = paper.line(0, 100, 300, 100).stroke({
  width: 5
}).style({
  cursor: 'pointer'
});

var line2 = paper.line(0, 200, 100, 200).stroke({
  width: 5
}).attr({
  stroke: 'green'
});

var circle = paper.circle(30).move(50, 50).fill('red').style({
  cursor: 'pointer'
});

//перемещение конца line1 примерно под курсор)
function move(event) {
  line1.attr({
    x2: event.pageX,
    y2: event.pageY
  })

  moveline2()

  //ловим событие перемещения мышки на холсте
  paper.mousemove(function(event) {
    line1.attr({
      x2: event.pageX,
      y2: event.pageY
    })

    moveline2()
  })

  paper.mouseup(function() {
    paper.mousemove(null)
  })
}

//функциональная зависимость координат второй линии от первой (любая)
function moveline2() {
  var x = line1.attr('x2');
  var y = line1.attr('y2');

  line2.attr({
    x2: x / 2,
    y2: (x + y) / 2
  })
}

//устанвка функциина нажатие ЛКМ над line1
line1.on('mousedown', move)

//анимация по клику
circle.click(function() {
  line1.animate().attr({
    x2: 300,
    y2: 400
  }).during(function(pos, morph, eased, situation) {
    moveline2()
  });

});
#draw {
  width: 400px;
  height: 400px;
  border: 2px solid silver
}
<!DOCTYPE html>

  <title>Пример</title>


text:
Q: Music app won't allow me to transfer an MP3 from iTunes to my iPhone, says "Media may be damaged" I have an MP3 file I'd like to move onto my phone from my Windows PC. I've imported it into iTunes and played it there, where it works just fine. I tried choosing "Add to Device...my iPhone" in the menu and...nothing happens. No error message, no warning tone, nothing.
I then tried converting the song within iTunes to .AAC format and copying the resulting file across, but still nothing happens. I've found through trial and error that I first need to delete the original file from iTunes, re-import it, convert it to .AAC and then choose "Add to Device...my iPhone", and then the transfer will actually take place.
Except it doesn't- the .AAC file transfers to my phone (minus the album art, strangely), but when I try to play it in the Music app I get the first actual error message I've seen, which is "Cannot Open, This media may be damaged".
I've transferred many songs through iTunes before, usually without difficulty. The only thing I can think of with this particular file is that it's much longer than a typical song, but again I've transferred long tracks before without issue.
Has anyone else ever run into this situation, and if so did you find a solution? I'd really like to know more about what "this media might be damaged" could more specifically be referring to. Is there something fundamental I'm missing here?
Here's the link to the source file if anyone wants to try themselves. For what it's worth, I'm running iTunes 12.12.2.2 on a Windows 10 laptop with the latest updates, transferring to an iPhone 8 Plus using iOS 15.2 with 17.85 GB available.


text:
Q: Issue with CASE expression in MySQL: Operand should contain 1 column(s) Ok, so I am writing SQL code in MySQL to get customer names from 2 different tables and display them for the user.
I have a CASE setup in my SQL, however when I run it I get the message

"Error Code: 1241. Operand should contain 1 column(s)."

The syntax is pulling information from an "account" table, displaying rows that are not present in a "transaction" table, and needs to sort them by account holder type, either business or individual. And either display the individual's first and last name (if the account is held by an individual) or the business name (if held by a business).
Here is my syntax giving the error:
use bank;

select acct.account_id as "Account ID",
case (select cust_id from account
  where acct.cust_id = ind.cust_id)
  when acct.cust_id = ind.cust_id
    then (select fname, ' ', lname from individual ind)
  when businessacct.cust_id = bus.cust_id
    then (select name from business bus)
  end cust_type,
acct.cust_id as "Customer ID",
acct.last_activity_date as "Date last active",
acct.avail_balance as "Available Balance",
(select concat(fname, ' ', lname)
  from employee
  where emp_id = acct.open_emp_id) as 'Opening Employee'
from account acct,
  individual ind,
  business bus
where acct.account_id not in (select account_id from transaction)
order by acct.cust_id;

I realize no one can really run this without the tables I have, but can anyone steer me in the right direction?

A: So there are a few issues in your query; you're not using the case expression correct and there are serious problems with the joins. Even if you corrected the problems in the case expression the query would most likely not function as intended as you don't join the tables in any meaningful way.
Since you didn't share any schema or sample data this is just a guess as to what the query probably should look like:
select
    acct.account_id as "Account ID",
    case
       when acct.cust_id = ind.cust_id then concat(ind.fname, ' ', ind.lname)
       when acct.cust_id = bus.cust_id then bus.name
    end cust_type,
    acct.cust_id as "Customer ID",
    acct.last_activity_date as "Date last active",
    acct.avail_balance as "Available Balance",
    concat(emp.fname, ' ', emp.lname)  as 'Opening Employee'
from account acct
join employee emp on emp.emp_id = acct.open_emp_id
left join individual ind on acct.cust_id = ind.cust_id
left join business bus on acct.cust_id = bus.cust_id
where acct.account_id not in (select account_id from transaction)
order by acct.cust_id;

You could probably replace the whole case expression with this:
coalesce(bus.name, concat(ind.fname, ' ', ind.lname)) cust_type,

which would select the bus.name is there is one (meaning it's a business) or use the values from individual instead.


text:
Q: Volumes between Host and Container I use Windows and I have a problem with this commando line.

docker run --name website -v $(pwd):/usr/share/nginx/html -d -p 8080:80 nginx

Docker: Error response from daemon: Conflict. The container name "/website" is already in use by container "9d253156c8179f6b3fe5b7997c504b71db2d8d6c24af3e5b4edbfe0d844d3d02". You have to remove (or rename) that container to be able to reuse that name.


text:
Q: Rails 4 - Multiple yield blocks on a partial Is it possible to have a partial using more than one yield block? I wanted to use it to implement bootstrap modal boxes on my project, kinda like this:

                <%= yield :header %>

                <%= yield :body %>

                <%= yield :footer %>

And this is more or less how I was thinking of using it
<%= render partial: "shared/modal" do %>
    <% content_for :header do %>
        ...
    <% end %> %>

    <% content_for :body do %>
        ...
    <% end %> %>

    <% content_for :footer do %>
        ...
    <% end %> %>
<% end %>

Is there a way to do this? Is this maybe a bad approach for some reason?

A: Through much trial and error, I think I solved this in Rails 5 but needed to insert a blank yield in my partial in order to get it to work:
_partial.html.erb

  <%= yield %>

    <%= yield :header %>

    <%= yield :text %>

Implemented as:
full_layout.html.erb
<%= render "partial" do %>
  <% content_for :header do %>

Header content

  <% end %>
  <% content_for :text do %>

Text content

  <% end %>
<% end %>

A: I think you have an issue with your render partial. Notice you have all of your content_for blocks within the render partial block.
<%= content_for :thing do %>
   Some content
<% end %>
<%= render partial: "blah" %>

A: It's no problem to use multiple yield blocks in your partial. Only thing is to make sure that many is actually needed. For an example content_for sections are basically placeholders for content that could vary based on the logic of the application. So, it's totally fine to use multiple yields in one page.

A: You can also just run put an yield there withouth the output. This way you can also use the default block.

  <% yield %>

      heading
      <%= yield :heading %>

    <%= yield %>

...


text:
Q: How can I resolve the error "certificate subject name does not match target host name"?   curl -X GET --header 'Accept: application/json' --header 'Authorization: Bearer 90d2c018-73d1-324b-b121-a162cf870ac0' 'https://172.17.0.1:8243/V1.0.2/stock/getNA?name=te'

The terminal prompted

"curl: (51) SSL: certificate subject name (localhost) does not match target host name '172.17.0.1'
"

However, after I changed the "172.17.0.1" to "localhost", it worked and I got the result.
Why? Is there a wrong configuration somewhere?
Meanwhile, there isn't any log information in file http_access.log.

A: CN of the default WSO2 certificate is localhost. Therefore you have to use localhost as the hostname when you send requests. Otherwise, the hostname verification fails.
If you want to use any other hostname, you should generate a certificate with that hostname, as Jena has mentioned.

A: When SSL handshake happens client will verify the server certificate. In the verification process client will try to match the Common Name (CN) of certificate with the domain name in the URL. if both are different host name verification will fail. In your case certificate has CN as local host and when you try to invoke using IP address, it fails. When you create the cert you can have single host name / multiple host name / wild card host name as CN value
For more details, see:

*

*Fixing Hostname Verification

*What is the SSL Certificate Common Name?

A: I actually had this problem and found a fix:
I was requesting a URI like 'http://some.example', but the variable for HTTPS was set to '1'

A: I had this problem when trying to pull from a Git directory after I'd added a new SSH key and my Git repository moved.
In the fray, Git's CN got confused. The solution for me was to delete the git directory and re-clone it via SSH. As the other users hinted at, you can't change the CN of a website's certificate, so you'll have to change the setting on your computer that has the wrong CN, or avoid using HTTPS (and use SSH like I did).

A: As others have hinted, this is failing because the TLS negotiation checks that the cert matches the hostname in the URL.
What's new is that curl now supports this scenario via a connect-to option. So, if your curl is sufficiently new (v7.18.1) this should work:
curl -X GET 'https://localhost/V1.0.2/stock/getNA?name=te' \
    --header 'Authorization: Bearer 90d2c018-73d1-324b-b121-a162cf870ac0' \
    --header 'Accept: application/json'  \
    --connect-to localhost:443:172.17.0.1:8243

Credit: https://stackoverflow.com/a/50279590/1662031
Similarly you may be able to leverage curls resolve option:
curl -X GET 'https://localhost:8243/V1.0.2/stock/getNA?name=te' \
    --header 'Authorization: Bearer 90d2c018-73d1-324b-b121-a162cf870ac0' \
    --header 'Accept: application/json'  \
    --resolve localhost:443:172.17.0.1


text:
Q: iOS 12 Shortcuts App - Possible to toggle specific notification settings? Device: iPhone X;
OS: iOS 12.0;
Application: Shortcuts
Goal: Using Shortcuts, create a workflow to turn off notifications for one specific application. (Example: Start Script, turns off notifications for Mail app)
Since iOS 12 dropped this week, I've been playing with the Shortcuts app for automating workflows. It seems to get pretty deep with options for scripting, and various system actions, but I cant seem to find a way to target specific application notifications. Does anyone know of a way to accomplish something like this?
I'm considering buying Pythonista for $10, since python scripts can be utilized in Shortcuts, but would prefer to be sure it could ultimately accomplish my goal.
Thanks in advance for any suggestions and thoughts! :)

A: It appears that you can indeed use the new Shortcuts feature with Phythonista. I've not tried this myself but there are some Reddit articles on the matter.
According to this post, you can do:

*

*You can launch python scripts using Run Script

*You can pass arguments and access them with sys.argv

*Shortcuts pauses the current workflow and waits until the app is returned to
*You can get back to Shortcuts using webbrowser.open('shortcuts://run-shortcut?name=My%20Shortcut')
There is also a video
And according to this post, there is a free alternative called Scriptable which is JavaScript instead of Python.
Thanks very much for this question which has prompted me to experiment some more with Shortcuts and discover these tools.


text:
Q: log4j not working with GWT I am trying to add log4J in my GWT application
I am refering to this http://log4j-gwt.sourceforge.net/
I added
<inherits name="org.apache.log4j.Log4j" />

in my gwt.xml file
but its giving compile time error
org.apache.log4j.Log4j   not resolved.

I added the log4j jar as well in my build path (screenshot attached)
I am struggling and googling for hours now but no luck


text:
Q: 'module' object has no attribute 'shortcuts' In my Django app's view, I have a method for registration, in which I am trying to render output using a template. The program compiled fine and the server ran without any problems, when I tried to access the register from a browser it is throwing exception claiming 'module' object has no attribute 'shortcuts' . May I know what i am doing wrong here.
 from django.http import HttpResponse
from commons import Commons
from djangolearn.models import UserExtForm
from djangolearn.models import UserForm
import django

def hello(request):
    return HttpResponse("hello world")

def register(request):
  uform = UserForm(prefix='user')
  uxtform = UserExtForm(prefix='userprofile')
  cont = dict(userform=uform,userprofileform=uxtform)
  return django.shortcuts.render(request, 'register.html', cont)

Templates settings from settings.py
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['D:/projects/eclipse/djangolearn/djangolearn/templates',],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

A: You need to explicitly import render or shortcuts because it is a helper function and django.shortcuts is package.
from django import shortcuts
from django.shortcuts import render


text:
Q: grep from a list to produce multiple dataframes I have a dataframe with unique values in it as follows
red
green
blue
yellow

I have another dataframe with colours and other columns as follows
red        1        4
green      2        4
blue       2        5
yellow     1        7
red        54      35
green      25      54
blue       33      66
yellow     63      63
blue       22      99
yellow     80      25
red        26      33
green      16      17

I need to create dataframes which are the result of grepping out the rows with each colour (with the dataframe named by colour eg:
dfred
 red        1        4
 red        54      35
 red        26      33
dfyellow
 yellow     1        7
 yellow     63      63
 yellow     80      25

dfblue
 blue       2        5
 blue       33      66
 blue       22      99

dfgreen
 green      2        4
 green      25      54
 green      16      17

I could do this one by one by think there's an easier way. Can this be done in a function?
I really don't know how to substitute each grep phrase into a function that would output such a named dataframe

A: We can do this with split to create a list of data.frames
lst <- split(df2, as.character(df2$col1))
names(lst) <- paste0('df', names(lst))

and then with list2env create the individual objects in the global environment (not recommended though)
list2env(lst, envir = .GlobalEnv)
dfred
#   col1 col2 col3
#1   red    1    4
#5   red   54   35
#11  red   26   33


text:
Q: What is the difference between these addressing modes...? What is the difference between a register, indirect, base+displacement, double indirect, and PC relative.  I'm not quite sure I understand how to differentiate between these different addressing modes given their use in some situation.  Can someone please help me recognize the difference between them?

A: Syntactically, at the level of the assembly code, the addressing mode is determined by multiple factors...

*

*the OP code used (e.g. some operations use implicitly specific registers or addressing modes)

*the operands: are these references to registers, to memory or immediate values

*some directives such as the byte directives as in MOV DWORD PTR ...
The operand(s), and the syntax that surrounds them, however are typically the most relevant with regards to determining the addressing mode.  This can be illustrated with the x86 MOV operation, as the same or very similar syntax applies to other operations on CPUs in the x86 family. Similar syntax and rules apply to other processors, but of course differences in architecture such as the list and roles of registers as well as other differences make the following relatively x86-specific.
MOV has the effect of copying the data referenced by its 2nd argument into the location referred by its first argument.  There are many possible combination with regard to the nature of these references:
MOV <reg>, <reg>      ;  register to register
MOV <reg>, <mem>      ;  memory to register
MOV <mem>, <reg>      ;  register to memory
MOV <reg>, <const>    ;  immediate value to register
MOV <mem>, <const>    ;  immediate value to memory

Furthermore, these references may be indirect when the corresponding operand is in brackets.  For example  MOV WORD PTR [ebx], 99  will move the value 99 expressed as a 16 bits integer, into the memory location pointed to by the EBX register.
Also, the indirect memory location in bracket may be expressed as a simple arithmetic expression such as MOV [esi+eax], dl.  Here the byte in register DL is copied to the memory location found by adding the contents of ESI and EAX registers.  Note that this needn't be just two registers, it could also be expressions like [esi + 8*ebx] or [esi - 16] etc.
With all that in mind, here a few examples of the MOV operation in context:
MOV eax, [edx]   ; Copies 4 bytes in memory at the address contained in EDX
                 ; into EAX the size (4bytes) is implied by the size of EAX.

MOV [MyVar], ebx ; Copies the contents of EBX into the 4 bytes at memory address
                 ; MyVar. (Assumes MyVar is a 32-bit constant).

MOV eax, [esi-4] ; Copies 4 bytes at memory address ESI -4 into EAX

MOV [esi+eax], bl ; Copies the contents of BL (one byte) into the byte at address
                  ; ESI+EAX

MOV BYTE PTR [MyVar], 123 ;  Copies the (decimal) value 123 coded as an 8 bits
                          ; to the memory address contained by MyVar.
                          ; Here the size directive (BYTE PTR) is necessary.


text:
Q: error: WatchKit apps must have a deployment target equal to iOS 8.2 (was 8.3) I just updated my project from 8.2. to 8.3 (using the latest xCode Version 6.3 6D570).
Now i get this error

error: WatchKit apps must have a deployment target equal to iOS 8.2
  (was 8.3).

The project and all targets are set to Latest SDK 8.3
What did I miss?

A: I resolved this by:

*

*Right-clicking my PROJECTNAME.xcodeproj file and choosing "Show Package Contents".

*Opening project.pbxproj in a text editor.

*Changing all instances of "IPHONEOS_DEPLOYMENT_TARGET = 8.3;" to "IPHONEOS_DEPLOYMENT_TARGET = 8.2;"

After this change my project compiled and ran fine.

A: Build successful.
I just changed the iOS Deployment Target of the Watch App Target to 8.2.
Why is that?

A: Ok , just select watch app -> go to build settings ->search for watchOS Deployment Target-> select lower version there based on the one of the watch you're using.


text:
Q: set expire time for a session I have a login page that uses session variables. How can i set an expire time for a session?
eg: after 15 minutes of inactivity destroy the session.
how can i do it?

A: You must set a variable in your session object with the time in every page it accesses, and in that all pages you will calculate if the current time have a difference from the last time setted of 15 minutes or more, if so you invalidate the session...
if not, you set a new time to that variable..


text:
Q: Facebook share pop with custom content - HTML and JS I am trying to create a facebook share pop up with custom text and thumbnail. It works fine on iOS, works fine on desktop but does not display a thumbnail and lastly it does not show any data within it's popup on an android device.
Here is the code I am using. I have used php to encode the text first.
        <?php
        $title=urlencode('My custom title');
        $url=urlencode('http://www.example.com');
        $summary=urlencode('Some summary text here. Some summary text here. Some summary text here. ');
        $image=urlencode('http://www.example.com/lib/img/fbshare.png');
        ?>

        <a onClick="window.open('http://www.facebook.com/sharer.php?s=100&p[title]=<?php echo $title;?>&p[summary]=<?php echo $summary;?>&p[url]=<?php echo $url; ?>&p[images][0]=<?php echo $image;?>','sharer','toolbar=0,status=0,width=548,height=325');" href="javascript: void(0)">

A: I test this code on desktop and is not working. Seems like facebook actually uses for the title and description of the shared content the meta-tags in the header of the page given in the url parameter. Try this: https://developers.facebook.com/docs/reference/dialogs/feed/


text:
Q: What does Transactional Backup Interval mean in the Backup Plan Wizard for Team Foundation Server? I'm in the process of setting up a backup plan for a Team Foundation Server. I downloaded Power Tools for TFS and I'm using the Backup Plan Wizard that was included in that pack. I am now at the step where I'm supposed to decide how to schedule the backups and I have no idea what to choose for my setup.
I get what everything means, except Transactional Backup Interval.

I would appreciate suggestions for a good schedule. What I would like to achieve is being able to restore and still look back a few versions, if possible. The minimum backup I would like to have is the latest version.
It might be important to add that I got to choose "Backup retention days" earlier and set that to 30.

A: The transactional backup interval likely refers to how often transaction logs for your TFS databases are backed up. The schedule you choose will probably depend on how busy your repository is.
At my current client there are six developers, and we share some of the load for source control between VSS and TFS (we're transitioning). Corporate policy says we must backup transaction logs every hour during business hours, and an additional one at midnight. Our local backups are on a four-day retention cycle with off-site backups lasting years.
I would make a decision based on how much work you'd want to lose if your repository was lost and your working copy was destroyed simultaneously (natural disaster?).


text:
Q: coreplot 2 plots in graph im currently creating a graph for an app, using coreplot and have a problem i cant explain.
i read (and it didnt help):
core-plot, unable to plot two graphs
QUESTION: why does only the second added plot get displayed? if i change the order i add them to the hostView, only the last one i add is displayed. see code & screenshots below.
the graph will hold 2 different plots
PROBLEM:
- both plots show perfectly if added alone.
- if i add both plots, only the second (last) one added gets displayed.
- to assure you that both are well on their own i added screenshots on the bottom.

First Plot a single 0 line
identifier : @"nullLine"
name: nullPlot

Second Plot a scatterplot of data i have stored
identifier : @"balanceChart"
name: plot

here is some of my code:
    CPTGraphHostingView *host = [self buildGraphView];   //returns a viewwithframe
    [view addSubview:host];

    graph = [[CPTXYGraph alloc ]initWithFrame:host.frame];
    host.hostedGraph = graph;

    CPTScatterPlot *plot = [[CPTScatterPlot alloc]init ];
    plot.dataSource = self;
    [plot setIdentifier:@"balanceChart"];

    // Setup plot space
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;
    plotSpace.allowsUserInteraction = YES;
    plotSpace.xRange                = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(1.0) length:CPTDecimalFromFloat(20.0)];
    plotSpace.yRange                = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(-200.0) length:CPTDecimalFromFloat(400.0)];

    CPTScatterPlot *nullPlot = [[CPTScatterPlot alloc]init ];
    nullPlot.dataSource = self;
    [nullPlot setIdentifier:@"nullLine"];
    [nullPlot setPlotSpace:plotSpace];
    [plot setPlotSpace:plotSpace];

    [graph addPlot:nullPlot];
    [graph addPlot:plot];

and my doubleForPlot function:
NOTE: i only add this function for completion - it does absolutely to 100% return the right values for both graphs!
-(double)doubleForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index{

// NULL CHART
if ([(NSString *)plot.identifier isEqualToString:@"nullLine"]) {
    if (fieldEnum == CPTScatterPlotFieldX) {
        NSLog(@"Plot: %@,fieldEnum: %d, index: %d",plot,fieldEnum,index);
        return index+1;
    }
    if (fieldEnum == CPTScatterPlotFieldY) {
        NSLog(@"Plot: %@,fieldEnum: %d, index: %d",plot,fieldEnum,index);
        double zero = 0;
        return zero;
    }
}

// BALANCE CHART
if ([(NSString *)plot.identifier isEqualToString:@"balanceChart"]) {

    if (fieldEnum == CPTScatterPlotFieldX) {

        NSLog(@"Axis: %d and Value: %d",fieldEnum, index+1);
        return (double)(index+1);
    }

    if (fieldEnum == CPTScatterPlotFieldY) {

        int dayInt = [dataHandler getDayNumber:[NSDate date]].intValue;
        double total = 0;
        for (Expense *exp in [allMonthExpenses objectAtIndex:index]) {
            total = total + exp.value.doubleValue;
        }

        NSDate *date = [NSDate dateWithTimeIntervalSinceNow:(-(dayInt-(int)index-1)*(60*60*24))];

        double budgetValue = [dataHandler getSpecificBudgetForDate:[NSDate dateWithTimeIntervalSinceNow:(-(dayInt-(int)index-1)*(60*60*24))] ];
        total = budgetValue+total;

        NSLog(@"\n Axis:%d \n Record for Day: %@ \n IndexForPlot: %d \n Value: %.2f \n",fieldEnum, date,index,total);

        return total;
    }
}

return 0;
}

here comes the numberOfRecordsForPlot method:
NOTE both plots have the same amount of records. this does also return the right number.
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot{
return [dataHandler getDayNumber:[NSDate date]].intValue;

}

sidenote dont mind the formatting of the plots please ;-)

A: I tried your code in a test app and it worked fine—both plots showed up. There must be something else going on in your code.


text:
Q: .htaccess Appends .php to URL My intention with the following code (specifically RewriteRule ^s/([a-zA-Z0-9\-]+)/?$ /index.php?s=$1 [L,QSA]) is for the URL
example.com/s/full-name

to work as if it were
example.com/index?s=full-name

Currently, my server is allowing me to use the URL-style example.com/s/$1, but it isn't displaying the content that can be found at index?s=full-name. Instead, it's changing the URL to
example.com/s/full-name.php/

when example.com/s/full-name is requested and I have no idea why. I would greatly appreciate any suggestions.
Options +SymLinksIfOwnerMatch
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_URI} !-f
RewriteCond %{REQUEST_URI} !-d
RewriteRule ^s/([a-zA-Z0-9\-]+)/?$ /index.php?s=$1 [L,QSA]

RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC]

Options -Indexes

ErrorDocument 400 /index?err=400
ErrorDocument 401 /index?err=401
ErrorDocument 403 /index?err=403
ErrorDocument 404 /index?err=404
ErrorDocument 500 /index?err=500

A: First, your conditions are wrong in the index routing command. The second thing is you have a rule that appends php to the end of your request but it does so without checking to see if the php file exists. Try reordering the rules and fix the conditions:
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^s/([a-zA-Z0-9\-]+)/?$ /index.php?s=$1 [L,QSA]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^([^\.]+)/?$ $1.php [NC,L]


text:
Q: How to use gather and spread to solve problem? (Tidyr) given table 1, convert to table 2.

I can solve the first part by creating table 1.
library(tidyverse)
grp = c("A", "A", "B", "B")
sex = c("F", "M", "F", "M")
meanL = c(0.22, 0.47, 0.33, 0.55)
sdL = c(.11, .33, .11, .31)
meanR = c(.34, .57, .4, .65)
sdR = c(.08, .33, .07, .27)
data <- as.data.frame(cbind(grp, sex, meanL, sdL, meanR, sdR))
head(data)

The best that I can do is gather all of the data into two columns, one containing the variable and the other containing the values.
data2 <- gather(data, categories, meanL:sdR)
head(data2, n=30)

The current place where I am struggling is in labeling the gender for each reading.

A: Here is a tidyverse option:
data %>%
        gather(k, v, -grp, -sex) %>%
        unite(k, sex, k, sep = ".") %>%
        spread(k, v)
#  grp F.meanL F.meanR F.sdL F.sdR M.meanL M.meanR M.sdL M.sdR
#1   A    0.22    0.34  0.11  0.08    0.47    0.57  0.33  0.33
#2   B    0.33     0.4  0.11  0.07    0.55    0.65  0.31  0.27

I suggest running the code above line-by-line, to see what each step does. In a nutshell, we reshape data from wide to long, combine columns, and reshape again from long to wide.


text:
Q: how to use angular bootstrap themes in java web application? The following website contains a dashboard UI that I want to use in my website.
http://startangular.com/product/sb-admin-angular-theme/
Not just this but there are lot more available in here http://startangular.com/.
I don't understand how do I use the templates to fill in my data that I get from my backend server. All the dashboard templates I find in the link above have this grunt.js file or run independently on a nodejs server.
I don't want to use nodejs server. I just want the UI wire frames from these and use them to create my website. Is that even possible?. I am not a front end developer. I am unable to create the UI using the css links provided in the page.
Thanks.


text:
Q: ZIndex of pushpins in WP7 bing map control I have a Bing silverlight map control for Windows phone 7. I am trying to display on top currently selected pushpin. Here is the snippet:
<my:Map x:Name="map" Canvas.ZIndex="1" CredentialsProvider="{StaticResource Credentials}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
                CopyrightVisibility="Collapsed" LogoVisibility="Collapsed">
            <my:MapItemsControl x:Name="Pushpins">
                <my:MapItemsControl.ItemTemplate >
                    <DataTemplate>
                        <my:Pushpin Location="{Binding Location}" Canvas.ZIndex="{Binding Zindex}" PositionOrigin="0.515625,0.859375" Content="{Binding Id}" Template="{StaticResource PushpinControlTemplate}" Tap="Pushpin_Tap"/>
                    </DataTemplate>
                </my:MapItemsControl.ItemTemplate>
            </my:MapItemsControl>
</my:Map>

The control is ignoring the ZIndex. Am I missing something or the ZIndex is not supported. The ZIndex is property of a class which implements INotifyPropertyChanged
private int _zIndex;
    public int Zindex
    {
        get { return _zIndex; }
        set
        {
            _zIndex = value;
            OnPropertyChanged(new PropertyChangedEventArgs("Zindex"));
        }
    }

A: In a recent project I used two map layers to achieve this.  The first map layer was bound to my list of pushpins ("resultsLayer"), the 2nd map layer was bound to a single 'SelectedItem' ("selectedLayer") on my view model.
The 2nd map layer will render on top of the first one.  So, when a pushpin on the first layer was selected, it was removed from the collection (consequently removed from the layer) and set to be the selected pin which added it to the 2nd layer.  The puspin control template for the 2nd layer contained the 'callout' which in my case was a button with some text in it that the user could click to open another page.
Here is my xaml:
    <m:Map CredentialsProvider="xxxx" x:Name="map" Center="{Binding MapCenter, Mode=TwoWay}" ZoomLevel="{Binding MapZoomLevel, Mode=TwoWay}">
        <m:MapLayer x:Name="resultsLayer" Visibility="{Binding IsBusy, Converter={StaticResource booleanNotCollapsedConverter}}">
            <m:MapItemsControl ItemsSource="{Binding VenuesFound}">
                <m:MapItemsControl.ItemTemplate>
                    <DataTemplate>
                        <m:Pushpin Location="{Binding VLocation}" PositionOrigin="BottomCenter" >
                            <m:Pushpin.Template>
                                <ControlTemplate>
                                    <Image x:Name="mapPin" Grid.Row="1" Source="{Binding MapPin}" Stretch="None" />
                                </ControlTemplate>
                            </m:Pushpin.Template>
                            <i:Interaction.Triggers>
                                <i:EventTrigger EventName="Tap">
                                    <gs:EventToCommand Command="{Binding SelectPinCommand}" />
                                </i:EventTrigger>
                            </i:Interaction.Triggers>
                        </m:Pushpin>
                    </DataTemplate>
                </m:MapItemsControl.ItemTemplate>
            </m:MapItemsControl>
        </m:MapLayer>
        <m:MapLayer x:Name="selectedLayer" DataContext="{Binding SelectedV}" Visibility="{Binding IsBusy, Converter={StaticResource booleanNotCollapsedConverter}}">
            <m:Pushpin Location="{Binding VLocation}" PositionOrigin="BottomCenter">
                <m:Pushpin.Template>
                    <ControlTemplate>
                        <StackPanel>
                            <Button Style="{StaticResource PushPinCallout}" Command="{Binding SelectItemCommand}">
                                <TextBlock Text="{Binding Name}" Foreground="White" Margin="2" TextWrapping="Wrap" />
                            </Button>
                            <Image x:Name="mapPin" Grid.Row="1" Source="{Binding MapPin}" Stretch="None" />
                        </StackPanel>
                    </ControlTemplate>
                </m:Pushpin.Template>
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="Tap">
                        <gs:EventToCommand Command="{Binding SelectPinCommand}" />
                    </i:EventTrigger>
                </i:Interaction.Triggers>
            </m:Pushpin>
        </m:MapLayer>
    </m:Map>

A: I had the same problem where I had multiple pushpins close together and the problem was exacerbated when I had additional content to show when the pushpin was clicked.
The way I got around this problem was to remove the pushpin and then re-add it. That way it became the topmost pushpin.
map1.Children.Remove(pushpin);
map1.Children.Add(pushpin);

A: As the BingMapsControl is not a Silverlight control it does not have any concept of a canvas.
Instead of trying to ensure the selected one is at the front, I'd change the selected pin to be of a larger, more prominent style.
It doesn't make sense (to me) to be able to control the z-index of pins as doing so could create a scenario where a pin appears to be on top of another pin, rather than on the map.


text:
Q: Again JoinTable is not filled in many-to-many hibernate relation |AA| many-to-many |BB| many-to-many |CC|
mapped with join tables became
|AA|--|AA_BB|--|BB|--|BB_CC|--|CC|
(I can't post images sorry, low reputation)
Edited:
Short question is
why if a Create a Aa element, Bb element, Cc element
add Cc to Bb collection, Bb to Aa collection
Save(Aa)
Works ok (AA_BB filled)?
But if I create a Bb element, Aa element, Cc element
Add Aa to Bb collection
Add Cc to Bb collection
Save(Bb)
(AA_BB not filled?)
BB_CC is always filled.
end edit
 CREATE TABLE BB_CC (
  BBIDBB number(10) NOT NULL,
  CCIDCC number(10) NOT NULL,
  PRIMARY KEY (BBIDBB,
  CCIDCC));
CREATE TABLE AA_BB (
  AAIDAA number(10) NOT NULL,
  BBIDBB number(10) NOT NULL,
  PRIMARY KEY (AAIDAA,
  BBIDBB));
CREATE TABLE CC (
  IDCC  number(10) NOT NULL,
  DESCR varchar2(10) NOT NULL,
  PRIMARY KEY (IDCC));
CREATE TABLE BB (
  IDBB  number(10) NOT NULL,
  DESCR varchar2(10) NOT NULL,
  PRIMARY KEY (IDBB));
CREATE TABLE AA (
  IDAA  number(10) NOT NULL,
  DESCR varchar2(10) NOT NULL,
  PRIMARY KEY (IDAA));
ALTER TABLE BB_CC ADD CONSTRAINT FKBB_CC976918 FOREIGN KEY (BBIDBB) REFERENCES BB (IDBB);
ALTER TABLE BB_CC ADD CONSTRAINT FKBB_CC529716 FOREIGN KEY (CCIDCC) REFERENCES CC (IDCC);
ALTER TABLE AA_BB ADD CONSTRAINT FKAA_BB470776 FOREIGN KEY (AAIDAA) REFERENCES AA (IDAA);
ALTER TABLE AA_BB ADD CONSTRAINT FKAA_BB23574 FOREIGN KEY (BBIDBB) REFERENCES BB (IDBB);

Hibernate Configuration File
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
<!--  ORACLE -->
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="connection.url">jdbc:oracle:thin:@10.10.1.8:1521:GEROS</property>
        <property name="connection.username">xxxx</property>
        <property name="connection.password">xxxx</property>
        <property name="dialect">org.hibernate.dialect.OracleDialect</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup-->
        <property name="hbm2ddl.auto">create</property>

        <!-- Names the annotated entity class -->
        <mapping class="it.erreeffe.erreeffe2.Aa"/>
        <mapping class="it.erreeffe.erreeffe2.Bb"/>
        <mapping class="it.erreeffe.erreeffe2.Cc"/>
    </session-factory>
</hibernate-configuration>

And the reversed jpa class from tables
Aa (Bb, Cc similar) some parts missing.
@Entity
public class Aa implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @SequenceGenerator(name="AA_IDAA_GENERATOR", sequenceName="SEQ_AA")
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="AA_IDAA_GENERATOR")
    private long idaa;

    private String descr;

    //bi-directional many-to-many association to Bb
    @ManyToMany(cascade={CascadeType.ALL})
    @JoinTable(
        name="AA_BB"
        , joinColumns={
            @JoinColumn(name="AAIDAA")
            }
        , inverseJoinColumns={
            @JoinColumn(name="BBIDBB")
            }
        )
    private Set<Bb> bbs;

My tests, the first working and the second do not.
First:
Session session;
        SessionFactory sf_ORA = new Configuration().configure(
                "hibernate.cfg.ora.xml").buildSessionFactory();
        session = sf_ORA.openSession();

//A
        Aa a = new Aa();
        a.setDescr("A1");
        a.setBbs(new HashSet<Bb>());
        //B
        Bb b1 = new Bb();
        b1.setCcs(new HashSet<Cc>());
        Bb b2 =new Bb();
        b2.setCcs(new HashSet<Cc>());
        b1.setDescr("B1");
        b2.setDescr("B2");
        //C
        Cc c1 = new Cc();
        Cc c2 = new Cc();
        Cc c3 = new Cc();
        c1.setDescr("C1");
        c2.setDescr("C2");
        c3.setDescr("C3");
        //FILL B
        b1.getCcs().add(c1);
        b1.getCcs().add(c2);
        b2.getCcs().add(c2);
        b2.getCcs().add(c3);
        //FILL A
        a.getBbs().add(b1);
        a.getBbs().add(b2);

session.beginTransaction();
        try
        {
            session.save(a);
            session.flush();
            session.getTransaction().commit();
        }
        catch(HibernateException ex)
        {
            session.getTransaction().rollback();
            throw ex;
        }

This do the right job:
Hibernate creates for me all the needed statements:
Hibernate: insert into Aa (descr, idaa) values (?, ?)
Hibernate: insert into Bb (descr, idbb) values (?, ?)
Hibernate: insert into Cc (descr, idcc) values (?, ?)
Hibernate: insert into Cc (descr, idcc) values (?, ?)
Hibernate: insert into Bb (descr, idbb) values (?, ?)
Hibernate: insert into Cc (descr, idcc) values (?, ?)
Hibernate: insert into AA_BB (AAIDAA, BBIDBB) values (?, ?)
Hibernate: insert into AA_BB (AAIDAA, BBIDBB) values (?, ?)
Hibernate: insert into BB_CC (BBIDBB, CCIDCC) values (?, ?)
Hibernate: insert into BB_CC (BBIDBB, CCIDCC) values (?, ?)
Hibernate: insert into BB_CC (BBIDBB, CCIDCC) values (?, ?)
Hibernate: insert into BB_CC (BBIDBB, CCIDCC) values (?, ?)

The joined result query is right:
A1|B1|C1
A1|B1|C2
A1|B2|C2
A1|B2|C3
Second (Ta-dan Here it is the problem)
Read B1 from DB add new Aa (A2) to B1.Aas collection add a new Cc (c4) to B1.Ccs collection, update B1.
Bb b1=null;
        session.beginTransaction();
        try
        {
            Query qGetB1=session.createQuery("Select id from Bb where DESCR ='B1'" );
            long idB1=(Long) qGetB1.list().get(0);
            b1=(Bb) session.load(Bb.class, idB1);
            session.flush();
            session.getTransaction().commit();
        }
        catch(HibernateException ex)
        {
            session.getTransaction().rollback();
            throw ex;
        }

        Aa a2 = new Aa();
        a2.setDescr("A2");
        Cc c4 = new Cc();
        c4.setDescr("C4");

        b1.getAas().add(a2);
        b1.getCcs().add(c4);

        session.beginTransaction();
        try
        {
            session.flush();
            session.saveOrUpdate(b1);
            session.flush();
            session.getTransaction().commit();
        }
        catch(HibernateException ex)
        {
            session.getTransaction().rollback();
            throw ex;
        }

Generate Hibernate's:
Hibernate: select bb0_.idbb as col_0_0_ from Bb bb0_ where DESCR='B1' //SEARCH B1 ID
Hibernate: select bb0_.idbb as idbb1_0_, bb0_.descr as descr1_0_ from Bb bb0_ where bb0_.idbb=? //GET B1
Hibernate: select aas0_.BBIDBB as BBIDBB1_1_, aas0_.AAIDAA as AAIDAA1_, aa1_.idaa as idaa0_0_, aa1_.descr as descr0_0_ from AA_BB aas0_, Aa aa1_ where aas0_.AAIDAA=aa1_.idaa and aas0_.BBIDBB=? GET B1.Aas
Hibernate: select ccs0_.BBIDBB as BBIDBB1_1_, ccs0_.CCIDCC as CCIDCC1_, cc1_.idcc as idcc2_0_, cc1_.descr as descr2_0_ from BB_CC ccs0_, Cc cc1_ where ccs0_.CCIDCC=cc1_.idcc and ccs0_.BBIDBB=? GET B1.Ccs
Hibernate: insert into Aa (descr, idaa) values (?, ?) //OK
Hibernate: insert into Cc (descr, idcc) values (?, ?) //OK
Hibernate: insert into BB_CC (BBIDBB, CCIDCC) values (?, ?) //OK

... What about AA_BB record???? //!!!!!!!!

Why the joinTable AA_BB is not filled?
Thank's all for the attention.
Regards,
Francesco.

A: When you have a bidirectional association, one side is the owner side (the side without the mappedBy attribute), and the other is the inverse side (the one with the mappedBy attribute).
Hibernate only considers the owner side to know if there is an association between two entities. So, if A is the owner side in the relation between A and B, you must add B instances to A's collection to make an association persistent. Adding A instances to B's collection has no effect.
In general, you are responsible for maintaining the coherence of the object graph, and thus you should make sure that the owner side (at least) is always updated.


text:
Q: Is length matching is necessary on I2C, UART signals, and SPI? I am currently designing a board where there is a UART, as well as SPI and I2C, should I length match or take care of differential pairs on those interfaces?

A: No, these signaling types don't need length matching. Operating at 1.2kbps-115.2kbps (UART), 100kbps-1.5Mbps (I2C), or up to about 50Mbps (SPI) over the usual board-level or cabled (UART) distances, the signal wavelength is still much longer than the electrical medium size. The signal quality will not be predominantly influenced by the electrical length of the conductor, but by parameters such as parasitic capacitance and the strength of pull-up resistors. A general rule of thumb is if the signal wavelength is less than 10x or 20x the size of the electrical medium, transmission lines are required and it is a "high speed design."
Additionally, none of the interfaces use differential signaling, if UART is RS-232. There are serial standards like RS-422 and RS-485 that use differential (balanced) signaling.

A: This answer assumes that the traces/wires are not so long as to require terminations to prevent reflections.
On all of them No.
For UART transmissions they are unidirectional in transmit and unidirectional in receive i.e. you send the signal and it gets received and maybe some form of asynchronous reply is sent back. Clocks are not sent and not required but it is different on SPI.
For a simple master to slave SPI transmission, clock and data arrive at the same relative phase at the far end and, if that is all the transmission is about then great - no further worries because at the slave end data is clocked into the slave synchronously and if there is a few nano second differences in timing due to slight length mismatches this isn't going to hurt things.
However, if the slave is expected to synchronously respond to the master a potential problem occurs because the data received at the master is displaced from the clock edges seen at the slave. This is now due to the end-to-end time delay because of the length of the SPI bus traces.
Normal SPI and IIC deal with this by not allowing lengths of traces to be massively long - if they are then you have to use a slower data rate. This is the bigger problem by far compared to keeping traces the same length.


text:
Q: Laravel Entrust, how to attach existing permission to role Here is my code I am using, it runs fine but when I'm inside the database checking if everything went okay I get this result

Why am I getting 0 for the permission ID and Role ID?
$developer = new Role();
$developer->name = 'Test';

$view_customers = new Permission();
$view_customers->name = 'view_customers';
$view_customers->display_name = 'View Customers';

$developer->attachPermission($view_customers->id);

A: try this
$developer = Role::where('name','=','Test')->get->first();

//if you want to attach new permission
$view_customers = new Permission();
$view_customers->name = 'view_customers';
$view_customers->display_name = 'View Customers';

//if you want to attach existing permission ex. you already have 'view_customers' in permission table
$view_customers = Permission::where('name','=','view_customers')->get->first();

$developer->attachPermission($view_customers);

A: attachPermission() works by model or array, if you want atach or detach by id use this
$developer->perms()->attach($view_customers->id);


text:
Q: How to add identifier to table row submit button I am currently trying to build a booking system for a theatre. I have 5 different productions which are found from my database with a query in php.
I have a table showing the productions and their associated ticket price. Each row states the production, ticket price and a submit button (using $_POST) to choose that production.
I am trying to send the title of the selected production as production_'production title'. e.g. if hamlet was selected I would retrieve the selection using $_POST['production_hamlet'].
However I do not know how to replace the title of each production found in the query when retrieving the POST.
e.g. on the next page when echoing out to see if it's submitted I don't know what to write after echo $POST['production.....'].
Here is my code:
<form method="post" action="choose_performance.php">

            Production
            Basic Ticket Price
            Select

        <?php
            $production_set = find_productions();
            while($row = mysqli_fetch_assoc($production_set)){?>

                    <?php echo $row['Title']?>
                    <input type="hidden" name="<?php echo "production_".$row['Title']?>" value="<?php echo $row['Title']?>" />

                    <?php echo $row['BasicTicketPrice'];?>
                    <input type="hidden" name="<?php echo "price_".$row['Title']?>" value="<?php echo $row['BasicTicketPrice']?>" />

                    <input type="submit" name="submit" value="Submit"
                onclick='alert("Thank you for your selection. Please choose your preferred performance time and date on the next page.");'>

            <?php
            }
            ?>
        </form>

Any advice on how to retrieve the POST would be amazing.
Thanks.

A: Just put the <form> tag inside your while loop so that each row has its own form for submission. This way, when the form is submitted, you only have 2 posted params (production & price). See below:

        <?php echo $row[ 'Title']?>

        <?php echo $row[ 'BasicTicketPrice'];?>

        <form method="post" action="choose_performance.php">
            <input type="hidden" name="production" value="<?php echo $row['Title'] ?>" />
            <input type="hidden" name="price" value="<?php echo $row['BasicTicketPrice'] ?>" />
            <input type="submit" name="submit" value="Submit" onclick='alert("Thank you for your selection. Please choose your preferred performance time and date on the next page.");'>
        </form>