text:
Q: How can I restart this game using the button at the top? I'm trying to make a simple snake game and so far most of it works, except restarting the game after the user has failed. I've added a button to the top and I'm hoping that a user can click the button to restart the game.
Here is the HTML

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

<input type="button" id="restart" value="restart" style="font: normal 30px
monospace; color: white; background-color: blue;">Restart</input>

Score:

the CSS
*{
padding: 0;
margin: 0;
}

body{
  background-color: black;
}
td{
width: 20px;
 height: 20px;

}

.blank{
 background-color: blank;
}

.snake{
background-color: white;
border-radius: 50%;
}

.wall{
background-color: #cf1020;
}

.fruit{
background-color: gold;
border-radius: 50%;
}

The javaScript
//settings
var snakeX = 2;
var snakeY = 2;
var height = 28;
var width = 50;
var interval = 100;
var increment = 1;

//game variables
var length = 0;
var tailX = [snakeX];
var tailY = [snakeY];
var fX;
var fY;
var running = false;
var gameOver = false;
var direction = -1; // up = 0, down = -1, left = 1, right = 2
var int;
var score = 0;
//temporary direction (this fixes users pressing keys too quickly and
turning into themselves)
var tempdir = direction;

/**
* entry point of the game
*/
function run(){
init();
int = setInterval(gameLoop, interval);
}

function init(){
createMap();
createSnake();
createFruit();
}

/**
* Generates the map for the snake
*/
function createMap(){
document.write("
");

for( var y = 0; y < height; y++){
    document.write("
");
    for( var x = 0; x < width; x++){
        if(x == 0 || x == width -1 || y == 0 || y == height -1){
            document.write("	");
        }else{
            document.write("
	");
        }
    }
    document.write("
");
}

document.write("
");

}

function createSnake(){
set(snakeX, snakeY, "snake");
}

function get(x,y){
return document.getElementById(x+"-"+y);
}

function set(x,y,value){
if(x != null && y != null)
    get(x,y).setAttribute("class", value);
}

function rand(min,max){
return Math.floor(Math.random() * (max - min) + min);
}

function getType(x,y){
return get(x,y).getAttribute("class");
}

function createFruit(){
var found = false;
while(!found && (length < (width-2)*(height-2)+1)){
    var fruitX = rand(1,width-1);
    var fruitY = rand(1,height-1);
    if(getType(fruitX, fruitY) == "blank")
        found = true;
}
set(fruitX, fruitY, "fruit");
fX = fruitX;
fY = fruitY;
}

/**
 * NOTE: notice use of new variable tempdir
 */
window.addEventListener("keypress", function key(event){
//if key is W set direction up
var key = event.keyCode;
if(direction != -1 && (key == 119 || key == 87))
    tempdir = 0;
//if key is S set direction down
else if(direction != 0 && (key == 115 || key == 83))
    tempdir = -1;
//if key is A set direction left
else if(direction != 2 && (key == 97 || key == 65))
    tempdir = 1;
//if key is D set direction right
else if(direction != 1 && (key == 100 || key == 68))
    tempdir = 2;
if(!running)
    running = true;
else if(key == 32)
    running = false;
});

function gameLoop(){
if(running && !gameOver){
    update();
}else if(gameOver){
    clearInterval(int);
}
}

/**
 * NOTE: notice use of new variable tempdir
 */
function update(){
direction = tempdir;
//prevents fruit from not showing up
set(fX, fY, "fruit");
//update the tail
updateTail();
//sets the last segment of the tail to blank  before moving the snake
set(tailX[length], tailY[length], "blank");
//updates the position of the snake according to the direction
if(direction == 0)
    snakeY--;
else if(direction == -1)
    snakeY++;
else if(direction == 1)
    snakeX--;
else if(direction == 2)
    snakeX++;
//draws the head of the snake on the tail
set(snakeX, snakeY, "snake");
//checks for collisions with self
for(var i = tailX.length-1; i >=0; i--){
    if(snakeX == tailX[i] && snakeY == tailY[i]){
        gameOver = true;
        break;
    }
}
//checks for collision with wall
if(snakeX == 0 || snakeX == width-1 || snakeY == 0 || snakeY == height-1)
    gameOver = true;
//checks for collisions with fruit
else if(snakeX == fX && snakeY == fY){
    //adds 1 to the score
    score+=1;
    //creates new fruit, which automatically replaces the old one
    createFruit();
    //adds the set increment to the length of the snake making it longer
    length+=increment;
}
//set
document.getElementById("score").innerHTML = "Score: "+ score;
}

function updateTail(){
for(var i = length; i > 0; i--){
    tailX[i] = tailX[i-1];
    tailY[i] = tailY[i-1];
}
tailX[0] = snakeX;
tailY[0] = snakeY;
}

run();

The Codepen
https://codepen.io/McComb/pen/EoYVRY

A: Not sure what requirements you have for this project, but i added jQuery to ease my work in it.
i added a new div in the body

i changed your createMap method with this :
/**
 * Generates the map for the snake
 */
function createMap(){

    var canvas;

    canvas = '
';
    for( var y = 0; y < height; y++){
        canvas += "
";
        for( var x = 0; x < width; x++){
            if(x == 0 || x == width -1 || y == 0 || y == height -1){
                canvas +=  "	";
            }else{
                canvas += "	";
            }
        }
        canvas += "
" ;
    }

    $('#canvas').html(canvas);

}

and added a reset method
function reset()
{

    //settings
     snakeX = 2;
     snakeY = 2;
     height = 28;
     width = 50;
     interval = 100;
     increment = 1;

    //game variables
     length = 0;
     tailX = [snakeX];
     tailY = [snakeY];

     running = false;
     gameOver = false;
     direction = -1; // up = 0, down = -1, left = 1, right = 2

     score = 0;
    //temporary direction (this fixes users pressing keys too quickly and turning into themselves)
     tempdir = direction;

    clearInterval(int);
    run();

    // reset score
    $('#score').text('Score: '+score);

}

here is the project with the changes :
https://codepen.io/anon/pen/vpBKyL


text:
Q: Specify config file in nuxt 3 I have a Nuxt 3 application (3.0.0-rc.13) generating a static website, and have to deploy to two locations:

*

*Firebase hosting

*Amazon S3 bucket

Hosting on Firebase needs a baseUrl of /, and Amazon needs a different baseUrl (/2223/). This can be configured in nuxt config, however I cannot find an cli option to specify which config file to use.
I have tried these, but they just pick the default nuxt.config.ts.
nuxt generate -c nuxt.config.amazon.ts
nuxt generate --config-file nuxt.config.amazon.ts

I found this issue that added support to it for Nuxt 2, but I cannot find anything about it for Nuxt 3. Am I missing something or is it just not supported at all?

A: Thanks for the solution @kissu
If anyone faces the same problem, here is how I implemented it:
package.json scripts:
"generate": "cross-env DEPLOY_TARGET=default nuxt generate",
"generate:amazon": "cross-env DEPLOY_TARGET=amazon nuxt generate",

nuxt.config.ts
const getBaseUrl = () => {
  const environment = process.env.DEPLOY_TARGET;

  switch (environment) {
    case "amazon":
      return "/2223/";
    default:
      return "/";
  }
};

export default defineNuxtConfig({
  app: {
    baseURL: getBaseUrl(),
  },
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: DocuSign send notification to listener web application on envelop completion I gone through link https://support.docusign.com/en/guides/ndse-admin-guide-connect. As per document send trigger event and post inbound XML data to our web application. I have created MVC application and expose method and configure in connect. So my question is.. How get this xml data?
Do I get xml from HttpContext.Request.Form[0]?
Or there some other object I will get.

A: Here is some sample C# code, yes, you use the HttpContext.Request object
        using (Stream stream = Request.InputStream)
        {
            int streamLen = Convert.ToInt32(Request.InputStream.Length);
            byte[] streamArray = new byte[streamLen];
            // Read stream into byte array.
            int streamRead = stream.Read(streamArr, 0, streamLen);
            requestContents = Encoding.UTF8.GetString(streamArrary);
            var serializer = new XmlSerializer(typeof(EnvelopeInformation));
            stream.Position = 0;
            var xmlTextReader = new TextReader(stream);
            envelopeInformation = (EnvelopeInformation)serializer.Deserialize(xmlTextReader);
        }

A: Thanks Inbar. Below is working for me
using (Stream stream = Request.InputStream)
{
int streamLen = Convert.ToInt32(Request.InputStream.Length);
byte[] streamArray = new byte[streamLen];
// Read stream into byte array.
int streamRead = stream.Read(streamArray, 0, streamLen);
string requestContents = Encoding.UTF8.GetString(streamArray);

System.IO.File.WriteAllText(ConfigurationHelper.FileSystem +
@"\ErrorLog\docusignLog_" +
System.DateTime.Now.ToString("ddMMyyyyHHmmss") + ".txt",
requestContents);
}


text:
Q: The subjunctive mood can be used freely for any hypothetical situation or is limited to some verbs and phrases? Is it correct to use the subjunctive mood like this: "The description would be the one the user assign".
I ask because it is said that the subjunctive mood is mostly used with certain phrases or verbs.  For example it is used with "wish" but not with "hope" (reference: English club).
So I would like to know if for example the sentence "The description would be the one the user assign" would sound weird or if it would be quickly understood without doubts.

A: No, you can't say "The description would be the one the user assign".
This is ungrammatical in modern English.
It is better to err on the side of the indicative (the non-subjunctive form) if unsure. The subjunctive is used rather less than its equivalent in some other languages.
In your phrase, you could use "assigned", but "assigns" would also work.


text:
Q: What is the naming convention or coding standard for categories in objective-c? I saw an example in The iPhone Developer's Cookbook that extends the UIDevice class using categories.
@interface UIDevice (Reachability)
   // some methods
@end

Typically classes are nouns and methods are verbs. From my point of view categories are similar to subclasses, so I would name the category a noun such as NetworkedUIDevice. How should the name of the category be determined?

A: I don't think a strict naming convention is established. Personally, I would go with something like @interface UIDevice (ReachabilityAdditions).
More importantly, you should add a custom prefix to your category methods to avoid namespace conflicts. And this prefix should probably be included in the category name as well.


text:
Q: Rails 4 - Search box that searches all keywords I followed a tutorial on setting up a search box and got it to work on exact phrase searches. I want to make it search for results that have all keywords being searched for.
For example, a search for "Red Necklace" should return a product that is called "Red Chain Necklace" but should not return "Red Earrings".
I've looked at couple railscasts on gems like searchlogic and ransack but they seem like too much for what I'm trying to do.
#model code
def self.search(query)
  where("description like ? or name like ?", "%#{query}%", "%#{query}%")
end

#controller code
def search
    @listings = Listing.search(params[:search])
end

#view
<%= form_tag(search_path, :method => "get", id: "search-form", class:"navbar-form navbar-right") do %>
<%= text_field_tag :search, params[:search], placeholder: "Search by color or style...", class:"form-control search-form" %>
<button type="submit" class="btn btn-default btn-md"></button>
<% end %>

I read some other answers on SO that mention the .split method. I tried it out in a couple ways but couldn't get it to work.

A: Suppose,
@products = Product.all
search_query = "Red Necklace"

search_query = "Red Necklace".split(" ")

// now the search_query becomes ["Red", "Necklace"]
Now, search those values in every product for finding the correct product.
result = []
@products.each do |p|
   c = 0
   search_query.each do |q|
     if p.name.include?(q)
       c +=1
     end
   end
   if c == search_query.length
     result << p
   end
end

Its a slow process and complexity is high.

A: Full Text Search
What you're looking for is full text search, which is relatively difficult to achieve using standard MYSQL.
The problem you have is that the db engines are not specifically designed to be "search" engines. They are meant as a way to store & organize data. As such, the "full text" search facilities of these systems is merely based on the query interface.
I'm sure someone more experienced & knowledgeable than I can explain the specifics of this; I'll just say that in order to create the search functionalit you want, you'll want to use one of the third party search applications:

*

*Sunspot Solr

*ElasticSearch

*Sphinx

The difference here is that all of these recommendations index your data, allowing much more in-depth, efficient & specific searching. Although I've not used them specifically, I would highly recommend using one of the above.
--
Solr
You'll want to check out this Railscast on how Solr works:

That's as much help I can give I'm afraid. I know you don't want this, but it's the best way for you to achieve the functionality you desire


text:
Q: How can I write different values to different pixels over multiple frames in FFmpeg? Thanks to Gyan, I know that the geq filter can modify pixels. I have seen expressions that modify a range of pixels; however, I want to iterate through each frame of a video and use my own f(x) for selecting the pixel and an array of color values to write to these pixels.
I know that there exists between() to select a range of frames but I do not want to write the same pixel changes to each frame.
How can I write different values to different pixels over multiple frames?
i.e. Frame 1: set pixel [0, 0] r-value to 255, Frame 2: set pixel [25, 16] g-value to 133, etc.


text:
Q: Jquery change image on rollover with fade I'm currently using the script below to change an image on rollover. There are many images that this effect needs to be applied to -  each image has its own rollover image. The script works for the rollover, but not for the fade.
I've read about using CSS and jquery for the fade effect: http://jqueryfordesigners.com/image-cross-fade-transition/
But it would be a real pain having to write the CSS for over 100 different images! I was just wondering if anyone knows what I'm doing wrong and how to make the script work? :)
$(function () {
$("img.rollover").hover(function () {
    this.src = this.src.replace("_off", "_on")
}, function () {
    this.src = this.src.replace("_on", "_off")
})
});

$("a img").hover(function () {
    jQuery(this).stop().fadeTo("fast", 0.5);
}, function () {
    jQuery(this).stop().fadeTo("fast", 1);
});

A: Instead of writing the CSS for over 100 different images, why not use a jQuery .each loop to add the CSS for you?
$("img.rollover").each(function() {
    this.css('background-image',this.src.replace("_off", "_on"));
});

...and then follow the single-image technique from the page you linked to.


text:
Q: Collapsing margin alignment in Firefox TLDR: this codepen works fine in Chrome, but the alignment is off in Firefox.
I'm building a jQuery plugin which modifies a text input to give it a dropdown button on the left. In order to get the positioning right, I add a wrapper div, which is the same height as the input, so the button can be absolutely positioned on top of the input, and yet still have the same height:
#wrapper {
  position: relative;
}
#overlay {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 30px;
}

This works fine until the input has vertical margin: then the container grows to include the margin, and so the dropdown button grows with it. My solution to this was margin collapsing: I gave the input display:block which meant that the container ignored it's margin. All good.
input {
  margin: 20px 0 40px; /* testing */
  display: block;
}

But now the problem is that by default, inputs are inline elements e.g. you might want to have a submit button next to the input. So I wrapped the whole thing in a container div with display:inline-block, so another inline element like a button can happily sit next to it.
#container {
  display: inline-block;
}

This works fine in Chrome, but has weird alignment issues in Firefox when there's any vertical margin on the input. Below I've added the final markup. There's also a codepen link at the top.

    <input>

<button>Submit</button>

Edit: the point is that this is a plugin and I'm trying to work with the user's existing markup and CSS e.g. they have this markup:
<input><button>Submit</button>

and their existing CSS has vertical margin on the input, and I want them to be able to just initialise my plugin on the input and it just work, without forcing them to change their markup/CSS. Now because the plugin needs to add lots of markup around the input (for the overlay and the dropdown list), I wrap it all up in a container div. This container div is the limit of our reach (and does not include the button element, or anything else they choose to put next to their inputs).

A: To fix this, you'll need to define a line-height in your parent div#test2. Without it, different browsers will give it different values. This will cause Firefox to cause this weird result.
Now, the line-height isn't the only problem, also the vertical-align's baseline value will generate a different result for inline elements than it is for inline-block elements that have a different height than the surrounding inline content. To fix this, change the value to top for the #container element (since that's the inline-block element).
The final result would have the following changed (only pasting the parts that changed):
#test2 {
    background-color: green;
    line-height:70px;
    #container {
        // replicate the inline nature of the input
        display: inline-block;
        vertical-align:top;
    }
    //the rest of the #test2 nested code
}

That would look like this.
Reply to comment
I've made something that does work by the requirements set. Since you said the extra code (so the divs around the input) are made by the plugin itself, I've taken the liberty of changing that a bit to make this work.
The way it can work quite easily is just not using inline-blocks at all, and sticking with the inline elements. This would change the styles to the following:
#container {
    // replicate the inline nature of the input
    display: inline;
}
#wrapper {
    display: inline;
    position: relative;
}
input {
    // you'll want to make sure the typed text doesn't appear behind the overlay
    padding-left:35px;
}
#overlay {
    position: absolute;
    top: 0px;
    bottom: 0px;
    left: 1px;
    width: 30px;
    background-color: #00C2FF;
}

