text:
Q: O documento enviado não é um xml valido do eSocial Estou enviando este xml para o webservice do e-social mas apresenta sempre a mesma mensagem:
Tem como você me ajudar dando uma olhada ai no xml.
O documento enviado não é um xml valido do eSocial. Nao ha a tag com namespace http://www.esocial.gov.br/schema/lote/eventos/envio/v1_1_1 )
<?xml version="1.0" encoding="UTF-8"?><SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlnssd="http://www.w3.org/2001/XMLSchema" xmlnssi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns6153="http://tempuri.org"><SOAP-ENV:Body>
<eSocial xmlns="http://www.esocial.gov.br/schema/lote/eventos/envio/v1_1_1">
<envioLoteEventos grupo="1">
<ideEmpregador>
<tpInsc>1</tpInsc> <ideTransmissor> </ ideEmpregador>
<nrInsc> 23111341 </ nrInsc>
<tpInsc> 1 </ tpInsc>
<nrInsc> 23111341000190 </ nrInsc>
</ ideTransmissor>
<eventos>
<evento Id = "ID1231113410001902018030510140000001">
<eSocial xmlns = "http://www.esocial.gov.br/schema/ Evt / evtInfoEmpregador / v02_02_02 ">
<evtInfoEmpregador Id =" ID1231113410001902018030510140000001 ">
<ideEvento>
<tpAmb> 2 </ tpAmb>
<procEmi> 1 </ procEmi>
<verProc> 1.0 </ verProc>
</ ideEvento>
<ideEmpregador>
< tpInsc> 1 </ tpInsc>
<nrInsc> 23111341000190 </ nrInsc>
</ ideEmpregador>
<infoEmpregador>
<inclusao>
<idePeriodo>
<iniValid> 2018-03 </ iniValid>
</ idePeriodo>
<infoCadastro>
<nmRazao> NOME EMPRESA ME </ nmRazao>
<classTrib> 01 </ classTrib>
<natJurid> 2240 </ natJurid>
<indCoop> 0 </ indCoop>
<indConstr> 0 </ indConstr>
<indDesFolha> 0 </ indDesFolha>
<indOptRegEletron> 1 </ indOptRegEletron>
<multTabRubricas> N </ multTabRubricas>
<indEntEd> N </ indEntEd>
<indEtt> N </ indEtt>
<contato>
<nmCtt> Nome do Contato </ nmCtt>
<cpfCtt> 12345678909 < / cpfCtt>
<foneFixo> 1123452345 </ foneFixo>
<email> usuario@dominio.com.br </ email>
</ contato>
<softwareHouse>
<cnpjSoftHouse> 12345678000195</cnpjSoftHouse>
<nmRazao>Nome da Software House</nmRazao>
<nmCont>Nome do Contato</nmCont>
<telefone> 1123452345 </ telefone>
<email> usuario@dominio.com.br </ email>
</ softwareHouse
>
<infoComplementares>
<situacaoPJ> <indSitPJ> 0 </ indSitPJ>
</ situacaoPJ>
</ infoComplementares>
</ infoCadastro>
</ inclusao>
</ infoEmpregador>
</ evtInfoEmpregador>
<Assinatura xmlns = "http://www.w3.org/2000/09/xmldsig#">
<SignedInfo> <CanonicalizationMethod Algorithm = "http: // www .w3.org / TR / 2001 / REC-xml-c14n-20010315 "/>
<SignatureMethod Algorithm =" http://www.w3.org/2000/09/xmldsig#rsa-sha1 "/>
<Reference URI = "#">
< Transforma>
<Transform Algorithm = "http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
<Algoritmo de transformação = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
</ Transforms>
<DigestMethod Algorithm = "http://www.w3.org/2000/ 09 / xmldsig # sha1 "/>
<DigestValue> Haor6NuS2GAGAnwZaeTSjc4kgjo = </ DigestValue>
</ Reference>
</ SignedInfo> <SignatureValue> <SignatureValue> <KeyInfo> <X509Data> <X509Certificate> </ X509Certificate> </ X509Data> </ KeyInfo> </ Signature>
</ eSocial>
</ evento>
</ eventos>
</ envioLoteEventos>
</ eSocial> </ SOAP-ENV: Corpo> </ SOAP-ENV: Envelope>

A: Veja um XML correto do S-1000 (Informações do Empregador) para o eSocial:
<?xml version="1.0" encoding="utf-8"?>
<eSocial xmlns="http://www.esocial.gov.br/schema/lote/eventos/envio/v1_1_1">
  <envioLoteEventos grupo="1">
    <ideEmpregador>
      <tpInsc>1</tpInsc>
      <nrInsc>12345678</nrInsc>
    </ideEmpregador>
    <ideTransmissor>
      <tpInsc>1</tpInsc>
      <nrInsc>12345678000123</nrInsc>
    </ideTransmissor>
    <eventos>
      <evento Id="ID1123456780000002018031902284900001">
        <eSocial xmlns="http://www.esocial.gov.br/schema/evt/evtInfoEmpregador/v02_04_01">
          <evtInfoEmpregador Id="ID1123456780000002018031902284900001">
            <ideEvento>
              <tpAmb>2</tpAmb>
              <procEmi>1</procEmi>
              <verProc>1.0</verProc>
            </ideEvento>
            <ideEmpregador>
              <tpInsc>1</tpInsc>
              <nrInsc>12345678</nrInsc>
            </ideEmpregador>
            <infoEmpregador>
              <inclusao>
                <idePeriodo>
                  <iniValid>2016-01</iniValid>
                </idePeriodo>
                <infoCadastro>
                  <nmRazao>NOME DA EMPRESA</nmRazao>
                  <classTrib>01</classTrib>
                  <natJurid>2240</natJurid>
                  <indCoop>0</indCoop>
                  <indConstr>0</indConstr>
                  <indDesFolha>0</indDesFolha>
                  <indOptRegEletron>0</indOptRegEletron>
                  <indEntEd>N</indEntEd>
                  <indEtt>N</indEtt>
                  <contato>
                    <nmCtt>Nome do Contato</nmCtt>
                    <cpfCtt>12345678901</cpfCtt>
                    <foneFixo>1123456789</foneFixo>
                    <email>usuario@dominio.com.br</email>
                  </contato>
                  <softwareHouse>
                    <cnpjSoftHouse>12345678000123</cnpjSoftHouse>
                    <nmRazao>NOME DA EMPRESA</nmRazao>
                    <nmCont>Nome do Contato</nmCont>
                    <telefone>1123456789</telefone>
                    <email>usuario@dominio.com.br</email>
                  </softwareHouse>
                  <infoComplementares>
                    <situacaoPJ>
                      <indSitPJ>0</indSitPJ>
                    </situacaoPJ>
                  </infoComplementares>
                </infoCadastro>
              </inclusao>
            </infoEmpregador>
          </evtInfoEmpregador>
          <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
            <SignedInfo>
              <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
              <SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />
              <Reference URI="">
                <Transforms>
                  <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
                  <Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
                </Transforms>
                <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />
                <DigestValue> [...] </DigestValue>
              </Reference>
            </SignedInfo>
            <SignatureValue> [...] </SignatureValue>
            <KeyInfo>
              <X509Data>
                <X509Certificate> [...] </X509Certificate>
              </X509Data>
            </KeyInfo>
          </Signature>
        </eSocial>
      </evento>
    </eventos>
  </envioLoteEventos>
</eSocial>

Assim você pode ver o que está errado no seu XML.


text:
Q: Reading variables into cmake from another CMakeLists.txt Using Ubuntu, C++ and cmake, I want to create a program Alpha which is based upon code for another program,Beta. I already have the source code for Beta, and I need to write code for Alpha which uses this existing code. I am trying to keep everything neat, so I have a separate directory for Alpha and Beta source files, Alpha.cpp and Beta.cpp.
Here is my directory structure:
/CMakeLists.txt
/Alpha.cpp (the main function)
/Beta
    /CMakeLists.txt
    /Beta.cpp

My CMakeLists.txt file for Alpha looks like this:
cmake_minimum_required(VERSION 2.8)
project(Alpha)
add_executable(Alpha Alpha.cpp Beta/Beta.cpp)

Now, in the original code for Beta, the CMakeLists.txt file has lots of information, such as checking the operating system, finding packages, and generally defining various cmake variables. I need to use those variables in the CMakeLists.txt file for Alpha, so that Beta.cpp is compiled properly.
So, my question: is it possible to retain all of this information in Beta/CmakeLists.txt, without having to write it all out in Alpha's CMakeLists.txt file? How do I then tell Alpha's CMakeLists.txt file to read Beta's CMakeLists.txt file to get these variables? I want to do this to keep everything neat, and to maintain modularity. Thanks!

