text:
Q: #1265 - Data truncated for column '' at row 2 when changing column to NOT NULL This is the structure for the database table I am working on:
 CREATE TABLE `schools` (
`id` int(11) NOT NULL,
`name` varchar(255) CHARACTER SET utf8 NOT NULL,
`describtion` text CHARACTER SET utf8 NOT NULL,
`keywords` varchar(255) NOT NULL,
`url` varchar(255) NOT NULL,
`status` varchar(255) CHARACTER SET utf8 NOT NULL,
`location` varchar(255) CHARACTER SET utf8 NOT NULL,
`school_type` varchar(255) CHARACTER SET utf8 NOT NULL,
`fees` varchar(255) CHARACTER SET utf8 NOT NULL,
`ownership` varchar(255) CHARACTER SET utf8 NOT NULL,
`thumbnail` varchar(255) NOT NULL,
`logo` varchar(255) NOT NULL,
`founded_at` varchar(255) NOT NULL,
`courses` text CHARACTER SET utf8 NOT NULL,
`undergradcourses` text CHARACTER SET utf8 NOT NULL,
`postgradcourses` text CHARACTER SET utf8 NOT NULL,
`shortcoursesandcertifications` text CHARACTER SET utf8 NOT NULL,
`technicalandvocationalcourses` text CHARACTER SET utf8 NOT NULL,
`website` varchar(255) NOT NULL,
`phone` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`entry_requirement` varchar(255) NOT NULL,
`rating_nigeria` varchar(255) NOT NULL,
`rating_africa` varchar(255) NOT NULL,
`created_at` varchar(255) NOT NULL,
`updated_at` varchar(255) NOT NULL,
`school_name` varchar(50) DEFAULT NULL,
`type` varchar(255) DEFAULT NULL,
`entrance_exam` varchar(50) DEFAULT NULL,
`religious_affiliation` varchar(50) DEFAULT NULL,
`term_structure` varchar(255) DEFAULT NULL,
`school_year` varchar(50) DEFAULT NULL,
`centers_of_excellence` varchar(50) DEFAULT NULL,
`ranking_metro_manila` varchar(50) DEFAULT NULL,
`ranking_philippines` varchar(50) DEFAULT NULL,
`0` varchar(50) DEFAULT NULL
 ) ENGINE=MyISAM DEFAULT CHARSET=latin1;

Here are my first 2 rows of data:
  INSERT INTO `schools` (`id`, `name`, `describtion`, `keywords`, `url`, `status`, `location`, `school_type`, `fees`, `ownership`, `thumbnail`, `logo`, `founded_at`, `courses`, `undergradcourses`, `postgradcourses`, `shortcoursesandcertifications`, `technicalandvocationalcourses`, `website`, `phone`, `email`, `entry_requirement`, `rating_nigeria`, `rating_africa`, `created_at`, `updated_at`, `school_name`, `type`, `entrance_exam`, `religious_affiliation`, `term_structure`, `school_year`, `centers_of_excellence`, `ranking_metro_manila`, `ranking_philippines`, `0`)
  VALUES
  (1, 'Centro Escolar University - Manila', 'Centro Escolar University is a private university in Manila, Philippines. It was founded on June 3, 1907 by two women, Librada Avelino and Carmen de Luna, and was originally called Centro Escolar de Señoritas. It became a university in 1933.', '', 'schools/centro-escolar-university---manila', '', 'Manila', 'Select Type', '10000 - 50000', 'Ownership', '2 - CEU1.PNG', '2 - CEU.jpg', '1907 ', '', 'School of Accountancy and Management\r\n
Bachelor of Science in Accountancy\r\n
Bachelor of Science in Business Administration Major in Financial Management\r\n
Bachelor of Science in Business Administration Major in Management\r\n
Bachelor of Science in Business Administration Major in Management Accounting\r\n
Bachelor of Science in Business Administration Major in Management with Specialization Track in Service Management in Business Process Outsourcing\r\n
Bachelor of Science in Business Administration Major in Marketing Management\r\n
Bachelor of Science in Legal Managemen\r\n\r\nSchool of Dentistry\r\nDentistry\r\n\r\nSchool of Education, Liberal Arts, Music and Social Work\r\n
Bachelor in Library and Information Science\r\n
Bachelor of Arts (Curriculum A) in Mass Communication and Broadcast\r\n
Bachelor of Arts (Curriculum A) in Mass Communication and Journalism\r\n
Bachelor of Arts (Curriculum A) in Mass Communication and Performing Arts\r\n
Bachelor of Arts major in Political Science\r\n
Bachelor of Arts with 18 units of Education (Curriculum B) in Mass Communication and Broadcast\r\n
Bachelor of Arts with 18 units of Education (Curriculum B) in Mass Communication and Journalism\r\n
Bachelor of Arts with 18 units of Education (Curriculum B) in Mass Communication and Performing Arts\r\n
Bachelor of Arts with 18 units of Education (Curriculum B) major in Political Science\r\n
Bachelor of Elementary Education Major in Pre-school Education\r\n
Bachelor of Elementary Education Major in Special Education\r\n
Bachelor of Music\r\n
Bachelor of Music (Music Education)\r\n
Bachelor of Science in Social Work\r\n
Bachelor of Secondary Education major in Biological Science\r\n
Bachelor of Secondary Education major in English\r\n
Bachelor of Secondary Education major in Mathematics\r\n-
Bachelor of Secondary Education major in Physical Science\r\n\r\nSchool of Medical Technology\r\n
Bachelor of Science in Medical Technology\r\n\r\nSchool of Nursing\r\n
Bachelor of Science in Nursing\r\n\r\nSchool of Nutrition and Hospitality Management\r\n
Bachelor of Science in Hotel and Restaurant Management\r\n
Bachelor of Science in Nutrition and Dietetics\r\n
Bachelor of Science in Tourism Management\r\n\r\nchool of Pharmacy\r\n
Bachelor of Science in Pharmacy\r\n
Bachelor of Science in Pharmacy specialized in Clinical Pharmac\r\n\r\nSchool of Science and Technology\r\n
Bachelor of Science in Biology\r\n
Bachelor of Science in Computer Engineering\r\n
Bachelor of Science in Computer Scienc\r\n
Bachelor of Science in Cosmetic Science\r\n
Bachelor of Science in Information Technology\r\n
Bachelor of Science in Psychology', 'School of Accountancy and Management\r\n
Master of Science in Accountancy\r\n
Master of Science in Business Administration Major in Financial Management\r\n
Master of Science in Business Administration Major in Management\r\n
Master of Science in Business Administration Major in Management Accounting\r\n
Master of Science in Business Administration Major in Management with Specialization Track in Service Management in Business Process Outsourcing\r\n
Master of Science in Business Administration Major in Marketing Management\r\n
Master of Science in Legal Managemen\r\n\r\nSchool of Dentistry\r\nDentistry\r\n\r\nSchool of Education, Liberal Arts, Music and Social Work\r\n
Master in Library and Information Science\r\n
Master of Arts (Curriculum A) in Mass Communication and Broadcast\r\n
Master of Arts (Curriculum A) in Mass Communication and Journalism\r\n
Master of Arts (Curriculum A) in Mass Communication and Performing Arts\r\n
Master of Arts major in Political Science\r\n
Master of Arts with 18 units of Education (Curriculum B) in Mass Communication and Broadcast\r\n
Master of Arts with 18 units of Education (Curriculum B) in Mass Communication and Journalism\r\n
Master of Arts with 18 units of Education (Curriculum B) in Mass Communication and Performing Arts\r\n
Master of Arts with 18 units of Education (Curriculum B) major in Political Science\r\n
Master of Elementary Education Major in Pre-school Education\r\n
Master of Elementary Education Major in Special Education\r\n
Master of Music\r\n
Master of Music (Music Education)\r\n
Master of Science in Social Work\r\n
Master of Secondary Education major in Biological Science\r\n
Master of Secondary Education major in English\r\n
Master of Secondary Education major in Mathematics\r\n-
Master of Secondary Education major in Physical Science\r\n\r\nSchool of Medical Technology\r\n
Master of Science in Medical Technology\r\n\r\nSchool of Nursing\r\n
Master of Science in Nursing\r\n\r\nSchool of Nutrition and Hospitality Management\r\n
Master of Science in Hotel and Restaurant Management\r\n
Master of Science in Nutrition and Dietetics\r\n
Master of Science in Tourism Management\r\n\r\nchool of Pharmacy\r\n
Master of Science in Pharmacy\r\n
Master of Science in Pharmacy specialized in Clinical Pharmac\r\n\r\nSchool of Science and Technology\r\n
Master of Science in Biology\r\n
Master of Science in Computer Engineering\r\n
Master of Science in Computer Scienc\r\n
Master of Science in Cosmetic Science\r\n
Master of Science in Information Technology\r\n
Master of Science in Psychology', 'Short Courses & Certifications\r\n-Associate in Accounting Technology Management\r\n-Associate in Hotel and Restaurant Management\r\n-Associate in Library and Information Science\r\n-Elementary Teacher Certificate\r\n-Secondary Teacher Certificate', '', 'http://www.ceu.edu.ph/', '(02) 735-6861 to 71', 'ceuadmission@ceu.edu.ph', '', '', '', '', '2018-02-11 16:11:58', 'Centro Escolar University', ' Private University', ' Required', ' Non-sectarian', ' Semester', ' starts in June', 'Teacher Education', '20th ', '83 ', NULL),
  (2, 'Central Institute of Technology', 'This has not been updated yet', '', 'schools/central-institute-of-technology', '', 'Manila', '', '10000 - 50000', '', '', 'central-institute-of-technology.png', '', '', 'Medical and Allied
-
Bachelor of Science in Radiologic Technology

Education Science and Teacher Training
-
Bachelor of Secondary Education Major in History

Architectural and Town-Planning
-
Bachelor of Science in Architecture', 'Medical and Allied
-
Master of Science in Radiologic Technology

Education Science and Teacher Training
-
Master of Secondary Education Major in History

Architectural and Town-Planning
-
Master of Science in Architecture', '', '', 'http://www.ccp.edu.ph/', '(+632) 715 5170 loc. 134', 'admission@ccp.edu.ph', '', '', '', '', '2018-02-02 09:16:49', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL),

Trying to change the "type" and "term_structure" columns into NOT NULL but I get an error (as seen in the question).
Any ideas?

A: Fixed it myself using this post: MySQL alter table modify column failing at rows with null values
Replaced all instances of NULL with a random text.  Then I replaced the random text with an empty string.  Then I changed the NULL to NOT NULL.


text:
Q: Link Stack Overflow profile pages to Google profile A question on Webapps has showcased a nice, new (to me) feature of Google:

– that is, the blog is associated with Jeff's Google profile.
Would it make sense to have this for Stack Overflow profile pages? That is, if I google for my name and Google shows my SO profile, Google would show the association with my Google profile?

A: For this to work, there need to be two things:

*

*A link with rel="author" from your user page to your Google profile

*A link back from your Google profile to the user page.

The second one you'll have to do yourself, and I suppose some use of the first one would be part of this feature request. (I just tried to put a manual ... link into my "about me" block, and this didn't work.)

A: In order for this magic to happen, basically three things need to be present:

*

*A link from the "content page" to the "author page" which contains the rel="author" parameter.

*A link from the "author page" to a Google profile which also contains the &rel=author query parameter.

*A link on the Google profile back to the website hosting those pages.

(Step 1 is omitted from Paŭlo's answer, but it shouldn't be -- without the link from the content page, this feature would only work on the author's page itself, not on any answers that that user actually wrote. That's not the intent of the feature, and it also wouldn't be that useful for anyone. The only time your Stack Overflow author page would come up in a search result is if you were already searching for that person anyway).
Steps 2 and 3 are already under the control of any Stack Exchange user -- however, Stack Overflow has to decide if it wants to take Step 1 (and enable step 2).
For the same reasons that Stack Overflow adds nofollow by default to outbound links from user pages, I don't think the author link should happen automatically for everyone. It should be a tool used to incentivize answer-ers. For example, ref="author" could be automatically added to the link to the answerer's profile on the accepted answer of a question, if the answerer has over 2,000 reputation. It would certainly incentivize having accepted answers (over votes) even more. I can also see people being more vigilant with keeping an answer up-to-date if their name is on the search result. Not to mention, search results with authors pop out more on the Google results page, and I wouldn't be surprised if (now or in the future) those results get some extra Google Juice of their own.
On the other hand, if someone does not want to have their name associated this way, it's incredibly easy to do: just don't include a link to Stack Overflow on your Google profile, or a link to your Google profile on your SO author page. It's explicitly opt-in and nearly impossible to achieve by accident, so there's no privacy concerns.

Adapted this answer from my duplicate question on this topic.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java Regex First Name Validation I understand that validating the first name field is highly controversial due to the fact that there are so many different possibilities. However, I am just learning regex and in an effort to help grasp the concept, I have designed some simple validations to create just try to make sure I am able to make the code do exactly what I want it to, despite whether or not it conforms to best business logic practices.
I am trying to validate a few things.

*

*The first name is between 1 and 25 characters.

*The first name can only start with an a-z (ignore case) character.

*After that the first name can contain a-z (ignore case) and [ '-,.].

*The first name can only end with an a-z (ignore case) character.
public static boolean firstNameValidation(String name){

    valid = name.matches("(?i)(^[a-z]+)[a-z .,-]((?! .,-)$){1,25}$");

    System.out.println("Name: " + name + "\nValid: " + valid);

    return valid;
 }

A: Try this regex
^[^- '](?=(?![A-Z]?[A-Z]))(?=(?![a-z]+[A-Z]))(?=(?!.*[A-Z][A-Z]))(?=(?!.*[- '][- '.]))(?=(?!.*[.][-'.]))[A-Za-z- '.]{2,}$

Demo

A: Your expression is almost correct. The following is a modification that satisfies all of the conditions:
valid = name.matches("(?i)(^[a-z])((?![ .,'-]$)[a-z .,'-]){0,24}$");

A: A regex for the same:
([a-zA-z]{1}[a-zA-z_'-,.]{0,23}[a-zA-Z]{0,1})

A: Lets change the order of the requirements:

*

*ignore case: "(?i)"

*can only start with an a-z character: "(?i)[a-z]"

*can only end with an a-z: "(?i)[a-z](.*[a-z])?"

*is between 1 and 25 characters: "(?i)[a-z](.{0,23}[a-z])?"

*can contain a-z and [ '-,.]: "(?i)[a-z]([- ',.a-z]{0,23}[a-z])?"
the last one should do the job:
valid = name.matches("(?i)[a-z]([- ',.a-z]{0,23}[a-z])?")

Test on RegexPlanet (press java button).
Notes for above points

*

*could have used "[a-zA-Z]"' instead of"(?i)"'

*need ? since we want to allow one character names

*23 is total length minus first and the last charracter (25-1-1)

*the - must come first (or last) inside [] else it is interpreted as range sepparator (assuming you didn't mean the characters between ' and ,)

A: Try this simplest version:
^[a-zA-Z][a-zA-Z][-',.][a-zA-Z]{1,25}$

Thanks for sharing.

A: A unicode compatible version of the answer of @ProPhoto:
^[^- '](?=(?!\p{Lu}?\p{Lu}))(?=(?!\p{Ll}+\p{Lu}))(?=(?!.*\p{Lu}\p{Lu}))(?=(?!.*[- '][- '.]))(?=(?!.*[.][-'.]))(\p{L}|[- '.]){2,}$


text:
Q: Disable input when no item got specific class name I got a little codepen where you can select multiple tabs (with jQuery selectable widget). I wanna do the following: If no item got the class name .ui-selected the input #plannername gets disabled.
I thought something like this should work:
if ($('.ui-selected').length === 0){
   $('#plannername').prop('disabled', true);
}
else{
   $('#plannername').prop('disabled', false);
}

But that doesn't work. I created the following:
var count = $('.ui-selected').length;
console.log(count);

That's giving me the correct amount of tabs selected.

$(function() {
    // define one function, to be used for both select/unselect
    function selectionChange(event, ui) {
        // Get indexes of selected items in an array
        var items = $('.ui-selected', this).map(function () {
            return $(this).index();
        }).get();
        // Show or hide sections according to the corresponding option's selection
        $("section").each(function () {
            $(this).toggle(items.indexOf($(this).index()) > -1);
        });
        console.log(items);
        var count = $('.ui-selected').length;
        console.log(count);
    }

    $("#selectable").selectable();
    $("#selectable").selectable({
        selected: selectionChange,
        unselected: selectionChange
    });
});

$(function(){
    $('#plannerform').submit(function(e){
        var val = $(this).find('#plannername').val();
        $('ul.plannerlist:visible').append('
' + val + '
');
        e.preventDefault();
        $('#plannername').val('');
    });
});
*{
  font-family: 'Josefin Sans', sans-serif;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
#selectable .ui-selecting {
  background: #9eefbc;
  transition:.8s ease-in-out;
  -webkit-transition: -webkit-transform 0.8s, background-color 0.8s;
 transition: transform 0.8s, background-color 0.8s;
 -webkit-transform: perspective(300px) rotate3d(1,0,0,-180deg);
 transform: perspective(300px) rotate3d(1,0,0,-180deg);
 -webkit-transform-origin: 50% 100%;
 transform-origin: 50% 100%;
 -webkit-perspective-origin: 50% 100%;
 perspective-origin: 50% 100%;
}
#selectable .ui-selected {
  background: #6dce91;
  transition:all 0.8s;
}
#selectable {
  list-style-type: none;
  position:absolute;
  width: 60%;
  margin-left:20%;
  display:flex;
  transition:.3s ease-in-out;
  z-index:1;
  margin-top:3px;
}
#selectable li {
  background:#ddffea;
  padding: 0.6em;
  font-size: 1.4em;
  flex-grow:1;
  transition:.3s ease-in-out;
  border:none;
  text-align:center;
  line-height:0.8em;
}

#selectable .ui-selected:after,
#selectable .ui-selected::after {
    position: absolute;
    top: 44px;
    margin-left:-50px;
    transition: .2s ease-in-out;
    content: '';
    width: 0;
    height: 0;
    opacity:1;
    animation:dreieckFade 1s forwards;
    border-top: solid 15px #6dce91;
    border-left: solid 20px transparent;
    border-right: solid 20px transparent;
}

@keyframes dreieckFade{
    0%{opacity:0;border-top: solid 0px #6dce91;}
    100%{opacity:1;border-top: solid 15px #6dce91;}
}

.ui-selectable-helper {
  visibility: hidden;
}

#content{
  width:60%;
  background-color:#9eefbc;
  margin-left:20%;
  padding-top:70px;
  margin-top:3px;
  padding-bottom:30px;
}

.tabcontent{
    top:44px;
    background-color:transparent;
    z-index:0;
    transition:.3s ease-in-out;
    font-size:2em;
    display:none;
    padding-left:100px;
}

#plannername{
  width:40%;
  background-color:#9eefbc;
  margin-left:20%;
  border:0;
  font-size:2em;
  padding:20px;
}
#plannername:focus{
  outline:0;
}
#plannersubmit{
  width:20%;
  background-color:#6dce91;
  border:0;
  font-size:2em;
  padding:20px;
  transition:.2s ease-in-out;
}
#plannersubmit:hover{
  transition:.2s ease-in-out;
  padding-left:40px;
  cursor:pointer;
}
#plannersubmit:focus{
  outline:0;
}
#plannersubmit:active{
  color:white;
}
.plannerlist{
    list-style-type:none;
}
<link href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" rel="stylesheet"/>