Notes:

*

*I didn't bother making the overlay cover the full height of the input, since your plugin would just make it a flag anyway. To make it cover the full height, just set negative top and bottom styles on the overlay, equal to the computed padding-top and padding-bottom (resp.) on the input. In this case, you'd have to change them to top:-5px;bottom:-5px;. (you can get the computed style via jQuery's $(input).css('padding-top'))

*You could actually also remove the whole #container from it, since the only style it has now is display:inline which really doesn't add anything to the whole thing.

*I've added a padding-left to your input, because otherwise you'd have to type behind the overlay, which is just silly.

A: Is the HTML generated by the plugin and it needs to stay exactly the same? I'm not sure I can figure out exactly why the second example is not working, but you seem to have too many div elements there. You could make since simpler:
HTML

    <input>

    <button>submit</button>

SCSS
input, button {
  border: 1px solid black;
  padding: 5px;
}

input {
  display: inline-block;
  padding-left: 35px;
}

#test1 {
  background-color: yellow;
  padding: 20px 0 40px 0;
  #wrapper {
    position: relative;
    #overlay {
      position: absolute;
      top: 1px;
      left: 1px;
      width: 30px;
      background-color: #00C2FF;
    }
  }
}

Codepen example
I've removed the margin, and instead used padding on the parent, it achieves the same thing. You'll also want some padding-left on your input field so the entered text doesn't disappear behind your overlay div.
EDIT: In case you are unable to change the markup:
SCSS:
#test2 {
  background-color: green;
  #container {
    // replicate the inline nature of the input
    display: inline-block;
    padding: 20px 0 40px 0;
  }
  #wrapper {
    // this is just here to be display:block and ignore the margin on the input
    display: block;
    position: relative;
  }
  input {
    // tell parent to ignore margin
    //display: block;
    margin: 0;
  }
  #overlay {
    position: absolute;
    top: 1px;
    bottom: 1px;
    left: 1px;
    width: 30px;
    background-color: #00C2FF;
  }
}

codepen demo
Removed the block and margin declarations from the input field, and moved the spacing to padding of the #container element.

A: "Disclaimer": Let me just start by saying that I did not find exactly what is causing the problems in Firefox, but I did think of an alternative way you could do it.
The way this works in both Firefox and Chrome is just to use the exact same HTML as you used for your #test1, but on top of that, also using the CSS :before pseudo-element (instead of using the #container and #wrapper). The code I used was:
#test2 {
    background-color: green;
    position:relative;
    &:before {
        content:"";
        display:block;
        position:absolute;
        left:1px;
        top:1px;
        bottom:1px;
        margin:20px 0 40px 0;
        width:30px;
        background:#00C2FF;
    }
}

demo
The way this works is to simply position the :before overlay on exactly the same place as the divs previously were. As you can see, I've used most of the same styles as you did, but instead, I've put them on the :before pseudo-class.

A: Other answers don't know why it doesn't work on Firefox. Well, I think that Firefox has the right behavior and it's a Chrome problem.
In short, you want to align an input with a button. But the input is inside a wrapper. Then, you can use vertical-align to control the vertical aligning between the wrapper and the button, but not between the input and the button.
Here you can see an screenshot with different vertical-align:

See the code.
If you want to align the input and the button (last case in the image), you have a problem, because any of the keywords you can use with vertical-align does that. Only in case that input's top margin and bottom margin are equal, then vertical-align: middle works.
But in general, you have have another solution: vertical-align also accepts a <length> value.
And, to get a perfect alignment, you should use the formula
vertical-align: -(input bottom margin)

Or, if you want to align them even if the button has a bottom margin, then
vertical-align: -(input bottom margin) + (button button margin)

The code formula above works with inline-block
, but not with <buttons>.
The formula must be fixed to
vertical-align: -(input bottom margin) -(input offsetHeight)/2 + 6

In your example

*

*(Input bottom margin) = 40px

*(Input offsetHeight) = 31px

Then, you need
vertical-align: -(input bottom margin) -(input offsetHeight)/2 + 6

Demo

A: I could achieve it with the following.Codepen  You will have to know the css applied to input and apply it to button as well
  button{
   position:absolute;
   margin-left:5px;
  }
  input, button {
   display: inline-block;
   margin: 20px 0 40px 0;
  }

A: please update below in your code.
input, button {
    border: 1px solid #000000;
    margin: 20px 0 40px;
    padding: 5px;
    vertical-align: top;
}

hope it will work
http://codepen.io/anon/pen/Isycu