A: CMake has an include construct which will allow you to pull in other files/modules.
http://www.cmake.org/cmake/help/v3.0/command/include.html
So you could separate out whatever you need from Beta/CMakeLists.txt into another file/module called Beta.cmake and include it in Alpha's CMakeLists with include (Beta/Beta.cmake).
So your directory structure would be
/CMakeLists.txt
/Alpha.cpp (the main function)
/Beta
    /CMakeLists.txt
    /Beta.cmake (variables required in Alpha's CMake)
    /Beta.cpp

And the Alpha's CMakeList.txt
cmake_minimum_required(VERSION 2.8)
project(Alpha)
include(Beta/Beta.cmake) (get variables needed from Beta)
add_executable(Alpha Alpha.cpp Beta/Beta.cpp)

Also see How to include an additional CMakeLists.txt

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to handle callbacks in Node.js? Let's say I have 3 files.
index.js makes a call to the backend like this
$.post('/test/', data, function(response) {
 //handle success here
})

routes.js handles the route like this
app.post('/test/', function(req, res){
   item.getItems(function(response){
     res.json(response);
   });
 });

items.js is the model which accesses the database and makes a POST request for each item
function getItems(callback) {
  database.query('SELECT * from items', function(result){
    result.forEach(function(item){
        request.post('/api/', item, function(req, res) {
          //finished posting item
        });
    });
  });
  //callback here doesnt wait for calls to finish
}

where/when should I call the callback passed to getItems() to handle a success/failure in index.js?

A: Because your request.post() operations are async, you have to use some method of keeping track of when they are all done and then you can call your callback.  There are multiple ways of doing that.  I'll outline a few:
Manually Keeping Track of Count of Request Operations
function getItems(callback) {
  database.query('SELECT * from items', function(result){
    var remaining = result.length;
    result.forEach(function(item){
        request.post('/api/', item, function(err, res) {
          --remaining;
          //finished posting item
          if (remaining === 0) {
              callback();
          }
        });
    });
  });
}

The main problem with doing this manually is that propagating error in nested async operations is difficult when you get to actually figuring out how you're going to handle errors.  This is much easier in the other methods shown here.
Using Promises
// load Bluebird promise library
var Promise = require('bluebird');

// promisify async operations
Promise.promisifyAll(request);

function queryAsync(query) {
    return new Promise(function(resolve, reject) {
        // this needs proper error handling from the database query
        database.query('SELECT * from items', function(result){
            resolve(result);
        });
    });
}

function getItems(callback) {
    return queryAsync('SELECT * from items').then(function(result) {
        return Promise.map(result, function(item) {
            return request.postAsync('/api/', item);
        });
    });
}

getItems.then(function(results) {
    // success here
}, function(err) {
    // error here
})

A: It seems strange that you're making an API request in your server-side code, unless this is some sort of middle tier code that interacts with the API... but you're interacting with a database, so I'm still confused on why you can't just do a database insert, or have a bulk insert API call?
Anyway, if you must do it the way you're asking, I've done this in the past with a recursive method that trims down the result array... I really don't know if this is a good approach, so I'd like to hear any feedback.  Something like this:
function recursiveResult(result, successfulResults, callback) {
  var item = result.shift();
  // if item is undefined, then we've hit the end of the array, so we'll call the original callback
  if (item !== undefined) {
    console.log(item, result);
    // do the POST in here, and in its callback, call recursiveResult(result, successfulResults, callback);
    successfulResults.push(item);
    return recursiveResult(result, successfulResults, callback);
  }
  // make sure callback is defined, otherwise, server will crash
  else if (callback) {
    return callback(successfulResults);
  }
  else {
    // log error... callback undefined
  }
}

function getItems(callback) {
  var successfulResults = [];
  var result = [1, 2, 3, 4];
  recursiveResult(result, successfulResults, callback);
}

console.log('starting');
getItems(function(finalResult) {
  console.log('done', finalResult);
});


text:
Q: A couple of url paths not working anymore after creating class ProfileDetailView I am working on a social website and after creating a class to render the user's profile in detail. The path that render all posts and all profiles aren't working anymore and I get the same error and when I uncomment the code from line 21 to 24 (def get_object) function it says "Does Not Exist at /posts/"

Profile matching query does not exist.
Page not found (404)
No profile found matching the query
Request Method:   GET
Request URL:  http://127.0.0.1:8000/posts/
Raised by:    network.views.<class 'network.views.ProfileDetailView'>

Using the URLconf defined in project4.urls, Django tried these URL patterns, in this order:
admin/
[name='index']
login [name='login']
logout [name='logout']
register [name='register']
<slug>/ [name='profile-view']

The current path, posts/, matched the last one.
"
Urls:
urlpatterns = [
    path("", views.index, name="index"),
    path("login", views.login_view, name="login"),
    path("logout", views.logout_view, name="logout"),
    path("register", views.register, name="register"),
    path("<slug>/", ProfileDetailView.as_view(), name="profile-view"),
    path("posts/", post_comment_create_view, name="posts"),
    path("liked/", like_unlike_post, name="like-post-view"),
    path("<pk>/delete", PostDeleteView.as_view(), name="post-delete"),
    path("<pk>/update", PostUpdateView.as_view(), name="post-update"),
    path("invites/", invites_received_view, name="invites-view"),
    path("allprofiles/", ProfileListView.as_view(), name="all-profiles-view"),
    path("send-invite/", send_invitation, name="send-invite"),
    path("remove-friend/", remove_friends, name="remove-friend"),
    path("invites/accept/", accept_invitation, name="accept-invite"),
    path("invites/reject/", reject_invitation, name="reject-invite"),

]

Views:
from .models import Relationship, Post, Profile, Like
from django.views.generic import TemplateView, View, UpdateView, DeleteView, ListView, DetailView
from .forms import ProfileModelForm, PostModelForm, CommentModelForm

class ProfileDetailView(DetailView):
    model = Profile
    template_name = 'network/profile.html'

     def get_object(self, slug=None):
        slug = self.kwargs.get('slug')
       profile = Profile.objects.get(slug=slug)
         return profile

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        user = User.objects.get(username__iexact=self.request.user)
        profile = Profile.objects.get(user=user)
        rel_r = Relationship.objects.filter(sender=profile)
        rel_s = Relationship.objects.filter(receiver=profile)
        rel_receiver = []
        rel_sender = []
        for item in rel_r:
            rel_receiver.append(item.receiver.user)
        for item in rel_s:
            rel_sender.append(item.sender.user)
        context["rel_receiver"] = rel_receiver
        context["rel_sender"] = rel_sender
        context["posts"] = self.get_object().get_all_authors_posts()
        context["len_posts"] = True if len(self.get_object().get_all_authors_posts()) > 0 else False

        return context

class MyProfileView(TemplateView):
    template_name = 'network/my_profile.html'

def index(request):
    qs = Post.objects.all()
    context = {
        'hello': 'hello world!',
        'qs':qs,
    }
    return render(request, "network/index.html", context)

def profile_view(request):
    profile = Profile.objects.get(user=request.user)
    form = ProfileModelForm(request.POST or None, request.FILES or None, instance=profile)
    confirm = False

    if request.method == 'POST':
        if form.is_valid():
            form.save()
            confirm = True

    context = {
        'profile': profile,
        'form': form,
        'confirm': confirm,
    }
    return render(request, 'network/profile.html', context)

def invites_received_view(request):
    profile = Profile.objects.get(user=request.user)
    qs = Relationship.objects.invitations_received(profile)
    results = list(map(lambda x: x.sender, qs))
    is_empty = False
    if len(results) == 0:
        is_empty = True

    context = {
        'qs':results,
        'is_empty': is_empty,
    }

    return render(request, 'network/invites.html', context)

def accept_invitation(request):
    if request.method =='POST':
        pk = request.POST.get('profile_pk')
        sender = Profile.objects.get(pk=pk)
        receiver = Profile.objects.get(user=request.user)
        rel = get_object_or_404(Relationship, sender=sender, receiver=receiver)
        if rel.status == 'send':
            rel.status = 'accepted'
            rel.save()

    return redirect('invites-view')

def reject_invitation(request):
    if request.method=="POST":
        pk = request.POST.get('profile_pk')
        receiver = Profile.objects.get(user=request.user)
        sender = Profile.objects.get(pk=pk)
        rel = get_object_or_404(Relationship, sender=sender, receiver=receiver)
        rel.delete()
    return redirect('invites-view')

def invite_profiles_list_view(request):
    user = request.user
    qs = Profile.objects.get_all_profiles_to_invite(user)

    context = {'qs': qs}

    return render(request, 'network/to_invite_list.html', context)

def profiles_list_view(request):
    user = request.user
    qs = Profile.objects.get_all_profiles(user)

    context = {'qs': qs}

    return render(request, 'network/profile_list.html', context)

class ProfileListView(ListView):
    model = Profile
    template_name = 'network/profile_list.html'
    context_object_name = 'qs'

    def get_queryset(self):
        qs = Profile.objects.get_all_profiles(self.request.user)
        return qs

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        user = User.objects.get(username__iexact=self.request.user)
        profile = Profile.objects.get(user=user)
        rel_r = Relationship.objects.filter(sender=profile)
        rel_s = Relationship.objects.filter(receiver=profile)
        rel_receiver = []
        rel_sender = []
        for item in rel_r:
            rel_receiver.append(item.receiver.user)
        for item in rel_s:
            rel_sender.append(item.sender.user)
        context["rel_receiver"] = rel_receiver
        context["rel_sender"] = rel_sender
        context["is_empty"] = False
        if len(self.get_queryset()) == 0:
            context["is_empty"] = True

        return context

def send_invitation(request):
    if request.method == 'POST':
        pk = request.POST.get('profile_pk')
        user = request.user
        sender = Profile.objects.get(user=user)
        receiver = Profile.objects.get(pk=pk)

        rel = Relationship.objects.create(sender=sender, receiver=receiver, status='send')

        return redirect(request.META.get('HTTP_REFERER'))
    return redirect('profile')

def remove_friends(request):
    if request.method == 'POST':
        pk = request.POST.get('profile_pk')
        user = request.user
        sender = Profile.objects.get(user=user)
        receiver = Profile.objects.get(pk=pk)

        rel = Relationship.objects.get(
            (Q(sender=sender) & Q(receiver=receiver)) | (Q(sender=receiver) & Q(receiver=sender))
        )
        rel.delete()
        return redirect(request.META.get('HTTP_REFERER'))
    return redirect('profile')

def like_unlike_post(request):
    user = request.user
    if request.method == 'POST':
        post_id = request.POST.get('post_id')
        post_obj = Post.objects.get(id=post_id)
        profile = Profile.objects.get(user=user)

        if profile in post_obj.liked.all():
            post_obj.liked.remove(profile)
        else:
            post_obj.liked.add(profile)

        like, created = Like.objects.get_or_create(user=profile, post_id=post_id)

        if not created:
            if like.value=='Like':
                like.value='Unlike'
            else:
                like.value='Like'
        else:
            like.value='Unlike'

            post_obj.save()
            like.save()

    return redirect('posts')

def post_view_json(request):
    qs = Post.objects.all()
    data = serializers.serialize('json', qs)
    return JsonResponse({'data': data})

def profile_test_view(request):
    profile = Profile.objects.get(user=request.user)
    return render(request, "network/profile_test.html", {'profile':profile})

def post_comment_create_view(request):
    qs = Post.objects.all()
    profile = Profile.objects.get(user=request.user)

    #Setting up pagination
    p = Paginator(qs, 5)
    page = request.GET.get('page')
    post_list = p.get_page(page)

    #Post form, comment form
    p_form = PostModelForm()
    c_form = CommentModelForm()
    post_added = False

    profile = Profile.objects.get(user=request.user)

    if 'submit_pForm' in request.POST:
        print(request.POST)
        p_form = PostModelForm(request.POST, request.FILES)
        if p_form.is_valid():
            instance = p_form.save(commit=False)
            instance.author = profile
            instance.save()
            p_form = PostModelForm()
            post_added = True

    if 'submit_cForm' in request.POST:
        c_form = CommentModelForm(request.POST)
        if c_form.is_valid():
            instance = c_form.save(commit=False)
            instance.user = profile
            instance.post = Post.objects.get(id=request.POST.get('post_id'))
            instance.save()
            c_form = CommentModelForm()

    context = {
        'qs': qs,
        'profile': profile,
        'p_form': p_form,
        'c_form': c_form,
        'post_added': post_added,
        'post_list': post_list,
    }

    return render(request, 'network/posts.html', context)

class PostDeleteView(DeleteView):
    model = Post
    template_name = 'network/confirmDelete.html'
    success_url = reverse_lazy('posts')

    def get_object(self, *args, **kwargs):
        pk = self.kwargs.get('pk')
        obj = Post.objects.get(pk=pk)
        if not obj.author.user == self.request.user:
            messages.warning(self.request, 'You need to be the owner of the post in order to delete it!')
        return obj

class PostUpdateView(UpdateView):
    form_class = PostModelForm
    model = Post
    template_name = 'network/update.html'
    success_url = reverse_lazy('posts')

    def form_valid(self, form):
        profile = Profile.objects.get(user=self.request.user)
        if form.instance.author == profile:
            return super().form_valid(form)
        else:
            form.add_error(None, "You need to be the owner of the post in order to update it!")
            return super().form_invalid(form)


text:
Q: How to show products from prestashop in a wordpress post with API? I am working with Wordpress and for my shop I am using prestashop (seperated).
Now I want to show some products with basic informations like price, name, image-url in wordpress.
I dont want to access the database directly, but I want to use the prestashop api.
Question: Which file of pretashop I have to include to wordpress, that its possible to use the prestashop API and what is the basic code to show a products with the article number xxx? THX a lot guys!

A: You can do that with the PrestaShop web service. Here's the reference:
http://doc.prestashop.com/display/PS15/Using+the+PrestaShop+Web+Service
And here are some examples how to work with that web service:
https://github.com/PrestaShop/PrestaShop-webservice-lib/


text:
Q: Как изменить цвет Меню в Tkinter? Возможно ли изменить цвет меню в Tkinter? То есть в моём примере меню выглядит стандартно(код и скрин ниже), но хотелось бы изменить его под стилистику VS Code(см. скрин). Как это можно сделать?
Код
import tkinter as tk
from tkinter import ttk

root = tk.Tk()

menu = tk.Menu(root)
root.config(menu = menu)

menu.add_cascade(label='Привет')

root.mainloop()

Скрины
Меню моего примера:

Меню VS Code:

A: menu = tk.Menu(root, bg="#505050")

Попробуйте таким образом.

A: Попробуйте написать root.config(bg='Some color'). В кавычках напишите цвет:
hex или название.

A: root.iconbitmap('some-path') # Путь к иконке
root.title('Файл  Правка  Выделение  Вид  Переход  Выполнить  Терминал  Справка') # Фейковые кнопочки :D
root.config(bg='#404040') # Можно окрасить окно, но, к сожалению, не меню (хотя, возможно у вас будет по-другому)

Возможно, это вам поможет.


text:
Q: Weird Android Studio Lint error on paddingStart UPDATE: Solution: http://www.reddit.com/r/androiddev/comments/2p3khg/conflicting_lint_messages_regarding_paddingstart/
I have designed a layout in which I have used the following multiple times in different ImageView(s). and I never get an error.
android:paddingStart="5dp"

and
android:paddingEnd="5dp"

However when I used this on a TextView:
 <TextView
    android:id="@+id/blah1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:paddingLeft="5dp"
    android:paddingStart="5dp"
    android:textSize="12sp"
    android:textStyle="italic" />

I get a lint warning on android:paddingStart="5dp". Warning:

Attribute paddingStart referenced here can result in a crash on some specific devices older than API 17 (current min is 16)

The weird part is that I am using android:paddingEnd on the following textview and I don't get any warning.
<TextView
    android:id="@+id/blah2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentEnd="true"
    android:layout_alignParentRight="true"
    android:paddingEnd="5dp"
    android:paddingRight="5dp"
    android:textSize="12sp"
    android:textStyle="italic" />

A: Just wanted to mark this question as closed. The solution is posted in the question as well. Just to reiterate:
http://www.reddit.com/r/androiddev/comments/2p3khg/conflicting_lint_messages_regarding_paddingstart/
It is a kind of hack and maybe not worth it unless you have a sufficient user base.


text:
Q: for x in y(): how does this work? I was looking for code to spin a cursor in the terminal and found this. I was wondering what was happening in the code. In particular for c in spinning_cursor(): I've never seen this syntax. Is it because I am returning one element from a generator at a time with yield, and this is assigned to c? Any other examples of this for x in y() use?
import sys
import time

def spinning_cursor():
    cursor='/-\|'
    i = 0
    while 1:
        yield cursor[i]
        i = (i + 1) % len(cursor)

for c in spinning_cursor():
    sys.stdout.write(c)
    sys.stdout.flush()
    time.sleep(0.1)
    sys.stdout.write('\b')

A: Using yield turns a function into a generator. A generator is a specialized type of iterator. for always loops over iterables, taking each element in turn and assigning it to the name(s) you listed.
spinning_cursor() returns a generator, the code inside spinning_cursor() doesn't actually run until you start iterating over the generator. Iterating over a generator means the code in the function is executed until it comes across a yield statement, at which point the result of the expression there is returned as the next value and execution is paused again.
The for loop does just that, it'll call the equivalent of next() on the generator, until the generator signals it is done by raising StopIteration (which happens when the function returns). Each return value of next() is assigned, in turn, to c.
You can see this by creating the generator on in the Python prompt:
>>> def spinning_cursor():
...     cursor='/-\|'
...     i = 0
...     while 1:
...         yield cursor[i]
...         i = (i + 1) % len(cursor)
...
>>> sc = spinning_cursor()
>>> sc
<generator object spinning_cursor at 0x107a55eb0>
>>> next(sc)
'/'
>>> next(sc)
'-'
>>> next(sc)
'\\'
>>> next(sc)
'|'

This specific generator never returns, so StopIteration is never raised and the for loop will go on forever unless you kill the script.
A far more boring (but more efficient) alternative would be to use itertools.cycle():
from itertools import cycle

spinning_cursor = cycle('/-\|')

A: In Python, the for statement lets you iterate over elements.
According the documentation :

Python's for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence

Here, the element will be the return value of spinning_cursor().

A: The for c in spinning_cursor() syntax is a for-each loop. It's going to iterate through each item in the iterator returned by spinning_cursor().
The inside of the loop will:

*

*Write the character to standard out and flush so it displays.

*Sleep for a tenth of a second

*Write \b, which is interpreted as a backspace (deletes the last character). Notice this happens at the end of the loop so it won't be written during the first iteration, and that it shares the flush call in step 1.

spinning_cursor() is going to return a generator, which doesn't actually run until you start iterating. It looks like it will loop through '/-\|', in order, forever. It's kind of like having an infinite list to iterate through.
So, the final output is going to be an ASCII spinner. You'll see these characters (in the same spot) repeating until you kill the script.
/
-
\
|

A: the spinning_cursor function returns an iterable (a generator from yield).
for c in spinning_cursor():

would be the same as
 for i in [1, 2, 3, 4]:

A: Martijn Pieters explanation is excellent. Below is another implementation of the same code you had in the question. it uses itertools.cycle to produce the same result as spinning_cursor.  itertools is filled with excellent examples of iterators and functions to help create your own iterators. It might help you understand iterators better.
import sys, time, itertools

for c in itertools.cycle('/-\|'):
    sys.stdout.write(c)
    sys.stdout.flush()
    time.sleep(0.1)
    sys.stdout.write('\b')


text:
Q: Richfaces tree is giving me an "Uncaught ReferenceError tree is not defined" I believe my problem is in a settings file somewhere, but I have no idea what file/setting that would be.  I have a standalone project with a working tree, but when I try to integrate it with my real project I start getting the mentioned error.  That's what makes me think I have a setting somewhere that's off.
I'm using JSF1.2 and richfaces 3.3.3.   Here's my JSP file.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%-- jsf:pagecode language="java" location="/src/java/pagecode/agencyMappingPages/mapping/Mapping.java" --%><%-- /jsf:pagecode --%>
<%@page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@taglib prefix="rich" uri="http://richfaces.org/rich"%>
<html>
    <f:view>
        <body>
            <rich:tree switchType="client" value="#{mappingBean.nodes}" var="node">
            </rich:tree>
        </body>
    </f:view>
</html>

Here's my bean code:
public TreeNode<String> getNodes() {
    TreeNodeImpl<String> nodes = new TreeNodeImpl<String>();
    TreeNodeImpl<String> root = new TreeNodeImpl<String>();
    root.setData("Test Tree Root");
    nodes.addChild(0, root);

    return nodes;
}

I'm using the following jars.  These are also the three jars I'm using in the functioning version of my tree.
richfaces-api-3.3.3.Final.Jar
richfaces-impl-3.3.3.Final.Jar
richfaces-ui-3.3.3.Final.Jar

I've got the following in my web.xml file.
<filter>
   <display-name>RichFaces Filter</display-name>
   <filter-name>richfaces</filter-name>
   <filter-class>org.ajax4jsf.Filter</filter-class>
</filter>
<filter-mapping>
   <filter-name>richfaces</filter-name>
   <servlet-name>Faces Servlet</servlet-name>
   <dispatcher>REQUEST</dispatcher>
   <dispatcher>FORWARD</dispatcher>
   <dispatcher>INCLUDE</dispatcher>
</filter-mapping>
<servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>-1</load-on-startup>
</servlet>
<servlet>
    <servlet-name>JavaScript Resource Servlet</servlet-name>
    <servlet-class>com.ibm.faces.webapp.JSResourceServlet</servlet-class>
    <load-on-startup>-1</load-on-startup>
</servlet>
<servlet>
    <servlet-name>Tiles2Servet</servlet-name>
    <servlet-class>org.apache.tiles.web.startup.TilesServlet</servlet-class>
    <init-param>
        <param-name>org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG</param-name>
        <param-value>/WEB-INF/tiles20-defs.xml</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.faces</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>JavaScript Resource Servlet</servlet-name>
    <url-pattern>/.ibmjsfres/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
</welcome-file-list>

Not sure if this'll be helpful, but here's the javascript it chokes on.  I had to omit quite a bit because the form wouldn't submit.  I copied this from Chrome's developers window.  It throws the exception at the second line:  var tree = new tree......
<script type="text/javascript">(function() {
var tree = new Tree("j_id_jsp_1558828084_1", "j_id_jsp_1558828084_1:input", "client",
    {
    onselect: "",
    onexpand: "",
    oncollapse: "",
    oncontextmenu: ""
},
function(event) {var params = {'j_id_jsp_1558828084_1:selectedNode':event.selectedNode} ;
if (!params.ajaxSingle && event.ajaxSingle) {
params.ajaxSingle = event.ajaxSingle;
}

So, what necessary file/setting am I missing?
I'm sure I'm forgetting the most important piece of info which is why I need you.
Thanks,
Dale

A: So I figured out what the problem was.  For some reason Richfaces was not sending the script or styling files to the browser.  It dynamically puts the links in the head.
So I add the following filters to the web.xml file and everything is happy now including me and my partner.
<context-param>
    <param-name>org.richfaces.LoadStyleStrategy</param-name>
    <param-value>ALL</param-value>
</context-param>
<context-param>
    <param-name>org.richfaces.LoadScriptStrategy</param-name>
    <param-value>ALL</param-value>
</context-param>

Hopefully this helps someone else.


text:
Q: Impossible to browse web after configuring iptables I'm trying to configure iptables on my ubuntu computer. These are my rules:
Chain INPUT (policy DROP)
target     prot opt source               destination
ACCEPT     tcp  --  anywhere             anywhere             tcp    dpt:https
ACCEPT     tcp  --  anywhere             anywhere             tcp  dpt:http
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:domain
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:ftps-data
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:ftps

Chain FORWARD (policy DROP)
target     prot opt source               destination
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:https
ACCEPT     tcp  --  anywhere             anywhere             tcp     dpt:http
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:domain

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Unfortunately, when I try to use the web explorer, it  can not connect. Just a blank page continuously trying to load.
I tried sending a ping to www.google.com, but the connection can not be established.
Maybe should I leave more ports open?
[EDIT] I change the rules, these are my new ones:
Chain INPUT (policy DROP)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere             state      NEW,ESTABLISHED
ACCEPT     all  --  anywhere             anywhere             state RELATED,ESTABLISHED
ACCEPT     all  --  anywhere             anywhere

Chain FORWARD (policy DROP)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Now it works!! :) I hope it is secure enough. I guess that block all traffic except the established connections by myself

A: You're not letting any related connection in... Quick way to fix it...:
#iptables -I INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

P.S: sorry for posting in a rush, i'm in my way to work. I'll come back with details
Now, the details...
Every time you want to connect over TCP/IP, there's a "three way handshake". Let's say you want to connect to stackexchange.com (no firewall involved):

*

*Your computer sends the first frame (SYN), something like "hey, i want to connect to you!". This frame leaves your computer from a random high port (let's say 47122), through your OUTPUT chain, to stackexchange.com, port 80;

*stackexchange.com replies with the second frame flagged ACK and SYN, something like "I've received your request, we can connect". This second frame leaves stackexchange.com port 80, goes through your INPUT chain, to your TCP port 47122;

*Your computer replies with the third frame flagged ACK, something like "I've received your reply, I'll be sending data". This frame leaves your computer from the same port 47122, through your OUTPUT chain, to stackexchange.com, port 80.

The rest of the data will be sent through the created socket yourcomputer:47122 - stackexchange.com:80, going out through your OUTPUT chain and returning through INPUT chain.
Let's see how your firewall handles that connection:

*

*First frame passes your OUTPUT chain freely, no rule to filter it, default policy ACCEPT;

*Second frame is checked against each rule of your INPUT chain, does not matches any of them (you have rules to accept frames with dpt http, https...) and reaches the default policy DROP, and that's it... your connection attempt fails.

To fix that, in your INPUT chain, you either accept frames with source port 80 (not really safe...), or, considering iptables has connection tracking, you ACCEPT ESTABLISHED and RELATED connection (the rule I've posted above).
Also, I'll add some notes regarding your firewall:

*

*INPUT - you're accepting connections from any source to your http,https,domain,ftps-data,ftps. As long as you're not hosting the appropriate servers on this computer, I recommend removing this rules.

*FORWARD - again, you're accepting connections to be forwarded, by your computer, to a http server. As long as you're not sharing your internet connection or you're not hosting VMs, I recommend removing this rules.

A: Petry pretty much nails it.
Basically, your setup permits traffic to a http/https/ftp port, but does not accept traffic coming from that port -- so your query goes out, but the response gets dropped.
Like most modern firewalls (defined as "after 1995 or thereabouts") the linux firewall tracks connections and allows for state-based filtering.
The line iptables -I INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT works as a catch-all -- any traffic whose initiation was permitted by any of the other rules in your firewall setup will be allowed to proceed without requiring any further explicit rules on your end.


text:
Q: ES6 and Typescript, class function properties without constructor This is proper Typescript (or ES6 if you ignore the static typing):
class Greeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}

var greeter = new Greeter("world");

console.log( greeter.greet() ); //Hello world

But the following creates Hello undefined, how would you rewrite this in a way it would work? And, if that's not possible, what would be the alternative to achieve this?
I'm looking into passing variables directly to functions.
class Greeter {
    greet(greeting: string) {
        return "Hello, " + this.greeting;
    }
}

var greeter = new Greeter();

console.log( greeter.greet("world") ); //Hello undefined

UPDATE:
I'm referring to PHP like class usage like:
class Greeter {
    public function greet($greeting){
        return $greeting;
    }
}

A: You can pass variable into object to store while doing a call. And you may use it afterwards like below without passing a variable. And then you can change it with another call.
class Greeter {
    greet(greeting: string) {
      this.greeting = greeting || this.greeting;
      return "Hello, " + this.greeting;
    }
}

var greeter = new Greeter();

console.log( greeter.greet("world") ); //Hello world
console.log( greeter.greet() ); //Hello world
console.log( greeter.greet("es6") ); //Hello es6


text:
Q: Sending array of dictionaries as curl parameter I am trying to send an array of dictionaries as parameter of a curl request. I have an object that look like this :
{ "name" => "xxx", "age" => "xxx" }

I know that you can send arrays this way :
curl -X POST -d 'objects[]=xxx&objects[]=xxx' https://xxx.xx

But I do not know how to send dictionaries as content of the array. As a final result, I would like to access to params like this
Php :
$_POST["objects"]["name"]

Rails
params[:objects][:name]

A: I did not find a way to achieve that. The solution I used was to send a JSON parameter and then serialize it from my backend.


text:
Q: Objective C Resize UIImage with Interpolation Error I'm trying to have interpolate this image when resizing, yet I keep getting this error. What is the correct form for using Interpolationquality?
]1

A: It looks like interpolationQuality wasn't an proper parameter. I figured out that CMD+clicking on the method gives the proper parameters you can use :)


text:
Q: Darken/color a selected element (content-box) and add a check-mark-icon AngularJS My question is related I think to jquery, angularjs and bootstrap.
I am rendering information that is coming from the backend and is presented on the front end in the form of several boxes. I am trying to get an "element selection effect" that when someone clicks on one or more of the boxes the entire box gets darker (or preferably blue with some level of transparency) and an ok-checkmark appears on it. The element is actually a bootstrap Well with some content inside.
I currently have an onClick event that colors the background, but it is not enough. Unlike an image, that can be entirely darkened when changing the background color, with a well (or any content box) it just colors the background and the content is still visible. I also want to add that green checked-mark icon inside the box when clicked, but I do not know how to add elements on the fly after onClick event.
Here is my relevant pieces of code (simplified objects, no backend):

var app = angular.module('myApp', []);
app.controller('SelectCtrl', function($scope) {

  $scope.collections = [
    {text:'content collection1'},
    {text:'content collection2'}];
  $scope.selectBox = function(collection){

    collection.isclicked =! collection.isclicked;
    $("#well").click(function(){
      if (collection.isclicked){
        //$("div").append('');
      }
    });
  }
});
.well:hover{
  cursor:pointer;
  cursor:hand;
  color: #555;
  text-decoration: none;
  background-color: #C0C0C0;
}

.well {

 border-color:#8CC63F;
 float:left;
 margin-right: 20px;

}

.well-active {

 background-color:#3399ff;

}

.well-active:hover {

 background-color:#3399ff;

}

{{collection.text}}

So as I mentioned, the way it works now is that the selected wells change their background color, but that's it. How do I darken/color the entire well, including the content, and how do I add an icon on top of that background (inside the well) after mouse-click?

A: You could do an ng-show/ng-hide in elements inside of the well div:

      {{collection.text}}

This will show the content if the collection is not checked, and a check mark if the collection is checked.


text:
Q: Cannot implicitly convert type, an explicit conversion exists (are you missing a cast?) I've set up a ViewModel (was previously using a ViewBag) but I've encountered an error in the following code, I've researched it but haven't personally been able to figure out my issue:
public ActionResult Index(string category, string search)
    {
        ProductIndexViewModel viewModel = new ProductIndexViewModel();
        var products = db.Products.Include(p => p.Category);

        if (!String.IsNullOrEmpty(search))
        {
            products = products.Where(p => p.Name.Contains(search) ||
                    p.Description.Contains(search) ||
                    p.Category.Name.Contains(search));

            viewModel.Search = search;

        }

        viewModel.CatsWithCount = from matchingProducts in products
                                  where matchingProducts.CategoryID != null
                                  group matchingProducts by
                                  matchingProducts.Category.Name into
                                  catGroup
                                  select new CategoryWithCount()
                                  {
                                      CategoryName = catGroup.Key,
                                      ProductCount = catGroup.Count()
                                  };

        if (!String.IsNullOrEmpty(category))
        {
           products = products.Where(p => p.Category.Name == category);
        }

        viewModel.Products = products;
        return View(viewModel);
    }

The error occurs down the bottom in the line:
viewModel.Products = products;

The exact error is

"Cannot implicitly convert type
  'System.Linq.IQueryable<OnlineStore.Models.Product>' to
  'System.Linq.IQueryable<OnlineStore.ViewModels.ProductIndexViewModel>'.
  An explicit conversion exists (are you missing a cast?)"

I'm very new to using Visual Studio and was just wanting to know what I would have to do to fix this error.
EDIT:
ProductIndexViewModel:
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace OnlineStore.ViewModels
{
    public class ProductIndexViewModel
    {
        public IQueryable<ProductIndexViewModel> Products { get; set; }
        public string Search { get; set; }
        public IEnumerable<CategoryWithCount> CatsWithCount { get; set; }
        public string Category { get; set; }
        public IEnumerable<SelectListItem> CatFilterItems
        {
            get
            {
                var allCats = CatsWithCount.Select(cc => new SelectListItem
                {
                    Value = cc.CategoryName,
                    Text = cc.CatNameWithCount
                });
                return allCats;
            }
        }
    }
    public class CategoryWithCount
    {
        public int ProductCount { get; set; }
        public string CategoryName { get; set; }
        public string CatNameWithCount
        {
            get
            {
                return CategoryName + " (" + ProductCount.ToString() + ")";
            }
        }
    }
}````

A: The problem was in my ProductIndexViewModel class. I had
public IEnumerable<ProductIndexViewModel> Products { get; set; }

instead of
public IEnumerable<Product> Products { get; set; }

Thank you to everyone who answered.

A: Your Products seem wrong in the ProductIndexViewModel class
public class ProductIndexViewModel
{
    public IQueryable<ProductIndexViewModel> Products { get; set; }

*

*Products is an IQueryable, which doesn't really make sense, and probably should be a List<T> or IEnumerable<T>
Example
public List<ProductIndexViewModel> Products { get; set; }

*The generic parameter looks wrong, it likely should be Product or some ViewModel like ProductViewModel in the case of a ViewModel you will need to Select/Project to it

*You should probably be calling, ToList on the results

Example
viewModel.Products = products.ToList();


text:
Q: UIViewController not responding to NSNotifications I have a UIViewController that's not responding to NSNotifications. I'm sure the action that is kicked off by the notification works. What could be wrong with my setup?
I use a singleton to load a feedViewController from the AppDelegate's didFinishLaunching. This feedViewController keeps a reference to a deckViewController, and this deckViewController reliably sends the notifications to which the feedViewController should be observing. Yet the notifications are never received. I made sure that the singleton keeps a strong reference to the view controller that should be receiving the notifications.
In the singleton that holds a reference to the notification observer:
 // .h file
 @property (nonatomic) ROFeedViewController *feedViewController;

 // .m file
 _feedViewController = [[ROFeedViewController alloc] init];
    IIViewDeckController *deckController = [[IIViewDeckController alloc] initWithCenterViewController:_feedViewController leftViewController:leftController rightViewController:rightController];
    _feedViewController.deckController = deckController;

In notification observer (ROFeedViewControler):
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewDeckPanned:) name:@"ViewDeckPanned" object:_deckController];
    ...
}

- (void)viewDeckPanned:(NSNotification *)notification {
    float offset = [(NSNumber *)[notification object] floatValue];
    if (offset > 0) {
        _leftButton.transform = CGAffineTransformMakeRotation(offset * M_PI / 180.0);
    } else {
        _rightButton.transform = CGAffineTransformMakeRotation(offset * M_PI / 180.0);
    }
}

Notifications reliable get sent from the notification sender (IIViewDeckController):
- (void)notifyDidChangeOffset:(CGFloat)offset orientation:(IIViewDeckOffsetOrientation)orientation panning:(BOOL)panning {
    [self performDelegate:@selector(viewDeckController:didChangeOffset:orientation:panning:) offset:offset orientation:orientation panning:panning];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ViewDeckPanned" object:[NSNumber numberWithFloat:offset]];

}

A: You setup:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewDeckPanned:) name:@"ViewDeckPanned" object:_deckController];

