text:
Q: Can't create registration form with image uploading in Django application I have a problem related to registrations form. I tried to implement One To One field, but it didn't bring any results.
My problems: I can not add to the User model ImageField and some other fields(I'm not sure about it) and when I fill image field in the registration form I can not get the image back in the Profile page.
The only thing I want is to create a registration form with some specific additional fields and image uploading. You can also suggest other ways of realizing this.
Models.py
from django.db import models
from django import forms
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=500, blank=True)
    picture = models.ImageField(upload_to='profile-photos')
    profile_sphere =
   models.CharField(null=True,max_length=1000,blank=True,verbose_name='Сфера деятельности', choices=(['it','Информационные технологии'],['wood','Деревообработка']))

@receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)
    instance.profile.save()

forms.py
from django import forms
from .models import Profile
from django.contrib.auth.forms import UserCreationForm , UserChangeForm
from django.contrib.auth.models import User
from django.core.validators import EmailValidator

class SignUp(UserCreationForm):
    email = forms.EmailField(max_length=254, help_text='Required. Inform a
        valid email address.')
    class Meta:
        model = User
        fields = ('username','first_name','last_name', 'email','password1',)

class NewForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ('profile_sphere','bio','picture',)

views.py (def register and def profile)
def register(request):
    newuser = None
    if request.method == 'POST':
        new = NewForm(request.POST,request.FILES)
        form = SignUp(request.POST)
        if form.is_valid():
            newuser = new.save(commit=False)
            user = form.save(commit=False)
            user.refresh_from_db()
            newuser.profile.image = new.get('picture')
            newuser.profile.sphere = new.cleaned_data.get('profile_sphere')
            newuser.profile.bio = new.cleaned_data.get('bio')
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password')
            user = authenticate(username=username, password=raw_password)
            return HttpResponseRedirect(reverse('accounts:login'))
    else:
        new = NewForm()
        form = SignUp()
    return render(request, 'accounts/register.html',{'form':form, 'new':new,
        'newuser.profile.image':newuser})

def profile(request,page_number=1):
    projectobj =
        Project.objects.filter(owner=request.user).order_by('date_added')
    current_page = Paginator(projectobj, 1)
    return render(request, 'accounts/profile.html',
    {'projectobj':current_page.page(page_number)})

in views in def register, i save two forms: newuser and signup form which I inherit from User model. in register function newuser = None to prevent "variable referenced before assignment" error.
What do I need to do?


text:
Q: Rails RecordNotFound couldnt find album with id I'm at the end of a nested resource Rails app but I can't seem to figure out how to delete a review. I can delete an album just fine. My reviews belong to albums. Users have both albums and reviews.
I would also like to be able to make sure Users cannot delete reviews that they didn't write. I think that is where my error is coming from.
I keep getting this error:
ActiveRecord::RecordNotFound in AlbumsController#destroy
Couldn't find Album with 'id'=17
Extracted source (around line #57):
55
56
57
58
59
60

    def set_album
        @album = Album.find(params[:id])
    end

    def album_params

Here is my reviews controller:
class ReviewsController < ApplicationController
    before_action :set_review, only: [:show, :delete, :edit, :update]
    before_action :set_current_user, only: [:index, :new, :edit, :delete]
    before_action :find_album, only: [:create, :edit]
    before_action :must_login, only: [:index, :new, :create, :edit, :update, :delete]

    def index
        @albums = Album.with_recent_reviews
    end

    def show
        #@reviews = Review.where("album_id = ?", params[:album_id])
    end

    def new
        if params[:album_id] && @album = Album.find_by(id: params[:client_id])
            @review = @album.reviews.build
        else
            redirect_to albums_path
        end
    end

    def create
        @review = current_user.reviews.build(review_params)
        @review.album = @album
        if @review.save
            redirect_to album_path(@album)
        else
            @album = @review.album
            render :new
        end
    end

    def edit
    end

    def update
        if @review.update(review_params)
            redirect_to album_path(params[:album_id])
        else
            render 'edit'
        end
    end

    def destroy
        if current_user.id == @review.user_id
            @review.destroy
            redirect_to album_path(params[:album_id])
        else
            flash[:error] = "Unable to delete your review. Please try again."
            redirect_to album_reviews_path(@review)
        #@review.destroy
        end
    end

    private

    def set_review
        @review = Review.find(params[:id])
    end

    def set_current_user
        @user = current_user
    end

    def find_album
        @album = Album.find(params[:album_id])
    end

    def review_params
        params.require(:review).permit(:title, :date, :content, :user_id, :album_id, album_attributes:[:artist, :title, :user_id])
    end

end

Here is my reviews index form where the delete link is located:
<% @albums.each do |album| %>

  <% if album.avatar&.attached? %>
    <image src="<%=(url_for(album.avatar))%>%" style="width:350px;height:350px;">
  <% end %>

  <%= album.artist %> - <%= album.title %>

  <%= link_to "View Album", album_path(album) %>
  <%= link_to "Edit Album", edit_album_path(album) %>

  <% album.reviews.each do |review| %>
    <% unless review.id.nil? %>
        Date written: <%= review.date %>

        Written by: <%= review.user.name %>

        Title: <%= review.title %>

        Review: <%= review.content %>

        <%= link_to "Edit Review", edit_album_review_path(album_id: album.id, id: review.id) %>
        <%= link_to 'Delete', album_path(album_id: album.id, id: review.id), method: :delete, data: { confirm: 'Are you sure?' } %>

    <% end %>
<% end %>

<% end %>

Albums controller:
class AlbumsController < ApplicationController
    before_action :set_album, only: [:show, :edit, :update, :destroy]
    before_action :must_login, only: [:new, :show, :create, :edit, :update, :destroy]

    def index
        @albums = Album.all
        @user = current_user
    end

    def show
        @review = @album.reviews.build
        @review.user = current_user
        # If you want to have some flag to indicate its status
        #@review.draft = true
        @review.save
        @reviews = Review.recent #scope
    end

    def new
        @album = Album.new
        @user = current_user
    end

    def create
        @user = User.find(current_user.id)
        @album = current_user.albums.build(album_params)
        @album.user_id = current_user.id
        if @album.save
            redirect_to album_path(@album)
        else
            render :new
        end
    end

    def edit
        @user = current_user
    end

    def update
        #@album = current_user.albums.build(album_params)
        @album.user_id = current_user.id
        if @album.update(album_params)
            redirect_to album_path(@album), notice: "Your album has been updated."
        else
            render 'edit'
        end
    end

    def destroy
        @album.delete
        redirect_to albums_path
    end

    private

    def set_album
        @album = Album.find(params[:id])
    end

    def album_params
        params.require(:album).permit(:artist, :title, :avatar, :user_id, review_attributes:[:title, :date, :content, :user_id, :album_id])
    end
end

A: You have this issue because you are not passing an album_id to the destroy action of the review controller. The reason you need an album_id is because your routes probably look like this (since you said they were nested):
http://localhost:3000/albums/1/reviews

You can see in your route that you need an album_id (the 1 after the album). Try changing your review destroy action to this:
def destroy
  if current_user.id == @review.user_id
    @album.reviews.find(params[:id]).destroy
    redirect_to album_path(params[:album_id])
  else
     flash[:error] = "Unable to delete your review. Please try again."
     redirect_to album_reviews_path(@review)
  end
end

You'll also have to change your before_action in the review controller to this, since you need the album_id to destroy the review:
before_action :find_album, only: [:create, :update, :destroy]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Behavior of force, velocity and acceleration when the power output becomes constant This might look like a homework question, but really isn't. I am teaching myself some basic physics and am shamefully stuck in one place. I have designed the problem below to help myself understand the situation better.
Suppose a motorbike weighing 100 kg is at rest and begins producing a constant force of $F=$ 800 N. The resistance to motion is $R=$ 500 N, so the the net force of 300 N causes acceleration in the positive direction, $a = (F-R)/m = 300/100 = 3$ m/s. The acceleration is constant, so the speed is given by v = at. The power produced is given by $P = Fv = Fat$, so it is increasing linearly over time and in direct proportion to speed. Suppose the bike accelerates for the first 5 seconds and then reaches a certain maximum power output that remains constant. Using the numbers above, the speed reached after 5 s is 15 m/s, and so the maximum power is 12 kW.
If my understanding is correct, at an instant when $P$ becomes constant, $v$ will still be increasing, so $F$ will have to be decreasing in inverse proportion, $F = P/v$. Since $F$ is decreasing, the acceleration will also be decreasing, $a = (F - R)/m$. So we have a three-way circular relationship where to find the function of $F$ we need the function of $v$, to find the function of $v$ we need the function of $a$, and to find the function of $a$, we need the function of $F$. How we find the curves for $F$, $a$ and $v$?
Also, is my understanding correct in that $v$ will drop down until $a = 0$, at which point $F = R$, so the maximum velocity allowed by the maximum power output $= P/F = P/R = $ 12000/500 = 24 m/s ?

A: The equation you're missing is the direct relationship between power $P$ and kinetic energy $K$. Specifically, for a constant power input, we have that $K=K_0+Pt$ where $K_0$ is the initial kinetic energy. Since we also know the definition of kinetic energy, $K=\frac{1}{2}mv^2$, we can say that
$$\frac{1}{2}mv^2=\frac{1}{2}mv_0^2+Pt$$
so we can solve for $v$ directly:
$$v=\sqrt{v_0^2+\frac{2Pt}{m}}$$
Once you have $v$ as a function of time, you can of course solve for the net force and $a$ as well.
One thing you can immediately see, though, is that the vehicle is always accelerating; there is no maximum allowed velocity. This makes sense, because you have required, in your definition of the problem, that there is a constant input of power regardless of speed; in other words, you have required that the kinetic energy of the vehicle always increases at a constant rate. Increasing kinetic energy implies increasing velocity for a vehicle of constant mass, so therefore $a>0$ for all time (though it does approach zero as kinetic energy gets higher and higher).


text:
Q: Close this popup when click outside in screen I want to close this popup when I click on screen too.
I wrote some Javascript but it is not working for me. I am very Poor in Javascript so I can't figure out what the problem is.
I have tried solutions from other blogs but can't get them to work.
Here is my code you can check it.

function openNav() {
    navMenuStatus = document.getElementById('popup').style.right;
    if (navMenuStatus == '-300px') {
        document.getElementById('popup').style.right = '0px';
    } else {
        document.getElementById('popup').style.right = '-300px';
    }
}
var navMenuStatus = document.getElementById('popup').style.right;
window.onclick = function(event) {
    if (navMenuStatus == '0px') {
        modal.style.right = "-300px";
    }
}
.pmenu {
  cursor: pointer;
  width: 70px;
  font-weight: 600;
  color: #fff;
  float: left;
}

.pmenu img {
  padding: 5px 11px;
  background-color: #fff000;
}

.pmenu p {
  text-align: center;
  padding: 10px 4px;
  background-color: #356381;
  margin: 0 0 0px;
  font-size: 14px;
}

.pbody {
  color: #fff;
  float: left;
  width: 300px;
  background-color: #356381;
  border-left: 5px solid #fff000;
}

.pbody p {
  text-align: center;
  font-size: 15px;
  margin: 10px;
}

.pbody h4 {
  text-align: center;
  font-weight: 600;
  margin: 0px;
  color: #000;
  background-color: #fff000;
  padding: 10px 0px;
}

.pbody h5 {
  font-size: 15px;
  text-align: center;
  background: #193e56;
  padding: 15px;
}

.address {
  text-align: center;
}

.address h6 {
  color: #356381;
  background-color: #fff000;
  font-size: 14px;
  padding: 10px 0px 10px 10px;
  margin-top: 0px;
  min-width: 245px;
  text-align: left;
}

.aicon {
  float: left;
  width: 50px;
  background-color: #193e56;
  color: #fff;
  padding: 14px 12px;
}

.aadd {
  float: left;
  color: #fff;
}

.popup {
  position: absolute;
  right: -300px;
  top: 20px;
  z-index: 3;
  transition: 0.3s all;
}

GET THE
BOOK

HOW TO GET THE PHONEBOOK

Books were delivered to every house in Lakewood and surrounding areas during the month of February.

If you did not receive one after this time you may pick one up at either one of the Wine on 9 locations.

North location
 6545 Rt 9 North, Howell, NJ 07731

South location
 945 River Ave, Lakewood, NJ 08701

A: First, the modal variable is not defined within the scope. I changed this to document.getElementById('popup') to solve the JavaScript error.
Second, to get the hide function to work properly, you can use a querySelector, which makes sure the function is triggered and the code block within the if statement is run only if clicked on the whitespace of the HTML.

function openNav() {
    navMenuStatus = document.getElementById('popup').style.right;
    if (navMenuStatus == '-300px') {
        document.getElementById('popup').style.right = '0px';
    } else {
        document.getElementById('popup').style.right = '-300px';
    }
}

window.onclick = function(event) {
    var overallTarget = document.querySelector('html')
    if (overallTarget == event.target) {
        document.getElementById('popup').style.right = "-300px";
    }
}
.pmenu {
  cursor: pointer;
  width: 70px;
  font-weight: 600;
  color: #fff;
  float: left;
}

.pmenu img {
  padding: 5px 11px;
  background-color: #fff000;
}

.pmenu p {
  text-align: center;
  padding: 10px 4px;
  background-color: #356381;
  margin: 0 0 0px;
  font-size: 14px;
}

.pbody {
  color: #fff;
  float: left;
  width: 300px;
  background-color: #356381;
  border-left: 5px solid #fff000;
}

.pbody p {
  text-align: center;
  font-size: 15px;
  margin: 10px;
}

.pbody h4 {
  text-align: center;
  font-weight: 600;
  margin: 0px;
  color: #000;
  background-color: #fff000;
  padding: 10px 0px;
}

.pbody h5 {
  font-size: 15px;
  text-align: center;
  background: #193e56;
  padding: 15px;
}

.address {
  text-align: center;
}

.address h6 {
  color: #356381;
  background-color: #fff000;
  font-size: 14px;
  padding: 10px 0px 10px 10px;
  margin-top: 0px;
  min-width: 245px;
  text-align: left;
}

.aicon {
  float: left;
  width: 50px;
  background-color: #193e56;
  color: #fff;
  padding: 14px 12px;
}

.aadd {
  float: left;
  color: #fff;
}

.popup {
  position: absolute;
  right: -300px;
  top: 20px;
  z-index: 3;
  transition: 0.3s all;
}

GET THE
BOOK

HOW TO GET THE PHONEBOOK

Books were delivered to every house in Lakewood and surrounding areas during the month of February.

If you did not receive one after this time you may pick one up at either one of the Wine on 9 locations.

North location
 6545 Rt 9 North, Howell, NJ 07731

South location
 945 River Ave, Lakewood, NJ 08701

A: Made some changes to your script... Try that one:

var navMenuStatus = document.getElementById('popup').style.right;

//click on ANY but not popup
document.querySelector(":not(#popup)").addEventListener("click", function( event ) {
    closeNav();;
}, false);

//click on popup event listenter
document.getElementById("popup").addEventListener("click", function( event ) {
    toggleNav();
    event.stopPropagation();
}, false);

function closeNav() {
  navMenuStatus = document.getElementById('popup').style.right;
  if (navMenuStatus == '0px') {
      document.getElementById('popup').style.right = '-300px';
  }
}

function toggleNav() {
    navMenuStatus = document.getElementById('popup').style.right;
    //alert(navMenuStatus);
    if (navMenuStatus == '-300px') {
        document.getElementById('popup').style.right = '0px';
    } else {
      closeNav();
    }
}
.pmenu {
  cursor: pointer;
  width: 70px;
  font-weight: 600;
  color: #fff;
  float: left;
}

.pmenu img {
  padding: 5px 11px;
  background-color: #fff000;
}

.pmenu p {
  text-align: center;
  padding: 10px 4px;
  background-color: #356381;
  margin: 0 0 0px;
  font-size: 14px;
}

.pbody {
  color: #fff;
  float: left;
  width: 300px;
  background-color: #356381;
  border-left: 5px solid #fff000;
}

.pbody p {
  text-align: center;
  font-size: 15px;
  margin: 10px;
}

.pbody h4 {
  text-align: center;
  font-weight: 600;
  margin: 0px;
  color: #000;
  background-color: #fff000;
  padding: 10px 0px;
}

.pbody h5 {
  font-size: 15px;
  text-align: center;
  background: #193e56;
  padding: 15px;
}

.address {
  text-align: center;
}

.address h6 {
  color: #356381;
  background-color: #fff000;
  font-size: 14px;
  padding: 10px 0px 10px 10px;
  margin-top: 0px;
  min-width: 245px;
  text-align: left;
}

.aicon {
  float: left;
  width: 50px;
  background-color: #193e56;
  color: #fff;
  padding: 14px 12px;
}

.aadd {
  float: left;
  color: #fff;
}

.popup {
  position: absolute;
  right: -300px;
  top: 20px;
  z-index: 3;
  transition: 0.3s all;
}

GET THE
BOOK

HOW TO GET THE PHONEBOOK

Books were delivered to every house in Lakewood and surrounding areas during the month of February.

If you did not receive one after this time you may pick one up at either one of the Wine on 9 locations.

North location
 6545 Rt 9 North, Howell, NJ 07731

South location
 945 River Ave, Lakewood, NJ 08701

A: Try this:
function openNav() {
    navMenuStatus = document.getElementById('popup').style.right;
    if (navMenuStatus == '-300px') {
        document.getElementById('popup').style.right = '0px';
    } else {
        document.getElementById('popup').style.right = '-300px';
    }
}
var modal = document.getElementById('popup');
var html = document.querySelector('html');
window.onclick = function(event) {
    if (event.target == html) {
        modal.style.right = "-300px";
    }
}


text:
Q: ArrayAdapter doesn't support getCheckedItemIds()? I hope to use lv.getCheckedItemIds().length to get the sum of selected items.
It seems that ArrayAdapter doesn't support getCheckedItemIds(), right?
private void InitListView(int pos) {
    List<String> msgList = getSMS(pos);
    ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_multiple_choice, msgList);
    lv.setAdapter(adapter2);
    lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    lv.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            SetSelectedAndTotal();
        }
    });
}