<form id="plannerform">
    <input id="plannername" placeholder="insert name" type="text" autocomplete="off"></input><input id="plannersubmit" type="submit" value="sign up"></input>
</form>

FR PM

SA AM

SA PM

SO AM

SO PM

MO AM

A: What you need to do is remove the disabled flag once the action of clicking one of the options has taken place. Essentially, what you should do is set the field to disabled by default, then enable it once a selection has been made:
$(function() {
  $('#plannername').prop('disabled', true);
  function selectionChange(event, ui) {
    ('#plannername').prop('disabled', false);
  }
}

I've created an updated CodePen showcasing this here.
Hope this helps! :)


text:
Q: Summing all the values of a function The following function
$$f(x)=\left\{\begin{array}{ll} 50, &0\leq x\leq10 \\ 10+6x-0.2x^2, & 10<x\leq30\end{array}\right.$$
gives me the number of products that are sold in the $x$-th day of a month.
How am I supposed to find the approximated total number of sold products in a month? Is there a easier way than not doing
$$f(0)+f(1)+f(2)+\ldots+f(29)+f(30)?$$

A: Yes.
$$\sum_{k=0}^{30} f(k)= \sum_{k=0}^{10} f(k) + \sum_{k=11}^{30} f(k) = \sum_{k=0}^{10} 50 + \sum_{k=11}^{30}(10 + 6k -0.2k^2)$$
$$=50 \times 11 + 10 \times 20 + 6 \left( \frac{30\times 31}{2} -\frac{10\times 11}{2} \right) - 0.2 \left(  \frac{30\times 31 \times 61}{6} -\frac{10\times 11 \times 21}{6} \right) = 1396$$

A: An approximation might be $$\int_{-0.5}^{10.5} 50 \,dx +  \int_{10.5}^{30.5} (10+6x-0.2x^2)\, dx$$ which would suggest $\frac{4187}{3} = 1396-\frac13$, so not far away


text:
Q: What is the term for different types that contain the same information? What is the correct term(s) for different types that contain exactly the same information? For example (F#):
type Type1 = (int * string)
type Type2 = (string * int)

When describing that these types can contain exactly the same information, I could say that Type1 and Type2 are ______. Which word(s) could I use?
And is there a corresponding term for types that are similar, but not exactly so? For example:
type Type3 = Map<string, int>
type Type4 = (string * int) list

There is a "lossless" mapping from Type3 to Type4, but not the other way around (a Map can only contain unique keys, whereas Type4, being a list, has no such restriction).
I'll accept an answer that provides relevant terms along with some credibly sourced definition (or convinces me that there are no relevant terms).

A: Let's start with Type3 and Type4. I assume that the "lossless" mapping you have in mind is the library function toList. This will just map a Map to a corresponding List containing all key / value pairs from the map. However, this mapping is not enough. You also need to transform all functions involving Type3 to structure-preserving functions involving Type4.
I will try a formal definition but, as said in my comment, I would like someone with more knowledge on this topic to write a better answer.
So, formally, given two types T1 and T2, a homomorphism h : T1 -> T2 is a pair (d, f), where d : T1 -> T2 maps all values in T1 to values in T2, and f : (T1 -> T) -> (T2 -> T) maps any function t : T1 -> T to a new function f t = t' : T2 -> T, such that t = (f t) . d.
This means that d maps the data representation from type T1 to a representation of type T2, while f maps all functions on T1 to functions on T2 in a way that preserves the structure.
In your example, T1 = Map<string, int>, T2 = (string * int) list, and d = toList. For all types T, the function f should map any function t : Map<string, int> -> T to a function f t : (string * int) list -> T in such a way that t m = (f t) (d m) for each map m.
For example, the function isEmpty : Map<string, int> -> bool should be mapped to f isEmpty = isEmpty' in such a way that if isEmpty m is equivalent to isEmpty' (d m). In words: if isEmpty tells you that a map is empty, then isEmpty' should tell you that the corresponding list representation is empty as well.
Once you have both mappings (on data and on functions), you can say that the first type is homomorphic to the second.
Two types are isomorphic if there are homomorphisms in both directions.
For your first example, the data mapping function d : (int * string) -> (string * int) is d (i, s) = (s, i) and, for all type T and functions t : (int * string) -> T, you can define t' = f t : (int * string) -> T by letting t' (i, s) = t (s, i). In this way, you can see that Type1 is homomorphic to Type2. By defining similar functions in the other direction you can see that Type2 is homomorphic to Type1. Therefore the two types are isomorphic.


text:
Q: OpenShift Container Platform unable to pull private Docker Hub images I have an instance of OpenShift Container Platform 3.9 running.

*

*I created a docker hub secrets with credentials to access private images.

*I linked the newly created secret to the default service account for pull access.

*I created an ImageStream, to access the private image, which seems to have access as it is correctly accessing the image sha.

*I created a DeploymentConfig to deploy the image. When deploying, I get the following error message when attempting to pull the image Failed to pull image "myorg/myimage": rpc error: code = Unknown desc = repository docker.io/myorg/myimage not found: does not exist or no pull access
The image stream looks as follows:
apiVersion: v1
kind: ImageStream
metadata:
  name: myimage
spec:
  dockerImageRepository: docker.io/myorg/myimage
  tags:
    - name: mytag
      generation: 2
      from:
        kind: DockerImage
        name: 'docker.io/myorg/myimage:mytag'
      importPolicy:
        scheduled: true

The deployment config looks as follows:
apiVersion: v1
kind: DeploymentConfig
metadata:
  name: myservice
  generation: 1
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: example
    spec:
      containers:
      - name: myservice
        image: myorg/myimage:mytag
        imagePullPolicy: Always
        ports:
        - containerPort: 8888

What could I be doing wrong?


text:
Q: Sql (Oracle) : insert a duplicate key Harry is the wizard and he creates a group which name is "the fellowship of the ring".Harry's wizard number is 77.
INSERT INTO group VALUES ('the fellowship of the ring','01');
INSERT INTO activity VALUES ('01','77','the fellowship of the ring');

Gondor also wants to join the group and the activity01.
From the table, we know "wizardno" is the primary key of the wizard table.
"groupname" is the primary key of the group table. "acitvityno" is UF key of the group table.
"acitvityno" is the primary key of the activity table.
"groupname" is the foreign key of the activity table.
"wizardno"  is UF key of the activity table.in
to add Gondor to Harry's group. Gondor's wizard number is 99.
I use
insert into activity values ('01','99','the fellowship of the ring');

Got the error:
Cause:An UPDATE or INSERT statement attempted to insert a duplicate key.
For Trusted Oracle configured in DBMS MAC mode, you may see this message if a duplicate entry exists at a different level.
*Action:   Either remove the unique restriction or do not insert the key.
But it must remain the unique restriction.
drop table wizard;
drop table activity;
drop table group;

CREATE TABLE wizard (
    wizardno          NUMBER(2) NOT NULL,
    wizardname        VARCHAR2(30) NOT NULL,
   );

ALTER TABLE wizard ADD CONSTRAINT wizard_pk PRIMARY KEY ( wizardno );
CREATE TABLE group (
    groupname        VARCHAR2(30) NOT NULL,
    activityno         NUMBER(2) NOT NULL
);

ALTER TABLE group ADD CONSTRAINT group_pk PRIMARY KEY ( groupname );

CREATE TABLE activity (
    activityno        NUMBER(2) NOT NULL,
    wizardno          CHAR(2) NOT NULL,
    groupname         VARCHAR2(30)
);

ALTER TABLE activity
   ADD CONSTRAINT activity_pk PRIMARY KEY ( activityno );

ALTER TABLE activity
    ADD CONSTRAINT activity_wizard_fk FOREIGN KEY ( wizardno )
        REFERENCES wizard ( wizardno );
ALTER TABLE  activity
    ADD CONSTRAINT activity_group_fk FOREIGN KEY ( groupname )
        REFERENCES group ( groupname );

A: *

*Do not use a reserved word group as a table name

*Use proper single quotes '' for string type variables

*You need to have corresponding values inserted for look-up tables (
in this case wizard ) which you referenced for decent integrity of
the tables.

*For Foreign Key and Primary Key relation, both reference columns in
both tables should be of the same type( you may convert the type of the column wizardno from CHAR(2) to number(2) in the activity table  ).

*A Primary key column's value shouldn't be duplicated ( here
constraint name is activity_pk )
So the following set of commands may be used :
drop table wizard;
drop table activity;
drop table group_;

CREATE TABLE wizard (
    wizardno          NUMBER(2) NOT NULL,
    wizardname        VARCHAR2(30) NOT NULL
   );

ALTER TABLE wizard ADD CONSTRAINT wizard_pk PRIMARY KEY ( wizardno );
CREATE TABLE group_ (
    groupname        VARCHAR2(30) NOT NULL,
    activityno         NUMBER(2) NOT NULL
);

ALTER TABLE group_ ADD CONSTRAINT group_pk PRIMARY KEY ( groupname );

CREATE TABLE activity (
    activityno        NUMBER(2) NOT NULL,
    wizardno          NUMBER(2) NOT NULL,
    groupname         VARCHAR2(30)
);

ALTER TABLE activity
   ADD CONSTRAINT activity_pk PRIMARY KEY ( activityno );

ALTER TABLE activity
    ADD CONSTRAINT activity_wizard_fk FOREIGN KEY ( wizardno )
        REFERENCES wizard ( wizardno );
ALTER TABLE  activity
    ADD CONSTRAINT activity_group_fk FOREIGN KEY ( groupname )
        REFERENCES group_ ( groupname );
INSERT INTO wizard VALUES ( 77, 'Abc');
INSERT INTO wizard VALUES ( 99, 'Def');

INSERT INTO group_ VALUES ('the fellowship of the ring','01');
INSERT INTO activity VALUES ('01',77,'the fellowship of the ring');
INSERT INTO activity VALUES ('02',99,'the fellowship of the ring');

A: *

*You should not use the GROUP keyword as a table name. Instead you could pluralise the table names (wizards, groups, activities).

*wizardno is a NUMBER(2) type in the wizards table and a CHAR(2) in the activities table when there is a foreign key reference between them. They should be the same type.

*You do not need to duplicate groupname in the activities table.

*If you do not want to allow duplicate wizards in each group then the primary key on the activity table should be a composite key on both the primary keys of the wizards and groups tables.

*You can use sequences to generate the unique primary key values.

Like this:
SQL Fiddle
Oracle 11g R2 Schema Setup:
CREATE TABLE wizards (
  wizardno    NUMBER(2)
              CONSTRAINT wizards_wizardno_pk PRIMARY KEY,
  wizardname  VARCHAR2(30)
              CONSTRAINT wizards_wizardname_nn NOT NULL
);

CREATE SEQUENCE wizards_wizardno_seq;

CREATE TABLE groups (
  groupname VARCHAR2(30)
            CONSTRAINT groups_groupname_u UNIQUE
            CONSTRAINT groups_groupname_nn NOT NULL,
  groupno   NUMBER(2)
            CONSTRAINT groups_groupno_pk PRIMARY KEY
);

CREATE SEQUENCE groups_groupno_seq;

CREATE TABLE activities (
    activityno NUMBER(2)
               CONSTRAINT activities_activityno_pk PRIMARY KEY,
    groupno    NUMBER(2)
               CONSTRAINT activities_groupno_nn NOT NULL
               CONSTRAINT activities_groupno_fk REFERENCES groups ( groupno ),
    wizardno   NUMBER(2)
               CONSTRAINT activities_wizardno_nn NOT NULL
               CONSTRAINT activities_wizardno_fk REFERENCES wizards ( wizardno ),
    CONSTRAINT activities_group_wizard_u UNIQUE ( groupno, wizardno )
);

CREATE SEQUENCE activities_activityno_seq;

INSERT INTO wizards ( wizardno, wizardname )
VALUES ( wizards_wizardno_seq.NEXTVAL, 'Harry' );

INSERT INTO wizards ( wizardno, wizardname )
VALUES ( wizards_wizardno_seq.NEXTVAL, 'Gondor' );

INSERT INTO groups ( groupname, groupno )
VALUES ( 'the fellowship of the ring', groups_groupno_seq.NEXTVAL );

INSERT INTO activities ( activityno, groupno, wizardno )
VALUES ( activities_activityno_seq.NEXTVAL, 1, 1 );

INSERT INTO activities ( activityno, groupno, wizardno )
VALUES ( activities_activityno_seq.NEXTVAL, 1, 2 );

Query 1:
SELECT wizardname,
       groupname
FROM   wizards w
       INNER JOIN activities a
       ON ( w.wizardno = a.wizardno )
       INNER JOIN groups g
       ON ( a.groupno = g.groupno )

Results:
| WIZARDNAME |                  GROUPNAME |
|------------|----------------------------|
|      Harry | the fellowship of the ring |
|     Gondor | the fellowship of the ring |


text:
Q: Select tag keeps expanding in second iframe I'm having difficulty populating the second iframe on this page:
http://www.licf.ronaldboadi.com/Movieshop/
Whenever you select an option in iframe 1, instead of iframe 2 being refreshed and a certain number of values being added - it keeps adding more values to the previous user selection. How can I stop this from happening?
Thanks!

A: You should clear the document contents each load by setting the src to "about:blank". Generally, that works like:
iframe_el.src = "about:blank";

In you context, just put this right above the document opne.
with( document.getElementById('movie').contentDocument ) {
    src = "about:blank";
    open();
    write(hstr);
    close();
}

Also, as a general best practice, don't use with. Just cache the object, like this:
var doc = document.getElementById('movie').contentDocument;
doc.src = "about:blank";
doc.open();
doc.write(hstr);
doc.close();


text:
Q: How can I recursively copy a directory into another and replace only the files that have not changed? I am looking to do a specific copy in Fedora.
I have two folders:

*

*'webroot': holding ALL web files/images etc

*'export': folder containing thousands of PHP, CSS, JS documents that are exported from my SVN repo.
The export directory contains many of the same files/folders that the root does, however the root contains additional ones not found in export.
I'd like to merge all of the contents of export with my webroot with the following options:

*

*Overwriting the file in webroot if export's version contains different code than what
is inside of webroot's version (live)

*Preserve the permissions/users/groups of the file if it is overwritten (the export
version replacing the live version) *NOTE I would like the webroots permissions/ownership maintained, but with export's contents

*No prompting/stopping of the copy
of any kind (ie not verbose)

*Recursive copy - obviously I
would like to copy all* files
folders and subfolders found in
export

I've done a bit of research into cp - would this do the job?:
cp -pruf ./export /path/to/webroot

A: *

*-u overwrites existing files folder if the destination is older than source

*-p perserves the permission and dates

*-f turns off verbosity

*-r makes the copy recursive

So looks like you got all the correct args to cp

A: Sounds like a job for cpio (and hence, probably, GNU tar can do it too):
cd export
find . -print | cpio -pvdm /path/to/webroot

If you need owners preserved, you have to do it as root, of course.  The -p option is 'pass mode', meaning copy between locations; -v is verbose (but not interactive; there's a difference); -d means create directories as necessary; -m means preserve modification time.  By default, without the -u option, cpio won't overwrite files in the target area that are newer than the one from the source area.

A: It might, but any time the corresponding files in export and webroot have the same content but different modification times, you'd wind up performing an unnecessary copy operation. You'd probably get slightly smarter behavior from rsync:
rsync -pr ./export /path/to/webroot

Besides, rsync can copy files from one host to another over an SSH connection, if you ever have a need to do that. Plus, it has a zillion options you can specify to tweak its behavior - look in the man page for details.
EDIT: with respect to your clarification about what you mean by preserving permissions: you'd probably want to leave off the -p option.


text:
Q: PHP, не работает exception есть такая конструкция:
try
{
    require_once("Classes/".$class_name.".php");
} catch(Exception $e)
{
    Sys::Route("Error", "Notfound");
    exit;
}

но почему-то исключение не срабатывает, а выдаёт fatal error, с include_once то же самое, в чём может быть причина?
A:
с include_once то же самое

Не так, чтобы то же самое. require выдает фатальную ошибку, а include — предупреждение.
Fatal error не ловится с помощью try/catch. Можете использовать register_shutdown_function(), но, как следует из названия — это конец.
Остальные ошибки можно поймать и "преобразовать" в исключение таким вот хитрым образом:
function handleError($errno, $errstr, $errfile, $errline, array $errcontext)
{
    // молчим, если ошибку подавили оператором @
    if (0 === error_reporting()) {
        return false;
    }

    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}

set_error_handler('handleError');


text:
Q: Why would google tests compile but not be able to see my project sources? Why would google tests compile but not be able to see my project sources?
Here's the error that I'm getting:
$ cmake . && make && make test
-- Configuring done
-- Generating done
-- Build files have been written to: mars_rover
Scanning dependencies of target mars_rover
[  8%] Building CXX object CMakeFiles/mars_rover.dir/src/rover.cpp.o
Linking CXX executable build/bin/mars_rover
[ 33%] Built target mars_rover
[ 41%] Built target gtest
[ 50%] Built target gtest_main
Scanning dependencies of target mars_rover_TEST
[ 58%] Building CXX object CMakeFiles/mars_rover_TEST.dir/test/test_mars_rover.cpp.o
mars_rover/test/test_mars_rover.cpp:2:10: fatal error: 'src/directions.h' file not found
#include "src/directions.h"
         ^
1 error generated.
make[2]: *** [CMakeFiles/mars_rover_TEST.dir/test/test_mars_rover.cpp.o] Error 1
make[1]: *** [CMakeFiles/mars_rover_TEST.dir/all] Error 2
make: *** [all] Error 2

Here's how I've got my project laid out:
$ tree {src,test,lib} -L 1
    src
    ├── directions.cpp
    ├── directions.h
    ├── main.cpp
    ├── plateau.cpp
    ├── plateau.h
    ├── point.h
    ├── rover.cpp
    └── rover.h
    test
    ├── input1
    ├── output1
    ├── test_main.cpp
    └── test_mars_rover.cpp
    lib
    ├── CMakeLists.txt
    └── gtest-1.7.0

And here's my CMakeLists.txt
cmake_minimum_required(VERSION 2.8)

# Options. Turn on with 'cmake -Dtest=ON'.
option(test "Build all tests." ON)

set(PROJECT_NAME mars_rover CXX)
project(${PROJECT_NAME})

set(CMAKE_CXX_FLAGS "-g -Wall -Werror")

file(GLOB_RECURSE PROJECT_SOURCES ${CMAKE_SOURCE_DIR}/src/*.cpp)
add_executable(${PROJECT_NAME} ${PROJECT_SOURCES})
SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/build/bin)
SET(LIBRARY_OUTPUT_PATH ${PROJECT_BINARY_DIR}/build/lib)

if (test)

  add_subdirectory(lib/gtest-1.7.0)
  enable_testing()
  include_directories(${gtest_SOURCE_DIR}/include ${gtest_SOURCE_DIR})

  # finding test sources
  file(GLOB_RECURSE TEST_SOURCES ${CMAKE_SOURCE_DIR}/test/*.cpp ${CMAKE_SOURCE_DIR}/src/*.cpp)
  add_executable(${PROJECT_NAME}_TEST ${TEST_SOURCES})

  # link to gtest
  target_link_libraries(${PROJECT_NAME}_TEST gtest gtest_main)

  add_test(CardinalDirectionTests ${EXECUTABLE_OUTPUT_PATH}/${PROJECT_NAME}_TEST --gtest_filter=MarsRoverTest.CardinalDirectionTests)
  add_test(RelativeDirectionTests ${EXECUTABLE_OUTPUT_PATH}/${PROJECT_NAME}_TEST --gtest_filter=MarsRoverTest.RelativeDirectionTests)

endif()

A: Your test executable can't find 'src/directions.h' since its parent (${CMAKE_SOURCE_DIR}) hasn't been added to the include_directories call.  Just adding it should work.
However, I can see a few other minor points in your setup.  Running through your CMakeLists.txt, here are the changes I'd make:
cmake_minimum_required(VERSION 2.8.12)

If you can specify 2.8.12 as the minimum, you have access to the more useful target_include_directories command.  Where include_directories is a bit of a blunderbuss approach, target_include_directories allows you to specify search paths just for that specific target.  If you specify these as PUBLIC or INTERFACE, then subsequent targets which link to this one will automatically inherit these search paths too.
In a similar vein, you could look at using target_compile_definitions and target_compile_options.

set(PROJECT_NAME mars_rover CXX)
project(${PROJECT_NAME})
project(mars_rover)
The project command sets the variable PROJECT_NAME, so your set command has little use here.  And CMake will detect that this is a C++ project by virtue of the source file suffixes.

By including all your sources in two separate targets (the main exe and the test exe), these will all be compiled twice.  To avoid this inefficiency, I'd make a library of all your sources in "/src" except "main.cpp" and then have an exe which only has main.cpp and links to this library.
Also, using file(GLOB ...) or file(GLOB_RECURSE ...) is discouraged as a means of gathering source lists.
set(CMAKE_CXX_FLAGS "-g -Wall -Werror")
file(GLOB_RECURSE PROJECT_SOURCES ${CMAKE_SOURCE_DIR}/src/*.cpp)
add_executable(${PROJECT_NAME} ${PROJECT_SOURCES})
# No need to include .h files, but they show up in IDEs like Xcode if you do.
set(libSources
    src/directions.cpp src/directions.h
    src/plateau.cpp src/plateau.h
    src/point.h
    src/rover.cpp src/rover.h
    )
add_library(${PROJECT_NAME}_LIB ${libSources})

# Anything linking to this will automatically have ${PROJECT_SOURCE_DIR}
# added to the compiler's search paths since it is PUBLIC.  Prefer
# ${PROJECT_SOURCE_DIR} to ${CMAKE_SOURCE_DIR} in case this project is not
# the top-level one.
target_include_directories(${PROJECT_NAME}_LIB PUBLIC ${PROJECT_SOURCE_DIR})

# Use generator expressions to conditionally apply the flags to Unix and Debug
# builds.  Anything linking to this will automatically have these flags also
# applied since they are PUBLIC.
target_compile_options(${PROJECT_NAME}_LIB PUBLIC
                       $<$<BOOL:${UNIX}>:-Werror -Wall $<$<CONFIG:Debug>:-g>>)

add_executable(${PROJECT_NAME} src/main.cpp)
target_link_libraries(${PROJECT_NAME} ${PROJECT_NAME}_LIB)

For the test, it looks like you have 2 or maybe 3 main functions - that's going to be a problem :-)  gtest_main is a small helper which provides a main function which calls the required gtest functions to invoke the tests.  I'm guessing you've also got main in "test/test_main.cpp" and since you're currently including all your "src/" files, I suppose you've also got a main in "src/main.cpp".
By splitting the mars_rover target into a lib and exe, you can just link to the lib and avoid explicitly excluding "src/main.cpp" from the test.  I can't tell whether you want to use your own "test_main.cpp" or use gtest's helper - I've assumed the latter:
include_directories(${gtest_SOURCE_DIR}/include ${gtest_SOURCE_DIR})
file(GLOB_RECURSE TEST_SOURCES ...)
add_executable(${PROJECT_NAME}_TEST ${TEST_SOURCES})
target_link_libraries(${PROJECT_NAME}_TEST gtest gtest_main)
add_executable(${PROJECT_NAME}_TEST test/test_mars_rover.cpp)

# Only bring gtest's include path into scope - its src dir is not designed to
# be public
target_include_directories(${PROJECT_NAME}_TEST PRIVATE
                           ${gtest_SOURCE_DIR}/include)

target_link_libraries(${PROJECT_NAME}_TEST ${PROJECT_NAME}_LIB gtest gtest_main)

Finally, there's no need to specify the full path to the test exe if you use the following syntax:
add_test(NAME CardinalDirectionTests
         COMMAND ${PROJECT_NAME}_TEST
             --gtest_filter=MarsRoverTest.CardinalDirectionTests)
add_test(NAME RelativeDirectionTests
         COMMAND ${PROJECT_NAME}_TEST
             --gtest_filter=MarsRoverTest.RelativeDirectionTests)


text:
Q: What is the different between alloc::sync::Arc and std::sync::Arc? I'm trying to use Arc in my code, but as i read the document, there is 2 places Arc is defined: std crate and alloc crate. So, what is the different between alloc::sync::Arc and std::sync::Arc?

A: From the alloc crate documentation:

This library provides smart pointers and collections for managing heap-allocated values.
This library, like libcore, normally doesn't need to be used directly since its contents are re-exported in the std crate. Crates that use the #![no_std] attribute however will typically not depend on std, so they'd use this crate instead.

So there's no difference between std::sync::Arc and alloc::sync::Arc.
alloc also provides Box, Vec, String, the collections module, and basically anything in the standard library that requires allocations (hence alloc) but not an underlying OS (filesystem, networking, etc). alloc is there if you want to write bare-metal (unhosted) software that still gets to use the nice standard library data structures.


text:
Q: Is there any way to hide or encrypt your python code for edge devices? Any way to prevent reverse engineering of python code? I am trying to make a smart IOT device (capable of performing smart Computer Vision operations, on the edge device itself). A Deep Learning algorithm (written in python) is implemented on Raspberry Pi. Now, while shipping this product (software + hardware) to my customer, I want that no one should log in to the raspberry pi and get access to my code. The flow should be something like, whenever someone logs into pi, there should be some kind of key that needs to be input to get access to code. But in that case how OS will get access to code and run it (without key). Then I may have to store the key on local. But still there is a chance to get access to key and get access to the code. I have applied a patent for my work and want to protect it.
I am thinking to encrypt my code (written in python) and just ship the executable version. I tried pyinstaller for it, but somehow there is a script available on the internet that can reverse engineer it.
Now I am little afraid as it can leak all my effort of 6 months at one go. Please suggest a better way of doing this.
Thanks in Advance.

A: Keeping the code on your server and using internet access is the only way to keep the code private (maybe). Any type of distributed program can be taken apart eventually. You can't (possibly shouldn't) try to keep people from getting inside devices they own and are in their physical possession. If you have your property under patent it shouldn't really matter if people are able to see the code as only you will be legally able to profit from it.
As a general piece of advice, code is really difficult to control access to. Trying to encrypt software or apply software keys to it or something like that is at best a futile attempt and at worst can often cause issues with software performance and usability. The best solution is often to link a piece of software with some kind of custom hardware device which is necessary and only you sell. That might not be possible here since you're using generic hardware but food for thought.


text:
Q: Search for different variations of text in pandas I have a pandas dataframe that consists of people and their degree type:
data = {'Name': ['Alice','Bob','Chris','David'],
    'Degree': ['phd','BA','MBA','B.Sc.']
    }

df = pd.DataFrame(data, columns = ['Name', 'Degree'])

And I would like to one hot encode based on the degree type:
data = {'Name': ['Alice','Bob','Chris','David'],
      'is_bachelors': [0,1,0,1],
      'is_masters': [0,0,1,0],
      'is_phd': [1,0,0,0]
     }

The problem is that people have input their degree type in lots of different ways. For example, for phd you could have PhD, phd, Ph. D, Ph.D., ph.d etc. Essentially lots of variations of spacings and periods.
Furthermore, I don't want MBA for example being flagged as bachelors (because it contains BA). I found this happened with pandas str.contains.
Any advice would be greatly appreciated.

A: Since the same degree types all start with the same character you can lower them and map on the first character:
data = {'Name': ['Alice','Bob','Chris','David'],
    'Degree': ['phd','BA','MBA','B.Sc.']
    }

df = pd.DataFrame(data, columns = ['Name', 'Degree'])
df['Degree'] = df['Degree'].str.lower().str[:1].map({'b': 'is_bachelors', 'm': 'is_masters', 'p': 'is_phd'})
df.pivot_table(index='Name', columns='Degree', aggfunc=len, fill_value=0)

result:

Name
is_bachelors
is_masters
is_phd

Alice
0
0
1

Bob
1
0
0

Chris
0
1
0

David
1
0
0

NB: you can add any other relevant letters to the mapping dictionary, eg. for dr. add 'd': 'is_phd'

A: For the 'PhD' example that you provide, you could remove punctuation and make everything lowercase, to capture all PhDs:
def preprocess (degree):
    return degree.replace('.', "").lower()

data['Degree'] = data.Degree.apply(preprocess)

Probably, this works for most variations in other degrees as well, but I cannot assess that without knowing the other variations.

A: You can use this:
import re

string= 'MBA'

if re.search('p', string, re.IGNORECASE):
    print(0)
elif re.search('m', string, re.IGNORECASE):
    print(1)
elif re.search('ba', string, re.IGNORECASE):
    print(2)
elif re.search('bs', string, re.IGNORECASE):
    print(2)

It solves the case sensitive, spacing, and punctuation problems. Also in cases such as 'MBA' where it contains a 'M' and 'BA' since any string containing an 'M' will be caught before it the 'BA' check.


text:
Q: Filtering database outputs rails I'm a little lost on this, so I have the activity feeds gem and the devise gem.
I want to have the ability to list all the posts made by a specified user
Controller
 def userstory
 @userstory = Story.where(params[:user_id])
 end

View
<% @userstories = Story.where(:user_ud) %>

<% @userstories.each do |story| %>

I also think my routes are wrong
 match '/stories/userstory/:user_id',     to: 'stories#userstory',       via: 'get'
resources :stories, :only =>[:show]

A: First, you need to ensure that stories has a user_id column pointing to users. Second, you need to properly define associations:
class Story < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :stories
end

Then in your controller add:
# I'm assuming this is index on a controller.
def index
  @stories = current_user.stories
end

You should be able to reference @stories in a view:
<%= @stories.each do |story| %>
  <!-- RENDER story HERE -->
<% end %>

A: Usually you handle params in Rails with forms, if you don't perform such action (fill a form, send it) you won't be able to deal with them. If you try to print in your view the current value of your params[:user_id] maybe you'll get nil, that's why when you try to find a Story through the id which in this case is nil then you get some response.
Try specifying your @stories within your controller and in the corresponding method and then use it in your view, maybe like:
# app/controllers/stories_controller.rb
def some_method
  @stories = Story.find_by_id(params[:user_id])
  ...

Just to mention, as far as I know, all the dynamic methods except for find_by_... and find_by_...! are deprecated since the Rails 4 version, so maybe you'd like to use find_by or where instead (see reference).
Seeing your routes then I assume you're in '/stories/userstory/id' in your navigator, and you click on some story to show it, then you need to use the method show in your StoriesController and this way to find such story through the params[:user_id].


text:
Q: Organizando elementos no cabeçalho do bootstrap panel Exemplo

        <title>Bootstrap Example</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

 Eventos Vinculados

                    <input type="text" class="form-control" ng-model="FiltroTabela" placeholder="Buscar..." style="width:300px" />

                    <button type="button" class="btn btn-primary" ng-click="novoEvento()"> Novo </button>

Para alinhar o título na esquerda utilizei o panel-title  pull-left mas no casos em serão usados input-groups e btn-groups qual seria o código para definir alinhamento dos elementos para direita ?


text:
Q: How to start executing javascript code on page load? I have a counter javascript code.It works fine but I want the counter to start executing onscroll but don't know how to do it. Any help with that?
<script type="text/javascript">
     $(document).ready(function () {
        var dataval = parseInt($('.progress').attr("data-amount"));
        if (dataval < 100) {
            $('.progress .amount').css("width", 0 + dataval + "%");
        }

        function modifyProgressVal(type) {
            dataval = parseInt($('.progress').attr("data-amount"));
            if (type == 1)
                dataval = Math.min(100, dataval + 10)
            else if (type == -1)
                dataval = Math.max(0, dataval - 10);
            $('.progress .amount').css("width", 100 - dataval + "%");
            $('.progress').attr("data-amount", dataval);
        }
    });
</script>

A: You can add a scroll event listener on the document like so:
document.addEventListener("scroll", () => {
 // execute code on scroll
});

A: The title and question are kinda confusing, but I think you might want your function to be called on load and on scroll; elaborating on Alex's answer, this should work:
document.addEventListener("scroll", () => {
    // execute code on scroll
});

document.dispatchEvent(new Event("scroll"));

A: Add .scroll function:
$(document).ready(function () {
$(document).scroll(function() {
    var dataval = parseInt($('.progress').attr("data-amount"));
    if (dataval < 100) {
        $('.progress .amount').css("width", 0 + dataval + "%");
    }

    function modifyProgressVal(type) {
    dataval = parseInt($('.progress').attr("data-amount"));
    if (type == 1) dataval = Math.min(100,dataval + 10)
    else if (type == -1) dataval = Math.max(0,dataval - 10);
    $('.progress .amount').css("width", 100 - dataval + "%");
    $('.progress').attr("data-amount", dataval);
}
}


text:
Q: Having to use $(document).ready() multiple times in same script I have a script with the following structure:
Test = {

    CONSTANTS : {},
    VARIABLES : {},
    MARKUP : {},
    FUNCTIONS : {
        init : function () {

            // Access variable from different namespace
            var all_constants = DifferentNamespace.CONSTANTS; // WORKS
            var tester = DifferentNamespace.CONSTANTS.chunk_of_markup; // SAYS UNDEFINED
        }
    },
    init : function () {

        // Call real init() function

        $(document).ready(function () {

            Test.FUNCTIONS.init();
        });
    }

};

$(document).ready(function () {

    Test.init();
});

If I remove either of the $(document).ready(..) function calls, when I try to access a constant from a different namespace it is undefined; with both is works well.
As you can see I'm using two init() functions, one it just to neaten up the call to init because I have wrapped functions inside an additional object.
If I remove the function that is on the same level as CONSTANTS, VARIABLES etc and try to call the init() within Test.FUNCTIONS it still does not work.
Edit:
If i console.log(all_constants) I get the full object (with .chunk_of_markup) but if I console.log(tester) is get undefined. If i wrap tester i get []
I should also note that the other namespace gets the markup from a seperate file.
Any ideas why?

A: Having two document ready doesn't make a difference here. You could have one document.ready and/or call Test.FUNCTIONS.init directly and all should work, and the fact that they are in different namespaces doesn't matter as well.
As for why you're getting undefined, I think it is probably because your chunk_of_markup variable is actually undefined at that point. My guess is that you're getting the value for it through AJAX and so the call is done asynchronously which means the DOM will be ready before it actually returns a value. When you use the Debugger then the value is evaluated at the point of time where you run the command so by then, the async call already returns successfully (it's a race condition, if you're fast enough and your AJAX is slow then you can still get undefined, and it's also why 2 ready functions happen to make it slow enough for the AJAX call to return but it's still unreliable).
In all cases, if my theory is correct, then you need to hook to the callback of the AJAX request rather that DOM ready event, this is the only place where you can guarantee that your variable is defined.

A: Why not call the function init() in the document Handler itself.. I don't think that will lead to the same problems.. You can remove the Test.init() completely as it does not seem to do anything in here
Test = {
    CONSTANTS : {},
    VARIABLES : {},
    MARKUP : {},
    FUNCTIONS : {
        init : function () {

            // Access variable from different namespace
            var all_constants = DifferentNamespace.CONSTANTS; // WORKS
            var tester = DifferentNamespace.CONSTANTS.chunk_of_markup; // SAYS UNDEFINED
        }
    }
};

$(document).ready(function () {

    Test.FUNCTIONS.init();
});


text:
Q: Determine if SQL UPDATE changed value of column I have a table with a text column called myTextColumn.  I would like to do something in the PHP application only if an UPDATE changed the value.  I am not using triggers.  Is there a better way to do so other than the following?  Thank you
function updateTable($data)
{
    $sql='SELECT id FROM myTable WHERE id=:id AND myTextColumn!=:myTextColumn';
    $stmt=db::db()->prepare($sql);
    $stmt->execute($data);
    if($stmt->fetchColumn()) {
        $sql='UPDATE myTable SET myTextColumn=? WHERE id=?';
        $stmt=db::db()->prepare($sql);
        $stmt->execute($data);
        return true;
    }
    else {return false;}
}

if(updateTable(array('id'=>123, 'myTextColumn'=>'Some text goes here')))
{
    echo('It Changed');
}

A: You can check the rowCount after your PDO call.  It'll tell you the number of rows affected by your UPDATE.
$sql='UPDATE myTable SET myTextColumn=? WHERE id=?';
$stmt=db::db()->prepare($sql);
$stmt->execute($data);
if ( $stmt->rowCount() > 0 )
{ /* do stuff */ }


text:
Q: serialize objects to transfer into the messagequeue instance I was going through the msdn post of system.messaging namespace and come across a doubt about object serialization. I want to know that is it always important to that object must be xmlserializable in order to be transferred over a MessageQueue instance.
Second, if we are invoking the MessageQueue.Send member is this also means that we are using default System.Messaging.XmlMessageFormatter.
An explanation would be appreciative.
Thanks

A: you don't have to use xml, you can use BinaryMessage like this
   BinaryMessageFormatter formatter = new BinaryMessageFormatter();
   System.Messaging.Message message = new System.Messaging.Message(YourObject, formatter);

second, xml message is the default, although I have always used binary, xml is to bulky for almost all kind of scenarios.


text:
Q: How to unquote URL quoted UTF-8 strings in Python thestring = urllib.quote(thestring.encode('utf-8'))

This will encode it. How to decode it?

A: What about
backtonormal = urllib.unquote(thestring)

A: if you mean to decode a string from utf-8, you can first transform the string to unicode and then to any other encoding you would like (or leave it in unicode), like this
unicodethestring = unicode(thestring, 'utf-8')
latin1thestring = unicodethestring.encode('latin-1','ignore')

'ignore' meaning that if you encounter a character that is not in the latin-1 character set you ignore this character.


text:
Q: How to close the new tab and return to the first tab in Robot Framework? My test scenario clicks the button that follows to the new tab of the browser, after verifying that we got the right page I need to close this tab and return to the first tab. How could I close the actual tab? I tried to use Close Window, but it closes the entire browser?

A: This code can help you open new tab and close that's new tab by and return to your first tab.
*** Test Cases ***
T1
    Open Browser    ${URL}   ${BROWSER}
    click element   name=btn
    ${title_var}        Get Window Titles
    Select Window       title=@{title_var}[1]
    close window

A: you can use below code to close active window and back to main window
${windowhandles}=   Get Window Handles
Switch Window   ${windowhandles}[1]
close window
Switch Window   ${windowhandles}[0]


text:
Q: Installing MYSQL Developer Tools on Win 10 32 Bit I'm trying to install the MYSQL developer tools on an 32 Bit win 10 system but i need visual studio 2015, 2017 or 2019 but I cant install them on my 32 bit system and without I cant install the tools I need.
Would be happy for some help or suggestions.
Greeting little student.


text:
Q: Getting contact Jacobian through multibody plant In using a multibody plant (MBP) for estabilishing dynamics constraints for multibody system with contact, we look at the dynamics equation
M(q) q_ddot + C(q, q_dot) = G(q) + B(q) u + J'(q) lambda
where q is the states of the system, *_dot and *_ddot denotes *'s time derivative and double derivative, respectively; M(q) is the inertial matrix, C(q, q_dot) consists of the terms for Coriolis, centripetal, and gyroscopic effect, G(q) is the gravitational force, B(q) is the actuator matrix, u is the input (torque/force), J'(q) is the contact Jacobian transposed, and lambda is the contact force in the contact frame.
is there a way to get the contact Jacobian terms J(q) from the plant or is it up for the users to implement it with the contact results?

Question Update:
I've been trying to verify the returned results from hand-derived Jacobian and there is some mis-matching that I don't understand.
First, I constructed a very simple system: a link fixed to world through a revolute joint and a sphere that can roll in the x-y plane through dummy prismatic joints. The link is named left proximal. The contact Jacobian is easy to derive by hand with contact point returned from contactResults using which, the contact dynamics is verified.
Now, here is how I find contact jacobian from drake functions:
geometryA_id = left_proximal_geometry_id
geometryB_id = object_geometry_id
signed_distance_pair = query_object.ComputeSignedDistancePairClosestPoints(geometryA_id, geometryB_id)
print(signed_distance_pair.distance)

linkA = get_name_by_geometryId(plant, geometryA_id)
bodyA = plant.GetBodyByName(linkA)
linkB = get_name_by_geometryId(plant, geometryB_id)
bodyB = plant.GetBodyByName(linkB)

frame_A_id = inspector.GetFrameId(signed_distance_pair.id_A)
frame_B_id = inspector.GetFrameId(signed_distance_pair.id_B)
frameA = plant.GetBodyFromFrameId(frame_A_id).body_frame()
frameB = plant.GetBodyFromFrameId(frame_B_id).body_frame()

frame_W = plant.world_frame()
p_GbCb = signed_distance_pair.p_BCb
p_GaCa = signed_distance_pair.p_ACa

wrt = JacobianWrtVariable.kQDot

Jv_v_BCa_W = plant.CalcJacobianTranslationalVelocity(plant_context, wrt, frameB, p_GbCb, frameA, frame_W);

# alternative, compute Jacobian matrix by individually find Jv for A and B w.r.t. world
Jva = plant.CalcJacobianTranslationalVelocity(
    plant_context,
    JacobianWrtVariable(0),
    frameA,
    p_GaCa,
    frame_W,
    frame_W
)
Jvb = plant.CalcJacobianTranslationalVelocity(
    plant_context,
    JacobianWrtVariable(0),
    frameB,
    p_GbCb,
    frame_W,
    frame_W
)
Jv_alternative = Jvb - Jva

Judging by the numerical results, Jvb is correct (mostly because it's on the object with the prismatic joints) but Jva is not matching up with what's expected.
I believe all the inputs are as described in the documentation and the printed values of p_GbCb looks reasonable (at least the the norm matches with the radius). However since the values don't check off there must be something I'm missing...

A: I think the recommended workflow is to get a QueryObject from the SceneGraph output port.  On this QueryObject you can call ComputeSignedDistancePairClosestPoints(), to find the closest points on each pair of bodies.  The distance between these two points is what we call φ(q) in the notes.  Then you can call the Jacobian methods on MultibodyPlant to take the gradients of φ with respect to q.

A: If you know where the points are, it is easy to get the Jacobian from MBP using methods like CalcJacobianTranslationalVelocity().
Likely you would have to look at the contact results to find the points; I'm not sure about that.

A: The contact Jacobian depends on where the contact point is. There are two ways to set the contact point

*

*As @RussTedrake mentioned, you can use ComputeSignedDistancePairClosestPoints to return all pairs of closest points. You can then check SignedDistancePair.distance, if the distance is no larger than 0, then you can use the witness points in the returned SignedDistancePair as the contact points (the caveat is that you need to transform the witness point in the geometry frame to the body frame using SceneGraphInspector::GetPoseInFrame(signed_distance_pair.id_A)), you could refer to this code. Notice that when q changes, the contact points in this approach would also change, and even the number of contact points could change (the point that was in contact becomes not in contact when q changes, or vice versa), hence the size of J and lambda would change. This size change could cause problem in trajectory optimization, as lambda is likely your decision variable, and you want your decision variables to have fixed size.

*If you are doing trajectory optimization, and you want to impose the constraint like "the robot heel is in contact with the ground", then I would suggest to designate the contact point to be the heel of the robot. Once you know the position of the robot heel in the foot frame (from URDF/SDF), you could compute the Jacobian using CalcJacobianTranslationalVelocity. And also impose a kinematic constraint that the heel is on the ground (you could refer to PositionConstraint on adding this kinematic constraint). By fixing the contact point in the body frame, you have a fixed size of J and lambda, which are important in optimization if lambda is your decision variable.


text:
Q: Convert Excel Formula to T-SQL I have a Excel formula I am trying to convert to SQL. The Formula is as follows
=1800*85%/450*E23

Say the value in E23 was 12 then the formula would equal 40.8
In SQL I have written this:

DECLARE @Number1 INT
DECLARE @Number2 INT
Declare @Number3 INT
Declare @Number4 FLOAT

Set @Number1 = 1800
Set @Number2 = 85
Set @Number3 = 450

SELECT @Number1 * @Number2 / @Number3 * Column1 AS FormulaResult
FROM DB;

If any one could advise how to make @Number2 = 85 into 85% instead, so I could get the same result as I do from Excel I would massively appreciate it.
Thank you

A: This is simple math. Note: to turn 85 in 85% multiply it by 0.01.
DECLARE
  @Number1 INT,
  @Number2 INT,
  @Number3 INT;
--Declare @Number4 FLOAT; -- don't know what you're doing with this

Set @Number1 = 1800
Set @Number2 = 85
Set @Number3 = 450

DECLARE @DB table (column1 int);
INSERT @DB VALUES (10),(11),(12),(15),(20);

SELECT column1, @Number1 * (@Number2*.01) / @Number3 * column1 AS FormulaResult
FROM @DB;

Results
column1     FormulaResult
----------- ---------------------------------------
10          34.000000
11          37.400000
12          40.800000
15          51.000000
20          68.000000


text:
Q: How to modifiy / edit built-in Azure DevOps widgets? I don't know how to find code of widgets provided by Microsoft in Azure DevOps so I can edit, merge and play with them.
Already checked the documentation and google.

A: I don't think they are open-source.  I couldn't find them on github, which is where they would be if they were.  That being said, there are quite a few marketplace extension that I do know are hosted on Github.  Find one that has support page linking to github that interests you.
If you haven't already, look through this documentation for adding a dashboard widget.


text:
Q: Raspberry Pi 4B - how to associate an application to a display Assume two applications running on a RPi 4B, each one using a screen (connected to the HDMI ports).
Requirements:

*

*Both applications are started at boot time.

*Each application must use a specific screen (something like a screen for engine information and the other for GPS mapping).

*The RPi is dedicated to running these applications.

How does one go about this? I found information on how to start an application during boot, but nothing about associating application X to display Y...


text:
Q: Add keyevent to switch ViewPart under IPageLayout how to assign key for switch focus on different viewpart??
example: (press "SWT.F7" to focus on viewpartA, "SWT.F8" to focus on viewpartB)
public class UserPerspective implements IPerspectiveFactory{
    ......
    ......
    public void createInitialLayout(IPageLayout layout){
        final IFolderLayout leftPanel = layout.createFolder(......);
        leftPanel.addView(viewpartA.ID);

        final IFolderLayout rightPanel = layout.createFolder(......);
        rightPanel.addView(viewpartB.ID);
    }
}

A: You can use the following key bindings. Read the documentation for the sequence carefully - it is a little tricky :-)
The value attribute below is the ID for your target view.
<extension
      point="org.eclipse.ui.bindings">
   <key
         commandId="org.eclipse.ui.views.showView"
         schemeId="org.eclipse.ui.defaultAcceleratorConfiguration"
         sequence="F6">
      <parameter
            id="org.eclipse.ui.views.showView.viewId"
            value="com.rcpcompany.so.ed.view">
      </parameter>
   </key>
   <key
         commandId="org.eclipse.ui.views.showView"
         schemeId="org.eclipse.ui.defaultAcceleratorConfiguration"
         sequence="SHIFT+F6">
      <parameter
            id="org.eclipse.ui.views.showView.viewId"
            value="com.rcpcompany.so.ed.view1">
      </parameter>
   </key>
</extension>


text:
Q: The differential of an almost everywhere constant function is almost everywhere zero? Let $f: \mathbb{R}^n \to \mathbb{R}$ be measurable and differentiable almost everywhere.
Is it true that $df=0 $ a.e on $\{f=0\}$?
If $f \in W^{1,p}$ then it's known to be true- but the proof* uses the fact that weak derivatives behave well w.r.t fundamental theorem of calculus, so I am guessing that withouth this assumption this should not hold in general.
*(It is Theorem 4.4 (iv) in "Measure theory and
fine properties of functions", revised ed)

A: Yes, it's true. In particular $df=0$ at every Lebesgue point (point of density $1$) of $\{f=0\}$, assuming the differential exists. When $f\in W^{1,p}$ the only relevant implied information is the a.e. approximate differentiability, under which assumption (instead of a.e. classical differentiability) the following should remain true with minor modifications.
Let us consider a point $x_0\in \{f=0\}$ such that $df(x_0)\neq 0$, and let us prove that the density of $\{f=0\}$ at $x_0$ is zero.
Set $df(x_0)[y]=\xi\cdot y$ with $\xi\neq 0$. By definition of differential
$$|f(x)|=|f(x)-f(x_0)|=|\xi\cdot(x-x_0)+o(|x-x_0|)|\geq |\xi\cdot (x-x_0)|-|o(|x-x_0|)|.$$
For every $\epsilon>0$ we can find a radius $r_\epsilon$ such that $o(|x-x_0|)\leq \frac\epsilon2|\xi||x-x_0|$ for $|x-x_0|<r_\epsilon$. In particular if $x\in B(x_0,r_\epsilon)$ and belongs to the cone
$$C_\epsilon:=\{x:|\xi\cdot (x-x_0)|\geq \epsilon |\xi||x-x_0|\}$$
it holds that
$$|f(x)|\geq |\xi\cdot (x-x_0)|-\frac\epsilon 2 |\xi||x-x_0|\geq \frac\epsilon2|\xi||x-x_0|>0 \quad\forall x\neq x_0.$$
Now in the limit $\epsilon\to 0$ the cone $C_\epsilon$ fills a portion of $B(x_0,r_\epsilon)$ going to $1$. In particular $f\neq 0$ in a portion of the balls $B(x_0,r_\epsilon)$ that goes to $1$. This implies that the density of $\{f=0\}$ at $x_0$ is zero, and concludes the proof since a.e. point of $\{f=0\}$ is of density $1$ by the Lebesgue differentiation theorem.
If I'm not wrong it can be proved that the set of points of $\{f=0\}$ where the differential is nonzero is $(n-1)$-rectifiable, and therefore of Hausdorff dimension $n-1$ (which is stronger than Lebesgue negligible).


text:
Q: Simple data analysis with Pandas - how to remove repetitive code Here's an example:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.dates as mdates
import matplotlib.ticker as ticker
import numpy as np

dfboth = {
        'I': [1,2,3,4,5,6],
        'S': ['X', 'Y', 'X', 'Y', 'X', 'Y'],
        'DVAR': [800, 300, 820, 330, 910, 350],
        'CVAR': [1001, 612, 990, 639, 600, 130]}

dfboth = pd.DataFrame(dfboth)
dfboth = dfboth.assign(DVARCHANGE=dfboth['DVAR'].diff(2))
dfboth = dfboth.assign(CVARCHANGE=dfboth['CVAR'].diff(2))

plt.rcParams["figure.figsize"] = (24, 9) # (w, h)

plt.subplot(2,2,1)
plt.plot('I','DVAR', data=dfboth[dfboth.S=="X"])
plt.plot('I','DVARCHANGE', data=dfboth[dfboth.S=="X"])
plt.title("X-D")
plt.legend()

plt.subplot(2,2,2)
plt.plot('I','DVAR', data=dfboth[dfboth.S=="Y"])
plt.plot('I','DVARCHANGE', data=dfboth[dfboth.S=="Y"])
plt.title("Y-D")
plt.legend()

plt.subplot(2,2,3)
plt.plot('I','CVAR', data=dfboth[dfboth.S=="X"])
plt.plot('I','CVARCHANGE', data=dfboth[dfboth.S=="X"])

plt.title("X-C")
plt.legend()

plt.subplot(2,2,4)
plt.plot('I','CVAR', data=dfboth[dfboth.S=="Y"])
plt.plot('I','CVARCHANGE', data=dfboth[dfboth.S=="Y"])
plt.title("Y-C")

plt.legend()

I have a series of data points (a time series), I=1,2,3 ... and they each pertain to a certain 'S', in this example, X and Y. For each reading, we have two variables DVAR and CVAR. I am trying to make this graph
I compare for S X and Y, DVAR and it's change from the previous reading, and CVAR and it's change in previous reading.
You can also see annoying repetition. But I actually have 12 S's not just X and Y. And I have more variables.
I believe there's a much better way of doing this than I have written using either stacked indexes or some kind of pivot table. But I've not been able to figure it out!

A: You can use a for-loop:
plot_titles = ["X-D", "Y-D", "X-C", "Y-C"]
y1 = ['DVAR', 'DVAR', 'CVAR', 'CVAR']
y2 = [y + 'CHANGE' for y in y1]
data1 = ["X", "Y", "X", "Y"]

for i in range(4):
    plt.subplot(2, 2, i+1)
    plt.plot('I', y1[i], data = dfboth[dfboth.S == data1[i]])
    plt.plot('I', y2[i], data = dfboth[dfboth.S == data1[i]])
    plt.title(plot_titles[i])
    plt.legend()


text:
Q: How to use React ref in MobX? My code like this
render() {
    return (
      <div>
        <Layout ref={element => this.ipDetailDOM = element} id="ip-detail">
            ...
        </layout>
      </div>
    )
}

But this.ipDetailDOM return an Adapter Object.
Adapter {props: {…}, context: {…}, refs: {…}, updater: {…}, _reactInternalFiber: FiberNode, …}

I do not know to use it?

A: You can use ReactDOM.findDOMNode(this.ipDetailDOM) to access the underlying DOM node.
Here is working demo: https://codesandbox.io/s/n453w61j5p


text:
Q: Convert list of fractions to numerical array I have data in the form of a list that looks like this:
'2/7,5/7,0,0,0,0,0,0,1,8131435000/20657804439,12526369439/20657804439,46/51,5/51,47240285000/61973413317,14733128317/61973413317\n',
'2/7,5/7,0,0,0,0,0,0,1,1304992/3861431,2556439/3861431,46/51,5/51,8805032/11584293,2779261/11584293\n',
'2/7,5/7,0,0,0,0,0,0,1,251888/1212389,960501/1212389,46/51,5/51,3238088/3637167,399079/3637167\n'

How do I convert this to a matrix of numbers? Preferably using decimals instead of fractions.

A: Here is the code:
lines = [
    '2/7,5/7,0,0,0,0,0,0,1,8131435000/20657804439,12526369439/20657804439,46/51,5/51,47240285000/61973413317,14733128317/61973413317\n',
    '2/7,5/7,0,0,0,0,0,0,1,1304992/3861431,2556439/3861431,46/51,5/51,8805032/11584293,2779261/11584293\n',
    '2/7,5/7,0,0,0,0,0,0,1,251888/1212389,960501/1212389,46/51,5/51,3238088/3637167,399079/3637167\n'
]

matrix = [[eval(x) for x in line.strip().split(',')]
                   for line in lines]


text:
Q: A different approach to prove Distributive Properties Is there any wrong with proving it like this (instead of proving it with logic arrows).
Q: Prove that $(A \cup (B \cap C)=(A \cup B) \cap (A \cup C)$.
Ans:
If $\ x \in A \cup (B \cap C)$ is true. Then there are 3 cases:
\begin{eqnarray*}
&x \in A \\
&x \in B\ \text{and}\ x \in C \\
&x \in A\ \text{and}\ x \in B\ \text{and}\ x \in C.
\end{eqnarray*}
Does not contradict $x \in A \cup B) \cap (A \cup C)$.
$$\therefore A \cup (B \cap C) \subset (A \cup B) \cap (A \cup C).$$
Then do the same thing with $(A \cup B) \cap (A \cup C)$.

A: I wouldn't accept this answer, because it avoids answering the question! For example, why is it that there are those 3 cases as you claim under the first assumption? And then after that why do none of them contradict $x \in ( A \cup B ) \cap ( A \cup C )$? The gap in the explanation is precisely the logic that you want to avoid, which is impossible because set union and intersection are defined logically.
Your attempt at the other question is reasonable, although not quite precise. (It is actually incorrect to use "$\Rightarrow$" because it does not mean what you think it means.) Here is a precise version:
Given $x \in A \cup ( B \cap C )$:
  $x \in A$ or $x \in B \cap C$.
  $x \in A$ or ( $x \in B$ and $x \in C$ ).
  $( x \in A$ or $x \in B$ ) and ( $x \in A$ or $x \in C$ ). [This is by boolean algebra.]
  $x \in A \cup B$ and $x \in A \cup C$.
  $x \in ( A \cup B ) \cap ( A \cup C )$.
Given $x \in ( A \cup B ) \cap ( A \cup C )$:
  [Exactly the same as above but in reverse order. Check that each step actually works!]
Whenever you have two such expressions involving set operations that you want to prove equal, you can expect that this phenomenon would happen. Another way that is often shorter is to literally expand the definition:
$A \cup ( B \cap C )$
$ = \{ x : x \in A \cup ( B \cap C ) \}$
$ = \{ x : x \in A \lor x \in ( B \cap C ) \}$
$ = \{ x : x \in A \lor ( x \in B \land x \in C ) \}$
$ = \{ x : ( x \in A \lor x \in B ) \land ( x \in A \lor x \in C ) \}$
$ = \{ x : x \in A \cup B \land x \in A \cup C \}$
$ = \{ x : x \in ( A \cup B ) \cap ( A \cup C ) \}$
$ = ( A \cup B ) \cap ( A \cup C )$.


text:
Q: How to parse a string of fullwidth integer characters to an integer in ruby How can I parse a string of fullwidth unicode integer characters to an integer in ruby?
Attempting the obvious results in;
irb(main):011:0> a = "\uff11"
=> "1"
irb(main):012:0> Integer(a)
ArgumentError: invalid value for Integer: "\xEF\xBC\x91"
      from (irb):12:in `Integer'
      from (irb):12
      from /export/home/henry/apps/bin/irb:12:in `<main>'
irb(main):013:0> a.to_i
=> 0

The equivalent in python gives;
>>> a = u"\uff11"
>>> print a
1
>>> int(a)
1

A: Ruby 1.9's numeric parsing is thinking in ascii only. I don't think there's any convenient elegant parsing methods that properly handle fullwidth unicode numeric codepoints.
A quick filthy hack function:
def parse_utf(utf_integer_string)
  ascii_numeric_chars = "0123456789"
  utf_numeric_chars = "\uff10\uff11\uff12\uff13\uff14\uff15\uff16\uff17\uff18\uff19"
  utf_integer_string.tr(utf_numeric_chars, ascii_numeric_chars).to_i
end

Pass in a string of fullwidth numeric characters and get out an integer.

A: Convert 'compatibility' characters like the fullwidths to their normalized versions (plain ASCII numbers in this case) before parsing as integer. For example, using Unicode::normalize_KC or UnicodeUtils::nfkc.


text:
Q: using mat-paginator with mat-table using observable array as the datasource I am using an observable array as the datasource. This works fine except that i am unable to figure out how to use paginator now. below is the html and ts
html
 <table mat-table #TABLE [dataSource]="cards" class="mat-elevation-z8">
                <!-- Email Column -->
             <ng-container matColumnDef="date">
                <th mat-header-cell *matHeaderCellDef  class="tbl-th"> Date </th>
                <td mat-cell *matCellDef="let element"> {{core.pretifyDate(element.date)}} </td>
              </ng-container>

            <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
            <tr mat-row *matRowDef="let row; columns: displayedColumns;">
            </tr>
          </table>
          <mat-paginator [pageSizeOptions]="[5, 10, 20, 50, 100]" [pageSize]="pageSize" showFirstLastButtons></mat-paginator>

.ts
export class CardQueueComponent implements OnInit {

  @ViewChild('TABLE', {static: false}) table: MatTable<any>;
  @ViewChild(MatPaginator, {static: true}) paginator: MatPaginator;

  displayedColumns: string[] = [ 'image', 'customer', 'email',  'date', 'process' ];
  cards: Observable<Card[]>
  pageSize = 5

  constructor(public dataSvc: SBDataService,
              public core:CoreService,
              private changeDetectorRefs: ChangeDetectorRef,
              ) { }

    async ngOnInit() {

      this.cards = this.dataSvc.fetchCards().pipe(
        map((cards: any) => cards.map(cardObj => {
          var c = new Card(cardObj.key, cardObj._frontImageUrl, cardObj._date, cardObj._rawData)

        return c
      }))
    );

    this.changeDetectorRefs.detectChanges();

    //this.dataSource.paginator = this.paginator;

  }

}

so the last commented line on paginator is something i need to figure out with after i directly associated cards observavble. Please advise

A: You just need to get a reference to your tables' DataSource and set your paginator in it. Eg:
dataSource = new MatTableDataSource()

async ngOnInit() {

  this.dataSvc.fetchCards().pipe(
    map((cards: any) => cards.map(cardObj => {
      var c = new Card(cardObj.key, cardObj._frontImageUrl, cardObj._date, cardObj._rawData)
  })).subscribe(cards => this.dataSource.data = cards);

);

ngAfterViewInit() {
  this.dataSource.paginator = this.paginator;
}

  <mat-table [dataSource]="dataSource">


text:
Q: Is every unit vector in $\mathbb{Q}^n$ the first column of a rational orthogonal matrix? Equivalently, does every unit vector in $\mathbb{Q}^n$ belong to some orthonormal basis for $\mathbb{Q}^n$?
This is clearly true for $\mathbb{Q}^2$, and for $\mathbb{Q}^3$ it seems to be true for every vector I check.  For example,

*

*$\displaystyle\frac{1}{3}\!\begin{bmatrix}1 \\ 2 \\ 2\end{bmatrix}$ is the first column of $\displaystyle\frac{1}{3}\!\begin{bmatrix}1 & 2 & 2 \\ 2 & 1 & -2 \\ 2 & -2 & 1\end{bmatrix}$

*$\displaystyle\frac{1}{7}\!\begin{bmatrix}2 \\ 3 \\ 6\end{bmatrix}$ is the first column of $\displaystyle\frac{1}{7}\!\begin{bmatrix}2 & 3 & 6 \\ 3 & -6 & 2 \\ 6 & 2 & -3\end{bmatrix}$

*$\displaystyle\frac{1}{9}\!\begin{bmatrix}7 \\ 4 \\ 4\end{bmatrix}$ is the first column of $\displaystyle\frac{1}{9}\!\begin{bmatrix}7 & 4 & 4 \\ 4 & 1 & -8 \\ 4 & -8 & 1\end{bmatrix}$
Here's an example in $\mathbb{Q}^4$:

*

*$\displaystyle\frac{1}{2}\!\begin{bmatrix}1 \\ 1 \\ 1 \\ 1\end{bmatrix}$ is the first column of $\displaystyle\frac{1}{2}\!\begin{bmatrix}1 & 1 & 1 & 1 \\ 1 & 1 & -1 & -1 \\ 1 & -1 & 1 & -1 \\ 1 & -1 & -1 & 1\end{bmatrix}$

Actually, all of the matrices in these examples are symmetric.  This wouldn't be true if you permuted the entries of the vectors, but you could manage to make them some column of a symmetric orthogonal matrix.  So we have the additional question:

Is every unit vector in $\mathbb{Q}^n$ a column of some rational symmetric orthogonal matrix?

A: Answer is yes.
In particular, if the first coordinate of the vector is not $-1$, the following matrix works:

This matrix represents the geometric reflection which sends your chosen vector to the standard unit vector.
If you want more information, you can look at Extending Orthonormal rational vectors.

Note: This result is generalized by Witt's Theorem.


text:
Q: Properties of determinants Prove using properties of determinants :
\begin{equation*}
\left|\begin{matrix}
b^2 + c^2 & a^2 & a^2\\
b^2 & c^2 + a^2 & b^2\\
c^2 & c^2 & a^2 + b^2
\end{matrix}\right| = 4a^2b^2c^2
\end{equation*}

A: To calculate a determinant of a $3\times 3$ matrix, you need to choose a reference row/column first. Let's say we choose to calculate the determinant along the first row.
Then you need to cross out the first row and first column and calculate the determinant of the remaining $2\times 2$ matrix, which is $(c^2+a^2)\times(a^2+b^2)-b^2\times c^2$. And then you multiply this with the chosen element, which is the intersecting element of first row and first column. In this case, $b^2+c^2$. And then you multiply the whole chunk by either $1$ or $-1$.
The way to choose either $1$ or $-1$ would be as follow:
\begin{bmatrix}
    1       & -1&1\\
    -1&1&-1 \\
    1&-1&1
\end{bmatrix}
If you follow this to calculate along the first row, and add them up together, you would have
$(b^2+c^2)\times[(c^2+a^2)\times(a^2+b^2)-b^2\times c^2]-a^2\times[b^2(a^2+b^2)-b^2\times c^2]+a^2\times [b^2\times c^2-c^2(c^2+a^2)]$
And if you clean this up, you would get $4a^2b^2c^2$


text:
Q: Using enumitem on a cheetsheet seems to cause -{}- to render as en-dash I'm using this cheatsheet class to create a git cheatsheet.
I have a couple commands the are too long for a single line, so I added the enumitem package to use the [style=unboxed] to force lines to wrap. They now wrap, but -{}- now reduces to an en-dash instead of --
Reproducable by adding cheatsheet.cls
to a ShareLatex project with the following document:
\documentclass[columns=3]{cheatsheet}
\usepackage[utf8]{inputenc}
\usepackage{enumitem}

\title{Test En-dash}
\author{ }
\date{March 2018}

\begin{document}

\maketitle

\newcommand{\gitcmd}[2]{\item[\small\texttt{\$ #1}] \hfill \\ #2}

\section{Configuration}
\begin{description}[style=unboxed]
\gitcmd{git config -{}-global user.name "<name>"}{Sets the name to be attached to your commits }
\gitcmd{git config -{}-global user.email "<email address>"}{Set to your email}
\end{description}

\section{Commit History}
\begin{description}%[style=unboxed]
\gitcmd{git log}{Display the version history of the current branch}
\gitcmd{git log -{}-oneline}{Display version history oneline summaries}
\end{description}

\end{document}

Toggling the [style=unboxed] comment on the two descriptions changes how -{}- is rendered. Adding a space between the dash and word (-{}- global) also works, but isn't a valid git command.
This appears to be a problem with cheetsheet.cls, as it does not occur if using the parent article class.

A: When the label is unboxed, TeX no longer sees {}. Use
-{\kern0pt}-

Instead.

A: First of all, thank you for using my cheatsheet-class,
It seems to be an issue with libertineand multicols, and the style=unboxed parameter (Aside: What does this do?)
If you do not want to remove the unboxed, a workaround would be to change the Typewriter-Font to Computermodern, which does not seem to show this behaviour:

\renewcommand{\ttdefault}{cmtt}


text:
Q: SQL query to get all records with sum less than 10000 I have data in a table which looks like the below data set.
I want to get a group of those items whose price sum is less than 10000.
CREATE TABLE Table1
(slno int, item varchar(10), price int);

INSERT INTO Table1
(slno, item, price)
VALUES
(1, 'item1', 1000),
(2, 'item2', 2000),
(3, 'item3', 3000),
(4, 'item4', 4000),
(5, 'item5', 5000),
(6, 'item6', 6000),
(7, 'item7', 10000),
(8, 'item8', 2000),
(9, 'item9', 8000),
(10, 'item10', 2500),
(11, 'item11', 9000),
(12, 'item12', 1000),
(13, 'item13', 2500),
(14, 'item14', 2500),
(15, 'item15', 2500);

My sql query looks like this:
SELECT slno, item,price
FROM
 (
 SELECT slno, item,price
 (
SELECT SUM(price)
  FROM Table1
 WHERE slno<= t.slno
 ) total
  FROM Table1 t
 ) q
   WHERE total <= 1000
   ORDER BY item

It's not giving the expected result though, it's giving only one set of records:
 (1, 'item1', 1000),
 (2, 'item2', 2000),
 (3, 'item3', 3000),
 (4, 'item4', 4000)

whereas I need it to give me something like this:
 1ST SET

 (1, 'item1', 1000),
 (2, 'item2', 2000),
 (3, 'item3', 3000),
 (4, 'item4', 4000)

 2ND SET
 (7, 'item7', 10000),

@GordonLinoff

A: This type of operation requires a recursive CTE.  In this case, you can assign a group to each row using such logic.  The following assumes that slno has no gaps as in your example data:
with cte as (
      select slno, item, price, 1 as grp, price as running_price
      from table1
      where slno = 1
      union all
      select t1.slno, t1.item, t1.price,
             (case when t1.price + cte.running_price > 10000 then grp + 1 else grp end),
             (case when t1.price + cte.running_price > 10000 then t1.price else cte.running_price + t1.price end)
      from cte join
           table1 t1
           on t1.slno = cte.slno + 1
     )
select *
from cte
order by slno;

Here is a db<>fiddle.


text:
Q: How shall I integrate this multivariable function when one of the variable in the function is in the form of limits How shall I integrate this multivariable function when one of the variable in the function is in the form of limits:
$$\int \left[     f(x,y)      \right]^{y=b}_{y=0} \, dx$$
Can I proceed by ignoring the limits:
$$\int f(x,y) \, dx$$
If yes, how can it be justified?

A: It seems that it simply means:
$$
\int f(x,b)-f(x,0) dx=\int f(x,b)dx - \int f(x,0)dx
$$


text:
Q: STKeychain fails to retrieve password after AppStore Update Scenario:

*

*Our app stores the backend token in the device's keychain (STKeychain, ex SFHFKeychainUtils).

*Background fetch is disabled.

*An upgrade was recently released.

We're getting reports of users having to re-sign in. This seems to be an issue during STKeychain token-retrieval (stored password is being retrieved as nil).
Is it there any known bugs in STKeychain (or iOS keychain itself) that would cause this kind of issue?
Thanks in advance, any leads will be very welcome!

A: I'm gonna go ahead and answer my own question, just in case someone else stumbles upon the same problem.
After a close look at the two xcodearchive files of the submitted app, i've noticed that the embedded provisioning profiles are not the same.
This was a result of the 'Automatic Profile Selector' picking up another profile (since the original one was expired).
I managed to reproduce this glitch, y creating two AdHoc builds, both with the exact same AppId's, yet, with different provisioning profiles.
Thanks!
Related issue here:
Does renewing a provisioning profile affect keychain access when I submit an app update to the AppStore?


text:
Q: Verificar se arquivo existe usando Javascript ou jQuery Como posso verificar usando Javascript ou jQuery que um arquivo existe ?
OBS: Abri a pergunta e já respondi.

A: Abaixo estão os meios que eu encontrei.
Javascript
function verificaUrl(url) {
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    return http.status != 404;
}

jQuery
$.ajax({
    url:'http://www.exemplo.com.br/arquivo.txt',
    type:'HEAD',
    success: function() {
        //arquivo existe
    }
    error: function() {
        //arquivo não existe
    },
 });


text:
Q: Subqueries vs MAX aggregate function peformance MAX aggregation vs Subqueries:
This seems to be a reoccurring issue in the queries that I have been writing recently, and I would like to discover which query style is:

*

*Most efficient (time and resources)

*More reliable and easier to maintain

*Makes the most sense to use

More Information:
The queries I am writing tend to always pull from one base table and will also join to several other tables; however, the joined tables often have a vertical orientation where the foreign key is referenced several times with a unique "descriptor" and "response." (See: Table #MovieDescriptions for an example.)

Please use the following SQL queries as a test scenario:

 -- Drop temp tables if exist

IF OBJECT_ID('TempDB..#Movies','U') IS NOT NULL
     DROP TABLE #Movies

IF OBJECT_ID('TempDB..#MovieDescriptions','U') IS NOT NULL
     DROP TABLE #MovieDescriptions

-- Creating temp tables

CREATE TABLE #Movies
(
     MovieID int IDENTITY(1,1),
     MovieName varchar (100),
     ReleaseYear datetime,
     Director varchar (100)
)

CREATE TABLE #MovieDescriptions
(
     MovieDescID int IDENTITY(1,1),
     FK_MovieID varchar(100),
     DescriptionType varchar(100),
     DescriptionResponse varchar(100)
)

-- Inserting test data

INSERT INTO #Movies (MovieName, ReleaseYear, Director) VALUES ('Gone With the Wind', CONVERT(datetime,'12/15/1939'), 'Victor Fleming')
INSERT INTO #Movies (MovieName, ReleaseYear, Director) VALUES ('2001: A Space Odyssey', CONVERT(datetime,'01/01/1968'), 'Stanley Kubrick')

INSERT INTO #MovieDescriptions (FK_MovieID, DescriptionType, DescriptionResponse) VALUES ('1', 'Written By', 'Sideny Howard')
INSERT INTO #MovieDescriptions (FK_MovieID, DescriptionType, DescriptionResponse) VALUES ('1', 'Genre', 'Drama')
INSERT INTO #MovieDescriptions (FK_MovieID, DescriptionType, DescriptionResponse) VALUES ('1', 'Rating', 'G')

INSERT INTO #MovieDescriptions (FK_MovieID, DescriptionType, DescriptionResponse) VALUES ('2', 'Written By', 'Standley Kubrick')
INSERT INTO #MovieDescriptions (FK_MovieID, DescriptionType, DescriptionResponse) VALUES ('2', 'Genre', 'Sci-Fi')
INSERT INTO #MovieDescriptions (FK_MovieID, DescriptionType, DescriptionResponse) VALUES ('2', 'Rating', 'G')

-- Using subqueries

SELECT
     MovieName,
     ReleaseYear,
     (SELECT DescriptionResponse
      FROM #MovieDescriptions
      WHERE FK_MovieID = #Movies.MovieID AND DescriptionType = 'Genre'
      ) AS Genre,
     (SELECT DescriptionResponse
      FROM #MovieDescriptions
      WHERE FK_MovieID = #Movies.MovieID AND DescriptionType = 'Rating'
      ) AS Rating
FROM #Movies

-- Using aggregate functions

SELECT
     MovieName,
     ReleaseYear,
     MAX(CASE WHEN md.DescriptionType = 'Genre' THEN DescriptionResponse END) AS Genre,
     MAX(CASE WHEN md.DescriptionType = 'Rating' THEN DescriptionResponse END) AS Rating
FROM #Movies m
     INNER JOIN #MovieDescriptions md
     ON m.MovieID = md.FK_MovieID
GROUP BY MovieName, ReleaseYear

In addition, if there is a better way of selecting this data, that would be helpful as well.

A: Assuming a more normal setup where your tables are properly indexed, and where the foreign key relationship columns have matching data types (hint hint: they don't currently match, int vs. varchar), then you should always find that the your second query (joins + aggregation) outperforms the first (subqueries in your select clause).  It may not be noticeable with small amounts of data. But the more your base table has data (#Movies), the more the difference will be obvious.
The reason is simple.  In your first query:
SELECT
     MovieName,
     ReleaseYear,
     (SELECT DescriptionResponse
      FROM #MovieDescriptions
      WHERE FK_MovieID = #Movies.MovieID AND DescriptionType = 'Genre'
      ) AS Genre,
     (SELECT DescriptionResponse
      FROM #MovieDescriptions
      WHERE FK_MovieID = #Movies.MovieID AND DescriptionType = 'Rating'
      ) AS Rating
FROM #Movies

If #Movies contains 1000 rows, then SQL Server really has no choice but to perform one full table scan on #Movies, and, for each of the 1000 rows, it needs to perform 2 additional queries on #MovieDescriptions.  In reality, you are executing a total of 2001 queries.  Because your subqueries are in the SELECT clause, SQL Server has no choice but to execute the query in this way.
On the other hand, your 2nd query:
SELECT
     MovieName,
     ReleaseYear,
     MAX(CASE WHEN md.DescriptionType = 'Genre' THEN DescriptionResponse END) AS Genre,
     MAX(CASE WHEN md.DescriptionType = 'Rating' THEN DescriptionResponse END) AS Rating
FROM #Movies m
     INNER JOIN #MovieDescriptions md
     ON m.MovieID = md.FK_MovieID
GROUP BY MovieName, ReleaseYear

Because you are using a join here, this gives SQL Server the flexibility of figuring out the most efficient way of joining the data from #Movies and #MovieDescriptions. Depending on your indexes, filters, number of rows, etc. it may decide to do a hash join, maybe it will use nested loops, etc.  The point is that SQL Server has more options, and can now figure out the best way of reducing the number data block reads from your 2 tables (and indexes).
EDIT: I should also add that the above assumes that you are fetching every row returned from the query.  If the query returns thousands of rows, but you only fetch the first 10 rows, then, in certain cases, the first query could actually outperform the second. That's because the subqueries will only execute on the rows as they get selected or fetched. If you never fetch some of the rows, you may never incur the cost of executing the subqueries on those unfetched rows.  Something to consider.

A: I like this version of your query  better..
SELECT
     MovieName,
     ReleaseYear,
     MAX(CASE WHEN md.DescriptionType = 'Genre' THEN DescriptionResponse END) AS Genre,
     MAX(CASE WHEN md.DescriptionType = 'Rating' THEN DescriptionResponse END) AS Rating
 FROM #Movies m
     INNER JOIN #MovieDescriptions md
     ON m.MovieID = md.FK_MovieID
GROUP BY MovieName, ReleaseYear

But This involves a sort on movies tables and this sort cost is 63% of total cost and you are restricted in getting all columns..

I rewrote this version using Apply which doesn't have sort and you are not restricted in getting all columns..
select
* from
#movies m
cross apply
(
select
max(case when descriptiontype='genre' then descriptionresponse  end) as genre,
max(case when descriptiontype='rating' then descriptionresponse  end) as rating
from
#MovieDescriptions md
where  md.fk_movieid=m.movieid)b

execution plan of above version..

Now Both queries doesn't have indexes..
What are the indexes that are needed for First query to work and scale..
An additional index on MovieName, ReleaseYear to avoid sort and to tell SQLServer these are unique..since you already had (assuming) primary key on Movieid ,having one more index to avoid sort is ,some thing which i don't prefer and if you need more columns from first query,you will have to add it again to index..
For The second query to scale better,
you will need an index on FK_movieid which i assume you have it already..
PS:
I may have missed bunch of things,But i would go with my query ..

A: There are many ways to get results from multiple tables like nested/sub queries, joins, aggrgate functions etc.
But Joins are way more efficient than subqueries when you need results from n number of tables.
It might not be observable for few tables. But when you work with 5 or 6 tables simultaneously, you will observer how joins perform.


text:
Q: loop in ruby not working, pulling exif meta from jpeg I can't seem to get this loop working. total noob to ruby.
working_dir.each do |x|
        puts x

        puts EXIFR::JPEG.new('/home/alan/workspace/ruby/latlong/#{x}').gps.latitude
end

I get
No such file or directory @ rb_sysopen - /home/alan/workspace/ruby/latlong/#{x} (Errno::ENOENT)

I am hard coding the path. please help. I am trying to pull exif meta data out of a directory of jpegs.

A: How about something like this:
folder_which_contains_jpegs = 'workspace/ruby/latlong'
folder_path = File.join(Dir.pwd, folder_which_contains_jpegs) # assume your current dir is `/home/alan`
unless File.directory?(folder_path)
  fail "Error: the directory #{folder_path} doesn't exist"
end

def jpeg_file_list(path, &block)
  Dir.glob(path + '/**/*.jpeg').each(&block)
end

jpeg_file_list do |image_path|
  puts image_path
  puts EXIFR::JPEG.new.image_path.gps.latitude
end

will something like this would work?

A: As mentioned in the comment, you are hitting the error due to lack of string interpolation in single quoted strings. Try switching the single quotes to double:
working_dir.each do |x|
  puts EXIFR::JPEG.new("/home/alan/workspace/ruby/latlong/#{x}").gps.latitude
end

Note:

*

*Though this is posted to pin point the error; follow @CuriousMind's answer, it might have better implementation that what you are trying to do.