text:
Q: What does 'the + adjective' mean?
From being one of the most popular and admired people at the school,
  Harry was suddenly the most hated.  (Harry Potter and the
  Sorcerer's Stone)

I've thought a 'the + adjective' means a group of people not a person. But the case has a singular meaning. Is the form used in both ways?

A: The antecedent is people at the school, although it's plural and Harry is singular, so the deleted portion we must recover is person at the school:

From being one of the most popular and admired people at the school, Harry was suddenly the most hated person at the school.

A: Quick note: It's certainly not necessarily a group OF PEOPLE. It could be a group of anything. "There are two kinds of cars: the fast and the slow." "Some animals are the hunters, other the hunted." Etc.
But more generally, you have to be careful about when the-plus-adjective is being used as a noun phrase, and when it is being used as a conventional adjective with an implied noun.
Consider: "Which dress do you want to wear, the blue or the red?" "The blue" and "the red" here are not being used as nouns to describe groups. Rather they are just shorthand for saying "the blue dress or the red dress". We omit the noun because the intended meaning is obvious.
If you said something like, "I feel sorry for the hated in our school", then "the hated" is being used as a noun. There is no noun for it to modify. But if you say, "Of all the students in our school, Harry was the most loved but now he is the most hated," "loved" and "hated" are both being used as ordinary adjectives modifying "students".

A: The main reason for your confusion has been missed by the two previous answers.

From being one of the most popular and admired people at the school, Harry was suddenly the most hated.

You are thinking of this as "the + adjective" when in actual fact it is "the + superlative adjective". It means Harry is the single person who is more hated than anyone else.
You are correct that "the + adjective" refers to a group of people. That's because in that case ("the poor", "the jealous", etc.) the 'adjective' is functioning as a noun.
However, when you use "the" with a superlative, it is functioning as an adjective and the noun is implied.

*

*the weirdest (person)

*the easiest (task)

*the most evil (villains)

etc.
The implied noun will come from the rest of the sentence. In your case, as @snailplane pointed out, it's person at the school.
One more example to contrast the two forms.

*

*The bullied often go on to become bullies themselves.

*Although many people were disliked at Rochdale Comprehensive, Bob was undoubtedly the most bullied.

A: The is the superlative form of adjective. the pattern then is THE+MOST+SUPERLATIVE form of ADJECTIVE(for 2/more syllables, but not all)
Ex.The most handsome
   The longest( for 1 or in some cases 2-syllable adjectives. Regardless of the number of syllables if the form of adjective is superlative,there is always THE.
THE+adjective on the other hand is a noun phrase which refesr to a group. For example, THE OLD retired to bed early while THE YOUNG partied all night., THE+ ADJ noun phrases there refer to a group of old people and a group of young people.


text:
Q: Google Drive Api To List Photos My google drive api is working nice for uploading files. But I am confused how can I list the file (especially photos) of user's drive to my website.
FYI: To download and listing I have copied the MediaFileUpload.php and created a new file named MediaFileDownload.php and then renamed all its function from %upload% to %download%.
Below is my code:
Index.php
    <?php
    /*
     * Copyright 2011 Google Inc.
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *     http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */

    include_once "templates/base.php";
    session_start();

    set_include_path("src/" . PATH_SEPARATOR . get_include_path());
    require_once 'Google/Client.php';
    require_once 'Google/Http/MediaFileDownload.php';
    require_once 'Google/Service/Drive.php';

    /************************************************
      ATTENTION: Fill in these values! Make sure
      the redirect URI is to this page, e.g:
      http://localhost:8080/fileupload.php
     ************************************************/
    $client_id = 'Your_Client_Id';
    $client_secret = 'Your_Client_Secret';
    $redirect_uri = 'http://localhost/MyApi/Google-Drive';

    $client = new Google_Client();
    $client->setClientId($client_id);
    $client->setClientSecret($client_secret);
    $client->setRedirectUri($redirect_uri);
    $client->addScope("https://www.googleapis.com/auth/drive");
    $service = new Google_Service_Drive($client);
    if (isset($_REQUEST['logout'])) {
      unset($_SESSION['download_token']);
    }

    if (isset($_GET['code'])) {
      $client->authenticate($_GET['code']);
      $_SESSION['download_token'] = $client->getAccessToken();
      $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
      header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
    }

    if (isset($_SESSION['download_token']) && $_SESSION['download_token']) {
      $client->setAccessToken($_SESSION['download_token']);
      if ($client->isAccessTokenExpired()) {
        unset($_SESSION['download_token']);
      }
    } else {
      $authUrl = $client->createAuthUrl();
    }

    /********************************************************
      If we're signed in then lets try to download our file.
     ********************************************************/
if ($client->getAccessToken()) {
    // This is downloading a file directly, with no metadata associated.
    echo "The code is being executed till Line No. 67.";
    /**************************************************************
    **     -----This comment is created by Ashish Shah-----     **
    ** The whole code is working if the user is not logged in.  **
    ** After user loggs in, Nothing is being displayed after    **
    ** this block.                                              **
    **************************************************************
    ** The problem is in Line No.76 to Line No.79               **
    **************************************************************/
    $file = new Google_Service_Drive_DriveFile();
    $result = $service->files->list(
        $file,
        array('downloadType' => 'media')
    );
}

    echo pageHeader("File Download - Downloading a Photo");
    if (
        $client_id == '<YOUR_CLIENT_ID>'
        || $client_secret == '<YOUR_CLIENT_SECRET>'
        || $redirect_uri == '<YOUR_REDIRECT_URI>') {
      echo missingClientSecretsWarning();
    }
    ?>

        <?php if (isset($authUrl)): ?>
          <a class='login' href='<?php echo $authUrl; ?>'>Connect Me!
        <?php endif; ?>

      <?php if (isset($result) && $result): ?>

          <?php var_dump($result->title); ?>

      <?php endif ?>

    <?php
    echo pageFooter(__FILE__);
    ?>

MediaFileDownload.php
<?php
/**
 * Copyright 2012 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

require_once 'Google/Client.php';
require_once 'Google/Exception.php';
require_once 'Google/Http/Request.php';
require_once 'Google/Http/REST.php';
require_once 'Google/Utils.php';

/**
 * @author Chirag Shah <chirags@google.com>
 *
 */
class Google_Http_MediaFileDownload
{
  const DOWNLOAD_MEDIA_TYPE = 'media';
  const UPLOAD_RESUMABLE_TYPE = 'resumable';

  /** @var string $mimeType */
  private $mimeType;

  /** @var string $data */
  private $data;

  /** @var bool $resumable */
  private $resumable;

  /** @var int $chunkSize */
  private $chunkSize;

  /** @var int $size */
  private $size;

  /** @var string $resumeUri */
  private $resumeUri;

  /** @var int $progress */
  private $progress;

  /** @var Google_Client */
  private $client;

  /** @var Google_Http_Request */
  private $request;

  /** @var string */
  private $boundary;

  /**
   * Result code from last HTTP call
   * @var int
   */
  private $httpResultCode;

  /**
   * @param $mimeType string
   * @param $data string The bytes you want to upload.
   * @param $resumable bool
   * @param bool $chunkSize File will be uploaded in chunks of this many bytes.
   * only used if resumable=True
   */
  public function __construct(
      Google_Client $client,
      Google_Http_Request $request,
      $mimeType,
      $data,
      $resumable = false,
      $chunkSize = false,
      $boundary = false
  ) {
    $this->client = $client;
    $this->request = $request;
    $this->mimeType = $mimeType;
    $this->data = $data;
    $this->size = strlen($this->data);
    $this->resumable = $resumable;
    if (!$chunkSize) {
      $chunkSize = 256 * 1024;
    }
    $this->chunkSize = $chunkSize;
    $this->progress = 0;
    $this->boundary = $boundary;

    // Process Media Request
    $this->process();
  }

  /**
   * Set the size of the file that is being uploaded.
   * @param $size - int file size in bytes
   */
  public function setFileSize($size)
  {
    $this->size = $size;
  }

  /**
   * Return the progress on the upload
   * @return int progress in bytes uploaded.
   */
  public function getProgress()
  {
    return $this->progress;
  }

  /**
   * Return the HTTP result code from the last call made.
   * @return int code
   */
  public function getHttpResultCode()
  {
    return $this->httpResultCode;
  }

  /**
   * Send the next part of the file to upload.
   * @param [$chunk] the next set of bytes to send. If false will used $data passed
   * at construct time.
   */
  public function nextChunk($chunk = false)
  {
    if (false == $this->resumeUri) {
      $this->resumeUri = $this->getResumeUri();
    }

    if (false == $chunk) {
      $chunk = substr($this->data, $this->progress, $this->chunkSize);
    }

    $lastBytePos = $this->progress + strlen($chunk) - 1;
    $headers = array(
      'content-range' => "bytes $this->progress-$lastBytePos/$this->size",
      'content-type' => $this->request->getRequestHeader('content-type'),
      'content-length' => $this->chunkSize,
      'expect' => '',
    );

    $httpRequest = new Google_Http_Request(
        $this->resumeUri,
        'PUT',
        $headers,
        $chunk
    );

    if ($this->client->getClassConfig("Google_Http_Request", "enable_gzip_for_downloads")) {
      $httpRequest->enableGzip();
    } else {
      $httpRequest->disableGzip();
    }

    $response = $this->client->getIo()->makeRequest($httpRequest);
    $response->setExpectedClass($this->request->getExpectedClass());
    $code = $response->getResponseHttpCode();
    $this->httpResultCode = $code;

    if (308 == $code) {
      // Track the amount downloaded.
      $range = explode('-', $response->getResponseHeader('range'));
      $this->progress = $range[1] + 1;

      // Allow for changing download URLs.
      $location = $response->getResponseHeader('location');
      if ($location) {
        $this->resumeUri = $location;
      }

      // No problems, but upload not complete.
      return false;
    } else {
      return Google_Http_REST::decodeHttpResponse($response);
    }
  }

  /**
   * @param $meta
   * @param $params
   * @return array|bool
   * @visible for testing
   */
  private function process()
  {
    $postBody = false;
    $contentType = false;

    $meta = $this->request->getPostBody();
    $meta = is_string($meta) ? json_decode($meta, true) : $meta;

    $downloadType = $this->getDownloadType($meta);
    $this->request->setQueryParam('downloadType', $downloadType);
    $this->transformToDownloadUrl();
    $mimeType = $this->mimeType ?
        $this->mimeType :
        $this->request->getRequestHeader('content-type');

    if (self::DOWNLOAD_RESUMABLE_TYPE == $downloadType) {
      $contentType = $mimeType;
      $postBody = is_string($meta) ? $meta : json_encode($meta);
    } else if (self::DOWNLOAD_MEDIA_TYPE == $downloadType) {
      $contentType = $mimeType;
      $postBody = $this->data;
    } else if (self::DOWNLOAD_MULTIPART_TYPE == $downloadType) {
      // This is a multipart/related upload.
      $boundary = $this->boundary ? $this->boundary : mt_rand();
      $boundary = str_replace('"', '', $boundary);
      $contentType = 'multipart/related; boundary=' . $boundary;
      $related = "--$boundary\r\n";
      $related .= "Content-Type: application/json; charset=UTF-8\r\n";
      $related .= "\r\n" . json_encode($meta) . "\r\n";
      $related .= "--$boundary\r\n";
      $related .= "Content-Type: $mimeType\r\n";
      $related .= "Content-Transfer-Encoding: base64\r\n";
      $related .= "\r\n" . base64_encode($this->data) . "\r\n";
      $related .= "--$boundary--";
      $postBody = $related;
    }

    $this->request->setPostBody($postBody);

    if (isset($contentType) && $contentType) {
      $contentTypeHeader['content-type'] = $contentType;
      $this->request->setRequestHeaders($contentTypeHeader);
    }
  }

  private function transformToDownloadUrl()
  {
    $base = $this->request->getBaseComponent();
    $this->request->setBaseComponent($base . '/download');
  }

  /**
   * Valid download types:
   * - resumable (DOWNLOAD_RESUMABLE_TYPE)
   * - media (DOWNLOAD_MEDIA_TYPE)
   * @param $meta
   * @return string
   * @visible for testing
   */
  public function getDownloadType($meta)
  {
    if ($this->resumable) {
      return self::DOWNLOAD_RESUMABLE_TYPE;
    }

    if (false == $meta && $this->data) {
      return self::DOWNLOAD_MEDIA_TYPE;
    }

    return self::DOWNLOAD_MULTIPART_TYPE;
  }

  private function getResumeUri()
  {
    $result = null;
    $body = $this->request->getPostBody();
    if ($body) {
      $headers = array(
        'content-type' => 'application/json; charset=UTF-8',
        'content-length' => Google_Utils::getStrLen($body),
        'x-download-content-type' => $this->mimeType,
        'x-download-content-length' => $this->size,
        'expect' => '',
      );
      $this->request->setRequestHeaders($headers);
    }

    $response = $this->client->getIo()->makeRequest($this->request);
    $location = $response->getResponseHeader('location');
    $code = $response->getResponseHttpCode();

    if (200 == $code && true == $location) {
      return $location;
    }
    throw new Google_Exception("Failed to start the resumable download");
  }
}

Please try to resolve my problem.
Thank You,

A: I have solved the problem...
But with the minor bug... My api is not able to fetch other than .jpg file. It can't fetch even .jpeg... Please resolve this... Otherwise all is working fine...
Here is the new index.php file.
index.php
    <?php
    /*
     * Copyright 2011 Google Inc.
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *     http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */

    include_once "templates/base.php";
    session_start();

    set_include_path("src/" . PATH_SEPARATOR . get_include_path());
    require_once 'Google/Client.php';
    require_once 'Google/Http/MediaFileDownload.php';
    require_once 'Google/Service/Drive.php';

    /************************************************
      ATTENTION: Fill in these values! Make sure
      the redirect URI is to this page, e.g:
      http://localhost:8080/fileupload.php
     ************************************************/
    $client_id = 'Your_Client_Id';
    $client_secret = 'Your_Client_Secret';
    $redirect_uri = 'http://localhost/MyApi/Google-Drive';

    $client = new Google_Client();
    $client->setClientId($client_id);
    $client->setClientSecret($client_secret);
    $client->setRedirectUri($redirect_uri);
    $client->addScope("https://www.googleapis.com/auth/drive");
    $service = new Google_Service_Drive($client);

    if (isset($_REQUEST['logout'])) {
        unset($_SESSION['download_token']);
    }

    if (isset($_GET['code'])) {
        $client->authenticate($_GET['code']);
        $_SESSION['download_token'] = $client->getAccessToken();
        $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
        header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
    }

    if (isset($_SESSION['download_token']) && $_SESSION['download_token']) {
        $client->setAccessToken($_SESSION['download_token']);
        if ($client->isAccessTokenExpired()) {
            unset($_SESSION['download_token']);
        }
    } else {
        $authUrl = $client->createAuthUrl();
    }

    /********************************************************
      If we're signed in then lets try to download our file.
     ********************************************************/
    if ($client->getAccessToken()) {
    // This is downloading a file directly, with no metadata associated.
    $file = new Google_Service_Drive_DriveFile();
    $result = $service->files->listFiles(
        $file,
        array('downloadType' => 'media')
    );
}
echo pageHeader("File Download - Downloading a Photo");
if(
        $client_id == '<YOUR_CLIENT_ID>' ||
        $client_secret == '<YOUR_CLIENT_SECRET>' ||
        $redirect_uri == '<YOUR_REDIRECT_URI>'
    ) {
    echo missingClientSecretsWarning();
}
?>

    <?php if (isset($authUrl)): ?>
    <a class='login' href='<?php echo $authUrl; ?>'>Log In To Your Google Account!
    <?php endif; ?>

Result:

<?php print_r($result)?>

<?php
    if (isset($result)){
        $i=0;
        echo "Image Path = ".$result['modelData']['items'][$i]['thumbnailLink']."
";
        foreach ($result as $key => $value){
            if(strcmp($result['modelData']['items'][$i]['mimeType'],'image/')){
                echo "Entered if cond";
?>

                    <img src="<?php echo $result['modelData']['items'][$i]['thumbnailLink'];?>">

<?php
            }
            $i++;
        }
    }
?>


text:
Q: How should I query the number of physical pixels in Retina hardware? I'm searching for a way of getting two pieces of information: (1) the full physical resolution of a display, even if it is a Retina screen;  (2) the resolution that the operating system will, according to current system settings, pretend the same screen has. So far I'm able to get (2) but not (1). It seems like I'm running up against the comment here that

There is even more mess if somebody sets "Scaled" Resolution in macOS System Preferences->Displays

without having been able to find any information about how to navigate that "mess".   So far I have the following, which I compile with clang -framework Cocoa -x objective-c -o grokResolution:
#import <AppKit/AppKit.h>

void ReportRect(CGRect rect, const char *description)
{
    printf("{'x': % 5g, 'y':% 5g, 'width':% 5g, 'height':% 5g, 'name':'%s'}\n",
        rect.origin.x, rect.origin.y,
        rect.size.width, rect.size.height,
        description);
}

int main(int argc, char** argv)
{
    NSScreen *screen = [[NSScreen screens] objectAtIndex:0];

    CGRect looksLike = [screen frame];
    CGRect backing = [screen convertRectToBacking:looksLike];

    ReportRect(looksLike, "looksLike");
    ReportRect(backing, "backing");
    printf("{'backingScaleFactor' : %0.2f}\n", [screen backingScaleFactor]);
}

My Retina screen has 2560x1600 physical pixels. If I use the default scaling setting, which the System Preferences app previews with "Looks like 1280 x 800", then the program outputs the following:
{'x':     0, 'y':    0, 'width': 1280, 'height':  800, 'name':'looksLike'}
{'x':     0, 'y':    0, 'width': 2560, 'height': 1600, 'name':'backing'}
{'backingScaleFactor' : 2.00}

So that seems correct.  However, if I click on the next scaling setting to the right in System Preferences, then re-run the program, I get:
{'x':     0, 'y':    0, 'width': 1440, 'height':  900, 'name':'looksLike'}
{'x':     0, 'y':    0, 'width': 2880, 'height': 1800, 'name':'backing'}
{'backingScaleFactor' : 2.00}

Now, while the System Preferences' "looks like" setting seems to be correctly reflected in the output of [screen frame], my understanding of the whole system is clearly flawed because I expected the backingScaleFactor and/or the convertRectToBacking to convert correctly from fake to real physical resolution. It seems the backingScaleFactor is not correctly adjusted when the system preference changes—in this case the conversion returns more pixels than my hardware really has.
How do I convert correctly?  Or is there another more direct way of querying the actual number of physical pixels a display has?
(I know about system_profiler SPDisplaysDataType | grep Resolution but I need a solution that will work within existing obj-C source code.)

A: The scale factor is always integral. So far, it's always 1 or 2. Some day, Apple may introduce 3x display support for macOS.
The backing store does not necessarily correspond to physical display pixels. For some "scaled" resolutions, the backing store is larger than the number of physical display pixels. Then it is scaled down for actual display. That's what's going on with your second example.
As to how to get the number of physical display pixels, there have been a couple of recent questions with some discussion of that and no firm answer. See this question and the links in the comments.


text:
Q: How to disable Grails Spring plugins at runtime? I have a situation where I need to declare the Grails Spring Security CAS plugin as a compile-time dependency like so (in my Grails app's BuildConfig.groovy):
plugins {
    // Other plugins omitted for brevity...

    compile ":spring-security-cas:1.0.5"
}

However, depending on logic that I don't have available to my app until runtime, I need to dynamically disable/re-enable the plugin on the fly, at runtime.
Is this possible to do? If so, how? If not, why?

A: In general the answer is no.  There is nothing in Grails that allows you to express anything like "if a certain system property is set, completely disable some particular plugin".  Grails plugins can do a lot of things that could not be undone or redone at runtime.  For example, a plugin can modify web.xml at build time.
Plugins can be written such that they interrogate the environment at runtime and behave differently based on that, but that is up to the plugin author to have accounted for that.  Some plugin behavior can also be modified at runtime by interacting with beans in the Spring application context.  It really depends on the plugin and what kind of behavior you are trying to turn on and off.


text:
Q: Как перебором списка назначить разные функции на Button в tkinter import tkinter

w = tkinter.Tk()
lst = ['Hello', 'World']

def prt(i):
    print(i)

for i in lst:
    b = tkinter.Button(master=w, text=i, command=prt(i))
    b.pack()

w.mainloop()

Возможно ли сделать так, чтобы при переборе списка для каждого его элемента создавалась кнопка с текстом элемента списка, а потом этот же элемент передавался в функцию, привязанную к кнопке и при нажатии на кнопку выполнялась функция?
При выполнении кода появляется окошко с двумя кнопками, в консоли сразу выполняются функции, при нажатии на кнопки ничего не происходит.
Пробовал обращаться через индекс элемента:
for i in range(len(lst)):

результат тот же.

A: Попробуйте так:
import tkinter

w = tkinter.Tk()
lst = ['Hello', 'World']

def prt(i):
    print(i)

for i in lst:
# +++                                            vvvvvvvvvvvvvvvvvv  <----
    b = tkinter.Button(master=w, text=i, command=lambda i=i: prt(i))
    b.pack()

w.mainloop()

A: Функции в python это "полноправные граждане" - игра слов при переводе с английского "functions are a first-class type" - "functions are first class citizens". C ними вы можете делать все, что и строками, цифрами, колекциями. То есть составлять из них списки, отправлять их как аргументы в другие функции и т. д.
import tkinter

w = tkinter.Tk()
lst = ['Hello', 'World']
btns = []

def prt1():
    print(lst[0])

def prt2():
    print(lst[1])

# Здесь мы пробегаемся по кортежу из функций.
for i, prt in enumerate((prt1, prt2)):
    b = tkinter.Button(master=w, text=lst[i], command=prt)
    b.pack()
    btns.append(b) # сохраняем кнопки в список,
                   # чтобы к ним можно было бы в будущем обратиться.
print(btns)
w.mainloop()

Даже объект "кнопка" подчиняется "законодательству" Pytnon. Я сохранил их в списке, хотя удобней было бы в словаре с ключом по имени соответствующей функции. Но это уже другая история...
[<tkinter.Button object .!button>, <tkinter.Button object .!button2>]

A: Я решил эту задачу через DataFrame.
from tkinter import *
import pandas as pd

создаем кортежи данных
rows = ('0', '0', '1', '1')
columns = ('0', '1', '0', '1')
buttons = ('7', '8', '9', '/')

формирую данные в массив
df = pd.DataFrame({'btn': buttons, 'r': rows, 'c': columns})

ap = Tk()
ap.title('as')

создаем простейший цикл, в котором значения присваиваются по индексу массива, данные которого очень легко редактировать.
for index in range(len(df)):
    b = Button(ap, text=df['btn'][index])
    b.grid(row=df['r'][index], column=df['c'][index])

ap.mainloop()

При запуске мы получим программу с 4-мя кнопками, расположенными по сетке в 2 ряда и 2 колонки и у которых уже есть присвоенное значение. Кнопкам можно присваивать нужную команду. На эти кнопки можно повесить одну команду и управлять через условие if-elif-else


text:
Q: How can USB 3G modems reach high speeds through a virtual serial port? I'm a bit puzzled about the virtual COM ports used by modern high speeds USB devices that creates several serial interfaces, one of which is used for data transfer.
A modern 3G/4G USB modem can reach speed over 20 Mbps, but the virtual COM ports that they use to actually transfer the data, have their baud rate set to 921600 symbols/s.
Do they use some high level bits/symbol modulation ? If yes, which ones?

A: Newer high-speed USB modem devices don't actually transfer data over virtual serial ports. They use them as a control channel to send AT commands to the "modem" but once they establish a network connection they create another virtual device that identifies itself as an ethernet adapter.

A: Compression is one factor in speeding up communication, another factor is sending several bits at once by modulation
"baud rate" is sloppishly used for many things.
The actual technical term is "symbol changes per second" and is directly related to modulation (above)
Please note the difference to "bit transfer rate per second"
so technically these are NOT THE SAME and has never been.
If you say "100 mega-bits per second" (the throughput/transfer rate) you're not telling a single 'bit' about the baudrate.
So "bit" and "baud" are mutually exclusive, unless "modulation" is also mentioned.
Nowadays the actual used "baudrate" is almost always LOWER than the throughput.
If you can find an old analogue 1200 bps modem, then you're likely have a device that has the same baudrate and throughput.


text:
Q: High score system not updating right So I have this little game I have for a project for school. Here is the part of the code I am having trouble with.
Public Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    C = C + 1
    Label1.Text = Math.Round(clickey / C, 2)
    Dim score As Double = clickey / C
    score = Math.Round(score, 2)
    Label2.Text = C
    Label3.Text = clickey
    Dim scoreH As Double
    If score > scoreH Then
        scoreH = score
        scoreH = Math.Round(scoreH, 2)
        Label8.Text = scoreH
    End If

End Sub

I try to make to so if the current score is greater than the high score, to then change the current score to the highest score (as shown in the if statement). However, no matter what, the label I use to display the high score is always equal the current score, even if the current score is lower than the highest score. =P


text:
Q: Special relativity mirror clock experiment inconsistency Say I set up a relativistic mirror clock experiment in which a spaceship contains a set of mirrors with a photon bouncing between them. Say the photon's motion is parallel to the direction of motion of the space ship, and the spaceship is moving at near to the speed of light, say 0.99c.
From the perspective of someone inside the ship, the photon bounces back and forth as normal, at a rate of one bounce per second or whatever it is. No problems there.
From the perspective of someone at some "stationary" point, the speed of the photon is c and the speed of the plates is 0.99c, so the photon must "race" to approach the front mirror and then when it bounces of the front mirror it should almost immediately hit the back mirror and start racing forward again.
So the observer on the ship sees regular periods but the observer outside the ship sees the first "half" of the second take much longer than the second "half". This seems to me like a paradox or a contradiction or something.
Where did my logic go wrong?

A: That's a very long ship.
Your logic didn't go wrong. The concept of simultaneity is broken with special relativity. Although the clock doesn't appear symmetric to the stationary observer, the ticks (a complete trip) remain consistent with the speed of light when you account for length contraction. And yes, to the stationary observer, it would seem like the trip going in the direction of the ship's velocity would take longer. That's because the light is essentially covering more distance. The trip back would shorter for the same reason.
I would suggest the ladder problem to clear this up: http://en.wikipedia.org/wiki/Ladder_paradox

A: The answer has to do with the relativity of simultaneity. Each observer can be imagined to measure the speed of anything, including a light ray, using clocks attached to different positions along their own ruler which have been synchronized in their own frame. So for example, if the ruler is 10 meters long, and an object passes the clock at the back end when that clock reads 6 seconds, and passes the clock at the front end when that clock reads 8 seconds, then the moving object was measured to travel 10 meters in 2 seconds, or 5 meter/second relative to that ruler/clock system. So, we can imagine the observer on board the ship has a ruler next to him which is at rest relative to the ship, and which stretches from one mirror to another, with clocks attached to each end next to the mirrors. We can likewise imagine an observer outside the ship has a ruler which is at rest relative to himself, and which is aligned right alongside the ship so that this observer can see which marking on his ruler is lined up with a mirror each time the light ray hits it, and what the reading on the clock sitting on that marking was at that moment. In this way, each observer can use their own ruler and synchronized clocks to measure the speed of the same light ray bouncing back and forth between the mirrors.
Each observer synchronizes their own clocks using the Einstein synchronization convention, which is based on the assumption that light should move at the same speed in both directions relative to themselves; for example, for any given pair of clocks in an observer's system, that observer could set off a flash of light at the midpoint between the two clocks, and set both clocks to read the same time at the moment the light from the flash reached them. This will necessarily have the consequence that each observer defines the other observer's clocks to be out-of-sync. For example, if the observer on the ship sets off the flash at the midpoint between two clocks on the ship, the other observer outside will see the clock closer to the front of the ship moving away from the marking on his ruler that was next to the flash when it happened, while the clock closer to the back is moving towards that marking, so he must say that in his own frame the light reached the back clock before the front one. But the observer on the ship set both clocks to read the same time when the light hit them, so from the perspective of the observer outside, the clock at the back will have a time that's ahead of the clock at the front.
To better understand the details of how both observers measure the speed of light to be c in both directions, it's helpful to consider not only the relativity of simultaneity but also time dilation (which causes each observer to measure the other observer's clocks running slow) and length contraction (which causes each observer to measure the other observer's ruler to be shortened). Again, suppose the observer on the ship has a ruler that extends from one mirror to the other, with clocks attached to each end. But now consider how the rulers and clocks of this observer will look in my frame, if I see the observer to be moving at some velocity v along my x-axis (with my ruler parallel to the x-axis). From my perspective, the ruler which the moving observer used to measure the distance is shrunk by a factor of $ \sqrt{1 - v^2/c^2} $ due to length contraction, the time between ticks on the clocks of the moving observer expands by $ 1 / \sqrt{1 - v^2/c^2} $ due to time dilation (or equivalently, in $T$ seconds of time in my frame I only see the moving observer's clock tick forward by $ T \sqrt{1 - v^2/c^2} $), and the rear clock's time-reading is ahead of the front clock's reading by $ vL/c^2 $ due to the relativity of simultaneity, where $L$ is the distance between the clocks in the observer's own frame, as measured by their own ruler.
To flesh this out, let's look at a numerical example. Say that the ruler is 50 light-seconds long in its own rest frame, moving at 0.6c in my frame. In this case the relativistic gamma-factor $ 1 / \sqrt{1 - v^2/c^2} $ (which determines the amount of length contraction and time dilation) is 1.25, so in my frame the ruler's length is 50/1.25 = 40 light seconds long. At the front and back of the ruler are clocks which are synchronized in the ruler's rest frame; because of the relativity of simultaneity, this means that in my frame they are out-of-sync, with the front clock's time being behind the back clock's time by $vL/c^2$ = (0.6c)(50 light-seconds)/$c^2$ = 30 seconds.
Now, when the back end of the moving ruler (which is next to the back mirror on the ship) is lined up with the 0-light-seconds mark of my own ruler, say there's a light flash at that position. Let's say at this moment the clock at the back of the moving ruler reads a time of 0 seconds, and since the clock at the front is always behind it by 30 seconds in my frame, then in my frame the clock at the front must read -30 seconds at that moment. 100 seconds later in my frame, the back end will have moved (100 seconds)*(0.6c) = 60 light-seconds along my ruler, and since the ruler is 40 light-seconds long in my frame, this means the front end will be lined up with the 100-light-seconds mark on my ruler. Since 100 seconds have passed, if the light beam is moving at c in my frame it must have moved 100 light-seconds in that time, so it will also be at the 100-light-seconds mark on my ruler, just having caught up with the front end of the moving ruler, where the front mirror is located.
Since 100 seconds passed in my frame, this means 100/1.25 = 80 seconds have passed on the clocks at the front and back of the moving ruler. Since the clock at the back read 0 seconds when the flash was set off, it now reads 80 seconds; and since the clock at the front read -30 seconds, it now reads 50 seconds. And remember, the ruler was 50 light-seconds long in its own rest frame! So in its frame, where the clock at the front is synchronized with the clock at the back, the light flash was set off at the back when the clock there read 0 seconds, and the light beam passed the clock at the front when its time read 50 seconds, so since the ruler is 50-light-seconds long, the beam must have been moving at 50 light-seconds/50 seconds = c as well! So you can see that everything works out--if I measure distances and times with rulers and clocks at rest in my frame, I conclude the light beam moved at 1 c, and if a moving observer measures distance and times with rulers and clocks at rest in his frame, he also concludes the same light beam moved at 1 c.
After reaching the front end of the moving ruler at 100 seconds in my frame, the light then bounces off the front mirror, then immediately begins traveling in the opposite direction towards the back end. Then at 125 seconds in my frame the light will be at a position of 75 light-seconds on my ruler, and the back end of the moving ruler, which is next to the back mirror, will be at that position as well. Since 125 seconds have passed in my frame, 125/1.25 = 100 seconds will have passed on the clock at the back of the moving ruler. Now remember that on the clock at the front read 50 seconds when the light reached it, and the ruler is 50 light-seconds long in its own rest frame, so an observer on the moving ruler will have measured the light to take an additional 50 seconds to travel the 50 light-seconds from front end to back end. So again, both me and the observer on the ship have measured the light to travel from front mirror to back mirror at a speed of 1 light-second per second.


text:
Q: Map/Reduce:How to output Hashmap after completion? I want to implement the algorithm of DPC(Clustering by fast search and find of density peaks). It is a big job so I decided to start from Calculation of Rho.
Here the Map:
 public void map(LongWritable key, Text value, Context context)
                throws IOException, InterruptedException {
            String line = value.toString();
            String[] lineSplit = line.split(" ");
            if (Double.parseDouble(lineSplit[2]) < dcThreshold) {
                IntWritable one = new IntWritable(
                        Integer.parseInt(lineSplit[0]));
                IntWritable two = new IntWritable(
                        Integer.parseInt(lineSplit[1]));
                context.write(one, two);
            }
        }

Here the Reducer:
public void reduce(IntWritable key, IntWritable values, Context context)
                throws IOException, InterruptedException {
            int[] indexs = new int[2];
            indexs[0] = Integer.parseInt(key.toString());
            indexs[1] = Integer.parseInt(values.toString());
            for (int i = 0; i < indexs.length; i++) {
                densityCountMap.put(indexs[i],
                        densityCountMap.get(indexs[i]) + 1);
            }
        }

Problem
densityCountMap is a hash map, which can be right only after the completion. How to output densityCountMap? in what way?
---------Solution---------
Thanks to mbaxi, you really inspired me for you mentioned that the reduce definition is incorrect and densityCountMap is not necessary.
I should have made it more clear that the goal is that both lineSplit[0] and lineSplit[1] be increased if lineSplit[2] is below an certain threshold value. Actually there is no need to override cleanup.
Mapper:
public static class TokenizerMapper extends
        Mapper<LongWritable, Text, IntWritable, IntWritable> {
    private final static IntWritable count = new IntWritable(1);

    public void map(LongWritable key, Text value, Context context)
            throws IOException, InterruptedException {
        String line = value.toString();
        String[] lineSplit = line.split(" ");
        if (Double.parseDouble(lineSplit[2]) < dcThreshold) {
            IntWritable one = new IntWritable(
                    Integer.parseInt(lineSplit[0]));
            IntWritable two = new IntWritable(
                    Integer.parseInt(lineSplit[1]));
            context.write(one, count);// Both should be increased
            context.write(two, count);// both as key
        }
    }
}

Reducer:
public static class IntSumReducer extends
            Reducer<IntWritable, IntWritable, IntWritable, IntWritable> {
        private IntWritable result = new IntWritable();

        public void reduce(IntWritable key, Iterable<IntWritable> values,
                Context context) throws IOException, InterruptedException {
            int sum = 0;
            for (IntWritable val : values) {
                sum += val.get();
            }
            result.set(sum);//densityCountMap is redundant if having known better the structure of Map/reduce
            context.write(key, result);//it equals to output densityCountMap
        }
    }

Thanks again, you brought more than just a help but an inspiration.

A: You can override the cleanup(Context context) method, keep populating your densityCountMap in the reduce() method and flush/write the contents to disk in cleanup(Context context) method.
cleanup() is invoked after all rows are processed.
---Edit as requested in comments section---
If you are using Eclipse editor, right click on Reducer class that you are extending, and click on Source->Override/Implement Methods, else you can lookup the javadocs.
private static class RhoCalculationReducer extends Reducer<Text,Text,Text,Text> {
}

There you will see a list of following methods [Please note the input parameters/datatypes may change depending on your class definition] -
cleanup(Context)
reduce(Text, Iterable<Text>, Context)
run(Context)
setup(Context)

Your reduce() or map() function are actually overriden implementations, where you provide your own processing logic.
setup() and cleanup() can be considered similar to constructor or destructor respectively for the map or reduce task.
setup() is called prior to start of map of reduce task and cleanup() is called at the end of task.
I also see your reduce definition is incorrect, instead of "IntWritable values" it should be "Iterable values",
For a reducer it is ensured that values for a single key are processed by single reducer, that is why the signature takes a key and a list of iterable values.
Probably you also want to aggregate records from single key together and may not need an additional densityCountMap as reducer already takes care of pulling all values for given key in one go.


text:
Q: java.io.IOException: 403 error loading URL jsoup login help me with jsoup login, i have to login, then redirect from login page to another page with saved session.
public void parseXhtml() throws IOException{
         String sessionID=null;
         Map<String, String> cookies = new HashMap<String, String>();
        cookies.put("login", "login");
        cookies.put("password", "password");
        Connection conn=Jsoup.connect("http://localhost:8080/dir/login.xhtml");

        Connection.Response res = Jsoup
                .connect("http://localhost:8080/dir/login.xhtml")
                .data(cookies)
                .execute();
        res = Jsoup.connect("http://localhost:8080/dir/dir/index.xhtml")
                .cookie("JSESSIONID", res.cookies().get("JSESSIONID"))
                .method(Method.GET)
                .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36")
                .execute();

         Document doc = res.parse();
         System.out.println(doc.html());
         sessionID = res.cookie("JSESSIONID");

         Document docu = Jsoup.connect("http://localhost:8080/dir/dir/index.xhtml")
                            .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36")
                            .cookie("JSESSIONID", res.cookies().get("JSESSIONID"))
                            .method(Connection.Method.GET)
                            .get();

it throws the below exception

java.io.IOException: 403 error loading URL http://localhost:8080/dir/dir/index.xhtml

if i'm doing like [Sending POST request with username and password and save session cookie it throws the same exception.

A: ExternalContext ec=FacesContext.getCurrentInstance().getExternalContext();
        HttpServletRequest req=(HttpServletRequest) ec.getRequest();
        HttpSession sess=(HttpSession) ec.getSession(true);
        String url = req.getRequestURL().append(";jsessionid=").append(sess.getId()).toString();

        ec.setRequest("http://localhost:8080/dir/dir/index.xhtml");
        HttpServletRequest req2=(HttpServletRequest) ec.getRequest();
        String url2 = req2.getRequestURL().append(";jsessionid=").append(sess.getId()).toString();
        Document doc2=Jsoup.connect(url2).get();
        System.out.println(doc2.html());

Finally i got it, I do not know if it is right, but works


text:
Q: How to delete an attachment in an email in Evolution? I would like to delete attachments from the email in the email client Evolution (at the moment 3.2.3, Ubuntu 12.04), so my the size of the IMAP-folders will not be bloated and can be reduced.

A: The feature is included in evolution version 3.x without any additional installation. But it took me a while to find out how I can do it. At least two ways to do it:
1. Right-click on the email with the attachment in the email list of one of your folders and you will find the "Remove Attachments" in the context menu.
2. Left-click on the email with the attachment in the mail list to mark it and find in the panel/main menu "Message" "Remove Attachments".
But unfortunately the most intuitive ways and where I looked for the command first does not work: Left-click context menu in the email itself and context menu of the attachment itself does not contain "remove attachments".


text:
Q: Multi-Domain Stores, One Secure Domain for Checkout, good practise? So this is my lay-out:
Multi-stores on different domains:
domain.com
domain.fr
domain.es
domain.pt
My hosting doesn't have multidomain SSL licence so I can only use the SSL on one domain.
since the base domain is always the same and only the extension changes, I was thinking of using secure.domain.com for secure checkout.
From what I have ready this is easily done on magento, but I have some questions:

*

*Is it a good practise to do this?

*The user won't see "warnings" like "You are changing website be careful", etc?

*I only want to use secure domain on check-out, no need to do it on login/account, can this be done?

*Will it work even if the domain.com store doesn't have the same products has the other stores?

Thank you!
Tiago

A: *

*Yes, it is fine to use a "shared" SSL domain for the secure portion in Magento in checkout. There are no technical issues with this. It may not be ideal, as it complicates tracking with things like Google Analytics, but there are no issues with using it in this manner.

*The user will not see any warnings if all items (images, css, js) on the secure pages are called securely. There are no issues with this.

*Yes, you can remove the security from other sections. In app/code/core/Mage, you'll find config.xml files that set the secure_url for various functions. You can modify these to remove the "" section to disable SSL for these features. The ones that use this are:
Centinel/etc/config.xml
Checkout/etc/config.xml
Customer/etc/config.xml
Downloadable/etc/config.xml
Install/etc/config.xml
Newsletter/etc/config.xml
Ogone/etc/config.xml
Paygate/etc/config.xml
Paypal/etc/config.xml
PaypalUk/etc/config.xml
Persistent/etc/config.xml
Review/etc/config.xml
Rss/etc/config.xml
Sales/etc/config.xml
Tag/etc/config.xml
Wishlist/etc/config.xml

*I don't see any issues with the stores having different products.


text:
Q: Activate profiles in maven sub modules I have the following multi-module maven project:
build
 -> build-common
 -> build-a
 -> build-b

In build-a and build-b I have a profile called myDeploy. Now I would like to build the parent project from commandline but only activate myDeploy for eg. subproject build-b. Is this possible?
Alternatively I could rename the profiles for each subproject to myDeploy-a and myDeploy-b.


text:
Q: Fade/Redraw/Modify ImageIcon on click in SWING JLabel on the fly I want a JLabel with an Icon to look "clicked", when mouse is clicked on the Label. The Label contains an ImageIcon. Instead of changing the icon to another one, I want to redraw the ImageIcon with another colorset (e.g.: setXORMode(new Color(255,0,0) ) "on the fly". Anyone has a hint how to manage that?
JLabel my_label = new JLabel("");
my_label.setIcon(new ImageIcon(MyClass.class.getResource("/path/to/resources/myicon.jpg")));
my_label.addMouseListener(new MouseAdapter() {
    @Override
    public void mousePressed(MouseEvent e) {
        //HERE I NEED THE VODOO :)
    }
});

A: I'd use LookupOp to modify a copy of the icon when it's loaded. Then use setIcon() in the mouse handler.

A: Assuming you read the image into from disk you would do something like this.
URL url = getClass().getResource("images/BB.jpg");
BufferedImage picture = ImageIO.read(url);

Later when you need to change XOrMode you would do the following:
Graphics2D g = picture.createGraphics();
g.setXORMode(new Color(255,0,0) )
g.dispose();

If you want to fadein/fadeout, I'd recommend the timing framework.  Also, if you want to repaint the part of the label itself in addition to the image in the label, you can override void paintComponent(Graphics g).
A very good resource for that you might consider looking into is the book Filthy Rich Clients.  It's full of this kind of stuff.  If you look the examples on the website from Chapter 4 there is some sample image code that might be useful.  It would be a very, very good book for you to pick up too.


text:
Q: Another collatz tree Here's a collatz tree that i drew.
It contains the powers of two along its backbone, and $(2^n-1)/3$ where possible. Those numbers themselves have each a backbone of their own with $(2^nk-1)/3$ where possible. Note that odd numbers do not have branches since we do not apply $3n+1$ to even numbers. The backbones highlighted in green are 'dead'. They are divisible by 3 so no vertex can have an integer $(2^nk-1)/3$. (I made a mistake though, 53 is not meant to be highlighted).
The collatz conjecture claims that every number is contained within this tree and that the only cycled or repeated number is $1$ which is labelled R in a circle and is branching from $2^2$. Anyway, my question is how do you explain or express the regularity of this 'fractal'? This includes the fact that the 'multiplier' leading to branches at every backbone is either two or four and each new branch is separated by $2^2$. Also is there a regularity in where the green backbones pop up? I imagine it can be shown through modular arithmetic.
It was a pain drawing this. I am open to any suggestions on computational methods, i.e. a fractal generator or something in order to make it look clearer.

A: In a compressed format (omitting the even numbers) an approach to draw that tree (in Excel) is this one:

The blocks of numbers are meant as infinite to the right side. The numbers, read downwards in the columns and then horizontal across the columns are in a sequence $a_{k+1}=4 a_k+1$ and the colored arrows show the dependance of child-boxes to parent-entries. For instance, the red arrow from the $17$-box to its parent $13$ means $17=(13 \cdot 4-1)/3$ where the multiplier is $4$ and the green arrow from the box $227$ to its parent $341$ means $227 = (341 \cdot 2-1)/3$ where the multiplier is $2$.
It can surely be optimized, though..., perhaps I come back to this, later.


text:
Q: what causes this error by `apt-get update` What causes this error when sudo apt-get update is issued?
W: GPG error: http://download.virtualbox.org trusty InRelease: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 54422A4B98AB5139

Sequence of events:
Install 14.04 (trusty), install VirtualBox from Ubuntu Software Centre and find it does not work, un-install VirtualBox using Ubuntu Software Centre, install from virtualbox.org using the Debian instructions at the link, issue apt-get update.
virtualbox.org, Instructions for Debian
Edit: There has been a response that suggests that this question is answered at a certain link. I read the answers at the link. This question is different. At the link we see how to resolve the error. This question is different because it asks for the cause. It does not ask for a resolution. This is my response to the link above about the "easiest way to resolve". I will check the comments and revise this edit if necessary.

A: Whenever we add a repository for installing packages we also need a GPG key used by apt to authenticate packages for security reasons.
When adding a Launchpad hosted PPA this key will automatically be downloaded to use. So we do not have to do anything in addition.
This is different when adding an external repository such as the Oracle repository for Virtual Box. We then have to manually download and add the signing key. To do this the following steps are involved:

*

*add the repository to our sources

*download the GPG key

*add this key for authentication

*update our apt cache

*install the desired software package

There are many different ways to achieve this, from command line or with graphical tools which I will not further elaborate here.
For adding the key there is a single-line command from the Virtual Box download page which always had worked for me:
wget -q https://www.virtualbox.org/download/oracle_vbox.asc -O- | sudo apt-key add -

A: The problem is that the command provided by the virtualbox website suggests adding the key using a command that simply will not work and also doesn't provide any error as to why.
Running the commands individually instead of in their piped form revealed there is what appears to be a DNS problem with wget. Here's the error I received:
user@computer:~$ wget https://www.virtualbox.org/download/oracle_vbox.asc
--2015-09-26 21:11:57--  https://www.virtualbox.org/download/oracle_vbox.asc
Resolving www.virtualbox.org (www.virtualbox.org)... failed: Temporary failure in name resolution.
wget: unable to resolve host address 'www.virtualbox.org'

Use aria2 instead (aria2 is way more advanced and reliable than wget anyhow but that's another discussion).
Because there is a DNS problem when using wget, I suggest using aria2 to download the key instead.
First, install aria2:
sudo apt-get install aria2

Then, run the following command to add the key:
aria2c https://www.virtualbox.org/download/oracle_vbox.asc; sudo apt-key add oracle_vbox.asc; rm oracle_vbox.asc

Finally, you should be able to run the following without issue:
sudo apt-get update

The following is an example of what you should see if adding the key is successful. Most importantly, it should say (OK):download completed. and OK on the last two lines respectively.
Download Results:
gid   |stat|avg speed  |path/URI
======+====+===========+=======================================================
cff9ac|OK  |    33KiB/s|/home/H2ONaCl/oracle_vbox.asc.1

Status Legend:
(OK):download completed.
OK

Please post any errors.

A: It was probably because the part of the instructions at virtualbox.org that instructed to
sudo apt-key add oracle_vbox.asc
was not performed.
There was no intention to use HTTPS so that command was skipped. VirtualBox installed successfully without use of apt-key add. It was probably a less secure way to install.


text:
Q: Javascript converting DateTime to "______ seconds/minutes/hours/months ago" The Twitter API returns time stamps of the form:
"Sat, 25 Jul 2009 04:54:42 +0000"
What's the best way to convert a time stamp of this form to "________ seconds/minutes/hours/months ago" depending on the time zone?
Thanks

A: Javascript Pretty Date by John Resig

A: I do this on my site often but I use PHP not javascript for the conversion


text:
Q: Availability of Video-Tag I used HTML's own video tag instead of the "old" flash way to display a video on my own site:
<video src="video.mp4" preload="auto" autobuffer controls autoplay>

</video>

I tested it on my own computer with 3 different browsers: Chrome (30), Firefox (24) and IE (10). It worked as expected.
Then I asked another user to test my site on different machines with different browsers. Unfortunately it didn't work on all machines, even though he used the same browser versions like me.
Firefox displayed him the following error: Video format or MIME type is not supported.

*

*How is it possible, that the same browsers behave different on
different machines?

*Why didn't Firefox display the alternative
content, in my case the vimeo video in the iframe?

*Is there a way to ensure and check that my videos will be displayed
in all browsers on all machines?

Thank you!

A: Firefox has no native MP4/H.264 support, it uses the codec available on the system for this, and in case there is no proper H.264 codec, the video won't play, and you'll receive that error message.
See also http://en.wikipedia.org/wiki/HTML5_video#Supported_video_formats
The fallback content is only used in case the browser doesn't understand the video element at all, unsupported codecs won't cause the fallback to be used.
In order to make sure the video plays in all major browsers, irrespective of the OS, you have to supply the video in different formats using the source element.
Currently using WEBM VP8/9, OGG Theora and MP4 H.264 should do it.
<video preload="auto" autobuffer controls autoplay>
    <source src="video.webm" type="video/webm">
    <source src="video.ogv" type="video/ogg">
    <source src="video.mp4" type="video/mp4">

</video>

You could also try utilizing the error event on the video element or on the last source element, and implement a JavaScript based fallback where you replace the video element with its content.
Example from the W3 specs:

<video controls autoplay>
 <source src='video.mp4' type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
 <source src='video.ogv' type='video/ogg; codecs="theora, vorbis"'
         onerror="fallback(parentNode)">
 ...
</video>

http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#source-default-media


text:
Q: html2canvas.js | Send image to variable for server I am creating a custom graduation stole configurator with jquery and codeigniter. I have got everything how I want it now and my plan is to use html2canvas to take a screenshot of the stole div when they click the add to cart button. I need to just pass this image to a hidden input value or something so that I can write the image to the server.
The stole configurator can be viewed here: custom stole configurator. When you click the Add to Cart button it currently generates the image of the stole and it looks like its working fairly well.
I'm just stuck on the best way or ANY way to put the URL to that image in a hidden input or somehow move the image to a folder and write a path to it.
My point in doing this is so that in the shopping cart there can be a link to "custom stole preview" and when they click on it, it shows this canvas render.
Any help on how I could accomplish this would be of great help. Thanks.
By the way, here is the JS that is doing the screen shot:
$('#addToCart').click(function(event) {
event.preventDefault();
 $('div.customstole').html2canvas();
 var queue = html2canvas.Parse();
 var canvas = html2canvas.Renderer(queue,{elements:{length:1}});
 var img = canvas.toDataURL();
 $('body').append(img);

});
EDIT:
$('#addToCart').click(function(event) {
    event.preventDefault();
     $('div.customstole').html2canvas();
     var queue = html2canvas.Parse();
     var canvas = html2canvas.Renderer(queue,{elements:{length:1}});
     $('#dataUrl').val(canvas.toDataURL());
});

A: Write the data URL to a hidden input, and then on the server side, base64_decode() it and write an image from the resulting string.


text:
Q: Can Scala survive without corporate backing? I was wondering whether Scala will get the takeup it deserves without explicit corporate backing (I was thinking by Sun/Oracle but I suppose it could be someone else, such as Google).
With Sun's recent decision not to include closures in JDK7, couldn't they put their weight behind Scala as the Java alternative for those wishing to have a more expressive language? After all, it seems to me that they should care most about the JVM, not Java per se. Does anyone think this is likely?

A: I think Scala will be fine. It has a lot of mind share now that Twitter has partially moved to it. I think it's unlikely Sun will concentrate on anything but Java, but they are probably happy that other languages are targeting the JVM.
I think the closure thing is lame, by the way. I love closures.

A: I think it will thrive because it doesn't have corporate bozos 'backing' them.  I personally like the idea that a language is so independent, and yet very good and well planned and thought out.
I think Google is likely to pick it up, but I don't think it will be an official backing.  I'm sure Google will find a cool project to use Scala with.

A: Corporate backing is only necessary for a language to succeed if it doesn't have a lot of support from working programmers.  Perl, Python, and Ruby all grew up without support from the Man (well, Ruby had the Japanese Man, but it wasn't a lot of help in the US).
I've not used Scala, but Twitter's endorsement of it suggests that it has enough programmer support to thrive even without a corporate big brother.

A: Of course it will survive.
There are bundles of languages lying around,  being supported by univerities, working groups, hobbiests, and programmers, up and down the world, and out in the wild. In some cases the fact their not supported by the Man, means they have some chance of survival, perhaps more to do with their cachet or maybe they server an important reserarch aspect.

A: Apart from the examples of previous languages that have succeeded without initial corporate backing, I think Microsoft's promotion of functional programming on the .NET platform may indirectly help Scala gain adoption.  Since the Java and .NET ecosystems are seen as close rivals, people aware of F# and the functional additions to C# may be inclined to look for JVM analogs, and to me Scala seems best equipped to fill that role.

A: You need to be more specific.  Thrive in what context?
I think Scala's community is near the critical mass that it needs to be a self-sustainable open source project even if its primary institutional backer, the EPFL, suddenly had a change of heart; and there is currently every sign that it will reach this critical mass.  I think Scala will be with us and actively maintained for a long time.
A more pressing issue if the type of uses for which it is suited.  The Scala compiler and standard library are far from perfect.  When you start pushing the language or a portion of the library there is still a decent chance that you will find bugs.  This is improving by leaps and bounds, but it in itself isn't the core of the problem.
The problem is in order to get fixes you pretty much have to upgrade to the next version of Scala as upgrades come out.  The problem with that is that most version upgrades contain breaking changes, thus in order to obtain fixes you are likely to have to change your own code.  There's also the binary incompatibility problem, which means all your Scala dependencies have to change versions, too.
This could be severe problem if you have a lot of dependencies on other Scala libraries (unlikely - there aren't many yet), if you are subject to severe infrastructure bureaucracy, or worse, you're a product-oriented company that needs to distribute fixes to customer with severe infrastructure bureaucracy.
In order for Scala to be viable in such situations long-term, someone will have to start back porting fixes to earlier versions so that people don't have to perform breaking upgrades just to get some fixes.  I'm sure this will happen, because it really wouldn't be that hard, but it will probably require someone seeing a business opportunity, because let's face it, backporting changes and doing regression testing isn't exactly exiting work.


text:
Q: How can I instantly get the result of my produced event in kafka and kafka-streams? I am simplifying my problem with the following scenario:
3 friends share a loyalty card. The card has two restrictions

*

*can be used max 10 times (does not matter which uses the card, ie
friend_a can use it 10 times.

*the max money in the card is 200. So with 1 "event" of value = 200 the card is "completed".

I am using a kafka producer that sends events in the kafka cluster like this

{   "name": "friend_1",   "value": 10 }
{   "name": "friend_3",   "value": 20 }

the events are posted to a topic that is connected with a kafka stream that groups by key and doing aggregation to sum the money spent. That seems to work, however I am facing a "concurrency issue"
Let's imaging the card is used 9 times, so only 1 time remains to be used and the total money spent is 190, that means there are 10 units left to spend.
So friend_2 wants to buy something that costs 11 units (which should not be allowed) and friend_3 wants to buy something that costs 9 units which should be allowed. Friend_3 will modify the state using the card for the 10th time. All other future attempts should not modify something.
So it seems reasonable for the card user to know if the event he sent modified the max used number and the total count. How can I do it in kafka? Using the streams aggregation I can always increase the values, but how can do I know if my action "modified the state" of the card?
UPDATE: the card user should immediately get a negative feedback if the transaction validates a rule.

A: From how I understand your question there are a few options.
One option is to derive a new stream after the aggregation that you filter() for data that would modify 'the state' of the card, like filtering all events that have > 200 units spent or > 10 uses. This stream can then be used to inform the card user(s) that the card has been spent, e.g. by sending an email.  This is approach can be implemented solely with the DSL.
When more flexibility or tighter control is needed, another option is to use the Processor API (which you can integrate with the DSL so most of your code could keep using the DSL), where you implement the aggregation step yourself (working with state stores that you attach to a Transformer or Processor). During the aggregation, you can implement the logic that checks whether the incoming event is valid (in your example: friend_3 with 9 units is valid, friend_2 with 11 units is not). If it is valid, the aggregation increases the card's counters (units and uses), and that's it. If it is invalid, the event is discarded and will not modify the counters, the Transformer/Processor can emit a new event to another stream that tells the card user(s) that something didn't work.  You can similarly implement the functionality to inform users that a card has been fully used, that a card is no longer usable, or any other 'state change' of that card.
Also, depending on what you want to do, take a look at the interactive queries feature of Kafka Streams.  Sometimes other applications may want to do quick point lookups (queries) of the latest state of something, like the card's state, which can be done with interactive queries via e.g. a REST API.
Hope this helps!


text:
Q: How to enable mixed content (insecure mode) in browsers (Chrome, Opera, FF) for local development at Mac OS? I simply tried almost all known ways to enable mixed content in browsers. Nothing works on Mac.
This link provides some solutions that aren't working for me.
Also i tried open -a Google\ Chrome --args --disable-web-security --allow-running-insecure-content without positive result. Do you have any thoughts how to make it work at Mac?

A: I found this command /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --user-data-dir=/tmp/tempchrome --allow-running-insecure-content --incognito &
It works fine.


text:
Q: How to free pointers in array of structs Given the following:
struct RES_RECORD
{
unsigned char *name;
unsigned char *rdata;
}

Implementing the following within a function/main:
struct RES_RECORD answers[20];

for (i=0;i<20;i++)
{
answers[i].name = strdup("Foo");
answers[i].rdata = malloc(SomeRunTimeValue);
}

How to I properly free() the memory allocations of the pointers within the array (answers)?

A: Exactly the way you allocated it:
for (i=0;i<20;i++)
{
   free(answers[i].name);
   free(answers[i].rdata);
}


text:
Q: Can semantic entailment be used in a formal proof? I am wondering about whether it is possible/makes sense that you could use the fact of semantic entailment (or logical consequence) in a formal proof?
Consider the example: Suppose $A \cap C \subset B$ and $a \in C$. Then $a \notin A\backslash B$. It is straightforward to prove by turning the negation into an implication and just directly proving it. In this example, I can imagine how these steps, starting from the premises, could be written out formally starting with the premises and using rules of inference to arrive at the next sentence, step-by-step until I arrive at the final sentence.
However I was wondering about what happens if instead you follow this sequence of logical inference until you arrived at the following (very contrived) sentence: $$\forall x [x \in A \land x \in C \implies x \in B] \land a \in C$$
Up until this sentence it seems to me that there would be a way of using logical inferences to get here from the premises. Here is where my question came from: It seems to me that by assuming cases for $a \in A$ and it's negation, we can show the conclusion. I.e.
If we assume $a \in A$ then we have $a\in A \land a \in C \rightarrow a \in B$, and
if we assume $a \notin A$ then we have $a \notin A$
To finally arrive at $a\notin A \lor a \in B$, which is exactly the conclusion.
However I don't know if this reasoning works in a logical proof. The cases I considered have the form $A$ and $\neg A$.So consider the truth table for $A \lor \neg A$, $P$, $Q$, and $P \lor Q$, and where we know that $A \vdash P $ and $\neg A \vdash Q$, where here $P$ and $Q$ could represent the statements $a \notin A$ and $a \in B$ respectively.
From the truth table (or quite obviously anyway), I can see that $P \lor Q$ is a logical consequence of $A \lor \neg A$. In other words, $(A \lor \neg A) \vDash (P \lor Q)$.
My understanding is that a formal proof is a sequence of sentences, which are derived from the rules of inference of our formal system. I have recently learnt the distinction about the difference between metalanguage and language of the formal system, and the semantic entailment does not seem to be a logical inference rule (at least of propositional calculus).
So ultimately my question is whether I can use the fact that $(A \lor \neg A) \vDash (P \lor Q)$ in a formal proof? For example, could I in the proof assume $A \lor \neg A$ (which I assume is valid since it is a tautology), and then state "since $(A \lor \neg A) \vDash (P \lor Q)$
, $P \lor Q$"
My apologies if I am misunderstanding the notions here, I only have a shallow understanding of logic so I am not sure if this answer is obvious either way.

A: The two premises of the argument are : $A \cap C \subset B$ and $a \in C$.
Then we have two cases :
(i) $a \in A$. Then $a \in A \cap C \subset B$, and thus $a \in B$. By $\lor$-intro : $a \notin A \lor a \in B$.
(ii) $a \notin A$. Thus by $\lor$-intro again : $a \notin A \lor a \in B$.
In conclusion, due to the fact that the two cases are exhaustive, we can conclude that under assumptions above : $a \notin A \lor a \in B$.
The logical rule of inference to be used is Disjunction Elimination (aka : Proof by cases) :

$\alpha \to \varphi, \lnot \alpha \to \varphi \vDash \varphi$,

using the tautology : $\alpha \lor \lnot \alpha$.
Here $\alpha$ is $a \in A$ and $\varphi$ is $a \notin A \lor a \in B$ and the argument has shown that :

$a \in C, A \cap C \subset B \vDash a \notin A \lor a \in B$.


text:
Q: Multiline tooltip doesn't work programmatically
 is supposed to separate lines on tooltip hover.
This doesn't work:
var doesntwork = document.getElementById("doesntwork")
doesntwork.title = "line1
asdfa";

But doing it in the html works:

See an example of this here, just hover on the squares:
https://jsfiddle.net/foreyez/3yg535jq/
Is there something I'm missing?

A: I run into this issue all the time.  For some reason xml special chars work fine when entered into the xml but not when they are added via javascript.  It is very annoying
I am not sure if it is a solution you can use, but instead of using
 you could use \n
doesntwork.title = "line1\nasdfa";

A: Try doing it like this: doesntwork.title = "line1\r\nasdfa";
/r for carriage return.
/n for newline
See fiddle: https://jsfiddle.net/DIRTY_SMITH/3yg535jq/4/

A: I found this little solution I came up with humorous if nothing else.
https://jsfiddle.net/1fp7frer/

var doesntwork = document.getElementById("doesntwork")
doesntwork.title = "line1
asdfas".replace(/&#(\d+);/g, String.fromCharCode);
#works {
  width:100px;
  height:100px;
  background:blue;
}

#doesntwork {
  width:100px;
  height:100px;
  background:red;
}


text:
Q: can you make screen reader in android, skip specific elements? I'm writing an application and I'm adding Accessibility features to it.
when I turn on the screen reader, it also reads icons and other unnecessary items on the screen.
can you make the screen reader in android, skip specific elements?
or read a different text then what the elements say?

A: You can control what it reads out by setting the android:contentDescription attribute on these elements.  If it's a purely decorative icon (for instance, one where the relevant text is already read out elsewhere), you can set the content description to "@null".  On API 16+, you can also set these graphical elements' android:importantForAccessibilityattributes to "no".
You can find all of this and more information in this guide.