private void SetSelectedAndTotal(){
    selectedAndTotal.setText(lv.getCheckedItemIds().length+ "/"
            + lv.getCount());
}

    public List<String> getSMS(int pos) {
        List<String> sms = new ArrayList<String>();
        Uri uriSMSURI = Uri.parse(valueList.get(pos));
        Cursor cur = getContentResolver().query(uriSMSURI, null, null, null,
                null);

        while (cur.moveToNext()) {
            String address = cur.getString(cur.getColumnIndex("address"));
            String body = cur.getString(cur.getColumnIndexOrThrow("body"));
            sms.add("Number: " + address + " .Message: " + body);

        }
        return sms;
    }

A: Here is a snippet from the documentation on using getCheckedItemIds():

The result is only valid if the choice mode has not been set to CHOICE_MODE_NONE and the adapter has stable IDs. (hasStableIds() == true)

By default, BaseAdapter (and it subclass ArrayAdapter) do not support stable item ids, so if you want to utilize this you will need to create your own subclass that returns true from hasStableIds() and always returns a unique value from getItemId() for each element.
Otherwise, you'll have to use getCheckedItemPositions() instead, which in the use case you described would provide the same answer you need without the extra work.


text:
Q: Spring-Fox doesn't support Jackson's @JsonTypeName annotation on Swagger-UI I've a SpringBoot based server (v2.2.2.RELEASE very old) that uses springfox-boot-starter:v3.0.0
I have few beans that are used as response in @RestController.
Here is a snippet of this response Pojo:
@JsonTypeName(value = "getUser")
@JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.NAME)
public class GetUserResponse {

  private final long userId;

  public GetUserResponse(long userId) {
    this.userId = userId;
  }

  @JsonProperty("uId")
  public long getUserId() {
     return userId;
  }

  ...
}

I run the server go to the swagger page and look at this endpoint, the response look like this:
{
   "uId": 0
}

What I expect to see is:
{
  "getUser" : {
    "uId" : 0
  }
}

For some reason Swagger doesn't parse the JsonTypeName nor JsonTypeInfo annotations thus doesn't add the root node to the response.
It is important to say that if I actually run the API then the response does contain the root node!! the problem only occurs when looking the structure of the response in the Swagger UI.
I also tried to work with @JsonRootName annotation but that really broke the Swagger and I couldn't even load Swagger-UI page.
Any idea how to make this works??


text:
Q: Function allocates always to the same address, and the variable doesn't change The function f allocates its result always to the same address, that makes the main() function always print out the same result, how do I make the function allocate the variable an another address and free them.
int *f(int a) {
    int b = 2 * a;
    return &b;
}

int main(void) {
    int *p4, *p8;

    p4 = f(4);
    p8 = f(8);

    printf("p4: %i / p8: %i\n", *p4, *p8);
}

A: The function f does not allocate anything, it returns the address of a local variable with automatic storage.  Accessing data via this pointer invokes undefined behavior as soon as b goes out of scope, when f returns.  The compiler should be able to detect such a silly bug.
To allocate memory, you should use malloc:
#include <stdio.h>
#include <stdlib.h>

int *f(int a) {
    int *p = malloc(sizeof(*p));
    if (p != NULL)
        *p = 2 * a;
    return p;
}

int main(void) {
    int *p4 = f(4);
    int *p8 = f(8);

    if (p4 != NULL && p8 != NULL) {
        printf("p4: %i / p8: %i\n", *p4, *p8);
    }
    free(p4);
    free(p8);
    return 0;
}