Which means that you are listening to notification of name "ViewDeckPanned" that come from _deckController (since object: parameter is supposed to define the notification sender).
But, that the same time, you post notification:
[[NSNotificationCenter defaultCenter] postNotificationName:@"ViewDeckPanned" object:[NSNumber numberWithFloat:offset]];

and you tell that [NSNumber numberWithFloat:offset] is a sender. Since _deckController and instance of NSNumber do not match each other, you get no notification info in your observer.
Simple change would be to pass nil as object: parameter (in both places - where you add observer, and where you post notification), and if you want to pass NSNumber along with notification, then create userInfo dictionary that contains it.


text:
Q: Unity - Child Rotation and Scale error I'm saw some wierd responses from Unity when I tried to do these actions :
1- I've created a Plane, simply rotated it (-32,-19,-56) and scaled it (3.21,1,2.43)
2- I've created a child cube for that plane and rotated it (-30,39,-78) and scaled it (3.54,4.8,6.42)
This is the final result in editor :

Did I do something wrong???
Why collider and renderer performing differently??
Is this a Unity bug? I'm currently using Unity 2017.3.1p1

A: Yes, it is some kind of bug.
To avoid it, don't child the objects directly to a non-uniformly scaled parent. Instead, child this non-uniform object (the cube) to an empty object, which will be the parent of the plane too.
Since an empty object is scaled 1,1,1, childing other objects to it don't cause this problem.


