text:
Q: Display form fields depending on user So I have a social network where users can post thinks. I would like to incorporate a blog system into the same feed app instead of making blog its own app. I was thinking that if I (or someone with adequate permissions) wanted to make a blog post they could use the same form used by everyone to make a post, however since they have higher permissions they would be shown an extra option on the form that allows them to make it a blog post. and on the blog page I would just filter out to only have posts with blog_post set to true to be shown.
I tried to do this with a simple if statement in the forms.py however I get an error:
Traceback (most recent call last):
  File "/anaconda/envs/test/lib/python3.6/site-packages/django/utils/autoreload.py", line 228, in wrapper
    fn(*args, **kwargs)
  File "/anaconda/envs/test/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run
    self.check(display_num_errors=True)
  File "/anaconda/envs/test/lib/python3.6/site-packages/django/core/management/base.py", line 359, in check
    include_deployment_checks=include_deployment_checks,
  File "/anaconda/envs/test/lib/python3.6/site-packages/django/core/management/base.py", line 346, in _run_checks
    return checks.run_checks(**kwargs)
  File "/anaconda/envs/test/lib/python3.6/site-packages/django/core/checks/registry.py", line 81, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/anaconda/envs/test/lib/python3.6/site-packages/django/core/checks/urls.py", line 16, in check_url_config
    return check_resolver(resolver)
  File "/anaconda/envs/test/lib/python3.6/site-packages/django/core/checks/urls.py", line 26, in check_resolver
    return check_method()
  File "/anaconda/envs/test/lib/python3.6/site-packages/django/urls/resolvers.py", line 254, in check
    for pattern in self.url_patterns:
  File "/anaconda/envs/test/lib/python3.6/site-packages/django/utils/functional.py", line 35, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/anaconda/envs/test/lib/python3.6/site-packages/django/urls/resolvers.py", line 405, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/anaconda/envs/test/lib/python3.6/site-packages/django/utils/functional.py", line 35, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/anaconda/envs/test/lib/python3.6/site-packages/django/urls/resolvers.py", line 398, in urlconf_module
    return import_module(self.urlconf_name)
  File "/anaconda/envs/test/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 978, in _gcd_import
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
  File "/Users/garrettlove/Desktop/evverest/evverest/urls.py", line 20, in <module>
    from feed import views
  File "/Users/garrettlove/Desktop/evverest/feed/views.py", line 4, in <module>
    from feed.forms import PostForm,CommentForm
  File "/Users/garrettlove/Desktop/evverest/feed/forms.py", line 7, in <module>
    class PostForm(forms.ModelForm):
  File "/anaconda/envs/test/lib/python3.6/site-packages/django/forms/models.py", line 248, in __new__
    "needs updating." % name
django.core.exceptions.ImproperlyConfigured: Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited; form PostForm needs updating.

forms.py:
from django.contrib.auth import get_user_model
User = get_user_model()

class PostForm(forms.ModelForm):
    class Meta:
        model = UserPost

        if User.username == 'garrett':
            fields = ('title','image','post_body','blog_post')
        else:
            fields = ('title','image','post_body')

        widget = {
            'title':forms.TextInput(attrs={'class':'post-title'}),
            'post_body':forms.Textarea(attrs={'class':'post-body'}),
        }

models.py:
from django.contrib.auth import get_user_model
User = get_user_model()

# Create your models here.
class UserPost(models.Model):
    author = models.ForeignKey(User,related_name='userpost',null=True)
    post_date = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=150,blank=False)
    post_body = models.TextField(max_length=1000,blank=False)
    image = models.ImageField(upload_to='post_pics',blank=True)
    blog_post = models.BooleanField(default=False)

    class Meta:
        ordering = ['-post_date']

    def publish(self):
        self.save()

    def get_absolute_url(self):
        return reverse('index')

    def __str__(self):
        return self.title

Views.py:
from django.shortcuts import render,get_object_or_404,redirect
from django.utils import timezone
from feed.models import UserPost,UserComment
from feed.forms import PostForm,CommentForm
from django.urls import reverse_lazy
from django.contrib.auth.decorators import login_required

from django.contrib.auth import get_user_model

from django.contrib.auth.mixins import LoginRequiredMixin
from braces.views import SelectRelatedMixin

from django.views.generic import (TemplateView,ListView,
                                    DetailView,CreateView,
                                    UpdateView,DeleteView)

User = get_user_model()

# Create your views here.

##Posts Views
class HomeView(LoginRequiredMixin,ListView):
    login_url = 'account_login'
    model = UserPost

class CreatePostView(LoginRequiredMixin,CreateView):
    login_url = 'users:user_login'
    redirect_field_name = '/userpost_list.html'
    model = UserPost
    form_class = PostForm

    def form_valid(self,form):
        form.instance.author = self.request.user
        self.object = form.save(commit=False)
        self.object.user = self.request.user
        self.object.save()
        return super(CreatePostView, self).form_valid(form)

class PostDetailView(DetailView):
    model = UserPost
    post_comments = UserComment.objects.all()
    context = {
            'post':model,
            'comments':post_comments,
            }

class UpdatePostView(LoginRequiredMixin,UpdateView):
    login_url = '/login/'
    model = UserPost
    fields = [
            'title',
            'post_body',
            ]
    template_name_suffix = '_edit_form'

    def get_success_url(self):
        postid = self.kwargs['pk']
        return reverse_lazy('index')

@login_required
def DeletePost(request,pk):
    post = get_object_or_404(UserPost,pk=pk)
    post.delete()
    return redirect('index')

##Comments Views
@login_required
def add_comment_to_post(request,pk):
    post = get_object_or_404(UserPost,pk=pk)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.author = request.user
            comment.save()
            return redirect('feed:post_detail', pk=post.pk)
    else:
        form = CommentForm()
    return render(request,'feed/comment_form.html',{'form':form})

@login_required
def comment_remove(request,pk):
    comment = get_object_or_404(UserComment,pk=pk)
    post_pk = comment.post.pk
    comment.delete()
    return redirect('feed:post_detail',pk=post_pk)

##BLOG VIEWS
class BlogView(ListView):
    model = UserPost

A: in your view need add user to kwargs:
class CreatePostView(LoginRequiredMixin,CreateView):
    # Your code here
    def get_form_kwargs(self):
        kwargs = super(CreatePostView, self).get_form_kwargs()
        kwargs.update({'user': self.request.user})
        return kwargs

after it use __init__ method (i correct it with Daniel solution)
class PostForm(forms.ModelForm):
    class Meta:
        model = UserPost
        fields = ('title','image','post_body','blog_post')

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user')
        super(PostForm, self).__init__(*args, **kwargs)
        if not user.username == 'garrett':
            self.fields.pop('blog_post')

A: This can't possibly work in this way. This is all evaluated when the class is defined, long before there are any users. And User is the class itself, not an instance of it; User.username is just a CharField object, not an actual username.
Instead, you need to set the full list of fields as default, but in the form's __init__ method you take the current user and modify the actual fields as necessary.
class PostForm(forms.ModelForm):
    class Meta:
        model = UserPost
        fields = ('title','image','post_body','blog_post')
    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user')
        super(PostForm, self).__init__(*args, **kwargs)
        if user.username != 'garrett'
            del self.fields['blog_post']