A: You have to declare b as static ore better yet,declare b as parameter in f function. You could do something like this
static bool f(int a,int *b)
{
    if(NULL == b)
    {
        return false;
    }
    *b = a * 2;
    return true;
}

It is better to write functions that return nothing(void) or a boolean to let you know if everything went fine and use pointers to modify data and reduce the use of the stack. Most safety-critical standards adopt this rule.


text:
Q: Data structure for Google Places API JSON in Yesod I am new to Haskell and Yesod development.
I try to parse JSON from Google Web Api using Aeson.
My JSON is like
{
   "html_attributions" : [],
   "results" : [
       {
         "geometry" : {
             "location" : {
             "lat" : 47.2487941,
             "lng" : 39.7119239
          },
         "viewport" : {
           "northeast" : {
              "lat" : 47.2488398,
              "lng" : 39.71313905
           },
           "southwest" : {
              "lat" : 47.24865699999999,
              "lng" : 39.71151884999999
           }
        }
     },
     "icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/lodging-71.png",
     "id" : "5aae9c47cad3016c64d3cc2c8d438ae656c8c0af",
     "name" : "AMAKS Congress hotel",
     "photos" : [
        {
           "height" : 2304,
           "html_attributions" : [
              "\u003ca href=\"https://maps.google.com/maps/contrib/116238492021115373516/photos\"\u003eDmitry Semenov\u003c/a\u003e"
           ],
           "photo_reference" : "CoQBdwAAAP5F6Xu0nGvQ8wjAyY4ENNKEWzw8CohQU_2Z15oXWIQOvzwAOBQduK4OQfh-nRyw0iKCwLMS2o9fKanMcxpC4xop22SrxZI45OZWmvC-bTf80kJlgdnlU0q-AsncUxcP6sbfWMaTmAPCsqiAFLJhHwHD93VXCvyV2V4pC2CUpWKAEhBAr9aS0xoapQvNmvcUYfU7GhT3IKDXEdZ49LtEeMXMaBQKlNZ6DQ",
           "width" : 4096
        }
     ],
     "place_id" : "ChIJNT2qOT7r40ARrxvwbj2Huxg",
     "rating" : 4.1,
     "reference" : "CmRRAAAAUR4QujRBtpkltqU51qCjuihX1JDEgX9ijFzkTeWGWkeQkw4spvaKqCPUrYit4jNs5AyT1hV-y0M72U2CtOTYgT_6chw5KAq0sB3l1k18BOoioDJqTL6HQ_kvqNn62ISIEhA-lNI9YXDt-cjErgJqHjGFGhQpYucBzRg9yilMU0MEn6b293lVUQ",
     "scope" : "GOOGLE",
     "types" : [
        "bowling_alley",
        "bakery",
        "lodging",
        "restaurant",
        "food",
        "store",
        "point_of_interest",
        "establishment"
     ],
     "vicinity" : "проспект Михаила Нагибина, 19, Ростов-на-Дону"
  },
  / more items here
  "status" : "ok"
}

I created data for representing JSON:
data Restaurant = Restaurant {status :: Text} deriving  (Show, Generic)

And it works, I can extract status. But when it comes to more complicated enclosed fields such as "results", I don't know how to describe and use it.
So what should I write instead of ??? in
data Restaurant = Restaurant {results :: ???, status :: Text} deriving (Show, Generic)

And then how can I get access to items inside (name, rating, etc.)?
Thank you!


text:
Q: How to make jface data binding work both ways? I'm trying to implement something similar to a property view in eclipse. That is also able to edit the properties of the selected object, and when the selection changes the displayed values should change as well. So I try to bind the Text fields to my model properties but for some reason the binding only works one way (view -> model). Any suggestions?

private org.eclipse.swt.widgets.Text length;

private void initBinding(){
    DataBindingContext ctx = new DataBindingContext();

    IObservableValue<String> propertyLength = BeanProperties.value(SqlDataModel.class, "length", String.class)
            .observe(dataModel);
    ISWTObservableValue<String> widgetLength = WidgetProperties.text(SWT.Modify).observe(length);
    ctx.bindValue(widgetLength, propertyLength);
}

The model is a POJO
public class SqlDataModel {

    private String length;

    public String getLength() {
        return length;
    }

    public void setLength(String length) {
        this.length = length;
    }

    ...


text:
Q: PHP sessions with HTML I have a website which uses PHP and HTML pages, I want to create a session which stores a username from the login page. But the login pages are php and the next pages are html.
Is this a problem or can I just add a small statement of php into the html page saying
 <?PHP session_start();
$_session['loginid']=$_post['username'];
?>

Or am I doing it wrong?
This is the first time i've used sessions and they confuse me a little.
thanks for any help.

A: If you have access to your apache configuration, or a simple .htaccess file, you can tell Apache to handle php code inside of an .html file. You can do this by creating an .htaccess file (remember the . (dot) as the first character in that filename) on the document root of the site (probably public_html/) and putting this into it:
# Add this to public_html/.htaccess file
AddHandler application/x-httpd-php .html
AddHandler application/x-httpd-php .htm

You should be able to reload the html page and your PHP code (from Michael Matthews answer) will run great.

A: You are trying to share a PHP session variable with a page that is of type text/html. As you suggested you must make the HTML page a PHP page for this to work and add a little snippet of PHP somewhere to display the user name.
Change your HTML page to PHP. At the top of the page add something like this:
<?php
  session_start(); // must be before any output
  $username = $_SESSION['username']; // or whatever you called it
  // check that $username is valid here (safe to display)
?>
html here
Hello <?= $username ?>!

A: As the sessions are handled by PHP, it needs PHP to maintain the state. You need at least session_start() to use the session variables stored in $_SESSION.

A: You can't put php into .html files without playing around with your server's configuration files.  You should only put php into .php files.
If you have a lot of .html files, you can simply rename them to .php files.  It's okay to put pure html into something.php.  So, you should make sure that all of your files end with .php, and then you can put any session logic you want into them.


text:
Q: python3: variable length values inside {} for print & .format() Is there a way to create a formatted string in python with flexible {} adjustments?
The default way is:
In [1]: "{:20}Hey B! You are {} blocks away.".format("Hey A!", 20-6)
Out[1]: 'Hey A!              Hey B! You are 14 blocks away.'

But is there a way to code the "distance between A and B" flexible? Like this..?
#not working
In [2]: x = 20
In [3]: "{:x}Hey! You are {} blocks away.".format("Hey! A", x-6)
Out[3]: 'Hey A!              Hey B! You are 14 blocks away.'

In [2]: x = 30
In [3]: "{:x}Hey! You are {} blocks away.".format("Hey! A", x-6)
Out[3]: 'Hey A!                        Hey B! You are 14 blocks away.'

Or is there any other way simple and convenient way to accomplish it?

A: Python allows nested formatting operators. When operating positionally, each positional argument is counted by where its open brace appears. So to use x for justifying "Hey! A" as desired, you can do:
"{:{}}Hey! You are {} blocks away.".format("Hey! A", x, x-6)
   ^^ These brackets fill in the desired width using the second positional arg

If you want to avoid thinking about the numbering in this case, you can name the argument providing the width, passing it via keyword, e.g. width:
"{:{width}}Hey! You are {} blocks away.".format("Hey! A", x-6, width=x)

You can see more examples under "Nesting arguments and more complex examples" here.

A: This isn't pretty, but it's one way:
x = 20

("{:"+str(x)+"}Hey! You are {} blocks away.").format("Hey! A", x-6)

# 'Hey! A              Hey! You are 14 blocks away.'

Alternative syntax:
''.join(("{:", str(x), "}Hey! You are {} blocks away.")).format("Hey! A", x-6)


text:
Q: Error when loader.load() I´m struggling to figure out what is the problem, I receive the following error when trying to do
FXMLLoader loader = new FXMLLoader(getClass().getResource("/leftBar.fxml"));
    Parent root = loader.load();

Error message:
 Exception in Application start method
 Exception in thread "main" java.lang.RuntimeException: Exception in       Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
at java.lang.Thread.run(Thread.java:745)
Caused by: javafx.fxml.LoadException:
/C:/onfocusproject/target/resources/main/leftBar.fxml:11

at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601)
at javafx.fxml.FXMLLoader.access$700(FXMLLoader.java:103)
at javafx.fxml.FXMLLoader$ValueElement.processAttribute(FXMLLoader.java:932)
at javafx.fxml.FXMLLoader$InstanceDeclarationElement.processAttribute(FXMLLoader.java:971)
at javafx.fxml.FXMLLoader$Element.processStartElement(FXMLLoader.java:220)
at javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:744)
at javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2707)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2527)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2409)
at tutorial.Application.initScreen(Application.java:74)
at tutorial.Application.start(Application.java:57)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
... 1 more
Caused by: java.lang.InstantiationException: tutorial.controller.impl.ControllerImpl
at java.lang.Class.newInstance(Class.java:427)
at sun.reflect.misc.ReflectUtil.newInstance(ReflectUtil.java:51)
at javafx.fxml.FXMLLoader$ValueElement.processAttribute(FXMLLoader.java:927)
... 18 more
Caused by: java.lang.NoSuchMethodException: tutorial.controller.impl.ControllerImpl.<init>()
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.newInstance(Class.java:412)
... 20 more

The structure of the project is the following

Many thanks for your help.


text:
Q: WordPress Symfony Co-habitation We have a site that runs on Symfony and that was developed by people much more competent that myself. I am however quite competent in WordPress and will be installing a blog on a the site.
Currently, the root of the site runs on Symfony but I would like for WordPress to take over without having to touch the Symphony core. Essentially, I would like to install WordPress in a sub directory of the www directory, say www/wordpress/ and have htaccess point to that directory as the root of my domain. BUT, there is one function of my Symfony installation I would like to still have access to, lets call it myfeature. When I go to mydomain.com/myfeature/ I would like for htaccess to point to mydomain.com/index.php/myfeature which is run by Symphony.
Here's what my current .htaccess file looks like.
<IfModule mod_rewrite.c>
  RewriteEngine On

  # we skip all files with .something
  RewriteCond %{REQUEST_URI} \..+$
  RewriteCond %{REQUEST_URI} !\.html$
  RewriteCond %{REQUEST_URI} !\.php
  #RewriteCond %{REQUEST_URI} !\.php
  RewriteRule .* - [L]

  # we check if the .html version is here (caching)
  RewriteRule ^$ /index.html [QSA]
  RewriteRule ^([^.]+)$ /$1.html [QSA]
  RewriteCond %{REQUEST_FILENAME} !-f

  # no, so we redirect to our front web controller
  RewriteRule ^(.*)$ /index.php [QSA,L]

  # hidden frontoffice controller
  RewriteRule ^index\.php/(.*)$ /index.php [QSA,L]
  # fo controllers
  RewriteRule ^frontend\.php/(.*)$ /frontend.php [QSA,L]
  RewriteRule ^frontend_dev\.php/(.*)$ /frontend_dev.php [QSA,L]