text:
Q: Search for record in database "Java.lang.NullPointerExepton" I want to search for the id of a movie in a table of the database. I'm new to database connection and new to java as well.  This code doesn't have error in my form but I created a record of id '1' and always gives me this error "Java.lang.NullPointerExepton".
I have the record with that id but always have that error. Any help will be appreciated
Connection conn = null;
    ResultSet rs = null;
    PreparedStatement pst = null;

        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:

    String url = "jdbc:mysql://localhost:3306/project";
            String userid = "root";
            String password = "";

    try{
                String sql="SELECT Movie_idMovie FROM rental_movie"
                        + "WHERE Movie_idMovie =?";
                pst=conn.prepareStatement(sql);
                pst.setString(1, jTextField1.getText());
                rs=pst.executeQuery();
                if(rs.next()){
                    String add1=rs.getString("Movie_idMovie");
                    jTextField2.setText(add1);
                }
            }
            catch(Exception e){
                JOptionPane.showMessageDialog(null,e);
            }
        }

A: The problem here is this:
Connection conn = null;

String url = "jdbc:mysql://localhost:3306/project";
String userid = "root";
String password = "";

pst=conn.prepareStatement(sql);

You missed the important step of actually opening the connection, leaving conn null when you try and use it. Try adding the following, before you call conn.prepare...
conn = DriverManager.getConnection(url, userid, password);