text:
Q: Writing to csv file via django is adding the module name in the first cell of the file header I am currently trying to write to a csv file from Django given a list of headers and various data.  The file is being successfully created with one exception, the first cell is always showing the module info right before the value of the header and I'm not sure why.  I read the documentation related to csv file outputting and modeled the code after it as indicated below:
file_name = '%s_success.csv' % file_name
response = HttpResponse(csv, content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=%s' % file_name
c = csv.writer(response)
headers = ['foo', 'bar', 'abc', '123']
c.writeheader(headers)
for row in data:
   ...
   ...

Result:
<module 'csv' from '/usr/local/lib/python2.7/csv.pyc'>foo, bar, abc, 123

I want:
foo, bar, abc, 123

What should I change?

A: It looks like you're including the module in the response:
response = HttpResponse(csv, content_type='text/csv')

Just try
response = HttpResponse(content_type='text/csv')

redpajama_set_name: RedPajamaStackExchange


text:
Q: $translate.instant does not translate values in AngularJS component when component starts With Angular Translate and $translate.instant() method I built AngularJS's select component with automatic switching between languages:
<translated-select
  elements="$ctrl.values"
  current-value="$ctrl.value"
  on-change="$ctrl.setValue(value)"
></translated-select>
{{ $ctrl.value }}
<hr>
<button ng-click="$ctrl.switchToPolish()">
  Switch to polish
</button>
<button ng-click="$ctrl.switchToEnglish()">
  Switch to english
</button>

As you can see on Plunker: Angular JS select with automated translations. Problem is that it shows selects options as undefined until I choose second option. Then everything works, and I can switch between english and polish translations of options. I tried even wait for first change with $onChanges hook and if change occurred run $digest with $timeout:
this.$onChanges = function (changes) {
  if (changes.elements) {
    $timeout(function () {
      this.values = changes.elements.currentValue;
    }.bind(this));
  }
  if (changes.currentValue) {
    $timeout(function () {
      this.value = changes.currentValue.currentValue;
    }.bind(this));
  }
}

But again and again, I have to choose second option in select to make it work. Am I missing something? I would be grateful if anybody will help me, thank you in advance.

A: $translate.instant() isn't aware of the fact that the translation might not be loaded completely.
As per documentation:

Returns a translation instantly from the internal state of loaded
  translation.

So if you don't rely on $translate.instant() you could also use the translate filter (which uses a watch internally) as follows:
<select ng-model="$ctrl.value"' + 'ng-options="value as (value | translate) for value in $ctrl.values" ' + ' ng-change="$ctrl.onSelect()" ' + '></select>

A complete example can be found here:
http://plnkr.co/edit/zmYgiOOVjXCmGprsvOLO?p=preview

A: Consider having a try of $onInit instead of $onChanges. As from the documentation:

$onInit() - Called on each controller after all the controllers on an element have been constructed and had their bindings initialized (and before the pre & post linking functions for the directives on this element). This is a good place to put initialization code for your controller.

this.$onInit = function() {
  this.values = this.elements;
  this.value = this.currentValue;

  this.onSelect = function() {
    this.onChange({
      value: this.value
    });
  };

  this.translate = function(key) {
    return $translate.instant(key);
  };
};

See: http://plnkr.co/edit/5T90efhcnaQoEGoLY1gZ?p=preview


text:
Q: If we can access private data members using Accessors than why cant we access private methods? We can access Private data members using accessor method such as
 private int num=5;

 public int get_num()
 {
  return num;
 }

and we can access the returned value from any class even though num is private data member.
So on Similar note cant we create accessor method that returns private methods?
I just had a thought about it,If we cannot do this please explain.Thank You

A: Private methods are created when refactoring your code. They are implementation details, which nobody outside needs to know. They are used inside public methods, which are supposed to provide the functionality you want to provide to your client(each public method can be called an API which is used/consumed by other classes i.e. its clients).
Access modifiers are provided to help you achieve proper abstraction. So anything marked private  is directly accessible only inside your class. But if you want someone outside to read/write its value, you expose it via getters/setters. Similarly private methods are not accessible outside the class. But nobody is stopping you from creating  public method that only calls this private method. This way you do achieve access to private method. But it would be a very poor design.

A: You can access private method via public method. This is sometimes used to wrap complicated private method and expose simpler, public API.
class Delegator {

    private void doPrivateStuff(int param) { ... }

    public void doStuffOnce() {
        doPrivateStuff(1);
    }

    public void doStuffIfConditionIsMet() {
        if(condition) {
            doPrivateStuff(1);
        }
    }
}

You can also access private methods using reflection.
http://tutorials.jenkov.com/java-reflection/private-fields-and-methods.html

A: Because the accessor is public, it can be accessed from outside the class; even if it returns private data.
The access modifier of the returned data isn't relevant, only the access modifier of the method matters.
If you created a public method that returned a reference to a private method, yes, you could then call the private method from outside the class. That would entirely defeat the purpose of making the method private however.
You my be wondering "why make a public getter to a private variable". The answer is that although it's possible to retrieve the private data, it isn't possible (unless you create a public setter as well) to change the public data. This assumes that the private days is immutable. If it's mutable, retuning a reference to private data negates any protection you get from making the variable private.

A: TL;DR
Accessing private methods violates the basic object oriented principle of encapsulation. The question is not "can we access a private method?" but "should we ever do it?". It contradicts the principle of information hiding and it breaks the contract an object "offers" to its consumers. Objects or classes that enforce you to do that should be considered poorly designed.
Why you shouldn't access private members
First a classes should implement a part of your domain logic that is so closely related that there are little interactions necessary with the outside world to fulfill its duties (this is called high cohesion). You then define a public interface for your class / object with functionality that you expose to the outside world - consumers of your object must only use this interface (this is called loose coupling).
Private methods can be seen as a way to structure your code inside your class in a better readable way - they are not intended to be shared with the outside world. Consider them as a "safe space" for the developer of the class to make arbitrary changes without breaking the contract. That's the reason why there can be bad side effects if you actually access private methods: your code is likely to break it the developer of the class decides to change the implementation of such a method. Effective Java, Chapter 4, Item 13 explains this for protected members:

For members of public classes, a huge increase in accessibility occurs when the access level goes from package-private to protected. A protected member is part of the class's exported API and must be supported forever. Also, a protected member of an exported class represents a public commitment to an implementation detail.

Exceptions
The only exception I know from the rule of "not accessing private members outside of an object" is in testing, when you either want to reset a certain variable (e.g. a Singleton) or you want to facilitate the testing of complex logic by testing the private parts of the implementation and hence reducing complexity in testing.


text:
Q: How to set QMainWindow as the modal one? I am using QMainWindow for GUI development of my project..One problem I am Stuck with is blocking all other visible windows from getting input, while one is in operation.
I can not use QDialog.Because rich features of QMainWindow is required.
How can I declare a particular window as modal?
I tried with QWidget::setWindowMOdality().
Here is a demo program, what I tried but it didnt work.
#include <QApplication>
#include <QMainWindow>
#include <QPushButton>

int main(int argc, char **argv){

QApplication a(argc, argv);

    QMainWindow *w1 = new QMainWindow();
    w1->resize(500,800);
    w1->move(100,50);
    w1->show();

    QMainWindow *w2= new QMainWindow();
    w2->resize(800,500);
    w2->move(50,50);
    w2->show();

    w2->setWindowModality(Qt::ApplicationModal);

    return a.exec();

}

A: Try setting the modal flag first, then show the widget.
w2->setWindowModality(Qt::ApplicationModal);
w2->show();

Also you could use QWidget and build the toolbar, menu bar and status bar.


text:
Q: R: barplot: space between outer bars and the plotting area I have a piece of code as below:
par(mar=c(0.1, 15, 0.5, 15))
barplot(dat[[1]][, 2], beside=TRUE, axes=FALSE, ylim=ylim.axis_left, space=0, col="#808080")
box()

which generatess this plot:

I want to get rid of the space between the left/right bar and the plotting area, as marked with the box(). I played a little with margins, but it's not the solution, since these shrink the plotting area itself but the space remains...

A: In absence of reproducible example I took mtcars data
barplot(mtcars$cyl, axes=FALSE, space=0, col="#808080")
box()

When you set xaxs and yaxs as below you can notice that the default margin on both side of plot is gone.
barplot(mtcars$cyl, axes=FALSE, space=0, col="#808080", xaxs="i", yaxs="i")
box()


text:
Q: Error 500 (Internal Server Error) during Pyrocms installation I have Composer and XAMPP Server with PHP 5.6 installed on Windows 7.
I'm following Pyrocms documentation here:
https://www.pyrocms.com/documentation/pyrocms/installation
Following the steps, I created a new pyrocms project inside htdocs/pyrocms and downloaded vendor packages with composer install
Now, while tring to open localhost/pyrocms/public in order to start Pyrocms installation, it gives me the following error:

Apparently, laravel.log file shows the following errors: different line number every different time.

[2016-09-11 15:14:11] production.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Maximum execution time of 30 seconds exceeded' in F:\famp\htdocs\pyrocms\vendor\leafo\scssphp\src\Parser.php:898
[2016-09-11 15:15:27] production.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Maximum execution time of 30 seconds exceeded' in F:\famp\htdocs\pyrocms\vendor\oyejorge\less.php\lib\Less\Parser.php:2462
[2016-09-11 15:16:15] production.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Maximum execution time of 30 seconds exceeded' in F:\famp\htdocs\pyrocms\vendor\leafo\scssphp\src\Parser.php:844
[2016-09-11 15:21:29] production.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Maximum execution time of 30 seconds exceeded' in F:\famp\htdocs\pyrocms\vendor\leafo\scssphp\src\Parser.php:1354

What could be the possible cause for maximum time exceeded error?

A: The error code 500 is a server error, so you should be able to find the reason of the failure in the server logs, somewhere like \xampp\apache\logs.
ETA: As you have edited your question, it's not rare that an installation script takes a long time. You should be able to find information about this in your CMS installation notes.
So, just for the installation time you can change your php.ini like this:
; Maximum execution time of each script, in seconds
; http://php.net/max-execution-time
; Note: This directive is hardcoded to 0 for the CLI SAPI
max_execution_time = 300


text:
Q: Obtain the upper bound for a sequence Let $c_1>0$ and $0<a<1$ be real numbers. How to argue that there exists a constant $C>0$ such that
$$a^{c_1\ln T}\leq T^{-C}$$
for all sufficiently large $T$, or even better, for all $T\in\mathbb{N}$?
The paper that I'm reading says that such $C$ exists but I'm not completely sure about it. Both sequences of the forms $a^{c_1\ln T}$ and $ T^{-C}$ converges to zero as $T\to \infty$. But to satisfy the inequality above I should pick $C$ so that $ T^{-C}$ converges to zero not faster than $a^{c_1\ln T}$ (otherwise the ratio of them would diverge).
My attempt
For all $T\in\mathbb{N}$, taking logs both sides
\begin{align}
a^{c_1\ln T}\leq T^{-C} &\iff c_1 \ln T \ln a\leq \ln 1-C\ln T\\
&\iff c_1\ln a\leq -C
\end{align}
Thanks in advance.

A: Since $a\in(0,1)$, there must be some $C>0$ such that $a^{c_1}=e^{-C}$. So take $C=-c_1\log a$. Then
$$T^{-C}=T^{c_1\log a}=T^{\log a^{c_1}}=(e^{\log T})^{\log a^{c_1}}=(e^{\log a^{c_1}})^{\log T}=a^{c_1\log T}.$$


text:
Q: Send email with HTML content I'm trying to send an email with an HTML body.
I have a String that contains some valid html:
<!DOCTYPE html>

    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>

%s

from which I replace %s by some HTML.
Then I try to send this as an HTML email with the following code:
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("text/html");
    intent.putExtra(Intent.EXTRA_SUBJECT, "subject");
    intent.putExtra(Intent.EXTRA_TEXT, myhtmlcontent);
    context.startActivity(Intent.createChooser(intent, context.getText(R.string.share)));

but I only receive the html source code as plain text
Now if I replace
intent.putExtra(Intent.EXTRA_TEXT, myhtmlcontent);

with
intent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(myhtmlcontent));

I receive a valid HTML email, but all my images have been replaced with some special character. Is there a way to keep my original html content and display it as a HTML email ?
Here's my full HTML code
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

Les enfants, l’heure est grave. Vous l’avez compris car vous l’avez lu dans le
    titre de la news (eh ouaip!), Edgar Wright ne réalisera finalement pas Ant
        Man. Alors qu’il était rattaché au projet depuis 2006 et qu’il en avait
    écrit le scénario avec Joe Cornish, Marvel a annoncé que le
    réal avait quitté le navire. La faute à quoi? Des « différences créatives »,
    soit la meilleure excuse qu’Hollywood aie jamais inventé.

Marvel a par ailleurs ajouté que le départ de Wright  ne
    changerait rien au casting ni à la date de sortie du film et qu’un remplaçant, dont le nom
    devrait bientôt tomber, avait déjà été engagé. Dommage, ça n’aura pas la même saveur.

Ant Man avec Paul Rudd, Michael Douglas, Evangeline Lilly, Corey Stoll, Michael
    Pena et Patrick Wilson. Mais sans Edgar Wright.
    Sortie en juillet 2015

Source: Variety

A: The interpretation of any Intent is up to the receiver. There are many ACTION_SEND handlers, including many email apps. There are no requirements for the HTML being sent out by the email app to be identical to the HTML that you supply.
In particular, few (if any) email apps will support HTML that contains some of the structures that your HTML contains, such as:

*

*<meta>

*class attributes

*style attributes

That is because most email apps will be using EditText to allow the user to edit the email, and most email apps will use Html.fromHtml() to generate the Spanned to supply to EditText as the starting text. Html.fromHtml() does not support the things I cited. This blog post cites what was supported back in 2010, and AFAIK it has not changed much since then.
So, if you stick to HTML tags and attributes that work with Html.fromHtml(), you will maximize the odds that your HTML will be sent intact, or close to intact. However, there is no guarantee that it will, as that is up to the email app author, not you.

A: What you have done seems right. Just upload the images on your server and give actual links to your images in the BODY of the email using the  tag.