</IfModule>

Thank You

A: Here you go. I don't think anything below the wordpress controller line will ever be reached, but I left it in anyway
<IfModule mod_rewrite.c>
RewriteEngine On

# we skip all files with .something
RewriteCond %{REQUEST_URI} ..+$
RewriteCond %{REQUEST_URI} !.html$
RewriteCond %{REQUEST_URI} !.php
#RewriteCond %{REQUEST_URI} !.php
RewriteRule .* - [L]

# we check if the .html version is here (caching). If yes, don't redirect
RewriteRule ^$ /index.html [QSA]
RewriteRule ^([^.]+)$ /$1.html [QSA]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule .* - [L]

# if the 'myfeature' prefix is there, redirect to Symfony controller
RewriteCond %{REQUEST_URI} ^/myfeature/
RewriteRule .* index.php [QSA,L]

# otherwise, redirect to wordpress controller
RewriteRule .* wordpress/index.php [QSA,L]

# hidden frontoffice controller
RewriteRule ^index.php/(.*)$ /index.php [QSA,L]
# fo controllers
RewriteRule ^frontend.php/(.*)$ /frontend.php [QSA,L]
RewriteRule ^frontend_dev.php/(.*)$ /frontend_dev.php [QSA,L]
</IfModule>

A: I integrated a wordpress blog with my symfony site using the following.
//Added to the autoload.php
require('../vendor/wordpress/wp-blog-header.php');

I installe the blog into the main web folder and the .htaccess was set as follows,
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !/blog -------Add this condition to by pass the rewrite rules
RewriteRule ^(.*)$ app.php [QSA,L]

This allows all of the other routes to be accessed as normal but the blog routes are left untouched and passed directly to wordpress. To pull things from the wordpress database i was able to call the wordpress methods in my symfony controllers and pass it to my twig template.
$posts = get_posts('numberposts=10&order=ASC&orderby=post_title');
return array('posts'=>$posts);

I am not sure if this is exactly what you are asking but it is how my wordpress blog and Symfony 2.0 site co-exist. It is a real pain though I have a wordpress template and a Symfony template that must be kept updated. I really wish I could come up with a better solution to bring these to great tools together.


text:
Q: Left a domain and now I can't log in Left the domain because of a trust issue and now windows tries to use the domain login instead of letting me input the local admin user, what should I do?
There is no "Other user" on the corner and i can't change the user, its only asking for a password.
I have switched utilman and cmd in the meanwhile to try to join the admin through netdom join but it requires admin rights.

A: Making windows enforce to input the username fixed this. Guide


text:
Q: How to check if cookies value available on dynamically load page(infinite scroll) I need to change the font-size of content on click of a button and store them in a cookie, the code is working for page load on the first time but I have infinite scroll on the website and next page is not get the value from the cookie and font-size show in the default value.
I tried putting all code all inside (document)on('ready', function) or window.on(load)
 var Cookie = "fontsize";
$(document).ready(function () {

    var fontsize = $.cookie(Cookie) || 'normal';

    if (fontsize == "normal") {
        $(".td-post-content p").css({
            "font-size": "20px"
        });
         console.log(fontsize + "normal state")
    }
    else  {

       $( '.td-post-content p' ).css( 'font-size', $.cookie("fontsize") + "px");
       console.log(fontsize + "else state")
    };
});

function getSize() {
    if (Cookie){
        size =  $( '.td-post-content p' ).css( 'font-size', $.cookie("fontsize") + "px");
        size = parseInt(size, 10);
    }
        size = $('.td-post-content p').css( "font-size");
        size = parseInt(size, 10);
    }

    getSize()
    console.log(size + "after getsize")

    $('#contentsWrapper').on( "click", "#up", function() {
      if ((size + 1) <= 26) {
        $( ".td-post-content p" ).css( "font-size", "+=1" );
        $( "#font-size" ).text(  size += 1 );
      }
       $.cookie(Cookie, fontsize = size, {expires: 365, path: '/', domain  : ''});
       console.log(size);
    });

    $('#contentsWrapper').on( "click", "#down", function() {
      if ((size - 1) >= 16) {
        $( ".td-post-content p" ).css( "font-size", "-=1" );
        $( "#font-size" ).text(  size -= 1  );
      }
       $.cookie(Cookie, fontsize = size, {expires: 365, path: '/', domain  : ''});
       console.log(size);
});

A: Here is an example of using a cookie value to update a style tag.
Essentially, on page load you retrieve the cookie value and create a  tag to target your page content via CSS rules. That way it still applies to items which are loaded in later.
When you click the buttons, you need to update the cookie and then refresh the style tag.
JS
var cookie = "fontsize";

var getFontSize = function(){
    var value = parseInt($.cookie(cookie))
  return  value||20;
}

var changeFontSize = function(direction){
  var newSize = Math.min(25, Math.max(15, getFontSize()+direction))
  $.cookie(cookie, newSize, {expires: 365, path: '/', domain  : ''});
  updateFontSize(newSize)
}
var updateFontSize = function(fontsize){
  var style = $('#font_size_style')
  if(!style.length){
    style = $('


text:
Q: How can I access code from linked list into my queue for function addproduct in queue, how can I access the Node * head from the list, so I can add all the item from the linked list into my queue, any help given will be much appreciated thank you. Like in class linkedlist i can access all the pointer use in class Node, but why can't i access the head in linkedlist in the queue.
class List;

class Node{
int data;
string food_name;
int price;
int quantity;

public:
Node* next;

//initialization list
//assignment operator
//constructor
Node(int d,string f_name, int p, int q){
    this->data = d;
    this->food_name = f_name;
    this->price = p;
    this->quantity = q;
    this->next = NULL;
}

//to access the private member in the Node
friend class List;
friend class Queue;
};

class List{
Node * head;
Node * tail;

public:

//empty constructor
List():head(NULL),tail(NULL){}

Node* begin(){
    return head;
}

void push_front(int data, string food_name, float price, int quantity){
    if(head==NULL){
        Node*n= new Node(data,food_name, price, quantity);
        head = tail = n;
    }
    else{
        Node*n = new Node(data,food_name, price, quantity);
        n->next = head;
        head = n;
    }
}

void push_back(int data, string food_name, float price, int quantity){
    if(head==NULL){
        Node*n= new Node(data,food_name, price, quantity);
        head = tail = n;
    }
    else{
        Node*n = new Node(data,food_name, price, quantity);
        tail->next = n;
        tail = n;
    }
}

void insert(int data, string food_name, float price, int quantity, int pos){
    //pos = position
    if(pos==0){
        push_front(data,food_name, price, quantity);
        return;
    }

    //otherwise
    Node* temp = head;
    for(int jump=1; jump<=pos-1;jump++){
        temp = temp->next;
    }
    Node *n = new Node(data,food_name, price, quantity);
    n->next = temp->next;
    temp->next = n;
}

}
friend class Queue;
};

class Queue{
public:
    Node * front;
    Node * rear;

    Queue(){
        front = NULL;
        rear = NULL;
    }

    bool isEmpty(){
        if(front==NULL && rear==NULL){
            return true;
        }
        else{
            return false;
        }
    }

    bool checkProductExist(int choice){
        Node *temp = front;
        bool exist = false;
        while(temp!=NULL){
            if(temp->data == choice){
                exist=true;
                break;
            }
            temp=temp->next;
        }
        return exist;
    }

    //enqueue
    void addproduct (int choice{
        Node *n = head;
        while(n->data != choice){
            n=n->next;
        }

        if(isEmpty()){
            front = n;
            rear = n;
            cout<<"Node Enqueue successfully"<<endl;}
        else{
            if(checkProductExist(choice)== true){
                Node * temp = front;
                while(temp->data!=choice){
                    temp=temp->next;
                }
                temp->quantity+=1;
                cout<<"Quantity +1"<<endl;
            }
            else{
                rear->next = n;
                rear = n;
                //top =n;
                rear->next=NULL;
                cout<<"Node Enqueue successfully"<<endl;
            }

        }

    }
    friend class List;
};


text:
Q: How do I check if two linear binary codes are equivalent? Suppose I have a list of generator matrices $G_i$, $i=1,\ldots N$, of the same size (each defines an $n$-bit linear binary code encoding $k$ logical bits).
I consider two codes to be equivalent if they contain the same codewords, or if they differ by permutation of the physical bits. This means that, if $G'$ is a generator matrix obtained from $G$ by permutation of columns, or elementary row operations (adding and subtracting rows), then $G'$ defines a code equivalent to the code defined by $G$. I believe this is the standard notion of equivalence.
I want to prune my list of generator matrices to contain only inequivalent codes. One way to partially prune is to put each matrix in reduced row echelon form, and then just delete duplicates, but that doesn't take into account column swaps. Is there a simple way to also take into account column swaps?
If the best solution is exponential time, that is also OK, but I'd like to know what it is.

A: There is a nice overview of this problem in the beginning of the following paper by Sendrier and Simos which is a good place to start.
Essentially the problem is harder than Graph Isomporphism (see p.5 of linked paper). The following is a quote.

Due to its relation to Graph Isomorphism, some researchers have tried to
  solve the Permutation Code Equivalence problem by interpreting graph
  isomorphism algorithms to codes. This approach, was followed in [5] using the
  fact that ELC orbits of a bipartite graph correspond to equivalence classes of
  binary linear codes. Mapping codes to graphs and using the software Nauty
  by B. D. McKay has been used in [19], for binary, ternary and quaternary
  codes where the permutation, linear and semi-linear equivalence was considered, respectively

References cited above:

*Danielsen, L.E., Parker, M.G.: Edge local complementation and equivalence of binary linear codes. Designs Codes Cryptography: 49, 161–170 (2008)

*Ostergard, P.R.J.: Classifying subspaces of hamming spaces. Designs Codes Cryptography: 27, 297–305 (2002)


text:
Q: Sending mail from HTML page with image in the body I have to bring up the outlook compose box when a button is pressed and the body should contain the image of a specific DIV.
I am using html2canvas to capture the image, with mailto i am able to fire a outlook compose mail instance but seems mailto is for simple plain text and is not supporting to embed image in the mailbox.
Any ideas, thoughts?

A: TL;DR: You cannot do this.

You can use Data URI Scheme to embed an image in HTML. If an emails MIME type is text/html you can do the same. You will have to encode your image with a suitable encoding (e.g.: base64).
For example:

However, you cannot include HTML in the body part of the mailto: URL. The content of the body parameter is considered plain-text as per RFC 2368.

The special hname "body" indicates that the associated hvalue is the body of the message. The "body" hname should contain the content for the first text/plain body part of the message. The mailto URL is primarily intended for generation of short text messages that are actually the content of automatic processing (such as "subscribe" messages for mailing lists), not general MIME bodies.

So if you use a URL encoded HTML as the body parameter of a mailto: URL, here is what happens:

Write Email!

Result:


text:
Q: How to create a pageContext in google app engine? To create a page context programmatically in our servlets we do the following:
JspFactory factory = JspFactory.getDefaultFactory();

PageContext pageContext = factory.getPageContext(this, request, response,
            "404", true, 4096, false);

This works fine on tomcat and the dev gae environment. However when deploying the app to the live environment  JspFactory.getDefaultFactory() returns null.
Header of web.xml has the following:
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

Does anyone know how to create a PageContext programmatically on google app engine?

A: Read it somewhere. Google APP Engine looks to use Tomcat behind.This looks like a bug. A workaround would be is set the default factory using
Class.forName("org.apache.jasper.compiler.JspRuntimeContext");


text:
Q: Extracting Date from a URL sub string So Im trying to extract Data from a URL substring.........
But I keep running into issues with referencing my data variables "reference error: data is not defined" and none of the data is appearing.
Anyone have any thoughts were Im messing up ???

body {margin: 0px; background: white url(back.jpg) repeat-y scroll 0px 0px}
#head {position: absolute; top: 0px; left: 130px; background-color: black; padding: 0px; width: 100%;
       padding: 0px}
#links {position: absolute; top: 105px; left: 0px}
#edge {position: absolute; top: 105px; left: 130px}

#main {position: absolute; top: 120px; left: 160px; width: 510px;
       font-family: Arial, Helvetica, sans-serif}

#main p {font-size: 9pt}
#main #intro {text-align: right}

table#summary {width: 510px; font-size: 9pt; padding: 5px;
               border-top: 1px solid black;
               border-bottom: 1px solid black}