text:
Q: Laravel 9 email verification Invalid Signature I've read all available solutions, but no chance. It always redirects to the 403 page with message (Invalid Signature).
Here is my route :
Auth::routes(['verify' => true]);

My env file :
APP_NAME='WebApp'
APP_ENV=local
APP_KEY=base64:V4/NjIiHJMalSGiXqCfzDJJVF4BfDwJ8Hnxr1M8I2Lc=
APP_DEBUG=true
APP_URL=http://127.0.0.1:8000

MAIL_MAILER=log
MAIL_HOST=mailhog
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"

But the provided link in log file is always invalid.
I'm using built in artisan sever php artisan serve
Update : This is the link in laravel.log file.
http://127.0.0.1:8000/email/verify/2/52e17b67fd82b0545bb4fbdc5748ed23104133c7?expires=3D1652547054&signature=3De8f38349c57d806fb67170ceee8e7300cbc40d61133e1f70c7929e843401db6a

I have tried php artisan key:generate and php artisan config:cache
The email is being send by laravel itself, I haven't customized anything.
Also I tried to override verify method provided by VerifiesEmails.php trait, but no chance. Here is what I did :
VerificationController.php :
public function verify(Request $request) {
    dd($request->fullUrl());
}

I got suspicious to the url according to some solutions but the url is all fine like above mentioned.

A: After struggling 9 hours with this and hitting my head against the wall; finally I found out that the SIGNATURE is fine, but when laravel logs it in laravel.log file, it corrupts the file content and prefixes the SIGNATURE with this 2 characters 3D.
This way everything breaks; I don't know why is this happening.
I won't delete this question in case others face this problem in future.

A: Man, you have just saved me this whole process.
In my case the PhpStorm also added = to the end of every line and 3D was also in expire=
Thank you very much

A: For anyone still running into this issue try configuring the TrustProxy middleware if you have a similar configuration to the below

*

*Have set URL::forceScheme('https'); in the boot method of AppServiceProvider

*Running laravel behind a reverse proxy

To get this working quickly, set the below in TrustProxies.php middleware.
protected $proxies = '*';

For more information on configuring the $proxies setting, check out the official Laravel documentation here

A: In my case, I was using Job Batches which have their own table in the database. There was an issue with one of the rows not having run and the exception message did mention BusBatch (something like that). To solve, I simply deleted the record from the database. Prior to noticing this issue, in Horizon, the batches tab would not get passed the loading circle. So if you're working with jobs and batches, this could be a lead.
I never encountered this problem before and seems like it could stem from many other things. Hope this is helpful.

A: In my case, my NGINX config was sending altered URLs, which was causing the signature verification to fail. I had copy/pasted from a different PHP site config, which was sending funny URL patterns.
More discussion: https://laracasts.com/discuss/channels/laravel/403-invalid-signature-every-time-i-try-to-verify-email-in-laravel-57
Corrected NGINX config:
location / {
    try_files $uri $uri/ /index.php?$query_string;
}

A: I had the same case as you, i tried the following and it worked
Find folder app/Http/Controllers/Auth/VerificationController.php
public function __construct()
    {
        $this->middleware('auth');
        // $this->middleware('signed')->only('verify'); // -> change
        $this->middleware('throttle:6,1')->only('verify', 'resend');
    }

I hope it helps you


text:
Q: How to link a Nuxt app to an API server in docker-compose I have two containers in my docker-compose.yml: frontend and server.
The frontend communicates to the API of the server via Apollo and uses process.env.VUE_APP_GRAPHQL_HTTP to get the http endpoint.
In the docker-compose.yml I have:
environment:
      HOST: 0.0.0.0
      VUE_APP_GRAPHQL_HTTP: 'http://server:4000/graphql'
      VUE_APP_GRAPHQL_WS: 'ws://server:4000/graphql'

Which works perfectly fine for server side rendering with NuxtJS. On the client side although I am getting an error:
OPTIONS http://server:4000/graphql net::ERR_NAME_NOT_RESOLVED

If I set VUE_APP_GRAPHQL_HTTP: 'http://localhost:4000/graphql' in docker-compose.yml it works on client side but not with server side rendering. I am getting ECONNREFUSED error then.
So the question is: how can I resolve the path to my API on server and client side with NuxtJS?
My complete docker-compose.yml
version: "3.7"
services:
  frontend:
    container_name: frontend
    image: node
    restart: unless-stopped
    command: npm run docker
    volumes:
      - ./frontend:/usr/src/app
      - ~/.ssh:/root/.ssh:ro
    working_dir: /usr/src/app
    ports:
      - "3000:3000"
    environment:
      HOST: 0.0.0.0
      VUE_APP_GRAPHQL_HTTP: 'http://server:4000/graphql'
      VUE_APP_GRAPHQL_WS: 'ws://server:4000/graphql'
    depends_on:
      - server
    networks:
      - app

  server:
    container_name: server
    image: node
    restart: unless-stopped
    command: npm run docker
    volumes:
      - ./server:/usr/src/app
      - ~/.ssh:/root/.ssh:ro
    working_dir: /usr/src/app
    ports:
      - "4000:4000"
    depends_on:
      - database
    environment:
      PORT: 4000
      DATABASE_URL: mongodb://database:27017
    networks:
      - app

  database:
    container_name: database
    image: mongo
    volumes:
      - ./data:/data/db
    ports:
      - "27017:27017"
    networks:
      - app

networks:
  app:

A: Probably not the best way but I solved it with special rules for server and frontend.
Load js file in apollo config  nuxt.config.js
    clientConfigs: {
      default: '~/plugins/apollo.js',
    },

plugins/apollo.js:
export default function(context) {
  let httpEndpoint = process.env.APOLLO_SERVER_HTTP || 'http://localhost:4000/graphql';
  let wsEndpoint = process.env.APOLLO_SERVER_WS || 'ws://localhost:4000/graphql';

  if (process.client) {
    httpEndpoint = process.env.APOLLO_CLIENT_HTTP || 'http://localhost:4000/graphql';
    wsEndpoint = process.env.APOLLO_CLIENT_WS || 'ws://localhost:4000/graphql';
  }

  return {
    httpEndpoint,
    httpLinkOptions: {
      credentials: 'same-origin',
    },
    wsEndpoint,
  };
}

pass variables via docker-compose:
    environment:
      HOST: 0.0.0.0
      APOLLO_SERVER_HTTP: 'http://server:4000/graphql'
      APOLLO_CLIENT_HTTP: 'http://localhost:4000/graphql'
      APOLLO_SERVER_WS: 'ws://server:4000/graphql'
      APOLLO_CLIENT_WS: 'ws://localhost:4000/graphql'

A: hmm too bad there hasn't been a better answer to this yet. You could definitely work around when testing as suggested by creating an entry in /etc/hosts to the api service as named in docker, but that would not really be ideal for ci/cd :-(


text:
Q: At what tier should data be escaped to send to a database? I have an MVC web application, and I'm wondering where the best place to escape data to send to a database is: the controller or model. I can't think of any arguments toward either side. Is there an accepted place to escape data? If not, what are the pros and cons of escaping data in a given tier?

A:
d) None of the above

You should use parameters.
You should never need to escape data for a database.
You do need to escape output for HTML; that should be done in the view.


text:
Q: background color position The background color I've set isn't being applied to the whole content area (content-wrapper). It's only being applied to about half the page. JsFiddle
(The position of the content is centered outside of JsFiddle)
<!DOCTYPE html>

    <link rel="stylesheet" href="sidenav3.css" type="text/css"/>
    <title>web page</title>

Title

Ham hock turkey flank corned beef beef brisket, chicken tri-tip sirloin ham sausage bresaola drumstick short loin speck. Kielbasa speck chicken flank bresaola, meatloaf frankfurter. Andouille pork chop spare ribs fatback pork loin. Strip steak meatball ribeye, turducken boudin shoulder fatback tongue cow meatloaf ground round short loin. Tri-tip prosciutto chuck capicola jerky. Pastrami chuck turkey, brisket pork belly hamburger corned beef speck.

&nbsp

T-bone frankfurter meatloaf, ham jerky pork boudin tail short loin. Filet mignon salami sirloin, leberkas sausage short loin pork. Prosciutto biltong kielbasa turkey ribeye brisket. Bacon swine shank, frankfurter boudin short ribs drumstick tongue tail fatback.

&nbsp

Turkey t-bone beef, tenderloin pig drumstick biltong ham turducken. Turducken kielbasa spare ribs t-bone tri-tip. Strip steak speck flank tenderloin. Prosciutto spare ribs flank, turkey rump beef ribs cow biltong tenderloin ham hamburger leberkas pastrami. Leberkas turkey flank capicola short loin kielbasa. Sausage meatloaf shankle venison flank ribeye tail strip steak. Turducken salami rump cow corned beef.

&nbsp

T-bone frankfurter meatloaf, ham jerky pork boudin tail short loin. Filet mignon salami sirloin, leberkas sausage short loin pork. Prosciutto biltong kielbasa turkey ribeye brisket. Bacon swine shank, frankfurter boudin short ribs drumstick tongue tail fatback.

&nbsp

T-bone frankfurter meatloaf, ham jerky pork boudin tail short loin. Filet mignon salami sirloin, leberkas sausage short loin pork. Prosciutto biltong kielbasa turkey ribeye brisket. Bacon swine shank, frankfurter boudin short ribs drumstick tongue tail fatback.

&nbsp

index

Item one

Item two

Item three

Item four

Item five

Item six

Item seven