text:
Q: How to hide selected option in Autocomplete using reactjs I want to hide the selected option in the Dropdown, the option should not appear in the next dropdown. For an example, there are 2 dropdowns, in the first dropdown - i have selected "Hockey" then "hockey" should not be shown in the second dropdown, It should show only "Baseball and badminton".
My JSON data will be appearing in this way:
"details": [
      { "id": "12wer1", "name": "ABC", "age": 15, "game": "badminton" },
      { "id": "78hbg5", "name": "FRE", "age": 21, "game": "Hockey" }
    ]

Here is the sample Code:
let games = [{ game: "Baseball"}, { game: "Hockey"}, { game: "badminton" }];

class Field  extends React.Component {
constructor(props) {
    super(props);
    this.state = {
      details: [{id: '', name: '', age: '', game: ''}]
    }
  }
  ...
  ...
render() {
return (
 ...
 ...
{this.state.details.map((y) => (
 <Autocomplete
     style={{ witdth: 200 }}
     options={games}
     getOptionLabel={(option) => option.game}
     onChange={(value) =>this.onGameChange(value, y.id)}
     value={games.filter(i=> i.game=== y.game)}
     renderInput={(params) =>
        <TextField {...params} label="Games" margin="normal" />
       }
   />))}
  ...
  ...
  )
 }
}

onGameChange = (e, id)=> {
let games = this.state.details;
            let data = games.find(i => i.id === id);
            if (data) {
                data.game = value.game;
            }
            this.setState({ details: games });
}

I have no idea, how to hide the selected option, can anyone help me in this query?
Thanks! in advance.

A: you can hide this is in CSS easily no need to do anything in ReactJS
autocomplete renders as an unordered list so something like this
.panel > ul > li:first-child {
 display:none;
}

A: A possible solution would be to

*

*create an array and store the values in an array when the user selects autocomplete

*while passing options, filter the values that have been passed to other autocompletes.
 const ary = [111,222,333];

 let obj = [{id: 111},{id: 222}];

 const i = 1; // this is your index in loop
 const ary2 = ary.slice()
 ary2.splice(i,1);
 console.log(obj.filter((o) => !ary.includes(o.name))); // this should be given to our options list in autocomplete


text:
Q: How can I add a limit to @Query along with OFFSET and FETCH NEXT? I have pagination in the queue, I also want there to be a limit of 100 items per issue.
That is, with page=14(starting from 0) and size=7, (sum 105) and limit 100, I should get 2 elements.
I'm trying to add a LIMIT but I don't understand how to specify it correctly with pagination
How to add LIMIT 100 to this Query?
(postgresql)
@Query("SELECT * FROM notification WHERE " +
        "(user_identifier is null or user_identifier = :userIdentifier) " +
        "and (date >= :date) " +
        "and (country is null or country = :country) " +
        "ORDER BY date desc " +
        "OFFSET :page " +
        "FETCH NEXT :size ROWS ONLY")
Flux<Element> findAllByUserIdentifierAndCountry(String userIdentifier, Timestamp date, String country, int page, int size);

So far I have used Flux .take() to pick up the required number of items


text:
Q: Child Numbers: Items follow section numbers I'd like the numbering of items in the document to reflect the numbers of the sections in which they are found. In the MWE, the numbering is
Section 1
1.
2.
Section 2
1.
2.
What I want is:
Section 1
1.1
1.2
Section 2
2.1
2.2
How can I achieve this?
\documentclass[11pt]{article}

\begin{document}
%\maketitle
%\section{}
%\subsection{}

\section{Structure}
\begin{enumerate}

\item
first point
\item
Second point

\end{enumerate}

\section{Circus Tents}
\begin{enumerate}
\item
number
\item
kind
\end{enumerate}

\end{document}

A: There are a number of ways to achieve this. First, if you're not into using packages, adjust \labelenumi by adding this to your document preamble:
\renewcommand\labelenumi{\thesection.\theenumi.}. It prefixes \thesection to the default label.

\documentclass{article}

\renewcommand\labelenumi{\thesection.\theenumi.}

\begin{document}

\section{Structure}

\begin{enumerate}
  \item
  First point

  \item
  Second point
\end{enumerate}

\section{Circus Tents}

\begin{enumerate}
  \item
  Number

  \item
  Kind
\end{enumerate}

\end{document}

This process is made a little more easy using enumitem:
\documentclass{article}

\usepackage{enumitem}
\setlist[enumerate,1]{label=\thesection.\arabic*.}

\begin{document}

\section{Structure}

\begin{enumerate}
  \item
  First point

  \item
  Second point
\end{enumerate}

\section{Circus Tents}

\begin{enumerate}
  \item
  Number

  \item
  Kind
\end{enumerate}

\end{document}


text:
Q: Analytic complex function with $u=v^2$ I must prove that if $f = u+iv$ is analytic with $v=u^2$ then $f$ is constant. My attempt is $$f(x,y) = u(x,y)+iv(x,y) = u(x,y)+iu(x,y)^2$$ and write $$\frac{\partial v}{\partial y} = \frac{\partial }{\partial y} (u(x,y)^2) = 2u(x,y) \cdot u_y$$ $$\frac{\partial v}{\partial x} = \frac{\partial}{\partial x} (u(x,y)^2) = 2u(x,y) \cdot u_x$$ f is analytic so we can use the Cauchy - Riemann equations $$\frac{\partial u }{\partial x} = 2u(x,y) \frac{\partial u}{\partial y}$$ $$\frac{\partial u}{\partial y} = -2u(x,y)\frac{\partial u}{\partial x}$$ so $$\frac{\partial u}{\partial x} = -4u(x,y)^2\frac{\partial u}{\partial x} \implies v(x,y) = -\frac{1}{4}$$ is that right? I feel like I'm missing a lot of things. Any help is appreciated!

A: The image of the holomorphic f lies on the parabola u=$v^2$ and hence the image omits more than one point in the complex plane. Thus the function is a constant by Picard's theorem.


text:
Q: Formalizing "no junk, no confusion" Goguen has popularized the initial algebra view of semantics via his "no junk, no confusion" slogan.  By "no junk", he means that models of a theory presentation should not have unnecessary elements, and "no confusion" that terms should not be mapped to equal values unless they are provably equal.  Sometimes, "no junk" is also interpreted as every element in the model is a denotation of a term, while "no confusion" as two different terms denote different elements in the model.  [These are classically equivalent statements, but they are not intuinistically equivalent, so I mention both].
My questions are:

*

*What is a 'good' formalization of this slogan?  By this I mean an explicit statement of "no junk, no confusion" in the meta-logic (since we're talking about models), where the logical strength of the corresponding statement is well understood.

*Are there logics in which these requirements can be internalized?

*What would be the corresponding slogan to "no junk, no confusion" for final coalgebras?

A: The way I understand each of the slogans is as follows:

*

*"No junk" I just take to mean that an appropriate induction principle is valid -- that is, we should look for initial models in the appropriate category of algebras for the theory. This also implies that every element of the model is in the image of the interpretation of the the algebraic theory.
Presumably the dualization to coalgebras would just be the validity of using bisimilarity to prove equality.

*"No confusion" is traditionally interpreted to mean that we should look for models in which two elements of the model are semantically equal if and only if the corresponding syntaxes are provably equal. This is the really bizarre requirement, since it amounts to requiring that the model be isomorphic to the term model! And yet Goguen and the algebraic specification community were emphatically not happy with decreeing the term model to be the intended model -- they work very hard to get the "right" model.
I personally (ie, I don't know that anyone else believes this) take the way this requirement is phrased to be an artifact of the history of algebraic specification. IIRC, they started out with purely algebraic theories -- that is, theories in which the equational axioms are all pure equalities. (E.g., the axioms for groups.) Now, of course every such algebraic theory has a degenerate model, since the one-element model validates all equalities.  So the no-confusion principle is intended to rule out such degenerate models.
These days, of course, the algebraic specification crowd has no problem with theories with inequalities (e.g., the field axioms), and I think this additional freedom lets us state the no-confusion principle in a better way. Namely, we should design algebraic theories whose models are categorical. That is, we want theories for which all models are isomorphic. This implies the traditional no-confusion criterion, and also explains why people try to adjust the signature when they can't prove it. (Of course, this is a non-first-order property in general, as you need higher-order logic or set theory to quantify over models.)

A: Belatedly, an answer in set-based situations to

*

*What would be the corresponding slogan to "no junk, no confusion" for final coalgebras?

Given an initial algebra, any algebra will have a special subobject which is the image of the initial structure. The subobject may have confused elements (terms) of the initial algebra, and the object may have extra junk. A map between objects will map the first special subobject to the second, possibly confusing more. The initial algebra has no confusion and no junk.
Given a final/terminal coalgebra, the elements of any coalgebra will have a special colouring in terms of images in the elements of the terminal structure. The object may have more than one element with the same colour, and the object may not use all the colours. A map between objects will preserve the colouring, the domain possibly using fewer colours. The terminal coalgebra colours without ambiguity and without redundancy. If two things behave the same way, they are the same; all behaviours are covered.
No junk, no confusion; No redundancy, no ambiguity.

A: The slogan is a meaningful english phrase.  After removing negation, we may obtain this phrase: "stay clean, stay clear".  So then, here is an actual theorem of quantified boolean formulas that describes both qualities formally:
Linear Corollary:  Quantified  monotone  boolean formulas are linearly decidable.
That is, no matter how many alternating quantifiers are in the prefix, when the body of the formula has "zero negations," then the monotonicity of the formula makes any quantifier prefix linearly decidable;  plug T for existentially quantified variables, NIL for universally quantified variables, then evaluate the boolean form, entirely linear in the size of the QBF.
Goguen may also enjoy the car/cdr Structure of Common Sense:  Good ideas   Usually have   Two words.


text:
Q: System keeps getting hung - Flash error I open firefox and browse through sites. Sometimes, automatically, the cursor stops moving, I can't use the keyboard too and system is hung. It doesn't go to the command line either. I found out that this may mostly be due to a adobe flash plugin. I don't know which one or which one to remove.
Every time this happens I have to manually force shutdown the computer and switch it on again.
I know I've been pretty vague in giving details but I don't know how exactly this problem occurs.
I'm using Ubuntu 14.04.

A: You resolve problems by trying one thing at a time
Is flash the problem?:

*

*disable flash in Firefox

*

*go to firefox/tools > addons > plugins and set shockwave flash to ask to activate

*does the problem still exist?

Is Firefox the problem?

*

*install another browser

*

*How to install Google Chrome

*does the problem still exists?

Good luck!

A: I was having exactly the same problem on 2 different machines I disabled flash on one of them and the problem seemed to go away. Will do the other tomorrow. IMO I think that either Fire Fox is buggy or its the Flash plugin either way it makes for a terrible experience you should not have to disable a plug in to make it stable


text:
Q: MySQL: Login Failed for User I have tried to connect to my SQL database being hosted on Plesk with InterServer using C# ASP.NET MVC. Despite numerous efforts, it never seems to want to connect. What am I doing wrong?
I've tried changing the connection string numerous times. Plesk and InterServer support ask me to deploy my code and access the database via localhost. Due to this, I have tried the following connection strings:
"SERVER=localhost;DATABASE=databasename;UID=username;PASSWORD=password;"
"SERVER=localhost:3306;DATABASE=databasename;UID=username;PASSWORD=password;"
"SERVER=localhost;PORT=3306;DATABASE=databasename;UID=username;PASSWORD=password;"
"SERVER=(Local);DATABASE=databasename;UID=username;PASSWORD=password;"

I have tried interchanging "Server" with "Data Source", among other keyword changes. I have also tried setting Trusted_Connection to both true and false, and setting Integrated Security to both true and false. It seems when I try to set them to true, the application tries to log in using my Plesk username rather than the User ID I specified in the connection string. This user has no association to the database nor am I able to associate it in the Plesk control panel to my knowledge.
I have also tried using the default connection string in the Plesk Control Panel alongside a couple of modifications to said connection strings, one of which even provided by InterServer support as they suspect the error is in my connection strings. Here are those strings:
"data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
"Data Source=(IPAddressWasHere)\MSSQLSERVER2017;Initial Catalog=nlstatic;Persist Security Info=True;User ID=username;Password=password"
"Data Source=.\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\db.mdf;Initial Catalog=Portal.Web;Integrated Security=True"
"Data Source=.\SQLExpress;Initial Catalog=localhost;Integrated Security=True"

I have also tried changing the proverName from System.Data.SqlClient to MySql.Data.SqlClient, but this seemed to not change the error message. Personally, I'm at the point where I suspect that this issue isn't with a connection string setup, but instead with the configuration of the MySQL database or its settings.
Despite trying to ask InterServer support for assistance regarding this, they refuse to look into the matter. Instead, they once asked me to "properly set up my VPS" (I don't have a VPS with them at all) and tried to convince me I was trying to connect via ODBC when I clearly stated it was through connection strings.
In case it's relevant, here's my C# code on how I'm using the connection string, though I don't feel it's the cause personally:
        public List<string> GetEffectByID(int id)
        {
            List<string> results = new List<string>();
            SqlConnection conn;
            string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

            conn = new SqlConnection(connectionString);

            try
            {
                using (SqlCommand command = new SqlCommand("getFxById", conn) { CommandType = CommandType.StoredProcedure })
                {
                    conn.Open();
                    using (SqlDataReader dr = command.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            results.Add(dr["myColumn"].ToString());
                        }
                    }
                    conn.Close();
                    return results;
                }
            } catch(Exception e)
            {
                if(conn.State == ConnectionState.Open) conn.Close();
                return new List<string>() { e.ToString() };
            }
        }

This stored procedure definitely exists in my database, and it works in phpMyAdmin
Is there something that I've missed throughout this entire process? I expect it to be able to connect and run the stored procedure when my View calls the function. Despite this, using the methods provided by Plesk/InterServer, it claims that the server was not found/accessible. When I try to use the connection strings I've created (Without using Integrated Security), it provides this error message instead:

System.Data.SqlClient.SqlException (0x80131904): Login failed for user 'Shizuku'. at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling, SqlAuthenticationProviderManager sqlAuthProviderManager) at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource1 retry) at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1 retry) at System.Data.SqlClient.SqlConnection.Open() at (Code file was here) ClientConnectionId:953f6859-a48b-4f58-a0b8-bef0702911a3 Error Number:18456,State:1,Class:14