table#summary h3 {margin: 0px}

td {vertical-align: top}
<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

   <title>Conference Summary Page</title>
   <link href="summary.css" rel="stylesheet" type="text/css" />

      10th Annual Conference of Computer Graphics and Image Processing

         University of Colorado, Boulder

         March 3 - March 7

         Conference Fee: $145

Registration Summary

         Total Conference Cost:

         Name:

         Address:

        E-mail:

         Phone:

        Attending Banquet ($30 per person):

        ACGIP Member (save $25):

Print this page and retain it for your records.


text:
Q: ROOT installation on mac OS El Capitan in Continuous Integration After ROOT installation using brew on mac OS El Capitan with the following code from travis file:
brew update > /dev/null;
brew install xz;
brew install homebrew/science/root;
source $(brew --prefix root)/libexec/thisroot.sh;

the following error occurs (build https://travis-ci.org/yandex/rep/jobs/168399771):
/usr/local/opt/root/libexec/thisroot.sh: line 45: shell_session_update: command not found

This leads to an error of importing ROOT in python:
python -c 'import ROOT'
Fatal Python error: PyThreadState_Get: no current thread

The source of the error, maybe, is the rvm. The following recipes of adding (first, second)
echo 'shell_session_update' > $HOME/.bash_logout;

or
echo 'shell_session_update() { :; }' > $HOME/.direnvrc;

both do not work.
Do you have any ideas how to fix this? Thanks in advance.


text:
Q: Android - Images from Assets folder in a GridView I have been working on creating a Grid View of images, with images being present in the Assets folder. Opening a File from assets folder in android link helped me with using the bitmap to read it. The code am currently having is:
 public View getView(final int position, View convertView, ViewGroup parent)
{

  try
    {
     AssetManager am = mContext.getAssets();
     String list[] = am.list("");
     int count_files = imagelist.length;
     for(int i= 0;i<=count_files; i++)
     {
      BufferedInputStream buf = new BufferedInputStream(am.open(list[i]));
      Bitmap bitmap = BitmapFactory.decodeStream(buf);
      imageView.setImageBitmap(bitmap);
      buf.close();
     }
   }
   catch (IOException e)
   {
   e.printStackTrace();
   }
  }

My application does read the image from the Assets folder, but it is not iterating through the cells in the grid view. All the cells of the grid view have a same image picked from the set of images. Can anyone tell me how to iterate through the cells and still have different images ?
I have the above code in an ImageAdapter Class which extends the BaseAdapter class, and in my main class I am linking that with my gridview by:
    GridView  gv =(GridView)findViewById(R.id.gridview);
    gv.setAdapter(new ImageAdapter(this, assetlist));

Thanks a lot for any help in advance,
Saran

A: No need to read all the items every time. Read only the item at the position given in getView method call. And display only that item that time.
BufferedInputStream buf = new BufferedInputStream(am.open(list[position]));

A: Saran, below is what I use to show images in the assets folder with the gallery. I imagine it's the same deal with a gridview:
public class myActivitye extends Activity
{
    private Gallery mGallery;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mGallery = (Gallery) findViewById(R.id.mygalleryinxml);

        //load images into memory
        mBitArray = new Bitmap[4];
        try
        {
            //these images are stored in the root of "assets"
            mBitArray[0] = getBitmapFromAsset("pic1.png");
            mBitArray[1] = getBitmapFromAsset("pic2.png");
            mBitArray[2] = getBitmapFromAsset("pic3.png");
            mBitArray[3] = getBitmapFromAsset("pic4.png");
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

        mGallery.setAdapter(new GalleryAdapter(this, mBitArray));
    }

    public class GalleryAdapter extends BaseAdapter
    {
        //member variables
        private Context mContext;
        private Bitmap[] mImageArray;

        //constructor
        public GalleryAdapter(Context context, Bitmap[] imgArray)
        {
            mContext = context;
            mImageArray = imgArray;
        }

        public int getCount()
        {
            return mImageArray.length;
        }

        public Object getItem(int position)
        {
            return position;
        }

        public long getItemId(int position)
        {
            return position;
        }

        //returns the individual images to the widget as it requires them
        public View getView(int position, View convertView, ViewGroup parent)
        {
            final ImageView imgView = new ImageView(mContext);

            imgView.setImageBitmap(mImageArray[position]);

            //put black borders around the image
            final RelativeLayout borderImg = new RelativeLayout(mContext);
            borderImg.setPadding(20, 20, 20, 20);
            borderImg.setBackgroundColor(0xff000000);//black
            borderImg.addView(imgView);
            return borderImg;
        }

    }//end of: class GalleryAdapter

    /**
     * Helper Functions
     * @throws IOException
     */
    private Bitmap getBitmapFromAsset(String strName) throws IOException
    {
        AssetManager assetManager = getAssets();

        InputStream istr = assetManager.open(strName);
        Bitmap bitmap = BitmapFactory.decodeStream(istr);
        istr.close();

        return bitmap;
    }
}


text:
Q: re-order data after split in R I have used the split function to group my data with the results as follow:
$H1050
     row.names    Avg  Tree
1071      1904 2.8530 H1050
1072      1905 2.4030 H1050
1073      1906 1.6030 H1050
1074      1907 1.7660 H1050
1075      1908 2.5150 H1050

$H1040
     row.names    Avg  Tree
1737       1664 4.3200 H1040
1738       1665 4.0900 H1040
1739       1666 5.3100 H1040
1740       1667 4.8000 H1040
1741       1668 3.7000 H1040
1742       1669 4.0400 H1040
1743       1670 4.2800 H1040

There are around 36 groups in total.  I am then looping through this data to plot each individual data group.  I would like to be able to re-order the split data by the number of elements in the row.names column.  For example, count the number of elements in the row.names column and then the group with the highest number should be at the top and descending accordingly.
What is the best approach here?
Thanks very much for your time and effort!

A: Something like this (assuming a list named l):
num.row.names = lapply(l, function(x) length(unique(x$row.names)))
num.row.names = do.call(c, num.row.names)
l = l[order(num.row.names, decreasing=T)]

If row.names is the names of the rows in the split data frames instead of a variable in the data frames (I'm not clear which it is from the OP), you would replace the first line with:
num.row.names = lapply(l, function(x) length(unique(row.names(x))))

A: Assuming splat is your split data set:
  splat[order(sapply(splat, function(x) length(x[["row.names"]])))]


text:
Q: Does ITextRenderer supporting base64 images while genarating pdf? public static void generatePdf(OutputStream os)
        throws IOException, DocumentException,
        com.lowagie.text.DocumentException {

    ITextRenderer renderer = new ITextRenderer();
    String buffer="";
    renderer.setDocumentFromString(getEscapedString(buffer));
    renderer.layout();
    renderer.createPDF(os, true);
    renderer.finishPDF();
    os.flush();
    os.close();
    log.info("---------------------End generatePdf method---------------------");
}


text:
Q: HTML5 URL Input Box without Protocol When you use a input type of url instead of the standard text. Firefox 4 will not submit the form without http:// or https:// in the input box.
All I'm after is a URL without the protocol such as www.google.com not http://www.google.com. Is there a parameter to do this or any other way (preferably without JavaScript)?

A: use the html5 novalidate attribute on the form, e.g.
<form method="post" novalidate>
   ...
</form>

this will give you the nice keyboard on mobile devices and let you do your own validation
https://www.w3.org/TR/html5/sec-forms.html#element-attrdef-form-novalidate

A: I use RegExr for all my regular expression creation needs.  They have a number of pre-defined regular expressions.
You might be able to reverse engineer this a little:
(https?://)?(www\.)?([a-zA-Z0-9_%]*)\b\.[a-z]{2,4}(\.[a-z]{2})?((/[a-zA-Z0-9_%]*)+)?(\.[a-z]*)?


text:
Q: ¿Cómo saber si mi app está en segundo plano? Estoy haciendo una app donde estoy reproduciendo un sonido de fondo. Pero si por alguna razón el usuario presiona el botón de "HOME", la app entra en segundo plano pero este sonido se sigue reproduciendo.
Me gustaría saber si hay algun modo de saber el estado en que se encuentra mi app para cuando ésta esté en segundo plano pausar la reproducción, y al volver, reanudar la reproducción.

A: Existe los metodos onPause y onResume. El primero se ejecutara cuando el usuario presione el boton HOME o baje la aplicacion, mientras que el segundo se ejecutara cuando el usuario vuelva a la aplicacion.
Estos métodos también se ejecutan cuando la aplicacion se inicia por primera vez y cuando la Activity se cierra. No se si existe la manera directa de solo el caso particular, pero podrias trabajar con variables boolean para identificar cuando entra por primera vez para asi no pausar el audio

A: En base a esta pregunta:
Saber la aplicacion que esta en primer o segundo plano en Android
Te da idea de como saber si tu aplicación esta en primer o segundo plano, puedes saber si tu aplicación esta en "segundo plano" mediante el método onPause():
@Override
protected void onPause() {
    super.onPause();
    //La app esta en segundo plano (background).
}

Esto lo puedes ver en el diagrama del ciclo de vida de tu Actvity:

A: Revisa el ciclo de vida de la actividades. Siempre cuando una actividad deja ser de primer plano, se llama a onPause(), seguido por onStop() en el caso que la actividad ya no esta visible (por ser completamente tapado o sacado de la vista en el caso de tocar HOME). Luego volviendo a la vista se llaman a onRestart(), onStart() y onResume().
En el enlace encuentras un diagrama útil para visualizar este flujo de trabajo en Android.

A:
Indica si su aplicación se está ejecutando en FOREGROUND

https://developer.android.com/reference/android/app/ActivityManager.RunningAppProcessInfo#IMPORTANCE_FOREGROUND_SERVICE
private boolean isExecute() {
        ActivityManager activityManager = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> processInfos = activityManager.getRunningAppProcesses();

        for (ActivityManager.RunningAppProcessInfo info : processInfos) {

            if (BuildConfig.APPLICATION_ID.equalsIgnoreCase(info.processName) && ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND == info.importance)
                return true;
        }
        return false;

}


text:
Q: Line by Line Printing in Java I want to print a page line by line on Dotmatrix Printer (Epson LQ-300 Printer).Which means, I will send a line of some text to printer and after a break I will send another, now both the lines should be on one page not on two pages.
Please show me how I can achieve this.
Regards.

A: You will probably need a communications library first - parallel or serial ports.
There is a rather old Sun implementation from Java 1.2 days, but we still use it successfully with Java 5. The interfaces are defined in the javax.comm package. Use that as a starting point.
As you do not provide more information on your situation, the following is somewhat vague but hopefully helpful anyway:
Com/Serial and parallel ports are depending on the platform, requiring a piece of native code. For Linux there is the RxTx project providing an implementation.
Then you will just write data to the port, once you opened it with the appropriate parameters (there is a port enumerator) according to the protocol the printer understands. For most Epson printers this is the ESC/P(2) standard. Printing multiple lines of plain text should be as easy as printing them to the screen once the set up is complete.

A: To be honest, I've never tried sending a printer myself, but I did some googling (did you?) and this tutorial looks promising.
Now, regarding the latter request, you simply want to construct a text buffer that you send your text into, and which can dump its contents to the printer at a later point. Please correct me if I oversimplified your problem =)


text:
Q: How to add an element into a specific position of a list, using Scheme? This is the code I have so far. I believe that I'm close, but what returns is just #procedure, acknowledging that a procedure has created, it does not return the list with the newly added element. I have  been working on this for hours and I am at a loss of where I have gone wrong.
(define (add-into new p lst)
  (cond ((null? lst)
         (cons new lst)
        ((eq? p 0)
         (cons new lst)
        (else
         (cons (car lst) (add-into (- p 1) new (cdr l))))))))

A: You have parentheses problems, in one place you passed l instead of lst and the order of the parameters is incorrect when doing the recursive call. This should fix the errors:
(define (add-into new p lst)
  (cond ((null? lst)
         (cons new lst))
        ((= p 0)
         (cons new lst))
        (else
         (cons (car lst) (add-into new (- p 1) (cdr lst))))))

A: Just pasting the code into DrRacket and pressing CTRL+i and I get this:
(define (add-into new p lst)
  (cond ((null? lst)
         (cons new lst)
         ((eq? p 0)
          (cons new lst)
          (else
           (cons (car lst) (add-into (- p 1) new (cdr l))))))))

Notice that you only have one term. If (null? lst) is #f there are no more terms in the cond so it will evaluate to a implementation defined value as it is it is undefined in the specification. In #lang racket that value is the same as returned if you evaluate (void)
To fix it you need to close the terms in the cond so that you have 3 terms instead of one. You should have seen this when you press enter that the parentheses didn't align to the previous term. If you want to use another editor you should get one that aligns and indent lisp syntax as writing lisp without is slightly painful.


text:
Q: Overflow for background color of text I applied background color to the links in my country list. It works well in general:

However, for the countries which have longer name, it doesn't work very well.

I'm trying to make the yellow color overflow everything and show country's full name clearly.
HTML:

 ...

 ...

 ...

...

CSS:
.flagColumn {
    width: 33%;
    float: left;
    border:0px solid;
    height:1.6em;
    overflow:hidden;
    white-space:nowrap;
    text-overflow:ellipsis;
    z-index: 1; position:relative;
}

.flagColumn:hover {
   overflow:visible;
   z-index: 2; position:relative;
   display: inline;
   background-color:yellow;
}

A: You can do this by wrapping the content of .flagColumn in an extra element, setting it to display: inline-block; and setting the background on that instead:

.flagColumn {
    float: left;
    height: 1.6em;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 33%;
    z-index: 1;
}
.flagColumn:hover {
    overflow: visible;
    position: relative;
    z-index: 2;
}
.flagColumn:hover span {
    background-color: yellow;
    display: inline-block;
    height: 100%;
}

This is test text!

This is a lot longer test text! This is a lot longer test text!

This is a lot longer test text! This is a lot longer test text!

JS Fiddle: http://jsfiddle.net/hL9qfuvb/1/


text:
Q: git error - failed to push some refs (pack-objects died with strange error) I'm getting an odd error when I try to push to a new remote repository. I'm a git newbie, but following some tutorials, I was able to setup a few test repositories on a remote server and push to them. But the main repository I want to push up is giving me trouble. Here's what I did.
On the remote server I created a new directory. I then initialized a bare git repository inside that directory. On my machine I added the remote, and then I pushed to remote site. It looked like it was working, but after a little while I came back and found this error.

Counting objects: 4364, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (4240/4240), done.
error: pack-objects died with strange error | 44 KiB/s
error: failed to push some refs to 'mysite:main_site_repo'

What could be wrong? In this repository, I do have a few media files (about 40MB each). Could they be a problem? I don't get any timeout errors, but I do see that it makes it through about 44MB before failing. Is there a way to have git spit out debug info?
Also I accidentally let this repository fall off the main branch and made a few commits while not on any branch. I merged everything back into the main branch and am now working from there again, but could this be the source of the problem?
git version on my computer: 1.6.4.4
git version on server: 1.6.2.3

A: Do you have any large binary file? Git does not handle large binary files well.
It is running out of memory. Try to disable delta and try again.
Use:
*.iso  binary -delta

in your .gitattribute, where *.iso is your large file name

A: Thanks to everyone for the responses. I will remember to check those things the next time something like this happens. It turns out though that this time the issue was caused by the server I was pushing to killing my long running process as part of a security precaution. I've chatted with the administrator and he's updated it so my push will work now.
Thanks again to everyone for all the help.

A: I've often received this error as a result of a permissions error where some files in the object directory are owned by the wrong user. This happens if you push to a repository locally as one user but push to that same repository remotely (over SSH) as a different user, as is often the case with gitosis. But the situation can happen in other contexts as well.

A: Unfortunately, the error message is rather vague and can point to a number of issues. The most common problem is that the version of Git on the remote server is different from the version used to push locally. I noticed that your local version of Git is 1.6.4.4, and the remote version is 1.6.2.3. Upgrade the Git version on the server to 1.6.4.4 and see if the problem goes away.


text:
Q: Can I move or hide the unity panel so my browser tabs appear at the very top of the screen? I really like Ubuntu, but one minor annoyance I've always had with it is that, when using a web browser that places its tabs at the top of the application (Chrome in my case, though Firefox does this too), the unity panel (bar at the top of the screen) prevents the browser tabs from being placed at the very top of the screen. This makes it marginally more difficult for me to position my mouse over the tabs, as I have to worry about my mouse's vertical positioning instead of just pushing it all the way to the top of the screen as I do on Windows.
Is there a way to hide this annoying bar or move it to the bottom of the screen so my browser tabs can utilize that valuable piece of screen real-estate instead of it being wasted on menu items I rarely use? (Or alternately, a solution like this would also be acceptable.)

A: That feature is not available on the unity desktop. You can, however, install another desktop environment.
lubuntu-desktop, gnome-session-fallback, xubuntu-desktop, and ubuntu-studio-desktop offer either autohide or in the case of gnome-session fallback there is a hide function you can click an arrow to hide the top panel.
For ubuntu-studio, xubuntu, and lubuntu you can right click on the panel, choose panel properties and there should be an autohide function somewhere in the options.

A: Press F11 in the browser to put it in full screen mode.


text:
Q: bad argument 'PREROUTING' setting up Home Assistant on UBUNTU virtual machine. Trying to forward port from gateway to virtual machine. I need to put the IP in range of the rest of my network. In terminal:
iptables -t -I PREROUTING -p tcp --dport 80 -j DNAT --to [address here]

I'm getting a "bad argument" for PREROUTING and Google is not helping.
Any ideas?


text:
Q: How to set captured images in portrait mode I am working on a application in which I have given facility to user that he can take a picture using his mobile camera and then I am displaying the image in a Imageview.
Now the problem is that if I am capturing the image in a portrait mode or in landscape mode it is always setting the image in landscape mode in ImageView, but I want the image to be set in portrait mode only. Please help me out with this problem.
Any help would be appreciable...
Thank you

A: Matrix mat = new Matrix();

ExifInterface exif = new ExifInterface(yourimagepath);
String orientstring = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
int orientation = orientstring != null ? Integer.parseInt(orientstring) : ExifInterface.ORIENTATION_NORMAL;
int rotateangle = 0;
if(orientation == ExifInterface.ORIENTATION_ROTATE_90)
            rotateangle = 90;
if(orientation == ExifInterface.ORIENTATION_ROTATE_180)
            rotateangle = 180;
if(orientation == ExifInterface.ORIENTATION_ROTATE_270)
            rotateangle = 270;

mat.setRotate(rotateangle, (float) bmpPic.getWidth() / 2, (float) bmpPic.getHeight() / 2);

File f = new File(yourimagepath);
Bitmap bmpPic = BitmapFactory.decodeStream(new FileInputStream(f), null, null);
Bitmap bmpPic1 = Bitmap.createBitmap(bmpPic, 0, 0, bmpPic.getWidth(), bmpPic.getHeight(), mat, true);

A: use like that
Matrix matrix=new Matrix();
imageView.setScaleType(ScaleType.MATRIX);   //required
matrix.postRotate((float) angle, pivX, pivY);
imageView.setImageMatrix(matrix);

for exp:
matrix.postRotate( 90f, imageView.getDrawable().getBounds().width()/2, imageView.getDrawable().getBounds().height()/2)

A: Here is a great solution I came across for this:

https://stackoverflow.com/a/34241250/8033090

One line solution:
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);

or
Picasso.with(context).load("file:" + photoPath).into(imageView);

This will autodetect rotation and place image in correct orientation
Picasso is a very powerful library for handling images in your app includes: Complex image transformations with minimal memory use. It can take a second to load but I just put some text behind the image view that says "Loading image" and when the image loads it covers the text.


text:
Q: Display php echo in another html file I have a php file with the following code:
echo($x);

Which simply prints
5.0

How would I display this value in a html file?

A: You can use any HTML manipulation APIs, like DOMDocument class. But, just to get you started, I assume you have a very simple HTML file:

And you want to put the value of the $x variable inside the  tag using a
 tag; simply:
<?php
$dom = new DOMDocument;
$HTML_file = "paht/to/your/file.html";
$dom->loadHTMLFile($HTML_file);

// To get the  tag in the HTML file
$xpath = new DOMXPath($dom);
$body = $xpath->query('//body')->item(0);

// Insert some tags inside the  tag
$x = 5;
$element = $dom->createElement('div', $x);
$body->appendChild($element);

// overwrites to the same file
$dom->saveHTMLFile($HTML_file);
?>


text:
Q: GORM bidirectional One-to-Many I'm trying to create a bidirectional one-to-many relationship between Foo and Bar domains in GORM.
Here's what I have so far:
class Bar {
   static belongsTo = [foo: Foo]
}

class Foo {
   Set bars = []
   static hasMany = [bars: Bar]
}

The problem that I'm having is when I go to use the relationship methods, they don't seem to behave the way that I think they should.  For example, you would think a statement like "foo.bars.add(bar)" would also set the foo field on the bar argument.  But when I call "bar.foo.id" I'm told that the foo field is null.  I can fix that problem if I use "bar.foo = foo" instead of "foo.bars.add(bar)".  Unfortunately, when I call "foo.bars.size()" it tells me that it is 0.
To get a clearer picture of what I'm talking about, here are my tests:
def testFoo() {
   def foo = new Foo()
   def bar = new Bar()

   foo.bars.add(bar)

   println "foo.bars.size() = ${foo.bars.size()}"
   println "bar.id = ${bar.id}"

   for(def xbar : foo.bars) {
      println "bar.id = ${xbar.id}"
   }

   println "foo.id = ${foo.id}"
   println "bar.foo.id = ${bar?.foo?.id}" // <- is null
}

def testBar() {
   def foo = new Foo()
   def bar = new Bar()

   bar.foo = foo

   println "foo.bars.size() = ${foo.bars.size()}" // <- is 0
   println "bar.id = ${bar.id}"

   for(def xbar : foo.bars) {
      println "bar.id = ${xbar.id}"
   }

   println "foo.id = ${foo.id}"
   println "bar.foo.id = ${bar?.foo?.id}"
}

What am I doing wrong?
Note: I'm running this through an integration test.  I've also found that "foo.addToBars(bar)" works the way that I think "foo.bars.add(bar)" and "bar.foo = foo" should work.
Update Here's a quick hack I did that does what I want (using Hibernate and JPA):
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.LinkedList;

import stuff.Foo;

public class MyList<Bar> extends LinkedList {

   private Foo foo;

   public MyList(Foo foo) {
      this.foo = foo;
   }

   @Override
   public boolean add(Object obj) {
      boolean result = super.add(obj);

      try {
         Method barMethod = obj.getClass().getDeclaredMethod("setFoo", Foo.class);
         barMethod.invoke(obj, foo);
      }
      catch(NoSuchMethodException noSuchMethod) {
         noSuchMethod.printStackTrace();
      }
      catch(InvocationTargetException invocationTarget) {
         invocationTarget.printStackTrace();
      }
      catch(IllegalAccessException illegalAccess) {
         illegalAccess.printStackTrace();
      }

      return result;
   }
}

A: If you read the documentation, you'll learn that, as you found out but are still questioning, the correct way to add items to a collection so they are persisted correctly is to use the addTo* methods.
So in your case, when you said that using addToBars worked, that's the right way to do this.  That said, there are some performance hits you take with that.  Another way is to do:
bar.foo = foo
bar.save()

The downside is that foo will not contain bar in its existing Set.  You'd have to pull it from the database again.  It's a bit of a give and take and you just use the best method for your situation.


text:
Q: How to autohide stalonetray? I'm using stalonetray to hold nm-applet. Is there a way to hide it after a wifi network is selected?
Or maybe with key bindings?
(ubuntu + xmonad)

A: You don't need stalonetray and nm-applet to select a wifi network. You can list wifi networks on the command line using nmcli dev wifi and connect to a network using nmcli dev wifi connect SSID password PASSWORD.
Or you could set up keybindings to start the tray using stalonetray and stop it using killall stalonetray. The applet can cope with it.


text:
Q: How can I import module with custom context in jest? How can I import module with custom context in jest?
I've tried something like this:
Module.js

(function(_scope) {
    console.log(_scope.variable);
})(this);

Test.js

describe('test', () => {
    var module = require("Module.js");
});

A: i hope i understand you currectly
Module.js
exports.log = (scope) => { console.log(scope)};

Test.js
var module = require("./Module.js");

const dataToLog = "foo";
module.log(dataToLog);// foo

please press up arrow if you find that useful


text:
Q: What is the relationship between these two versions of BSD? The BSD conjecture is usually formulated like this.

If $E/\mathbf{Q}$ is an elliptic curve, then
$$ \text{rank }E/\mathbf{Q} = \text{ord}_{s=1} L(E,s), $$
where $L(E,s)$ is the Hasse-Weil $L$-function of $E$.

But in Anthony Knapp's book Elliptic Curves (see Conjecture 1.9 on page 17), there is an another more "elementary" formulation of BSD, given like this:

If $E/\mathbf{Q}$ is an elliptic curve, then
$$ \prod_{p<X} \dfrac{\#E(\mathbf{F}_p)}{p} \sim (\text{const}) (\log X)^r, $$
where $r = \text{rank }E/\mathbf{Q}$.

The main difference between the two versions of BSD is that the "analytic" sides are formulated differently. In the first version, the analytic quantity is $\text{ord}_{s=1}L(E,s)$. In the second version, the analytic quantity is the rate of growth of the product $\prod_{p<X} \dfrac{\#E(\mathbf{F}_p)}{p}$.
My question is: why are these two analytic quantities the same? That is, why is the exponent $r$ in the formula
$$\prod_{p<X}{} \dfrac{\#E(\mathbf{F}_p)}{p} \sim (\text{const})(\log X)^r$$
actually equal to $\text{ord}_{s=1} L(E,s)$?
The heuristic reason for this is that if we formally evaluate $L(E,s)$ at $s=1$ via the Euler product definition, we get
$$L(E,1) "=" \prod_{p<X} \dfrac{p}{\#E(\mathbf{F}_p)},$$
but this does not rigorously make sense because the Euler product definition only converges for $\text{Re }s> 3/2$. So is there a rigorous way to justify this phenomenon?

A: The $L$-function reformulation of BSD was given by Goldfeld here:

Goldfeld, Dorian. Sur les produits partiels eulériens attachés aux courbes elliptiques. (French) [On the partial Euler products associated with elliptic curves] C. R. Acad. Sci. Paris Sér. I Math. 294 (1982), no. 14, 471–474.

The proof is not too long, and it proceeds by showing the exponent $r$ in that product leads to a zero-free region for $L(E,s)$ of $Re(s) > 1+r$.  Interestingly, the formal manipulation to relate the BSD product to $L(E,1)$ is off by a factor of $\sqrt 2$!  See also

Conrad, Keith. Partial Euler products on the critical line. Canad. J. Math. 57 (2005), no. 2, 267–297.

for more about this issue.

A: The convergence can be established for $s=1$.
From https://en.wikipedia.org/wiki/Elliptic_curve#The_Birch_and_Swinnerton-Dyer_conjecture
we have
$$L(E(\mathbf{Q}), s) = \prod_{p\not\mid N} \left(1 - a_p p^{-s} + p^{1 - 2s}\right)^{-1} \cdot \prod_{p\mid N} \left(1 - a_p p^{-s}\right)^{-1}$$
Hasse Theorem gives $|\# E(K) - (q + 1) | \le 2\sqrt{q}$, hence $s>\frac32$.
However, a further argument (e.g. Sato-Tate conjecture) proves that the $a_p$ are evenly distributed about $0$, so that the function approximates the alternating zeta function instead of the zeta function.


text:
Q: Weird output for decipher function I have this function that decrypts a caesar encrypted message with a certain key and it gives me the right letters for the output but theres some weird blackspace after it.
Here's the function:
#include <iostream>
#include <string.h>
#include "proj1.h"
#include <cstdlib>
using namespace std;

int main()
{

  char dec[MAXMSGLEN];

  int i = 0;

  while(i < NUMMSGS){
    char solve = SolveCipher(cipher[i], dec);

      if(solve == '\0')
        {
          cout  << "Message #" << (i + 1) << " was not intertesting. " <<endl;
        }
      else
        {
          cout << "Message #" << (i + 1) << ",Key " << solve << endl;
          cout << "\t" << dec << endl;
        }

      i++;

  }

  return 0;
}

void Decipher(char cip[], char key){

  for(int i = 0; i < MAXMSGLEN && cip[i] != '\0'; i++){
    if (cip[i] != ' '){
      cip[i] = char(cip[i] - ((key - 'A')% 26));
      if (cip[i] < 65){
        cip[i] = ((65 - cip[i])-90);

      }

    }
    else{
      cip[i] = cip[i];
    }

  }
}

char SolveCipher(const char cip[], char dec[]){

  char msg[MAXMSGLEN];
  char check[MAXMSGLEN];
  char word[MAXCRIBLEN];

  //Deciphers message with every key
  for(char i = 'A'; i <= 'Z'; i++){

    //clears msg
    memset(msg, 0, (sizeof(msg)/sizeof(msg[0])));

    //stores cip in msg
    for(int j = 0; cip[j] != '\0'; j++){
      msg[j] = cip[j];
    }

    Decipher(msg, i);
    cout<< msg <<endl;
  }
  return '\0';
}

Here's the encrypted keys I have to loop through:
const char cipher[NUMMSGS][MAXMSGLEN] = {
  "HAAHJR HA KHDU AVTVYYVD",
  "DHFGS NBKNBJ ZMC ZKK HR VDKK",
  "Q PIDM JQMJMZ NMDMZ",
  "JCTFGT DGVVGT HCUVGT UVTQPIGT",
  "LRPYE I HTWW XPPE JZF LE ESP NZXXZYD",
  "KLSQ GML LGG DSLW YGL FGLZAF AF EQ TJSAF",
  "QEBC GUR ZVPEBSVYZ ORUVAQ GUR FGNGHR",
  "GZSGZWD NX XTRJBMJWJ JQXJ FY UWJXJSY",
  "RZVOCZM AJM OJHJMMJR HJMIDIB RVMH RDOC GJR XGJPYN",
  "ROBO MYWO LKN XOGC DKVUSXQ DRSC KXN DRKD"
};

And FYI I need to keep the parameters as they are now. I cannot change them to strings or anything like that.
If I brute force loop through the black spaces come inside the words
ROBO MYWO LKN XOGC DKVUSXQ DRSC KXN DRKD
QNAN LXVN KJM WNFB CJUTRWP CQRB JWM CQJC
PM▒M KWUM JIL VMEA BITSQVO BPQA IVL BPIB
OL▒L JVTL IHK ULD▒ AHSRPUN AOP▒ HUK AOHA
NK▒K IUSK HGJ TKC▒ ▒GRQOTM ▒NO▒ GTJ ▒NG▒
MJ▒J HTRJ GFI SJB▒ ▒FQPNSL ▒MN▒ FSI ▒MF▒
LI▒I GSQI FEH RIA▒ ▒EPOMRK ▒LM▒ ERH ▒LE▒
KH▒H FRPH EDG QH▒▒ ▒DONLQJ ▒KL▒ DQG ▒KD▒
JG▒G EQOG DCF PG▒▒ ▒CNMKPI ▒JK▒ CPF ▒JC▒
IF▒F DPNF CBE OF▒▒ ▒BMLJOH ▒IJ▒ BOE ▒IB▒
HE▒E COME BAD NE▒▒ ▒ALKING ▒HI▒ AND ▒HA▒
GD▒D BNLD A▒C MD▒▒ ▒▒KJHMF ▒GH▒ ▒MC ▒G▒▒
FC▒C AMKC ▒▒B LC▒▒ ▒▒JIGLE ▒FG▒ ▒LB ▒F▒▒
EB▒B ▒LJB ▒▒A KB▒▒ ▒▒IHFKD ▒EF▒ ▒KA ▒E▒▒
DA▒A ▒KIA ▒▒▒ JA▒▒ ▒▒HGEJC ▒DE▒ ▒J▒ ▒D▒▒
C▒▒▒ ▒JH▒ ▒▒▒ I▒▒▒ ▒▒GFDIB ▒CD▒ ▒I▒ ▒C▒▒
B▒▒▒ ▒IG▒ ▒▒▒ H▒▒▒ ▒▒FECHA ▒BC▒ ▒H▒ ▒B▒▒
A▒▒▒ ▒HF▒ ▒▒▒ G▒▒▒ ▒▒EDBG▒ ▒AB▒ ▒G▒ ▒A▒▒
▒▒▒▒ ▒GE▒ ▒▒▒ F▒▒▒ ▒▒DCAF▒ ▒▒A▒ ▒F▒ ▒▒▒▒
▒▒▒▒ ▒FD▒ ▒▒▒ E▒▒▒ ▒▒CB▒E▒ ▒▒▒▒ ▒E▒ ▒▒▒▒
▒▒▒▒ ▒EC▒ ▒▒▒ D▒▒▒ ▒▒BA▒D▒ ▒▒▒▒ ▒D▒ ▒▒▒▒
▒▒▒▒ ▒DB▒ ▒▒▒ C▒▒▒ ▒▒A▒▒C▒ ▒▒▒▒ ▒C▒ ▒▒▒▒
▒▒▒▒ ▒CA▒ ▒▒▒ B▒▒▒ ▒▒▒▒▒B▒ ▒▒▒▒ ▒B▒ ▒▒▒▒
▒▒▒▒ ▒B▒▒ ▒▒▒ A▒▒▒ ▒▒▒▒▒A▒ ▒▒▒▒ ▒A▒ ▒▒▒▒
▒▒▒▒ ▒A▒▒ ▒▒▒ ▒▒▒▒ ▒▒▒▒▒▒▒ ▒▒▒▒ ▒▒▒ ▒▒▒▒
▒▒▒▒ ▒▒▒▒ ▒▒▒ ▒▒▒▒ ▒▒▒▒▒▒▒ ▒▒▒▒ ▒▒▒ ▒▒▒▒

Any ideas on this one?

A: Your problem is that you are changing the values in a string "all the way" to the MAXMSGLEN. Now what happens is you decrypt the main body of the message (say 10 characters) and don't stop but keep on going, updating the values outside of range.
The fix is to stop once you see the "end-of-string" null-terminator '\0:
void Decipher(char cip[], char key){

    for(int i = 0; i < MAXMSGLEN && cip[i] != '\0'; i++){
    if (cip[i] != ' '){
      cip[i] = char(cip[i] - ((key - 'A')% 26));
      if (cip[i] < 65){
          cip[i] = ((65 - cip[i])-90);
        }
    }
  }
}

Or, if you prefer a more readable code (don't cram too much into the loops' control block):
void Decipher(char cip[], char key){

    for(int i = 0; i < MAXMSGLEN; i++){
    if(cip[i] == '\0'){
        break; // end the loop once we reached the string terminator
    }
    if (cip[i] != ' '){
      cip[i] = char(cip[i] - ((key - 'A')% 26));
      if (cip[i] < 65){
          cip[i] = ((65 - cip[i])-90);
        }
    }
  }
}

Update: Avoid using "magic numbers" like 65 and 90. your code would be way easier to understand if you use 'A' and 'Z' instead. Here's the fixed decypher function:
void Decipher(char cip[], char key){

    for(int i = 0; i < MAXMSGLEN; i++){
    if(cip[i] == '\0'){
        break; // end the loop once we reached the string terminator
    }
    if (cip[i] != ' '){
      cip[i] = char(cip[i] - ((key - 'A')% 26));
      if (cip[i] < 'A'){
          cip[i] = ('Z' - ('A' - cip[i])); // <-- this is where you were getting negative values
        }
    }
  }
}

A: Simply pass the string as a string:
void Decipher(std::string& cip, char key) {
  for (char& ch : cip) {
    if (ch != ' ') {
      ch = char(ch - ((key - 'A') % 26));
      if (ch < 65) {
        ch = ((65 - ch)-90);
      }
    }
  }
}

This way information about its length is also passed and you can simply do a range-based loop through the characters.


text:
Q: How to achieve test isolation testing Oracle PL/SQL? In Java projects, JUnit tests do a setup, test, teardown.  Even when mocking out a real db using an in-memory db, you usually rollback the transaction or drop the db from memory and recreate it between each test.  This gives you test isolation since one test does not leave artifacts in an environment that could effect the next test.  Each test starts out in a known state and cannot bleed over into another one.
Now I've got an Oracle db build that creates 1100 tables and 400K of code - a lot of pl/sql packages.  I'd like to not only test the db install (full - create from scratch, partial - upgrade from a previous db, etc) and make sure all the tables, and other objects are in the state I expect after the install, but ALSO run tests on the pl/sql (I'm not sure how I'd do the former exactly - suggestions?).
I'd like this all to run from Jenkins for CI so that development errors are caught via regression testing.
Firstly, I have to use an enterprise version instead of XE because of XE doesn't support java SPs and a dependency on Oracle Web Flow.  Even if I eliminate those dependencies, the build typically takes 1.5 hours just to load (full build).
So how do you acheive test isolation in this environment?  Use transactions for each test and roll them back?  OK, what about those pl/sql procedures that have commits in them?
I thought about backup and recovery to reset the db after each test, or recreate the entire db between each tests (too drastic).  Both are impractical since it takes over an hour to install it.  Doing so for each test is overkill and insane.
Is there a way to draw a line in the sand in the db schema(s) and then roll it back to that point in time?  Sorta like a big 'undo' feature.  Something besides expdp/impdp or rman.  Perhaps the whole approach is off.  Suggestions?  How have others done this?
For CI or a small production upgrade window, the whold test suite has to run with in a reasonable time (30 mins would be ideal).
Are there products that might help acheive this 'undo' ability?

A: In Oracle you can use Flashback Technology to restore the serve to a point back in time.
http://download.oracle.com/docs/cd/B28359_01/backup.111/b28270/rcmflash.htm

A: 1.5 hours seems like a very long time for 1100 tables and 400K of code.  I obviously don't know the details of your envrionment, but based on my experience I bet you can shrink that to 5 to 10 minutes.  Here are the two main installation script problems I've seen with Oracle:
1. Operations are broken into tiny pieces
The more steps you have the more overhead there will be.  For example, you want to consolidate code like this as much as possible:
Replace:
create table x(a number, b number, c number);
alter table x modify a not null;
alter table x modify b not null;
alter table x modify c not null;

With:
create table x(a number not null, b number not null, c number not null);

Replace:
insert into x values (1,2,3);
insert into x values (4,5,6);
insert into x values (7,8,9);

With:
insert into x
select 1,2,3 from dual union all
select 4,5,6 from dual union all
select 7,8,9 from dual;

This is especially true if you run your script and your database in different locations.  That tiny network lag starts to matter when you multiply it by 10,000.  Every Oracle SQL tool I know of will send one command at a time.
2.  Developers have to share a database
This is more of a long-term process solution than a technical fix, but you have to start sometime.  Most places that use Oracle only have it installed on a few servers.  Then it becomes a scarce resource that must be carefully managed.  People fight over it, roles are unclear, and things don't get fixed.
If that's your environment, stop the madness and install Oracle on every laptop right now.  Spend a few hundred dollars and give everyone personal edition (which has the same features as Enterprise Edition).  Give everyone the tools they need and continous improvment will eventually fix your problems.

Also, for a schema "undo", you may want to look into transportable tablespaces.  I've never used it, but supposedly it's a much faster way of installing a system - just copy and paste files instead of importing.  Similiarly, perhaps some type of virtualization can help - create a snapshot of the OS and database.

A: Kevin McCormack published an article on The Server Labs Blog about continuous integration testing for PL/SQL using Maven and Hudson.  Check it out.  The key ingredient for the testing component is Steven Feuerstein's utPlsql framework, which is an implementation of JUnit's concepts in PL/SQL.
The need to reset our test fixtures is one of the big issues with PL/SQL testing.  One thing which helps is to observe good practice and avoid commits in stored procedures: transactional  control should be restricted to only the outermost parts of the call stack.  For those programs which simply must issue commits (perhaps implicitly because they execute DDL) there is always a test fixture which issues DELETE statements.  Handling relational integrity makes those quite tricky to code.
An alternative approach is to use Data Pump.  You appear to discard impdp but Oracle also provides  PL/SQL API for it, DBMS_DATAPUMP.  I suggest it here because it provides the ability to trash any existing data prior to running an import.  So we can have an exported data set as our test fixture; to execute a SetUp is a matter of running a Data Pump job.  You don't need do do anything in the TearDown, because that tidying up happens at the start of the SetUp.

A: Although Oracle Flashback is an Enterprise Edition feature the technology it is based on is available in all editions namely Oracle Log Miner:
http://docs.oracle.com/cd/B28359_01/server.111/b28319/logminer.htm#i1016535
I would be interested to know whether anybody has used this to provide test isolation for functional tests i.e. querying v$LOGMNR_CONTENTS to get a list of UNDO statements from a point of time corresponding to the beginning of the test.
The database needs to be in archive mode and in the junit test case a method annotated with
@Startup

would call DBMS_LOGMNR.START_LOGMNR. The test would run and then in a method annotated with
@Teardown

would be query v$LOGMNR_CONTENTS to find the list of UNDO statements. These would then be executed via JDBC. In fact the querying and execution of the UNDO statements could be extracted into a PLSQL stored procedure. The order that the statements executed would have to be considered.
I think this has the benefit allowing the transaction to commit which is where an awful lot of bugs can creep in i.e. referential integrity, primary key violations etc.