The CSS
span.anchor {
    display: block;
    height: 50px;
    margin-top: -50px;
    visibility: hidden;
}

ul {padding: 0; margin: 0;}
body {padding:0; margin:0;}

h1 {
 font-size:34px;
 text-align: center;
}

#header {
  height: 35px;
  width: 100%;
  background-color: #336699;
  position: fixed;
  top: 0px;
  z-index: 10;
}

#content-wrapper {
  position: absolute;
  top: 0px;
  bottom: 0px;
  left: 0px;
  right: 0px;
  background: #f6f6f6;
}

#content {
  width: 90%;
  height: 100%;
  float: right;
  margin-top: 70px;
  margin-bottom: 50px;
  padding-right: 75px;
  line-height: 2.5em;
  font-size: 13pt;
}

#menu ul li {
 list-style-type: none;
}

 #menu ul ul {
   display:none;
   position: fixed;
}

 #menu ul ul a {
}

 #menu ul a {
  text-decoration: none;
  color: black;
}

#menu ul li:hover ul {
  display:block;
  left: 0;
  line-height: 20px;
  width: 220px;
  height: 750px;
  background: #CCC;
  border-top-right-radius:1em;
  border-bottom-right-radius:1em;
  padding-left: 22px;
  text-align: left;
  line-height: 35px;
  padding-top:20px;
  font-size: 14px;
  border:1px solid grey;
  box-shadow: 3px 3px 4px #888888;
}

 #menu-wrap {
   position:fixed;
   top: 80px;
   width: 55px;
   height: 22px;
   border-top-right-radius: 6px;
   border-bottom-right-radius:6px;
   background: grey;
   text-align: center;
   padding-top: 3px;
   z-index: 0;
   box-shadow: 2px 2px 3px #888888;
}

#footer {
  height: 10px;
  width: 100%;
  background-color: green;
  position: fixed;
  bottom: 0px;
}

A: The reason is that top:0px; bottom:0px basically forces the element height to be 100% of its container, which turns out to be 100% of the viewport as well.
Removing bottom:0px lets content-wrapper expand as needed, together with its background:
http://jsfiddle.net/VNtJw/15/

A: Remove position:absolute;
Seems to fix it on your jsfiddle example.

A: I can't access your site but if I'm reading you correctly it may also help if you but the background-color element within a CSS body group so the background will scale and be present regardless.
body{
      background-color: #f6f6f6;
    }

I hope this helps!


text:
Q: Can't connect to database with php? I'm trying to connect to my database via php but I keep getting a 500 Internal Server Error. It is hosted on GoDaddy. I'm fairly new to php. Here is my code:
<?php
// Create connection
$conn = mysql_connect('server name', 'username', 'password');
mysql_select_db('users', $conn);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} else {
    echo "Connected successfully";
}
?>

Obviously I have entered my server name, username and password but not showing them here. I can't get it to connect at all. I wanted to be able to just to display a row of data on a page to check it works but I can't even get that far yet! I'm probably missing something obvious. Any help would be great. Thanks!

A: There are several reasons for getting 500 error on page and will discuss all of them below.

*

*You have used mysql_* function to establish connection to database which is deprecated in newer version of php.

*You may have issue with .htaccess code which is blocking you.

However you can check some points to figure out your issue.
Check your .htaccess file whether it is blocking you or not
Check your php version (If you php version is >= 5.5) then try below.
<?php
// Create connection
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

mysqli_close($con);

Hope this will help you!!
Thanks & Regards

A: you seems to be use the mysql as an object and it is not supported only mysqli that can behave like this .
so if you need to use mysql extension and it is not recommend since it is deprecated.
<?php
// Create connection
$conn = mysql_connect('server name', 'username', 'password');
mysql_select_db('users', $conn);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysql_error());
} else {
    echo "Connected successfully";
}
?>


text:
Q: Number of scalar addition required to compute P(QR) ,where P,Q,R be matrices or order $3× 5,5×7,7×3$ Firstly i don't understand what is meant by scalar additions here ? This is my main concern here ,computation comes after .If anyon can help it will be great

A: The number of scalar additions is nothing but the addition of products of scalars of a row of a matrix to the column of another matrix in the multiplication of matrices.
      Suppose we have two matrices A of m cross n order and B of n cross p order.Let, m = 2, n = 3 and p = 4 which is defined below as:

              A = a b c  ; B = g h i j
                  d e f        k l m n
                               o p q r

       Now we want to find their product that is conformable(i.e. can find their product as the number of columns in matrix A are equal to the number of rows of matrix B that is 3).So, their product is defined as:

            A*B = a*g+b*k+c*o   a*h+b*l+c*p   a*i+b*m+c*q   a*j+b*n+c*r
                  d*g+e*k+f*o   d*h+e*l+f*p   d*i+e*m+f*q   d*j+e*n+f*r

        Here we can see when we multiply row 1 of matrix A to the column 1 of matrix B, we find 2 no. of scalar addition(+) at a11 position i.e. (n-1) = (3-1) = 2.We'll get same for a12, a13 and a14 position.So for 1st row total no of scalar additions are = (n-1)*p = 2*4 = 8 (i.e. p times (n-1)).Similarly, for second row at a21 position, there will be 2 no. of scalar additions, so for a22, a23 and a24. Therefore, total no. of scalar additions for the second row will be again 8.

    From here we can conclude that the total no. of scalar additions are = m*(n-1)*p = 2*2*4 = 16(can verify by 8+8 = 16)

    Now, we come to the question;

    Given; P of 3 cross 5,Q of 5 cross 7 and R of 7 cross 3 and we have to find no. of scalar additions for P(QR) i. e. first we have to find for QR.So,

 for Q*R, m = 5, n = 7, p = 3 i.e. m*(n-1)*p = 5*6*3 = 90

 Then Let Q*R = Some matrix B whose order is 5 cross 3(after multiplication of Q and R)

 Now for P*B, m = 3, n = 5,p = 3 i.e. m*(n-1)*p = 3*4*3 = 36

Hence total no. of scalar additions are = 90+36 = 126


text:
Q: setting date time picker in android I am using a date picker and time picker in my application. I want to set both in same dialog box. or at the same time i want to set date and time.Is this possible?how so?pls give me a example.
Thanks in advance.

A: use following function
private void showDateTimeDialog() {
    // Create the dialog
    final Dialog mDateTimeDialog = new Dialog(this);
    // Inflate the root layout
    final RelativeLayout mDateTimeDialogView = (RelativeLayout) getLayoutInflater().inflate(R.layout.date_time_dialog, null);
    // Grab widget instance
    final DateTimePicker mDateTimePicker = (DateTimePicker) mDateTimeDialogView.findViewById(R.id.DateTimePicker);
    // Check is system is set to use 24h time (this doesn't seem to work as expected though)
    final String timeS = android.provider.Settings.System.getString(getContentResolver(), android.provider.Settings.System.TIME_12_24);
    final boolean is24h = !(timeS == null || timeS.equals("12"));

    // Update demo TextViews when the "OK" button is clicked
    ((Button) mDateTimeDialogView.findViewById(R.id.SetDateTime)).setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            /*((TextView) findViewById(R.id.Date)).setText(mDateTimePicker.get(Calendar.YEAR) + "/" + (mDateTimePicker.get(Calendar.MONTH)+1) + "/"
                    + mDateTimePicker.get(Calendar.DAY_OF_MONTH));
            if (mDateTimePicker.is24HourView()) {
                ((TextView) findViewById(R.id.Time)).setText(mDateTimePicker.get(Calendar.HOUR_OF_DAY) + ":" + mDateTimePicker.get(Calendar.MINUTE));
            } else {
                ((TextView) findViewById(R.id.Time)).setText(mDateTimePicker.get(Calendar.HOUR) + ":" + mDateTimePicker.get(Calendar.MINUTE) + " "
                        + (mDateTimePicker.get(Calendar.AM_PM) == Calendar.AM ? "AM" : "PM"));
            }*/

            String date =  (mDateTimePicker.get(Calendar.MONTH)+1) + "/" + mDateTimePicker.get(Calendar.DAY_OF_MONTH)  + "/"
                    +mDateTimePicker.get(Calendar.YEAR)+"  "+mDateTimePicker.get(Calendar.HOUR_OF_DAY) + ":" + mDateTimePicker.get(Calendar.MINUTE)+" "+(mDateTimePicker.get(Calendar.AM_PM) == Calendar.AM ? "AM" : "PM");
            edt_admin_due_date.setText(date);
            mDateTimeDialog.dismiss();
        }//MM/dd/yyyy hh:mm
    });

    // Cancel the dialog when the "Cancel" button is clicked
    ((Button) mDateTimeDialogView.findViewById(R.id.CancelDialog)).setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            mDateTimeDialog.cancel();
        }
    });

    // Reset Date and Time pickers when the "Reset" button is clicked
    ((Button) mDateTimeDialogView.findViewById(R.id.ResetDateTime)).setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            mDateTimePicker.reset();
        }
    });

    // Setup TimePicker
    mDateTimePicker.setIs24HourView(is24h);
    // No title on the dialog window
    mDateTimeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    // Set the dialog content view
    mDateTimeDialog.setContentView(mDateTimeDialogView);
    // Display the dialog
    mDateTimeDialog.show();
}

and datetimepicker file is as follow.
public class DateTimePicker extends RelativeLayout implements View.OnClickListener, OnDateChangedListener, OnTimeChangedListener {

// DatePicker reference
private DatePicker      datePicker;
// TimePicker reference
private TimePicker      timePicker;
// ViewSwitcher reference
private ViewSwitcher    viewSwitcher;
// Calendar reference
private Calendar        mCalendar;

// Constructor start
public DateTimePicker(Context context) {
    this(context, null);
}

public DateTimePicker(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

public DateTimePicker(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);

    // Get LayoutInflater instance
    final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    // Inflate myself
    inflater.inflate(R.layout.datetimepicker, this, true);

    // Inflate the date and time picker views
    final LinearLayout datePickerView = (LinearLayout) inflater.inflate(R.layout.datepicker, null);
    final LinearLayout timePickerView = (LinearLayout) inflater.inflate(R.layout.timepicker, null);

    // Grab a Calendar instance
    mCalendar = Calendar.getInstance();
    // Grab the ViewSwitcher so we can attach our picker views to it
    viewSwitcher = (ViewSwitcher) this.findViewById(R.id.DateTimePickerVS);

    // Init date picker
    datePicker = (DatePicker) datePickerView.findViewById(R.id.DatePicker);
    datePicker.init(mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH), this);

    // Init time picker
    timePicker = (TimePicker) timePickerView.findViewById(R.id.TimePicker);
    timePicker.setOnTimeChangedListener(this);

    // Handle button clicks
    ((Button) findViewById(R.id.SwitchToTime)).setOnClickListener(this); // shows the time picker
    ((Button) findViewById(R.id.SwitchToDate)).setOnClickListener(this); // shows the date picker

    // Populate ViewSwitcher
    viewSwitcher.addView(datePickerView, 0);
    viewSwitcher.addView(timePickerView, 1);
}
// Constructor end

// Called every time the user changes DatePicker values
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
    // Update the internal Calendar instance
    mCalendar.set(year, monthOfYear, dayOfMonth, mCalendar.get(Calendar.HOUR_OF_DAY), mCalendar.get(Calendar.MINUTE));
}

// Called every time the user changes TimePicker values
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
    // Update the internal Calendar instance
    mCalendar.set(mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH), hourOfDay, minute);
}