I feel as if that error means I'm closer to solving the issue currently, but I'm not entirely sure. Is there anything I haven't tried or any error I've made that I just simply missed?

A: I found out the error: My host, InterServer, was rejecting the connection, claiming that a "localhost connection was a remote connection". After several hours of back and forth with support, I finally requested a refund.
After this, the support agent finally started trying to get it to work desperately, scrambling for a solution by changing my Web.config as he was convinced it was my issue, not his. To no avail, he made a test domain and copied my files/database. Of course, he didn't have my C# code and this led to an "Object not set to a reference" error for an object creation statement (using the new keyword). As a last resort, he created a PHP file that literally read "Connection succeeded" and had no actual code in it, then sent me a link to it claiming that "the error was not on the server's side, see?"
The solution to my problem was to not buy shared hosting from InterServer, and potentially not even to go with InterServer as a whole. Their support is awful, and they employ these kinds of shady tactics to keep customers troubleshooting past the 30 day money-back period. Buyer beware.


text:
Q: Once Again NgFor only supports binding to Iterables such as Arrays As many before me, I have this error :
Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

I was trying many solutions like :
error display in *ngfor json array object
But nothing works.
  public getInterfaces(): Observable<InterfaceBrief[]> {
    let headers = this.createBasicHeaders();
    let options = new RequestOptions({
      method: 'get',
      headers: headers});
    let url = this.restApi +"/dashboard/list";
    console.log(url);
    return this.http.get(url, options)
      .map(this.extractData)
      .catch(this.handleError);
  }

  private extractData(res: Response) {

    let body = res.json();
    console.log("GOOD");
    return body.data || {};
  }

export class DashboardComponent implements OnInit {

  errorMessage: string;
  interfacesBrief: InterfaceBrief[];

  constructor(private _service: AuthService, private _emotService: EmotClientService) {
  }
  ngOnInit() {
    this.getInterfaces();
  }
  getInterfaces() {
    this._emotService.getInterfaces().subscribe(

      data => this.interfacesBrief = data,
      error => this.errorMessage = <any>error
    );
  }
}

When I  changed:
    return body.data || {};

to :
return body.data.items || {};

I have error :
Cannot read property 'items' of undefined

ERR :Cannot read property 'data' of undefined

A: Based on comment, when you console.log your response: Array[2] 0 : Object 1 Object client: "client1" countKO: 3 (...) you clearly are not having a data object in your response, therefore you should just return the response as is.
private extractData(res: Response) {
  let body = res.json();
  return body || []; // here!
}

And when you have received your response, you just iterate that array and display the properties you want, so something like this:
<div *ngFor='let item of interfacesBrief'>
  {{item.client}} - {{item.countKO}}
  <!-- print whatever else properties you have and want to display -->
</div>

A: *

*return only res.json()
(why becasue sometimes if data is not fetched proerply than angular will throw error here).

*try to use elvis operator (safe navigation) in the HTML.
Try this code
  private extractData(res: Response) {

    let body = res.json();
    console.log("GOOD");
    return body || {};
  }

  export class DashboardComponent implements OnInit {
   ...............

  getInterfaces() {
    this._emotService.getInterfaces().subscribe(

      data => {
        this.interfacesBrief = data
        console.log(this.interfacesBrief ,"Without Error")
      },
      error => this.errorMessage = <any>error
    );
  }
}

<div *ngFor='let items of interfacesBrief?.data?.items'>
  {{items}}
</div>


text:
Q: How to create clickable magnet URL in discord embeds In the embed description I have the magnet url [Link]({{3.rssFields.link}}). How do I make this clickable? I would like it to open the available torrent client. Would appreciate any suggestions.

A: Well, I don't know about the bot but discord has made magnet links unclickable for security reasons. I suggest you use the magnet link.
Also, the correct form is [link text](magnet link). I don't see a reason why you have so many {{}}.


text:
Q: JSF 2.0 - Myfaces have problems rendering composite components Some days ago I've changed mojarra to myfaces to solve this problem, now I'm having an strange problem rendering my composite components, they simply aren't rendered the second time I open one popup (the popup is a composite component too).
The first time, as you can see in fieldset, all is rendered ok:

then I click in "CANCELAR" (cancel) button, and the second time, none of my composite components, except the dialog, is rendered:

when I've looked at log, I found these messages:
[#|2012-04-10T15:22:00.681-0300|SEVERE|glassfish3.1.1|org.apache.myfaces.renderkit.html.HtmlCompositeComponentRenderer|_ThreadID=19;_ThreadName=Thread-2;|facet UIComponent.COMPOSITE_FACET_NAME not found when rendering composite component prevenda:popupPreVenda:j_id_2uz|#]
[#|2012-04-10T15:22:00.684-0300|SEVERE|glassfish3.1.1|org.apache.myfaces.renderkit.html.HtmlCompositeComponentRenderer|_ThreadID=19;_ThreadName=Thread-2;|facet UIComponent.COMPOSITE_FACET_NAME not found when rendering composite component prevenda:popupPreVenda:inputRazaoSocial|#]
[#|2012-04-10T15:22:00.685-0300|SEVERE|glassfish3.1.1|org.apache.myfaces.renderkit.html.HtmlCompositeComponentRenderer|_ThreadID=19;_ThreadName=Thread-2;|facet UIComponent.COMPOSITE_FACET_NAME not found when rendering composite component prevenda:popupPreVenda:j_id_2vi|#]
[#|2012-04-10T15:22:00.685-0300|SEVERE|glassfish3.1.1|org.apache.myfaces.renderkit.html.HtmlCompositeComponentRenderer|_ThreadID=19;_ThreadName=Thread-2;|facet UIComponent.COMPOSITE_FACET_NAME not found when rendering composite component prevenda:popupPreVenda:j_id_2vn|#]
[#|2012-04-10T15:22:00.686-0300|SEVERE|glassfish3.1.1|org.apache.myfaces.renderkit.html.HtmlCompositeComponentRenderer|_ThreadID=19;_ThreadName=Thread-2;|facet UIComponent.COMPOSITE_FACET_NAME not found when rendering composite component prevenda:popupPreVenda:j_id_2vs|#]

as you can see, the problem is that myfaces can't find a facet in composite component...
The only composite component that uses facets is hrgi:popup:
<c:interface>
    <c:attribute name="titulo" default="sem titulo" required="false"/>
    <c:attribute name="renderizar" default="false" required="false"/>
    <c:attribute name="modal" default="true" required="false"/>
    <c:attribute name="bordaConteudo" default="true" required="false"/>
    <c:facet name="cabecalho" required="false"/>
    <c:facet name="conteudo" required="true"/>
    <c:facet name="botoes" required="true"/>
</c:interface>

<c:implementation>
<h:outputStylesheet library="css" name="hrgiPopup.css" target="head"/>
<h:outputStylesheet library="css" name="clearfix.css" target="head"/>
<h:outputScript library="js" name="hrgiPopup.js" target="head"/>
<h:panelGroup layout="block" rendered="#{cc.attrs.renderizar}"
              class="hrgi-dialog-panel clearfix">
    <h:panelGroup layout="block" class="hrgi-dialog-overlay clearfix" rendered="#{cc.attrs.modal}"></h:panelGroup>
    <h:panelGroup id="popup" layout="block" class="hrgi-dialog-box clearfix">
        <h:panelGroup layout="block" class="hrgi-dialog-title clearfix">
            <h:outputText style="float:left" value="#{cc.attrs.titulo}"/>
        </h:panelGroup>
        <h:panelGroup layout="block" class="hrgi-dialog-content clearfix">
            <c:renderFacet name="cabecalho" required="false"/>
            <h:panelGroup layout="block" class="hrgi-dialog-background clearfix"
                          rendered="#{cc.attrs.bordaConteudo}">
                <c:renderFacet name="conteudo" required="true"/>
            </h:panelGroup>
            <h:panelGroup layout="block" class="clearfix" rendered="#{not cc.attrs.bordaConteudo}">
                <c:renderFacet name="conteudo" required="true"/>
            </h:panelGroup>
            <c:renderFacet name="botoes" required="true"/>
            <script type="text/javascript">
                cercarEventoTab("#{cc.clientId}:popup");
            </script>
        </h:panelGroup>
    </h:panelGroup>
</h:panelGroup>
</c:implementation>

Is this a bug of MyFaces?? Mojarra doesn't show any problem like this!
UPDATED
The problem just happens when user clicks "CANCELAR" button... The action call this code to clear the fields and close the dialog:
public void cancelar(ActionEvent evento){
    fechar();
    UIComponent componente=evento.getComponent().getParent().getParent().getParent();
    componente.getFacet("conteudo").getChildren().clear();
}

this code was adapted from the approaches you can see here. In this case, only components inside facet conteudo are recreated. Works fine, except with the my composite components.

A: The code in MyFaces is ok. The log suggest org.apache.myfaces.renderkit.html.HtmlCompositeComponentRenderer cannot find the c:implementation entry in your composite component file, Since 2.1.6, some changes were done to prevent use '/' characters inside libraryName (see MYFACES-3454 for details). A web config param (org.apache.myfaces.STRICT_JSF_2_ALLOW_SLASH_LIBRARY_NAME) was added to enable the backward behavior, but note the new behavior is mentioned in a explicit way inside the spec.
If that doesn't work, please try create a simple demo app reproducing the bug and create an issue in MyFaces Issue Tracker. In that way, there are better chances that it could get solved in a future release.
UPDATE
I tried to reproduce it with the information provided without success. The problem is the call to
componente.getFacet("conteudo").getChildren().clear();

That code remove all components inside the facet, and MyFaces is smart enought to remember the components that were removed. When the view is restored, MyFaces algorithm builds the view as in the first request and then remove the components to restore the state correctly. This behavior is expected, so there is no bug in MyFaces code. Instead, I suppose the previous behavior described is a bug in Mojarra, and you should change your code to reset your input components in other way, maybe clearing the values inside the bean, or creating a method expression attribute in your composite component that can be called when cancel operation occur and clear the required input fields. There is a lot of ways to do it.

A: I don't know why, but after I've created some class to handle exceptions, this problem disappeared...
public class HRGIExceptionHandler extends ExceptionHandlerWrapper {

    private ExceptionHandler wrapped;

    public HRGIExceptionHandler(ExceptionHandler wrapped) {
        this.wrapped = wrapped;
    }

    @Override
    public ExceptionHandler getWrapped() {
        return wrapped;
    }

    @Override
    public void handle() throws FacesException {
        Iterator i = getUnhandledExceptionQueuedEvents().iterator();
        while (i.hasNext()) {
            ExceptionQueuedEvent event = (ExceptionQueuedEvent) i.next();
            ExceptionQueuedEventContext context = (ExceptionQueuedEventContext)event.getSource();
            Throwable t = context.getException();
            try{
                t.printStackTrace();
            }finally{
                i.remove();
            }
        }
        getWrapped().handle();
    }
}

and
public class HRGIExceptionHandlerFactory extends ExceptionHandlerFactory {

    private ExceptionHandlerFactory parent;

    public HRGIExceptionHandlerFactory(ExceptionHandlerFactory parent) {
        this.parent = parent;
    }

    @Override
    public ExceptionHandler getExceptionHandler() {
        ExceptionHandler result = new HRGIExceptionHandler(parent.getExceptionHandler());
        return result;
    }
}

finally I've added this to faces.config:
<factory>
    <exception-handler-factory>com.hrgi.web.erp.HRGIExceptionHandlerFactory</exception-handler-factory>
</factory>


text:
Q: Отладка скриптов В web программировании я относительно недавно, но вроде бы знаю уже достаточно, однако недавно возникла серьезная проблема. Суть такова: мне дают задание для какого либо сайта, соответственно, мне нужно узнать принцип работы данного скрипта, какие классы и в каком месте в файловой системе используются, но так все проекты у меня(как и большинство сейчас) это полноценные обьектно-ориентированные системы и структура скрипта состоит из множества подключений из различных библиотек, я не могу нормально разобраться в принципе подключения и использования того или иного класса. Какие есть программы или может быть библиотеки php, которые позволяют получить полную трассировку классов и функций, т.е. при вызове в каком либо скрипте я получал полноценную информацию, откуда подключаются классы, какие функции и методы используются.
A: Отладка

*

*Zend Debugger из Zend Studio

*Расширение Xdebug для PHP

*Работа с кодом(debug_backtrace, debug_print_backtrace, var_dump)

-
    var_dump(debug_backtrace());

Тестирование

*

*PhpUnit - каркас для модульного тестирования

A: Эм... глазками и ручками + поиск :)
Вот, собственно, и все :)
А в догонку - есть волшебная функция var_dump, которая покажет структуру любого типа объекта.
Так же, можешь в гугле посмотреть результаты по "профилирование кода". Это и есть что-то вроде дебаггера.


text:
Q: Error creating topic in Apache Kafka When using the command:

/usr/local/kafka/bin/kafka-topics.sh --create --zookeeper localhost:2181
  --replication-factor 1 --partitions 1 --topic test

I get the following error:
Unrecognized option: --create
Error: Could not create the Java Virtual Machine
Error: A fatal exception has occurred. Program will exit.

I am following the instructions in the Kafka: The Definitive Guide book.
Thanks in advance.

A: I had the same problem as yours.
I was able to make it work by adding sudo in the script: /usr/local/kafka/bin/kafka-topics.sh
exec sudo $(dirname $0)/kafka-run-class.sh kafka.admin.TopicCommand "$@"

A: You should check whether you have downloaded the correct (compiled) version.
This may happen if you are trying to run the script in the source code version.


text:
Q: How to grey out an option in system tray C# The problem is quite simple: is there a way I can grey out an option in the system tray? I have seen greyed/bold out options in other programs I use, so additionally how do I bold any options.
Here is my current code:
    ContextMenu tray = new ContextMenu();
    tray.MenuItems.Add("Open", TrayClose);

    NotifyIcon trayIcon = new NotifyIcon();
    trayIcon.Text = "myBeautifulProgram";
    trayIcon.Icon = Properties.Resources.program;

    trayIcon.ContextMenu = tray;
    trayIcon.Visible = false;

So it now looks like this (ignore the border):

Is there any way I can make this like greyed out or bold?

A: Your call
tray.MenuItems.Add("Open", TrayClose);

returns a MenuItem. It has useful members such as Enabled or DefaultItem.

A: In your case, you can do something like this. Important part is to set your menu item's Enabled property to false. This is just simple code that shows how it works - you can make it more elegant than this I believe :)
 tray.MenuItems.Add("Open", TrayClose);
 tray.MenuItems[0].Enabled = false;


text:
Q: Computing the derivative of a determinant expression I am trying to compute the derivative of the function $f(t)=\det(tC+I)$ where $I$ is the identity matrix. I know the answer should be $tr(C)$ but I am struggling to find an easy way to see this. Some suggestions I have received are using the Leibniz rule for determinants and I am interested if there is a way to do it using the Jacobi formula.

A: You can write: $$\det(tC+I)= t^n\det(C + \frac{1}{t} I) = t^nP_{(-C)}(\frac{1}{t})$$ where $P_{A}$ is the characteristic polynomial of $A$. From this you can see that the polynomial coefficients of $t^nP_{(-C)}(\frac{1}{t})$ are the coefficients of $P_{(-C)}$ written in reverse order. We get:
$$t^nP_{(-C)}(\frac{1}{t}) = 1 + tr(C)t \cdots + \det(C)t^n$$
As $\det(C)$ is the bottom coefficient of $P_{(-C)}$, it is the top coefficient of $t^nP_{(-C)}(\frac{1}{t})$.
From this we see that the derivative in $t$ of $$\det(tC+I) = 1 + tr(C)t + \cdots +\det(C)t^n$$ is $tr(C)$ at $t=0$.

A: The determinant is the product of all the eigenvalues of a matrix
So, given the eigenvalues of $C$ as $\gamma_i$, $f(t) = \prod t \gamma_i - 1$
The derivative of this expression is
$\dot f(t) = \sum \frac{1}{t \gamma_i - 1} f(t)$
Note if the derivative was the trace of $C$ then the determinant would grow linearly with respect to $C$ and that's only true if $C$ is a $1 \times 1$ matrix.


text:
Q: Trying to get a single row in a query? I am trying to get a single record in the case statement, where am i suppose to put the seelect statement top(1)
 CASE WHEN CAST(VehicleCC AS MONEY) BETWEEN -1 AND 50 THEN '33.94'
                          WHEN CAST(VehicleCC AS MONEY) BETWEEN 51 AND 125 THEN '39.65'
                          WHEN CAST(VehicleCC AS  MONEY) BETWEEN 126 AND 500 THEN '55.90'
                          WHEN CAST(VehicleCC AS  MONEY) BETWEEN 501 AND 650 THEN '67.31'
                          WHEN CAST(VehicleCC AS MONEY) BETWEEN 651 AND 1000 THEN '78.65'
                          WHEN CAST(VehicleCC AS MONEY ) > 1001 THEN '79.85'
                          else
                           (SELECT TOP(1) cast (VehicleCC as varchar (50)) FROM  HIRE_INSTRUCTION HIRP
                              INNER JOIN VEHICLE VEH ON HIRP.FKFleetVehicleID=VEH.vehicleid
                              WHERE HIRP.FKBLDRefID=cl.FKBLDRefID AND HIRP.Deleted=0 AND VEH.Deleted=0
                                ORDER BY veh.VehicleCC DESC) END AS [Hire Rate Charged Per Day],

A: If TOP(1) isn't working, try RANK():
SELECT VehicleCC
FROM (
    SELECT CAST(VEH.VehicleCC as varchar (50)),
        RANK() OVER(ORDER BY CAST(VEH.VehicleCC as varchar (50))) AS CCRank
    FROM  HIRE_INSTRUCTION HIRP
        INNER JOIN VEHICLE VEH
            ON HIRP.FKFleetVehicleID=VEH.vehicleid
    WHERE HIRP.FKBLDRefID=cl.FKBLDRefID
        AND HIRP.Deleted=0
        AND VEH.Deleted=0
    ORDER BY veh.VehicleCC DESC
    ) CC
WHERE CCRank = 1

A: You can use set rowcount to limit the number of rows returned by a query.
set rowcount 1 -- the query will return one record

select * from table

set rowcount 0 --back to normal


text:
Q: What is the purpose of the Maurer–Cartan structural equations and the compatibility conditions? In the "Maurer–Cartan form" article from Wikipedia:

A system of non-degenerate g-valued 1-forms $θ_U$ defined on open sets
in a manifold M, satisfying the Maurer–Cartan structural equations and
the compatibility conditions endows the manifold M locally with the
structure of the homogeneous space $G/H$. In other words, there is
locally a diffeomorphism of M into the homogeneous space, such that
$θ_U$ is the pullback of the Maurer–Cartan form along some section of
the tautological bundle

*

*I understand what this mean, but don't understand what is the purpose to define such compatible forms on M. Is there a more rigorous description of the purpose? (Does the 3rd subquestion bellow have an answer to this?)

*I feel this has some connection with the intuitive concept of "rolling a Klein geometry homogeneous space on a manifold", is it?

*I also feel this is a just a special case (i.e. a special principal bundle: the tautological principal bundle) of the "The principal connection for a connection form" section of the "Connection form" article in Wikipedia, is it?

*Why does it emphasize "there is locally a diffeomorphism of M into the homogeneous space", isn't M already a submanifold of the homogeneous space and of course there is a diffeomorphism?


text:
Q: How to calculate the confidence interval of a line based on its coefficients? I fitted a mixed model as following:
$Y = \beta_0 + \beta_1 T + \beta_2 X + \beta_3 X T + \beta_iW_i$
$T$ is time, $X$ is my variable of interest and $W_i$ are various confounding variables. I also used a specific covariance matrix to modelise the random effect of time (Sp(POW) from SAS).
I want to summarise my data into a regression line of the type.
$Y = aT + b$
with $a = \beta_1 + \beta_3$ and $b = \beta_2$.
Since my betas are estimations and thus random variables, they come along with errors and even their own confidence intervals.
How can I get the CI of $Y$ for any $T$, so I can plot my line with a pretty ribbon ?

A: Should be var(Y) = var(a)*X² + var(b) + 2X cov(a,b)
cov(a,b) is the covariance between a and b. Generally, the statistical software will not give you this covariance bt default, and you need to force the software to print it out.
Answer after your changes:

$Y = aT + b$
with $a = \beta_2$ and $b = \beta_1 + \beta_3$.

Then $Y = aT + b = \beta_1 + \beta_3 +\beta_2T = (1, T, 1)(\beta_1, \beta_2, \beta_3)'$
$Var(Y)=(1, T, 1)Cov(\beta_1, \beta_2, \beta_3)(1, T, 1)'$
where $Cov(\beta_1, \beta_2, \beta_3)$ is the variance-covariance matrix of estimated fixed effect. You can get it by adding option COVB in MODEL statement in PROC MIXED.
Then you can use PROC IML to perform the matrix calculation to get $Var(Y)$, then se of $Y$, then CI of $Y$ and, finally get a graph.

A: There are many confidence intervals you could draw around the range of fitted effects for $Y$ in a mixed model. I'll note two.
You can draw the marginal effect: To do this, ditch the mixed model and fit a GEE instead. Use the vcovHC function from the sandwich library instead to increase the magnitude of standard error of the conditional mean. Plot the line as you've described.
You can draw the conditional effect. If you have a random intercept model (the simplest type), you can obtain the conditional variance of the $Y$ response for a fixed exposure profile (X) and random effect provided the assumption of independence between the random effect and exposure is met. You would do this by extracting the residual variance from the $Y$ as you say. Look into lme4 documentation for details on doing that.
More complex growth models need a bit more thought and specification to get a useful answer.


text:
Q: Ubuntu 20.04 Freeze on loading screen. Have Intel UHD 620 graphics I am running Ubuntu 20.04 and my computer is freezing solid on the login screen. Have to hard reset holding the power button.
Initially, I had Mate 20.04 installed (I believe in April) and it worked great till Aug.
I have since tried several full clean installs (Actually new OS on / and keeping my same personal data on /home). All new installs fail to get past the login screen.
Currently, I am trying Ubuntu (not mate) 20.04. It will boot if I place this command in the boot grub: "intel_idle.max_cstate=1", but then the cpu n fan run constantly.
I have tried adding "dis_ucod_ldr to teh /etc/default/grub, as it has been linked to freezing on Intel UHD 620 cards.
I have also updated to the latest EFI bios... no impact.
I am currently using the latest ubuntu kernel 5.11.0-36-generic
But have the same issue using various 5.4 or 5.8 kernels
I believe the following may be helpful. It is what I get when booted using "intel_idle.max_cstate=1"
Thanks Mark

inxi -G Graphics:
Device-1: Intel UHD Graphics 620 driver: i915 v:kernel
Display: wayland server: X.Org 1.20.11 driver: fbdev
unloaded: modesetting,vesa resolution: 1920x1080~60Hz
OpenGL:renderer: Mesa Intel UHD Graphics 620 (KBL GT2) v: 4.6 Mesa 21.0.3
sudo lshw -C video   *-display
description: VGA compatible controller
product: UHD Graphics 620
vendor: Intel Corporation
physical id: 2
bus info: pci@0000:00:02.0
version: 07
width: 64 bits
clock: 33MHz
capabilities: pciexpress msi pm vga_controller bus_master cap_list rom
configuration: driver=i915 latency=0
resources: irq:128 memory:ee000000-eeffffff memory:d0000000-dfffffff ioport:f000(size=64) memory:c0000-dffff
sudo lshw -C cpu   *-cpu
description: CPU
product: Intel(R) Core(TM) i5-8250U CPU @ 1.60GHz
vendor: Intel Corp.
physical id: 12
bus info: cpu@0
version: Intel(R) Core(TM) i5-8250U CPU @ 1.60GHz
serial: To Be Filled By O.E.M.
slot: U3E1
size: 3399MHz
capacity: 4005MHz
width: 64 bits
clock: 100MHz
capabilities: lm fpu fpu_exception wp vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi


text:
Q: Contributing a template to Eclipse via a Plugin to the Java Editor, but should vary based on the context So I wrote a plugin to contribute a template to the java editor in eclipse by using the extension "org.eclipse.ui.editors.templates". This just adds the template. That's not what I want. I want to replace the existing template with the new one, that too based on a condition.
For example, if the file name is "john.java", within that file if I type "sysout", I want my template to show up rather than the default one. Any ideas how I might be able to do this ?

A: OK. I finally found a work around. JDT plugin does not offer an extension point for what I was trying to do. So I got the TemplateStore and modified it to suit my needs.
@Override
public void sessionStarted() {
    filterTemplates();
}

private void filterTemplates() {
    templateStore = getTemplateStore();
    file = getFileThatsVisibleInTheEditor();

    if (//file name is john.java) {
        deleteTemplate(templateStore, "org.eclipse.jdt.ui.templates.sysout");
    } else {
        deleteTemplate(templateStore, "com.eclipse.jdt.ui.templates.sysout");
    }

    try {
        templateStore.save();
    } catch (IOException e) {
    }
}

private void deleteTemplate(TemplateStore templateStore, String id) {
    TemplatePersistenceData templateData = templateStore.getTemplateData(id);
    if (templateData != null) {
        templateStore.delete(templateData);
    }
}

@Override
public void sessionEnded() {
    getTemplateStore().restoreDeleted();
}

private TemplateStore getTemplateStore() {
    if (templateStore == null) {
        final ContributionContextTypeRegistry registry = new ContributionContextTypeRegistry(JavaUI.ID_CU_EDITOR);
        final IPreferenceStore store = PreferenceConstants.getPreferenceStore();
        templateStore = new ContributionTemplateStore(registry, store, "org.eclipse.jdt.ui.text.custom_templates");
        try {
            templateStore.load();
        } catch (IOException e) {
        }
        templateStore.startListeningForPreferenceChanges();
    }
    return templateStore;
}

This whole this is written inside a class that extends IJavaCompletionProposalComputer. So every time you press Ctrl+Space, this code will be executed and your flavor of template will get executed.
In the above code, I have replaced the normal java sysout with the one that my plugin contributes based on the condition, so that at any point in time only one version of the 'sysout' is shown in the proposal. This is a hack, but I got my things done.


text:
Q: Custom subview gives memory leak when analyzed I am trying to create my own custom subview for an app.  The view is a subclass of UIView and contains a couple of UIButtons and a UITextField.  The code actually builds and runs without problems, but when I do an "Analyze" of the code it gives me 4 potential memory leaks.  I will be including this subview in a larger project so I want to nip any errors here before adding it to the bigger project.  Here's the code where one of the leaks occurs:
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.nameView.delegate = self;
    [self.nameView.newName resignFirstResponder];   // this is line 60
    [self.nameView setHidden:YES];
    [self.nameView setNeedsDisplay];
}

The error it gives me is:"Potential leak of an object created on line 60"
Then if I click on that error is says: "Object allocated on line 60 is not referenced later in this execution path and has a retain count of +1, object leaked"
Thanks in advance for any help you can give me.
Gil
CocoaFu, thanks for the help - I am new to the site and I will try to give the proper feedback.  As far as this problem goes I should have included a bit more information.
nameView is the name of my custom view
newName is the name of a UITextField in the view.
I will try then suggestions here and let you know if they work.  Thanks again.  This is a great site!

A: [self.nameView.newName resignFirstResponder];

is the same as:
[[[self nameView] newName] resignFirstResponder];

which means that newName is a method and methods that begin with new or copy are expected to return a retained instance.  I suspect that newName does not do that but the rules say it does.  The solution is to follow Objective-C naming rules: change the name newName.
Not, you don't say but perhaps newName is a property.  Well, @synthesize creates accessor methods newName and setNetName.


text:
Q: Dependencies does not inject during weblogic deployment I want to deploy my project on weblogic but when I deploy the war, my spring applicationContext gets loaded and when it starts hydrating my caches it crashes giving me a null pointer exception. When I debugged I saw that my persistence entity class, that is used during the method, is instantiated with out its dependencies meaning they did not get injected.
My entity class is marked with @Configurable and the getter and setter methods for the dependencies are marked with @Transient. Also, when I run my tests it does inject the dependencies in the entity class and it seems it does not inject when I am trying to deploy to weblogic. I have no idea where to start looking for the problem thus I have no idea which code I should supply you with.
Any tips on what I should google or where to look into would be much appreciated. Also if you want to have a look at some code just ask and I will add it.
Thank you and I apologize for the lack of code but I have no idea which bit would actually help and which code would be useless.
EDIT:
Adding code
Entity class
@Configurable
@javax.persistence.Entity
@Table(name = "Some_Table")
public class InteractionImpl implements Interaction, Serializable {

    private Long interactionId;
    private Long initiatorEntityNr;
    private Long agentEntityNr;

    transient private BuilderB builderB;
    transient private BuilderA builderA;

    @Id
    @Column(name = "justAnotherID")
    public Long getInteractionId() {
        return interactionId;
    }

    public void setInteractionId(Long interactionId) {
        this.interactionId = interactionId;
    }

    @Column(name = "someCodeB")
    private Long getInitiatorEntityNr() {
        return initiatorEntityNr;
    }

    private void setInitiatorEntityNr(Long initiatorEntityNr) {
        this.initiatorEntityNr = initiatorEntityNr;
    }

    @Column(name = "someCodeA")
    private Long getAgentEntityNr() {
        return agentEntityNr;
    }

    private void setAgentEntityNr(Long agentEntityNr) {

        this.agentEntityNr = agentEntityNr;
    }

    @Transient
    public Agent getAgent() throws CrmEntityCreationException {
        if (getAgentEntityNr() != null)
            return builderA.buildShallowEntity(getAgentEntityNr());
        else
            throw new CrmEntityCreationException("There was no agent entity number so the entity could not be found");
}

    @Transient
    public void setAgent(Agent agentEntity) {
        setAgentEntityNr(agentEntity.getEntityNumber());
    }

    @Transient
    public Customer getInitiator() throws CrmEntityCreationException {
        if (getInitiatorEntityNr() != null) {
            return builderB.buildShallowEntity(getInitiatorEntityNr());
        } else {
            throw new CrmEntityCreationException("The interaction does not contain an initiator entity number");
        }
    }

    @Transient
    public void setInitiator(Customer initiatorEntity) {
        setInitiatorEntityNr(initiatorEntity.getEntityNumber());
    }

    @Transient
    private BuilderB getCustomerBuilder() {
        return builderB;
    }

    @Inject
    @Transient
    public void BuilderB(BuilderB builderB) {
        this.builderB = builderB;
    }

    @Transient
    private BuilderA getBuilderA() {
        return builderA;
    }

    @Inject
    @Transient
    public void setBuilderA(BuilderA builderA) {
        this.builderA = builderA;
    }

}

Application Context
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:jee="http://www.springframework.org/schema/jee"

       xsi:schemaLocation="
       http://www.springframework.org/schema/jee
       http://www.springframework.org/schema/jee/spring-jee.xsd
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.1.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">

    <context:load-time-weaver weaver-class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
    <tx:annotation-driven transaction-manager="transactionManager" mode="aspectj"/>
    <context:component-scan base-package="crm.persistence"/>
    <context:component-scan base-package="crm.services.impl"/>
    <context:annotation-config/>
    <context:spring-configured/>

    <bean id="hazelcast" class="com.hazelcast.core.Hazelcast" factory-method="newHazelcastInstance"/>

    <bean id="httpComponentMessageSender" class="org.springframework.ws.transport.http.HttpComponentsMessageSender"/>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
        <property name="url" value="jdbc:oracle:thin:@someConnection:1521:xe"/>
        <property name="username" value="someUsername"/>
        <property name="password" value="somePassword"/>
    </bean>

    <bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="loadTimeWeaver" ref="loadTimeWeaver"></property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="emf"/>
    </bean>

    <bean class="org.springframework.transaction.aspectj.JtaAnnotationTransactionAspect" factory-method="aspectOf">
    </bean>

    <bean id="interactionCache" class="crm.services.impl.Caching.InteractionCacheImpl">
        <property name="ammountOfInteractionToReturn" value="10"/>
    </bean>

    <bean id="interactions" class="crm.persistence.entities.InteractionImpl" scope="prototype"/>

    <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="targetObject" ref="interactionCache"/>
        <property name="targetMethod" value="rehydrateAllCaches"/>
    </bean>

    <bean id="agentCache" class="crm.services.impl.Caching.AgentCacheImpl"/>

    <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="targetObject" ref="agentCache"/>
        <property name="targetMethod" value="rehydrateAll"/>
    </bean>

    <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="targetObject" ref="alertCache"/>
        <property name="targetMethod" value="rehydrateAll"/>
    </bean>
 </beans>

Then my spring webservice servlet
    <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:sws="http://www.springframework.org/schema/web-services"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/web-services http://www.springframework.org/schema/web-services/web-services.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <import resource="classpath:applicationContext.xml"/>

    <!--scans for spring-ws annotation-->
   <sws:annotation-driven/>

</beans>

My web.xml
    <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <servlet>
        <servlet-name>spring-ws</servlet-name>
        <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
    </servlet>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
    <servlet-mapping>
        <servlet-name>spring-ws</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>

and then my weblogic.xml
    <?xml version="1.0" encoding="UTF-8"?>
<weblogic-web-app xmlns="http://xmlns.oracle.com/weblogic/weblogic-web-app" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd http://xmlns.oracle.com/weblogic/weblogic-web-app http://xmlns.oracle.com/weblogic/weblogic-web-app/1.0/weblogic-web-app.xsd">

    <context-root>/CrmService</context-root>
    <container-descriptor>
        <prefer-application-packages>
        <package-name>org.jboss.logging.*</package-name>
        </prefer-application-packages>
    </container-descriptor>
</weblogic-web-app>

As seen in my application context I have two caches that I rehydrate. The hydrate method calls a DAO to find a list of relevant interactions (Entity class) and then calls the getAgent() and getInitiator() methods. Since builderA and builderB does not get injected it throws a null pointer exception.
Just to remind you that it injects these classes in my integration tests but not when I try and deploy it to weblogic. I don't use tomcat


text:
Q: FOP fails to generate pdf for certain URLS I have an issue with generating pdf files using the apache fop tool from url based data, whenever there are certain characters or keywords such as utm or rel as the below given url
https://www.youtube.com/embed/1mDT-x2XnEg?autoplay=1&rel=0&feature=oembed&enablejsapi=1&wmode=opaque
I get the following error
SEVERE: Exception
org.apache.fop.apps.FOPException: The reference to entity "rel" must end with the ';' delimiter.
javax.xml.transform.TransformerException: The reference to entity "rel" must end with the ';' delimiter.

My XML DATA FILE - mytest.xml contains:
<url>https://www.youtube.com/embed/1mDT-x2XnEg?autoplay=1&rel=0&feature=oembed&enablejsapi=1&wmode=opaque</url>

My XSL TEMPLATE FILE - mytest.xsl contains
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
      xmlns:fo="http://www.w3.org/1999/XSL/Format">
  <xsl:output method="xml" indent="yes"/>
  <xsl:template match="/">
    <fo:root>
      <fo:layout-master-set>
        <fo:simple-page-master master-name="A4-portrait"
              page-height="29.7cm" page-width="21.0cm" margin="2cm">
          <fo:region-body/>
        </fo:simple-page-master>
      </fo:layout-master-set>
      <fo:page-sequence master-reference="A4-portrait">
        <fo:flow flow-name="xsl-region-body">
          <fo:block>
            Testing URLS: <xsl:value-of select="url"/>!
          </fo:block>
        </fo:flow>
      </fo:page-sequence>
    </fo:root>
  </xsl:template>
</xsl:stylesheet>

Tested on Commandline
FOP Version 2.2 on kali linux and opensuse linux 42.3
myvar=mytest && /opt/fop-2.2/fop/fop  -r -v -xml $myvar.xml -xsl $myvar.xsl -pdf $myvar.pdf

I have tried adding quotes around the URL, but to no effect. Fop seems to be interpreting the urls word by word or so it seems.
I tried another file using basiclink tag in template - mytest.xsl
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
      xmlns:fo="http://www.w3.org/1999/XSL/Format">
  <xsl:output method="xml" indent="yes"/>
  <xsl:template match="/">
    <fo:root>
      <fo:layout-master-set>
        <fo:simple-page-master master-name="A4-portrait"
              page-height="29.7cm" page-width="21.0cm" margin="2cm">
          <fo:region-body/>
        </fo:simple-page-master>
      </fo:layout-master-set>
      <fo:page-sequence master-reference="A4-portrait">
        <fo:flow flow-name="xsl-region-body">
          <fo:block>

            <fo:basic-link external-destination="url({url/@href})"  color="blue" text-decoration="underline">  <xsl:value-of select="url/@href"/> </fo:basic-link>
          </fo:block>
        </fo:flow>
      </fo:page-sequence>
    </fo:root>
  </xsl:template>
</xsl:stylesheet>

No luck, Still the same.
Any help will be appreciated.

A: Escape & as &.
Your problem isn't with FOP, it's with your XML syntax.  In XML, & is the start of an entity reference, so the XML parser (not FOP itself) is trying to evaluate &rel (the longest sequence after the & that's valid as an entity name) as an entity name and is not finding the ; that is required to end the entity reference.
See https://www.w3.org/TR/REC-xml/#sec-references.

A: This issue was resolved with the use of wrapping the urls with CDATA as shown below:-
<![CDATA[\"$url\"]]>

CDATA stands for Character Data. We use it to escape some characters which otherwise will be treated as a standard regular XML. The data inside this will not be parsed, else you will end up with errors as its gonna be  parsed as a standard regular XML.


text:
Q: About the stackalert twitter bot Is the stack alert twitter bot service still on? If not is there a similar service out there any where...?

A: http://twitter.com/stackalert
No updates since Sep 1st. You can setup an account (using openid) with Twitterfeed, and make your own stackoverflow-twitter-bot to broadcast questions every 30 minutes or so from the RSS feeds.

A: Stack Trilogy seems to be doing the same.

A: Hello, I had the idea, then ceded it all to @teifion, who had started @so_agg before that (@stackalert was just a cooler name). I reserved the domain name and stuck up a page, just in case we hit the jackpot. It will expire in February 2010, if I remember correctly.
I subsequently gave up on Twitter completely, and didn't have any further contact with Teifion, though he has been on SO fairly recently, and has an account here too. So I have no idea if it was blocked, or he stopped, or something hung somewhere and he hasn't been to see why.


text:
Q: PerformanceCounters on .NET 4.0 & Windows 7 I have a program that works fine on VS2008 and Vista, but I'm trying it on Windows 7 and VS2010 / .NET Framework 4.0 and it's not working. Ultimately the problem is that System.Diagnostics.PerformanceCounterCategory.GetCategories() (and other PerformanceCounterCategory methods) is not working. I'm getting a System.InvalidOperationException with the message "Cannot load Counter Name data because an invalid index '' was read from the registry."
I can reproduce this with the very simple program shown below:
class Program
{
    static void Main(string[] args)
    {
        foreach (var pc in System.Diagnostics.PerformanceCounterCategory.GetCategories())
        {
            Console.WriteLine(pc.CategoryName);
        }
    }
}

I did make sure I'm running the program as an admin. It doesn't matter if I run it with VS/Debugger attached or not. I don't have another machine with Windows 7 or VS2010 to test it on, so I'm not sure which is complicating things here (or both?). It is Windows 7 x64 and I've tried forcing the app to run in both x32 and x64 but get the same results.

A: It seems performance counters were corrupted on my system. Although I didn't follow this post exactly, it led me to the solution. Here is what I did:
In an command prompt with administrator/elevate privileges typed the following:
lodctr /?

Useful stuff in there...
Then typed:
lodctr /R

According to the docs from the prior step, this gets windows to rebuild the perf registry strings and info from scratch based on the current registry settings and backup INI files. I have a feeling this is what did the magic. However, next I noticed the .NET performance counters were not there anymore so based on this I typed the following to reload them:
lodctr "C:\Windows\Microsoft.NET\Framework64\v4.0.20506\corperfmonsymbols.ini"

Note that this path is for .NET Framework 4.0 on x64. You can imagine the path for other variations of the framework/platform. I'm guessing you should always load the counters from the highest version of the .NET framework that you have installed, but that is just a guess.
I hope this helps someone else someday!


text:
Q: How to omit a secondary return from a function call during a struct value assignment I would like to assign a value within a variable declaration of type struct, however, I need to call a function that returns a secondary value (an error) which I would like to disregard in the assignment.
Is there a way to do so? For example:
type myStruct struct{
    address common.Address
}

func main() {
    newVar := myStruct{
      address: common.HexToAddress("xyz")
    }
}

The issue is that common.HexToAddress() returns 2 values, a common.Address as well as an error. I would like to omit the error and assign it as above. I would prefer not to have to do:
var newVar2 myStruct
myStruct,_ = common.HexToAddress("xyz")

A: It's usually not exactly recommended to ignore errors, which may be one reason why the language does not make this easy.
That being said, a pattern you see sometimes is a package offering a Must function, for those cases where just doing a panic() on an error is the right thing to do; e.g., when initializing package-level variables.
For example, there's text/template.Must. The implementation simply tests the error and panics if it is not nil. You can consider adding such a function as well (possibly local to your file), allowing you to write your struct initialization as:
newVar := myStruct{
  address: must(common.HexToAddress("xyz")),
}
// ...
func must(address common.Address, err error) common.Address { ... }

This relies on the feature that if a function returns multiple values, and another function takes the same amount of parameters, you can invoke the latter directly on the return values of the former.
If you don't want to go that far, you do need to explicitly ignore the second return value by assigning it to the blank identifier _. You could of course do that separately, so that you still get to use a structure literal, but it may not be any cleaner than what you suggested originally:
address, _ := common.HexToAddress("xyz")
newVar := myStruct{address: address}

A: You're probably looking for some kind of syntactic sugar. Go is intentionally sparse on such things, because in the opinion of the language designers, it tends to make things less obvoius, thus less readable.  So you have limited options here.
If you really don't care about the error, here are your options:
Assign to a temporary variable as you suggested (usually the most natural/readable option):
addr, _ := common.HexToAddress("xyz")
newVar := myStruct{
    address: addr,
}

Use the return value of an anonymous function:
newVar := myStruct{
    address: func() common.Address { addr, _ := common.HexToAddress("xyz"); return addr }(),
}

If you control the common package, consider adding a variant that ignores (or panics on) errors:
newVar := myStruct{
    address: common.MustHexToAddress("xyz"),
}

Write your own wrapper function:
func hexToAddress(hex string) common.Address {
    addr, _ := common.HexToAddress(hex)
    return addr
}

newVar := myStruct{
    address: hexToAddress("xyz"),
}


text:
Q: pandas :pd.date_range output error I have a data set with 3 columns ID, vrddat, enddat and 21000 rows.
ID       vrddat      enddat

1       2015.01.01  2015.01.03
2       2015.03.01  2015.03.03

PS: Each ID can have multiple vrddat's and enddat's.
I need output as below:
ID      vrddat      enddat       day

1    2015.01.01   2015.01.03  2015.01.01
1    2015.01.01   2015.01.03  2015.01.02
1    2015.01.01   2015.01.03  2015.01.03
2    2015.03.01   2015.03.03  2015.03.01
2    2015.03.01   2015.03.03  2015.03.02
2    2015.03.01   2015.03.03  2015.03.03

I used following code to get above output
for index,row in data.iterrows():
    data_2 = pd.DataFrame(pd.date_range(row['vrddat'],row['enddat'], freq ='D'))

Using above code I get only 98 rows, but ideally output should contain way more rows than the input. Could any one suggest why I'm getting this kind of output. Is my code not iterating each and every row? How do I get ID, vrddat and enddat variables also in my output?
Please suggest.

A: You can use first cast to_datetime both columns vrddat and enddat and then use itertuples with concat for creating new expanding DataFrame. Last merge, but is necessary ID in df is unique.
df.vrddat = pd.to_datetime(df.vrddat)
df.enddat = pd.to_datetime(df.enddat)

df1 = pd.concat([pd.Series(r.ID,pd.date_range(r.vrddat, r.enddat)) for r in df.itertuples()])
        .reset_index()
df1.columns = ['day','ID']
print (df1)
         day  ID
0 2015-01-01   1
1 2015-01-02   1
2 2015-01-03   1
3 2015-03-01   2
4 2015-03-02   2
5 2015-03-03   2

print (pd.merge(df,df1, on='ID', how='left'))
   ID     vrddat     enddat        day
0   1 2015-01-01 2015-01-03 2015-01-01
1   1 2015-01-01 2015-01-03 2015-01-02
2   1 2015-01-01 2015-01-03 2015-01-03
3   2 2015-03-01 2015-03-03 2015-03-01
4   2 2015-03-01 2015-03-03 2015-03-02
5   2 2015-03-01 2015-03-03 2015-03-03

If ID is not unique, is possible use unique index for merging:
df.vrddat = pd.to_datetime(df.vrddat)
df.enddat = pd.to_datetime(df.enddat)
df = df.reset_index()

df1=pd.concat([pd.Series(r.index,pd.date_range(r.vrddat,r.enddat)) for r in df.itertuples()])
      .reset_index()
df1.columns = ['day','index']
print (df1)
         day  index
0 2015-01-01      0
1 2015-01-02      0
2 2015-01-03      0
3 2015-03-01      1
4 2015-03-02      1
5 2015-03-03      1

print (pd.merge(df,df1, on='index', how='left').drop('index', axis=1))
   ID     vrddat     enddat        day
0   1 2015-01-01 2015-01-03 2015-01-01
1   1 2015-01-01 2015-01-03 2015-01-02
2   1 2015-01-01 2015-01-03 2015-01-03
3   2 2015-03-01 2015-03-03 2015-03-01
4   2 2015-03-01 2015-03-03 2015-03-02
5   2 2015-03-01 2015-03-03 2015-03-03


text:
Q: (Verification) $C \approxeq A$ or $C \approxeq \text{section of } A$ $\forall C$ s.t. $C \subset A$ Claim
Let A is well-ordered set.
$C \approxeq A$ or $C \approxeq \text{section of } A$ $\forall C$ s.t. $C \subset A$
Proof
If $C=A$, $C \approxeq A$ since a well-ordered set is order-isomorphic to oneself.
If $C \neq A$, there $\exists a \in A$ s.t. $a \notin C$. Then
$A\setminus C = \{a \in A \;|\;a \notin C\}$.
Now, since A is well-ordered, there $\exists$ least element in $A\setminus C$, so let this least element be $m_0$.
Now let $S_{m_o} = \{a \in A \;|\; a< m_0\}$ which is a section of A.
Now define $\phi : C \to S_{m_0}$ s.t. $\forall C_0, C_1 \in C$ if $C_0 \le C_1$ then $\phi(C_0) \le \phi(C_1)$
There $\exists \;\text{such}\;\phi$ since $C$ and  $S_{m_0}$ are all-well-ordered since A is well-ordered.
So by definition $\phi$ is increasing. Also, $\phi$is bijective since the number of element in $C$ and $S_{m_0}$ is equal.
Thus,  $\phi^{-1}$ also exists and it is also increasing and bijective by definition.
Thus $C \approxeq \text{section of } A$


text:
Q: What's the difference between "got used to" and "was getting used to"? What's the difference between "got used to" and "was getting used to"?
I got used to driving on the left.
I was getting used to driving on the left.

A: This is a case of past simple vs. past continuous. The first describes a completed action, the other describes one still in progress.

I got used to driving on the left.

The speaker is now used to driving on the left. That process is finished.

I was getting used to driving on the left.

At the time being spoken about, the speaker was still not 100% used to driving on the left, but they were working on it.
Where some people get tripped up is when the continuous is used to mean an action is almost or pretty much completed - the difference between

Throughout January, I was getting used to driving on the left

and

By February, I was getting used to driving on the left

This is still different from past simple in that however close the action is to completion, it still isn't there yet.


text:
Q: Jackson ObjectMapper how to use a JsonView when reading a POJO to a JsonNode So I have a strange issue where jackson's ObjectMapper has a valueToTree(someObject) method that takes a POJO and outputs a JsonNode. However, the object I have has a bajillion fields on it that should not be serialized when doing this, and typically when I want to serialize the object to bytes or to a string this is easily accomplished with something like this:
mapper.writerWithView(User.WithRoles.class).writeValueAsBytes(myUser)

However, it doesn't appear that I can use a JsonView with this valueToTree method, so my only options appear to be to either create the json manually (ugh) or do some nightmare like this:
final JsonNode userJson = mapper.readTree(mapper.writerWithView(User.class).writeValueAsBytes(userAndRoles.getKey()));

Where I double parse the json. Surely there has to be a better way, right?
There is a similar question here, but interestingly the author seems to have just wanted a JsonNode because Play Framework's ok(content), unauthorized(content) etc methods only accepted JsonNodes back then or something? I don't know. Anyway the accepted answer there does not help me, I actually need a JsonNode and I need for that JsonNode to NOT contain fields that don't belong to the JsonView I want.