// Handle button clicks
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.SwitchToDate:
            v.setEnabled(false);
            findViewById(R.id.SwitchToTime).setEnabled(true);
            viewSwitcher.showPrevious();
            break;

        case R.id.SwitchToTime:
            v.setEnabled(false);
            findViewById(R.id.SwitchToDate).setEnabled(true);
            viewSwitcher.showNext();
            break;
    }
}

// Convenience wrapper for internal Calendar instance
public int get(final int field) {
    return mCalendar.get(field);
}

// Reset DatePicker, TimePicker and internal Calendar instance
public void reset() {
    final Calendar c = Calendar.getInstance();
    updateDate(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
    updateTime(c.get(Calendar.HOUR_OF_DAY),c.get(Calendar.MINUTE));
}

// Convenience wrapper for internal Calendar instance
public long getDateTimeMillis() {
    return mCalendar.getTimeInMillis();
}

// Convenience wrapper for internal TimePicker instance
public void setIs24HourView(boolean is24HourView) {
    timePicker.setIs24HourView(is24HourView);
}

// Convenience wrapper for internal TimePicker instance
public boolean is24HourView() {
    return timePicker.is24HourView();
}

// Convenience wrapper for internal DatePicker instance
public void updateDate(int year, int monthOfYear, int dayOfMonth) {
    datePicker.updateDate(year, monthOfYear, dayOfMonth);
}

// Convenience wrapper for internal TimePicker instance
public void updateTime(int currentHour, int currentMinute) {
    timePicker.setCurrentHour(currentHour);
    timePicker.setCurrentMinute(currentMinute);
}

}
this will work fine in my code

A: Following code will help you to get both,
date_time_picker.xml
<?xml version="1.0" encoding="utf-8"?>

 <ScrollView android:id="@+id/scrollView1"
android:layout_width="match_parent" android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">

<LinearLayout android:layout_width="match_parent"
    android:id="@+id/linearLayout1" android:orientation="vertical"
    android:layout_height="match_parent">
    <DatePicker android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:id="@+id/datePicker"></DatePicker>
    <TimePicker android:id="@+id/timePicker"
        android:layout_width="wrap_content" android:layout_height="wrap_content"></TimePicker>
    <TableRow android:id="@+id/tableRow1" android:layout_height="wrap_content"
        android:layout_width="match_parent" android:gravity="center">

        <Button android:id="@+id/btnSetDateTime"
            android:layout_height="wrap_content" android:text="Set"
            android:layout_width="120dp"></Button>

    </TableRow>
</LinearLayout>

use the following java code:
ScrollView DTPicker = (ScrollView) View.inflate(context,
                    R.layout.date_time_picker, null);

        Button  btnSet = (Button) DTPicker.findViewById(R.id.btnSetDateTime);
            DatePicker dp = (DatePicker) DTPicker.findViewById(R.id.datePicker);
             TimePicker tp = (TimePicker) DTPicker.findViewById(R.id.timePicker);

            btnSet.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    String strDateTime = dp.getYear() + "-"
                            + (dp.getMonth() + 1) + "-"
                            + dp.getDayOfMonth() + " "
                            + tp.getCurrentHour() + ":"
                            + tp.getCurrentMinute();
}});

alert = new AlertDialog.Builder(context).create();
            alert.setTitle("Reminder");
            alert.setView(DTPicker);
            alert.show();


text:
Q: Show that $x^{20}+x^{15}+x^{10}+x^5$ is divisible by $x^2+1$ Show that $ f(x)=x^{20}+x^{15}+x^{10}+x^5$ is divisible by $x^2+1$
I tried to simplify it by putting $x^5=y$
It simplifies the polynomial but I cannot put it in the case of the divisor.
So I assumed that $x^2+1$ is a divisor of $f(x)$
Then examine the assumption is correct then $x^2+1=(x-i)(x+i)$
Now for $x=\pm i$ using synthetic division it leaves remainder 0
Am I at the right direction, please tell

A: Hint: Show that $x^2+1$ divides $x^{10}+1$, and that $x^{10}+1$ divides $f(x)$.

A: There is no need for synthetic division. Just evaluate $x^{20} + x^{15} + x^{10} + x^5 $ at $x=\pm i$:
$$
(\pm i)^{20} + (\pm i)^{15} + (\pm i)^{10} + (\pm i)^5
=
1 + \mp i - 1 + \pm i
= 0
$$
Therefore, $x\pm i$ divides $x^{20} + x^{15} + x^{10} + x^5 $ and so does their product, because their are coprime.

A: By Euclid lemma you can express
$ f(x)=g(x)q(x) + r(x) $
where $ g(x)= x^2 + 1$ and degree of $ r(x) $ is less than that of $g(x) $
hence $ r(x) $ can be assumed as $ax+b$ rest I leave to you
And your direction is absolutely right just prove it mathematically

A: Yes, your method works: You checked that $i$ is a root by using synthetic division; since it is, you know that $x-i$ is a factor. Next, you checked whether $-i$ is also a root by using synthetic division; since it is, you also know that $x-(-i)=x+i$ is a factor. Putting this information together, you know that the expression has a factor of $(x-i)(x+i) = x^2 + 1$ as desired.

A: HINT:
Note that $$\begin{align}x^{20}+x^{15}+x^{10}+x^5&=x^5((x^5)^3+(x^5)^2+x^5+1)\\&=x^5(x^5+1)((x^5)^2+1)\\&=x^5(x^5+1)(x^{10}+1)\end{align}$$ and $$(-i)^{10}=i^{10}=i^2=-1$$ so $x-i$ and $x+i$ are factors of the polynomial $x^{10}+1$.

A: Now, even if we don't have any insight we can  always resort to long division:
$(x^2 + 1)| \begin{cases}x^{18} & & - x^{16} &&+ x^{14} &... & & \\
x^{20} & & & && x^{15} &&&&& x^{10}&&&&& x^5\\
x^{20} & & x^{18}\\
--&--&--&--&--&--\\
&& -x^{18}\\
&& -x^{18} && - x^{16}&\\
--&--&--&--&--&--\\
&&&&x^{16}&+x^{15}\\
...\\
\end{cases}$
We'll call that plan B.
(Which will give us $(x^2 + 1)(x^{18}-x^{16} + x^{14} + x^{13} - x^{12} - x^{11} + x^{10} + x^{9} -x^7 + x^5)$ but it's long and tedious and not very insightful.  And wouldn't be practical for proving something like $x^2 + 1$ divides $x^{100} + x^{75} + x^{50} + x^{25}$ which ... I think it does.)
....
But if we try to be insightful:
The way I see it there are two things to realize.
1) $a^3 + a^2 + a + 1 =$
$(a^3 + a^2) + (a+1)=$
$a^2(a+1) + (a+1) = $
$(a^2 + 1)(a+1)$.
To make this more general (although really hard to read:)
$a^{nk - 1} + a^{nk - 2} + .... + a + 1= $
$(a^{nk-1} +  .... + a^{(n-1)k}) + (a^{(n-1)k -1} + ..... + a^{(n-2)k}) + ..... + (a^{k-1} + ... + 1) =$
$a^{(n-1)k}(a^{k-1} + .... + 1) + a^{(n-2)k}(a^{k-1} + .... + 1) + ... + a^k(a^{k-1} + ..... + 1) + (a^{k-1} + .... + 1) = $
$(a^{(n-1)k} + a^{(n-2)k} + .... 1)(a^{k-1} + a^{k-2} + ... + 1)$.
... Yeesh ...
but that means
$x^{20} + x^{15} + x^{10} + x^5 = $
$x^5(x^{15} + x^{10} + x^5 + 1) = $
$x^5(x^{10} + 1)(x^5 + 1)$.
... and factoring the $(x^{10} + 1)$ looks like it has potential.
2)  $(a -1)(a^{k-1} + a^{k-2} + .... + 1) = a^k -1$
is well known.  But we can "flip signs" depending on parity:
$(a+1)(a^{k-1} - a^{k-2} +  a^{k-3} - ... + a - 1) = a^k - 1$ if $k$ is even
$(a+1) (a^{k-1} - a^{k-2} +  a^{k-3} - ... -a + 1)= a^k + 1$ if $k$ is odd.
So
$(x^{10} + 1) = ((x^2)^5 + 1) = (x^2 + 1)(x^8 - x^6 + x^4 - x^2 + 1)$.
....
And that's it
$x^{20} + x^{15} + x^{10} + x^5 = $
$x^5(x^{10} + 1)(x^5 + 1)=$
$x^5(x^2 + 1)(x^8 - x^6 + x^4 -x^2 + 1)(x^5 + 1)$
Which has $x^2 + 1$ as a factor.
...

A: $$
x^{20} + x^{15} + x^{10} + x^5 = x^5(x^5+1)(x^{10}+1)=x^5  \left((1 + x)(1 - x + x^2 - x^3 + x^4)\right) \left((1 + x^2) (1 - x^2 + x^4 - x^6 +
    x^8)\right)
$$


text:
Q: How to design a Treeview with following Scheme Treeview should look like following:
Treeview Scheme
My Code looks like this:
<TreeView ItemsSource="{Binding Design.AllSystems}">
    <HierarchicalDataTemplate DataType="{x:Type core:System}" ItemsSource="{Binding Windings}">
        <StackPanel>
            <TextBlock Text="{Binding SystemType.Detail1}"/>
            <TextBlock Text="{Binding SystemType.Detail2}"/>
            <TextBlock Text="{Binding SystemType.Windings}"/>
        </StackPanel>
    </HierarchicalDataTemplate>
</TreeView>

I try to achieve following:
There is a list of systems which contains some Details without Child elements and a Collection with Windings. I want to display those Details if the User jumps into a System. Additional there is a static Windings Entry which should display all Windings in the Windings-Collection.
I can't figure out how to do this. I am very thankful for any approach.

A: I think the easiest way to do this is to represent your information in some common type and build the structure in view models. You could use different types for the different levels if it helps you represent them or encapsulate their functionality, but this ultimately depends on what you will do with it.
For example, define a tree view entity:
public class TreeViewItemViewModel : ViewModelBase
{
    #region Properties

    public string Name { get; set; }

    public ObservableCollection<TreeViewItemViewModel> Children { get; set; }

    #endregion
}

You could extend this for specific roles if desired, and encapsulate the complexity of assembling the various child structures from multiple collections via these entries:
public class SystemTreeViewItemViewModel : TreeViewItemViewModel
{
    // Other Properties
}

public class WindingTreeViewItemViewModel : TreeViewItemViewModel
{
    // Other Properties
}

Then assemble a larger hierarchy of nodes:
public ObservableCollection<TreeViewItemViewModel> Systems { get; } = new ObservableCollection<TreeViewItemViewModel>
{
    new SystemTreeViewItemViewModel
    {
        Name= "System 1",
        Children = new ObservableCollection<TreeViewItemViewModel>
        {
            new TreeViewItemViewModel { Name = "SystemDetail1" },
            new TreeViewItemViewModel { Name = "SystemDetail1" },
            new TreeViewItemViewModel
            {
                Name = "Windings",
                Children = new ObservableCollection<TreeViewItemViewModel>
                {
                    new WindingTreeViewItemViewModel
                    {
                        Name = "Winding A",
                        Children = new ObservableCollection<TreeViewItemViewModel>
                        {
                            new TreeViewItemViewModel { Name = "Detail1" },
                            new TreeViewItemViewModel { Name = "Detail2" },
                        }
                    },
                    new WindingTreeViewItemViewModel
                    {
                        Name = "Winding A",
                        Children = new ObservableCollection<TreeViewItemViewModel>
                        {
                            new TreeViewItemViewModel { Name = "Detail1" },
                            new TreeViewItemViewModel { Name = "Detail2" },
                        }
                    }
                }
            }
        }
    },
    new SystemTreeViewItemViewModel
    {
        Name= "System 2"
    }
};

Then define HierarchialDataTemplate entries for each node type:
<TreeView ItemsSource="{Binding Systems}">
    <TreeView.Resources>
        <HierarchicalDataTemplate DataType="{x:Type viewModels:SystemTreeViewItemViewModel}" ItemsSource="{Binding Children}">
            <Border Background="Red">
                <TextBlock Text="{Binding Name}" />
            </Border>
        </HierarchicalDataTemplate>
        <HierarchicalDataTemplate DataType="{x:Type viewModels:WindingTreeViewItemViewModel}" ItemsSource="{Binding Children}">
            <Border Background="LimeGreen">
                <TextBlock Text="{Binding Name}" />
            </Border>
        </HierarchicalDataTemplate>
        <HierarchicalDataTemplate DataType="{x:Type viewModels:TreeViewItemViewModel}" ItemsSource="{Binding Children}">
            <Border Background="Yellow">
                <TextBlock Text="{Binding Name}" />
            </Border>
        </HierarchicalDataTemplate>
    </TreeView.Resources>
</TreeView>

Example on GitHub


text:
Q: Creation of google analytic tracker not giving result for enableAdvertisingIdCollection(true) I am trying to implement Google Analytics. I have tried with the following code , however I am not getting a result for enableAdvertisingCollection on my Google analytics account.
Google suggesting some another code for creation of tracker. I am not getting difference between my code and Google's code. Any one can help me?
My Code:
GoogleAnalytics analytics =        GoogleAnalytics.getInstance(getApplicationContext());

Tracker tracker = analytics.newTracker("XXXXXXXXX"); // Send hits to tracker id UA-000-1

    // All subsequent hits will be send with screen name = "main screen"
    tracker.setScreenName("main screen");
    tracker.enableExceptionReporting(true);
    tracker.enableAdvertisingIdCollection(true);
    tracker.enableAutoActivityTracking(true);
    tracker.send(new HitBuilders.EventBuilder().build());

Google Suggesting Code:
Tracker t = ((AnalyticsSampleApp) getActivity().getApplication()).getTracker(
        TrackerName.APP_TRACKER);
t.enableAdvertisingIdCollection(true);

A: This happens when there is no enough data to display. Google Analytics doesn't want to make users identifiable in some way, so it applies thresholds.
In fact, when you skip the validation, you see this message:

"Some data in this report may have been removed when a threshold was applied. Learn more"

Just wait for more users to report and you will start to see data.


text:
Q: Should integration testing of DAOs be done in an application server? I have a three tier application under development and am creating integration tests for DAOs in the persistence layer.  When the application runs in Websphere or JBoss I expect to use the connection pooling and transaction manager of those application servers.  When the application runs in Tomcat or Jetty, we'll be using C3P0 for pooling and Atomikos for transactions.
Because of these different subsystems, should the DAO's be tested in a fully configured  application server environment or should we handle those concerns when integration testing the service layer?  Currently we plan on setting up a simple JDBC data source with non-JTA (i.e. resource-local) transactions for DAO integration testing, thus no application server is involved....but this leaves me wondering about environmental problems we won't uncover.

A: Besides testing each module using unittests, the integration test should test groups of modules.
I don't want to be pedantic but in therorie this is folowed by system test for black box testing by QA.
For smaller projects this may not be feasible

A: I think you're on the right track with this line of thinking. If possible you should set up a continuous integration server (e.g. Hudson) that runs your production environment. That way you can develop with pretty high confidence using Tomcat etc., running tests against your local setup, and when you check in your code be sure that those same tests are being run against the real deal.


text:
Q: Regex modification php I have this regex: /\*([^<|\n|\r]+)/
which matches all characters in a string starting with a * and ending in a new line or a '<', how can I modify this regex to not match strings if they start with a ** (so it will not match if the second character is also a *)

A: What you need is negative lookarounds.
/(?<!\*)\*(?!\*)([^<\n\r]+)/

Also, [^<|\n|\r] doesn't do what you think it does. It will match anything that isn't <, \n, \r, or a literal | character. You don't need the | inside a character class unless you want to match a literal |.

A: I think this should work. It's called a "zero-width negative look-ahead assertion"
/\*(?!\*)([^<|\n|\r]+)/

A: /\*[^\*]([^<|\n|\r]+)/

The alteration effectively says "match a * but only when the next character is not a *"


text:
Q: How to add dynamic text in standalone PyQGIS to reflect iteration of layer names I am working with a standalone PyQGIS script below (that was given as an answer to How to iterate over layers and export them as PNG images with PyQGIS in a standalone script). The script exports the "boundary, climits, and Div1_Irrig_1956_0" layers as one png. The script then exports the "boundary, climits, and Div1_Irrig_1976_1" layers as another png and so on. I am trying to add to the code a way to include a text element in each export process that reflects the Div1_Irrig... layer name.

from qgis.core import QgsApplication, QgsMapLayerRegistry, QgsVectorLayer, QgsProject
from qgis.gui import QgsMapCanvas, QgsMapCanvasLayer, QgsLayerTreeMapCanvasBridge
from PyQt4.QtCore import QTimer, QSize
import sys, os
import time

qgisApp = QgsApplication([], True)
qgis_prefix = "C:\\OSGeo4W\\apps\\qgis"
qgisApp.setPrefixPath(qgis_prefix, True)
qgisApp.initQgis()

# Required variables with your shapefile paths and names
pngsPath = 'E:/IrrigatedLands/FC_qgis/'
boundaryLayer = QgsVectorLayer("E:\\IrrigatedLands\\FC_qgis\\boundary.shp", 'boundary', 'ogr')
climitsLayer = QgsVectorLayer("E:\\IrrigatedLands\\FC_test\\citylimits\\climits.shp", 'climits', 'ogr')
otherLayers = {'Div1_Irrig_1956_0': QgsVectorLayer("E:\\IrrigatedLands\\FC_qgis\\Div1_Irrig_1956_0.shp", 'Div1_Irrig_1956_0', 'ogr'),
    'Div1_Irrig_1976_1':QgsVectorLayer("E:\\IrrigatedLands\\FC_qgis\\Div1_Irrig_1976_1.shp", 'Div1_Irrig_1976_1', 'ogr'),
    'Div1_Irrig_1987_2': QgsVectorLayer("E:\\IrrigatedLands\\FC_qgis\\Div1_Irrig_1987_2.shp", 'Div1_Irrig_1987_2', 'ogr')}
count = 0

canvas = QgsMapCanvas()
canvas.resize(QSize(500, 500)) # You can adjust this values to alter image dimensions
#canvas.show()

# Add layers to map canvas taking the order into account
QgsMapLayerRegistry.instance().addMapLayer(boundaryLayer)
QgsMapLayerRegistry.instance().addMapLayers(otherLayers.values() )
QgsMapLayerRegistry.instance().addMapLayer(climitsLayer)
layerSet = [QgsMapCanvasLayer(climitsLayer)]
layerSet.extend([QgsMapCanvasLayer(l) for l in otherLayers.values() ])
layerSet.append(QgsMapCanvasLayer(boundaryLayer))
canvas.setLayerSet( layerSet )

# Link Layer Tree Root and Canvas
root = QgsProject.instance().layerTreeRoot()
bridge = QgsLayerTreeMapCanvasBridge(root, canvas)

def prepareMap(): # Arrange layers
    for lyr in otherLayers.values(): # make all layers invisible
        base = os.path.basename(lyr)
        name = os.path.splitext(base)[0]
        layerOn = "" # When required layer is turned on this will be the layer name to output
        root.findLayer( lyr.id() ).setVisible(0) # Unchecked

        for lyr in otherLayers:
            lyr.visible = False
            if lyr.name == "climits":
                lyr.visible = True
            if lyr.name == "boundary":
                lyr.visible = True
            if lyr.name == name:
                lyr.visible = True
                layerOn = lyr.name

            if layerOn:
                print layerOn

    root.findLayer( otherLayers.values()[count].id() ).setVisible(2) # Checked
    canvas.zoomToFullExtent()
    QTimer.singleShot(8000, exportMap) # Wait a second and export the map
    return

def exportMap(): # Save the map as a PNG
    global count # We need this because we'll modify its value
    canvas.saveAsImage( pngsPath + otherLayers.keys()[count] + ".png" )
    print "Map with layer",otherLayers.keys()[count],"exported!"
    if count < len(otherLayers)-1:
        QTimer.singleShot(8000, prepareMap) # Wait a second and prepare next map
    else: # Time to close everything
        qgisApp.exitQgis()
        qgisApp.exit()
    count += 1
    return

prepareMap() # Let's start the fun
qgisApp.exec_()


text:
Q: Crystal Reports 2013 How do I exclude Null Values in a Crosstab average? How do I get a crosstab in Crystal Reports 2013 to exclude null values from a crosstab average?
For example

Procedure Name : OCT RETINA

Procedure Count : 8

Procedures with Completion Times Populated : 6

Summary of all 6 Completion Times : 101

I was expecting the average of the Completion Times to be calculated as 101/6. Instead, Crystal Reports is calculating the average as 101/8. It needs to be calculated as 101/6 (without counting null values in the denominator).
Adding another group is not an option because of the very specific way the values are sorted in the detail (hence a crosstab in a footer). The names of the procedures are dynamic so keeping a running total of each procedure's average completion time is not an option either.
Thanks in advance!!!!

A: One solution would be instead of taking the field create a formula use that in cross tab.
Create a formula @count
if << procedure field>>=<<your value>>
then 1
else 0

Now place the formula and take sum instead of count

A: Thanks for everyone's feedback! The answer is to use Weighted Average instead of just a plain old Average.
All I had to do was

a. Create a formula field called IncludeProcInDenominator and set the value to
if {Command.ProcTime} > 0 then 1
b. Right click on the Average Proc Time calculation in the crosstab and select Edit Summary
c. When the Edit Summary dialog box appears, in the Calculate This Summary drop down, select Weighted average with
d. In the dropdown box underneath that, select @IncludeProcInDenominator
In effect, the only values that are averaged are the ones where @IncludeProcInDenominator = 1
Thanks for everyone's help!


text:
Q: How does Linq Determine if a propety has a storage field? I was looking at a dbml file in xml editor and noticed that some of the properties had a storage field and some did not.  I also noticed that some had name, which I assuming is the name of the field in sql.  If the property in the dbml file has a different name from the one in sql, it will add the member attribute.  I don't understand why some fields have a storage attribute and some do not?

A: From MSDN
**DataAttribute.Storage Property**
Gets or sets a private storage field to hold the value from a column.

Have a look here

A: Sometimes the field in the database has a name that is not overly helpful in explaining what it does and so a programmer will change the name in the code to help them remember what it is for and add the Name parameter to tell Linq that it is actually stored someplace else.
What the Storage property does is allow you to put business logic into the public field accessors and still allow Linq to access the data directly without going through that business logic.  This way Linq will not run your business code each time, it will just load and save the data from your private storage variable.
See: http://msdn.microsoft.com/en-us/library/bb386940.aspx