text:
Q: Custom date picker Android - Kotlin I'm trying to create a custom calendar in Android. I want to create somethning like this
custom calendar.
As you can see the design is slightly different than normal date picker for android. I tried to change it in xml, but like I found out, it isnt possible. So my question is - how to do that? Should I create custom class which extend from DatePicker? I was trying to find the solution by myself, but I found only answers to change color etc, but I want to also change design and font.
I will be very grateful for your help


text:
Q: Compare elements in large list of data I've got the question on interview by python recently. The question was:

we have a large list of pictures in python(as I understood we simply read their content, and then got list of their contents), [...], this list will occupy 1gb of RAM e.g. What is the best way to compare them(do pictures the same)?
  I answered that we can separate this list into several lists and then compare elements in them.

But I got answer that: "it is wrong".
So my question the same what is the best way here to compare them?
Currently I think maybe use python's sets and compare lengths of source list and set?

A: Assuming the list contains the raw byte strings of the image contents, one quick and dirty way to weed out possible duplicates is to compare the lengths of the byte strings.  Two pictures with unequal length byte strings cannot be duplicates.
Then, for each group of pictures with equal length byte strings, hash the byte strings and compare those.  If the hashes are equal then the pictures are duplicates, otherwise they're not.  (For extra speed, don't bother hashing if there are only two byte strings in a group; just compare the strings directly byte-by-byte.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Forcing \bibname to all capitals I need to enforce a style guideline which requires that all chapter and chapter-level equivalents have their headers and table of contents entries in all capital letters.  I've managed this for most everything at this point, but am running into problems with the bibliography.  I know that I can preset the bibliography name to be all caps by redefining \bibname (the class file is based on a the report class).  However, I need to support users who might redefine the \bibname themselves (or by use of something like babel) so I'd like to find a programatic way to force the \bibname, whatever it is, to be in all caps.  Unfortunately, my attempts at this far have failed.
What I've tried is to replace the \bibliography command with a replacement which first recases \bibname, adds the ToC entry, and then calls the old \bibliography command, as can be seen in this MWE:
\documentclass{report}

\usepackage{hyperref} %must be supported, but not required

\makeatletter

\providecommand{\texorpdfstring}[2]{%
    #1%
}

\def\@chapter[#1]#2{%
    \ifnum \c@secnumdepth >\m@ne
        \refstepcounter{chapter}%
        \typeout{*** \@chapapp\space\thechapter\space ****}%
        \addtocontents{toc}{\protect\pagebreak[3]}%
        \def\@LastLevel{0}%
        \addcontentsline{toc}{chapter}{\protect\numberline{\thechapter.}\space\texorpdfstring{\MakeUppercase{#1}}{#1}}%
    \else
        \addtocontents{toc}{\protect\pagebreak[3]}%
        \def\@LastLevel{0}%
        \addcontentsline{toc}{chapter}{\texorpdfstring{\MakeUppercase{#1}}{#1}}%
    \fi
    \chaptermark{#1}%
    \@makechapterhead{#2}%
}

\def\@makechapterhead#1{%
    \cleardoublepage
    \vspace*{0\p@}%
    {\parindent \z@ \raggedright \centering\normalfont\Large
        \ifnum \c@secnumdepth >\m@ne
            \bfseries \MakeUppercase{\chaptername}\ \thechapter
            \vskip -3pt
        \fi
        \interlinepenalty\@M
        \bfseries\texorpdfstring{\MakeUppercase{#1}}{#1}\par\nobreak
        \vskip 15\p@
    }%
}

\def\@makeschapterhead#1{%
    \cleardoublepage
    \vspace*{0\p@}%
    {\parindent \z@ \raggedright \centering\normalfont\Large
        \interlinepenalty\@M
%        \bfseries \texorpdfstring{\MakeUppercase{#1}}{#1}\par\nobreak
        \bfseries #1\par\nobreak
        \vskip 15\p@
    }%
}

%% Unnumbered bibliography
\let\oldbibliography\bibliography
\renewcommand\bibliography{%
  \addcontentsline{toc}{chapter}{\texorpdfstring{\MakeUppercase{\bibname}}{\bibname}}%
  \oldbibliography
}

%%%%%%%%%%%%%%%%%%%%%
% Page Style Definitions
%%%%%%%%%%%%%%%%%%%%%

\newcommand{\ps@bottom}{%
    \let\@mkboth\markboth % <-- This is the problematic line
    \renewcommand{\@oddhead}{}%
    \renewcommand{\@evenhead}{\@oddhead}
    \renewcommand{\@oddfoot}{\hfil\thepage\hfil}%
    \renewcommand{\@evenfoot}{\@oddfoot}
}

\pagestyle{bottom}

\makeatother

%%

\begin{document}
\tableofcontents

\chapter{Sample Chapter}

\cite{book-full}

\clearpage
\bibliographystyle{plain}
\bibliography{xampl}

\end{document}

Any ideas as to what I'm doing wrong and how I might fix it?
Note: The MWE is exapanded to include the existing code which enforces capitaliation for regular chapters and a slightly simplified version of the custom page style, which appears to raise conflicts with attempted solutions so far.
Edit: Some additional experimentation on my part has narrowed down the conflicting code even further.  I've marked the line that appears to cause the solution given by @phelype-oleinik to fail.  That line, unfortunately, is part of the code I inherited when I took over maintenance of this class file, so I don't know how necessary it is.  If you think that removing it is the answer to solving this conflict, please indicate why it may not be needed.

A: You can do with \@makeschapterhead the same you did to \@makechapterhead and add the \texorpdfstring{\MakeUppercase{#1}}{#1} thing:
\documentclass{report}

\usepackage{hyperref} %must be supported, but not required

\makeatletter

\providecommand{\texorpdfstring}[2]{%
    #1%
}

\renewcommand\tableofcontents{%
    \if@twocolumn
      \@restonecoltrue\onecolumn
    \else
      \@restonecolfalse
    \fi
    \chapter*{\contentsname}%
     \@mkboth{\MakeUppercase\contentsname}%
             {\MakeUppercase\contentsname}%
    \@starttoc{toc}%
    \if@restonecol\twocolumn\fi
    }

\def\@chapter[#1]#2{%
    \ifnum \c@secnumdepth >\m@ne
        \refstepcounter{chapter}%
        \typeout{*** \@chapapp\space\thechapter\space ****}%
        \addtocontents{toc}{\protect\pagebreak[3]}%
        \def\@LastLevel{0}%
        \addcontentsline{toc}{chapter}{\protect\numberline{\thechapter.}\space\texorpdfstring{\MakeUppercase{#1}}{#1}}%
    \else
        \addtocontents{toc}{\protect\pagebreak[3]}%
        \def\@LastLevel{0}%
        \addcontentsline{toc}{chapter}{\texorpdfstring{\MakeUppercase{#1}}{#1}}%
    \fi
    \chaptermark{#1}%
    \@makechapterhead{#2}%
}

\def\@makechapterhead#1{%
    \cleardoublepage
    \vspace*{0\p@}%
    {\parindent \z@ \raggedright \centering\normalfont\Large
        \ifnum \c@secnumdepth >\m@ne
            \bfseries \MakeUppercase{\chaptername}\ \thechapter
            \vskip -3pt
        \fi
        \interlinepenalty\@M
        \bfseries\texorpdfstring{\MakeUppercase{#1}}{#1}\par\nobreak
        \vskip 15\p@
    }%
}

\def\@makeschapterhead#1{%
    \cleardoublepage
    \vspace*{0\p@}%
    {\parindent \z@ \raggedright \centering\normalfont\Large
        \interlinepenalty\@M
        \bfseries \texorpdfstring{\MakeUppercase{#1}}{#1}\par\nobreak
        \bfseries #1\par\nobreak
        \vskip 15\p@
    }%
}

%% Unnumbered bibliography
\let\oldbibliography\bibliography
\renewcommand\bibliography{%
  \addcontentsline{toc}{chapter}{\texorpdfstring{\MakeUppercase{\bibname}}{\bibname}}%
  \oldbibliography
}

%%%%%%%%%%%%%%%%%%%%%
% Page Style Definitions
%%%%%%%%%%%%%%%%%%%%%

\newcommand{\ps@bottom}{%
    \let\@mkboth\markboth % <-- This is the problematic line
    \renewcommand{\@oddhead}{}%
    \renewcommand{\@evenhead}{\@oddhead}
    \renewcommand{\@oddfoot}{\hfil\thepage\hfil}%
    \renewcommand{\@evenfoot}{\@oddfoot}
}

\pagestyle{bottom}

\makeatother

%%

\begin{document}
\tableofcontents

\chapter{Sample Chapter}

\cite{book-full}

\clearpage
\bibliographystyle{plain}
\bibliography{xampl}

\end{document}

You will still need to manually issue an \addcontentsline for the bibliography, since it's an unnumbered chapter (I commented an option to make it numbered, if you want).
Also, due to an oddity of LaTeX's standard classes (kept for compatibility with LaTeX 2.09. See classes.dtx around line 3739 or classes.pdf section 8.1.1 -- Table of Contents). Different from the \listoffigures and such, which contain:
\chapter*{\listfigurename}%
 \@mkboth{\MakeUppercase\listfigurename}%
         {\MakeUppercase\listfigurename}%

the \tableofcontents macro contains:
\chapter*{\contentsname
 \@mkboth{\MakeUppercase\contentsname}%
         {\MakeUppercase\contentsname}}%

Note the \@mkboth instruction inside the \chapter* command in the second case. This will pass \@mkboth (which is \let to \markboth) to \MakeUppercase which whill, essentially, do \MakeUppercase{\markboth{sur}{prise!}}. I had the exact same problem when writing this class and the solution I found was to make \tableofcontents have a similar code to \listoffigures:
\renewcommand\tableofcontents{%
    \if@twocolumn
      \@restonecoltrue\onecolumn
    \else
      \@restonecolfalse
    \fi
    \chapter*{\contentsname}%
     \@mkboth{\MakeUppercase\contentsname}%
             {\MakeUppercase\contentsname}%
    \@starttoc{toc}%
    \if@restonecol\twocolumn\fi
    }

and I saw no difference between this one and the other (modulo that it didn't compile previously :P). And as it says in the documentation, it's for compatibility...


text:
Q: Adding A Button Between post-content and Related Posts Thumbnail Plugin on WordPress I am trying to add a button to my WordPress template. Basically, I have the post and then there is the Related Posts Thumbnails widget that appears. I want the button to go between the text of the post and the related posts thumbnail widget. The code in my 'Single Post' that contains all of this is as follows:

<?php the_content(__('More: Read the rest of this entry...', 'life-is-simple')); ?>

I know the Related Posts Thumbnails plugin falls within this code because it's at that place when I 'Inspect Element' on Google Chrome. I can't find how to edit the order of things within that div though. Any help would be greatly appreciated, thanks!
EDIT
Clarification: I am using the Life Is Simple WordPress theme although it has been custom editing quite a bit (mostly on the CSS side of things though).

A: That plugin is probably appending the output to the_content with a filter .
That means , that the output is being added to the_content automatically. it is a common behaviour.
You need to look at the plugin´s admin interface to see if you can have an alternative way (I believe there is ) which is using a template tag. in that case, you should put the template tag after the div where the the_content() is .
EDIT I :
After a small dig, - in fact there is - you need to put
<?php get_related_posts_thumbnails(); ?>

Then the plugin should know by itself not to append to the_content.
For parameter passing, or if something is not working, go read their APi or help files.

A: You'll probably need to edit single.php or archive.php in your theme. If nothing is occuring there that looks familiar, it's probably using a loop. In which case you might find what you are looking for either in loop.php, loop-single.php, or loop-archive.php depending on what type of page you are on and how the theme was constructed. Add your button near where you find Read the rest of this entry...
With more information (such as what theme you are using), one might be able to help more as well.


text:
Q: What are the three arguments to Gdk.threads_add_idle()? Using python and the gi.repository module, I am trying to call Gdk.threads_add_idle, but I get the error message that three arguments are required. The documentation, however, only mentions two args.
You can try the function (on a linux only, i guess) by typing the following in a python interpreter:
from gi.repository import Gdk

Gdk.threads_add_idle(...)

Any ideas what the three args are?

A: By looking on a source code search engine, I was able to find a python project using that call.
Gdk.threads_add_idle(GLib.PRIORITY_DEFAULT_IDLE, self._idle_call, data)

It looks like introspection data is wrong, the priority should already default to PRIORITY_DEFAULT_IDLE (as specified in the the documentation you pointed out). You should file a bug on http://bugzilla.gnome.org.
UPDATE:
Pouria's bug report has been resolved NOTABUG, as this is a naming confusion between the C and Python API.


text:
Q: Cookies not accurate if people share the same IP address? When user A connects to my web site I set a cookie to this user's browser to identify him and to track what he is doing to deliver content in accordance to his behaviour.
When user B connects and comes from the same IP address then user B gets user A's cookies and vice versa. It would seem the cookies get mixed up because the web server is seeing one user instead of several as several users are coming from the same IP.
This problem only occurs with one set of users that use the same ISP. This ISP assigns the same IP address (and hostname) to multiple accounts/users. (Many people share one IP) If two people (or more) from this same ISP on the same IP shows up on my site then cookie operations seems to be shared amongst them which is causing problems.
What can be done to accurately track individual users when they are coming from the same IP (sharing an IP address) as cookies seem to not work properly when this happens? Perhaps the problem is coming from the ISP in question?
Will SSL solve this? Perhaps it's the way I set the cookies?
I'm posting an example below in Perl on how I set cookies:
use CGI;
$q = CGI->new;

### the routine &get_random_number used below is a unique random number
### generator that also uses $ENV{HTTP_USER_AGENT} for entropy
### &get_random_number returns a unique number (session id)
$session_id = &get_random_number;

$thecookie1 = $q->cookie(-name=>'something', -value=> $session_id );
print $q->header(-cookie => $thecookie1);

This is the code that reads the cookie:
use CGI;
$q = CGI->new;
$thecookie = $q->cookie('something');

The situation explained here in this post only happens with a specific ISP (All users using this ISP is coming from the same IP and has the same hostname) - The ISP shares a single IP with many users. This ISP provides mobile internet for cell phones.
Update 1:
I believe it must have something to do with a caching proxy server implemented by the ISP in question as this only happens with the ISP in question.
I have done the following in the hopes of solving it: (The number of times the problem occurred decreased drastically) - The last change I made
was adding no-cache meta tags to the page setting the cookies which I hope completely solves it. Time will tell probably.
From the page setting cookies I do the following:
print $q->header(-type=>'text/html',
-Pragma=>'no-cache',
-Cache_Control=> 'no-store,no-cache,must-revalidate,post-check=0,pre-check=0',
-expires=>'now -1d',
-cookie=> $cookie
);

print qq[
<head>
<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
<meta http-equiv="pragma" content="no-cache" />

etc... etc...
];

Update 3:
Upgrading Apache seemed to solve it but the problem came back. I did solve it but the only way I could get it solved was to move everything to https://
Moving to https:// solved it period.

A: I suspect that these users share a caching proxy. Be sure to disable caching of the response containing the Set-Cookie header. We do that by outputting the CGI header as follows:
print header(-type=>'text/html', -expires=>'now -1d', -cookie=>\@cookies);

A: I realise you consiider this issue solved by the Apache update but I assure you that's not what "fixed" it. Upgrading Apache has just resulted in some changes to your configuration and if you restore your original configuration the problem will re-occur in the new version too. In other words this also certainly isn't an Apache bug you're seeing but a problem with how you configured it.
Basically it looks like you had a situation where Apache was setting its own cache headers in addition to or replacing the ones you set via Perl. You may have been doing this via mod_headers or through a mis-configuration of mod_expires or mod-cache

A: Cookies don't have anything to do with IP addresses, they are created client side and linked to the browser.  For instance if a user logged in to your website using Chrome they would have a different set of cookies than if the logged in using IE on the same computer (and IP address).
I suggest your problem may be to do with what you are putting in the cookies, which is completely up to you and your code.
Have you tried using sessions instead?  In PHP, you just need to call session_start() and then set data in the $_SESSION variable.
If you post some example code of what you are doing, I might be able to give you a more specific answer.


text:
Q: Partial specialization advice Hello all I have this example. Usually in this case I would use Visitor pattern. However for some reason the person who wrote Base, DerivedA, DerivedB prefers dynamic_casts. Keep in mind that I can not change Base, DerivedA, DerivedB classes.
I have got around casting with partial specialization. Please let me know if this is a good solution or there is a better one?
#include <iostream>
using namespace std;

class CBase{};

class CDerivedA: public CBase{};

class CDerivedB : public CBase{};

class CDerivedC : public CBase{};

template <typename T>
void Draw(T* face)
{
    cout<<"Base"<<endl;
}

template <>
void Draw<>(CDerivedA* face)
{
    cout<<"A"<<endl;
}

template <>
void Draw<>(CDerivedB* face)
{
    cout<<"B"<<endl;
}

int main() {
    CDerivedA* a = new CDerivedA ();
    CDerivedB* b = new CDerivedB ();
    CDerivedC* c = new CDerivedC ();

    Draw(a);
    Draw(b);
    Draw(c);

    return 0;
}

A: If the types are known at compile time, you can simply use function overloading. This also works in addition to a base class overload (or a generic function template if needed).
void Draw(CBase* face);
void Draw(CDerivedA* face);
void Draw(CDerivedB* face);

If the types are known at runtime, and you have no option to modify the classes (i.e. add virtual functions), you need some kind of dispatching mechanism. An approach that doesn't involve a lot of classes and boilerplate code would be a table mapping types to functions, e.g. std::map<std::type_index, std::function<void()>> or similar. It may not be as efficient because of the lookup and dynamic dispatch overhead.


text:
Q: Wordpress MYSQL Error Can someone help me fix the error below?
ERROR

[Fri Mar 04 23:37:59.682275 2016] [:error] [pid 9392] [client
  222.127.94.8:45468] WordPress database error You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server
  version for the right syntax to use near '' at line 10 for query
  SELECT DISTINCT ID, post_title, post_password, comment_ID,\n
  comment_post_ID, comment_author, comment_author_email,
  comment_date_gmt, comment_approved,\n
  comment_type,comment_author_url,\n SUBSTRING(comment_content,1,110) AS
  com_excerpt\n FROM wp_comments\n LEFT OUTER JOIN wp_posts ON
  (wp_comments.comment_post_ID =\n wp_posts.ID)\n WHERE comment_approved
  = '1' AND comment_type = '' AND\n post_password = ''\n ORDER BY comment_date_gmt DESC LIMIT made by require('wp-blog-header.php'),
  require_once('wp-includes/template-loader.php'),
  include('/themes/theme/404.php'), dynamic_sidebar,
  call_user_func_array, WP_Widget->display_callback, Comments->widget,
  referer:

Code in Theme:
$sql = "SELECT DISTINCT ID, post_title, post_password, comment_ID,
comment_post_ID, comment_author, comment_author_email, comment_date_gmt, comment_approved,
comment_type,comment_author_url,
SUBSTRING(comment_content,1,100) AS com_excerpt
FROM $wpdb->comments
LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID =
$wpdb->posts.ID)
WHERE comment_approved = '1' AND comment_type = '' AND
post_password = ''
ORDER BY comment_date_gmt DESC LIMIT ".$comment_posts;

$comments = $wpdb->get_results($sql);
$output = $pre_HTML;

foreach ($comments as $comment) {

What do i need to replace in the CODE above to fix the error?
Thank you in advance

A: i got similar type of problem while using order by and limit in wordpress query.i rewrite query shown in here. i think wordpress have different structure while appending variable.try it.


text:
Q: What can't IntelliJ do that other JetBrains IDE's can? I was just wondering what unique features other JetBrains IDE's offer that IntelliJ IDEA Ultimate cannot offer (even with plugins). For example, I know it is impossible to get C/C++ support in IDEA right now (at least good support). However, looking at tools like DataGrip and the new Rider IDE, it's not very clear if IntelliJ encapsulates all of these features.

A: In terms of large feature areas, AppCode, CLion and Rider are separate products which aren't available as plugins for IntelliJ IDEA. DataGrip's functionality is available out of the box in IntelliJ Ultimate.
There are also lots of smaller differences in the user interface (mainly around project setup), because each language-specific IDE is optimized for the workflows used in the community of users of that language.


text:
Q: Is it possible to Compare two columns in Microsoft SQL server so that the comparison skips punctuation marks and other character like %, ' etc? I have two columns having data like below.
Column1
AMC Standard, School
Column2
AMC Standard School.
In need to compare these two columns such that comparison is made for the words only and not for any additional, meaning from the above example Column1 and ColumnC are match but due to the Comma ",' and the period sign "." the simple comparison of Column1 and Column2 suggests it as a mismatch.

A: you can replace the non comparable characters to empty string (in your case , and .)and then compare them. Something like this.
SELECT 1 WHERE REPLACE('AMC Standard, School',',','') = REPLACE('AMC Standard School.','.','')

Based on jarlh comments, You should (if possible) update the columns and remove the punctuation marks if they are not using in any comparison and display.

A: One option is to use SQL Servers SoundEx() and Difference() functions (https://msdn.microsoft.com/en-us/library/ms187384.aspx and https://msdn.microsoft.com/en-us/library/ms188753.aspx respectively)
DECLARE @val1 varchar(50) = 'AMC Standard, School'
      , @val2 varchar(50) = 'AMC Standard School.'
;

SELECT @val1
     , @val2
     , SoundEx(@val1)
     , SoundEx(@val2)
     , Difference(SoundEx(@val1), SoundEx(@val2))
;

The return value of Difference() is between 0 and 4, with a higher number signifying a closer match.
IMPORTANT NOTE: This type of comparison is not as exacting as a method that cleans up your data beforehand as in those scenarios you can use an exact (a=a) comparison, whereas this method looks for similar values.

A: Try like this
DECLARE @column1 VARCHAR(100)='AMC Standard, School (Near to ABC Building)'
DECLARE @column2 VARCHAR(100)='AMC Standard, School (Opposite KFC)'

SELECT 'MATCHED' AS COLUMN_COMPARE
WHERE  replace(replace(replace(@column1, ',', ''), '.', ''), substring(@column1, CHARINDEX('(', @column1), CHARINDEX(')', @column1) - 1), '') = replace(replace(replace(@column2, ',', ''), '.', ''), substring(@column2, CHARINDEX('(', @column2), CHARINDEX(')', @column2) - 1), '')


text:
Q: How modify Facebook's Webview to maintain it correctly displayed on device screen? I'm developing a little Android application that connects to Facebook and shares some content. I would like to know if there's a way to modify the size (height and widht) of this default Facebook's webview, because it is a little high and because of that the top bar default of the application is being hide for it.
Is this possible?
I'm using the newest Facebook SDK for Android: 3.0
Thanks i advance.
EDIT: the webview is like this.

It should be like this, but like in my case, it's a little high and hiding part of app's top bar. For example, where is Facebook's name, the top of web view shows just half of it.

A: It seems that is a normal behavior from Facebook's API, by using the SDK for Android, because the samples availables have the same behavior. See SessionLoginSample on https://github.com/facebook/facebook-android-sdk
I think that's it. Hope it helps.
Thanks everyone for help too.


text:
Q: How to call backend Python script from Android background:
I have scenario where I have an Android app running on client and communicating with a PHP server.
question:
I want to run one Python script from the server, so I first tried calling Python from PHP like follows:
$output = passthru("mypy.py ".$var1." ".$var2);

When I just run PHP file it works.
But when I call it from Android the incoming request is too slow. I don't know is that Python script is executing (I am still testing this), but I know this is a very bad method of doing this.
I Googled and found that I have to use Django or Flask. But I just have one Python script which I have to run. How do I call one Python script from Android client?

A: I finally found solution to my problem using Flask
from flask import Flask, redirect, url_for, request
app = Flask(__name__)

@app.route('/success/<name>')
def success(name):
    return 'welcome %s' % name

@app.route('/login',methods = ['POST', 'GET'])
def login():
    if request.method == 'POST':
        user = request.form['nm']
        return redirect(url_for('success',name = user))
    else:
        user = request.args.get('nm')
        return redirect(url_for('success',name = user))

if __name__ == '__main__':
    app.run(debug = True)

and I just make a http call on http://my_machine_ip:port_no/login from android using volley
and it's work like a charm

A: At Last I Solved my Problem. But using a technology service that is ngrok. I suggest everyone facing a problem similar to this must try ngrok
At least watch one video and consult from its documentation it is very easy!!!! believe me.....I think it take time not more than 10 minute


text:
Q: What's the purpose of a pod's service account, if automountServiceAccountToken is set to false? The API credentials for service accounts are normally mounted in pods as:
/var/run/secrets/kubernetes.io/serviceaccount/token

This token allows containerized processes in the pod to communicate with the API server.
What's the purpose of a pod's service account (serviceAccountName), if automountServiceAccountToken is set to false?

A: A little of theory:
Let's start with what happens when pod should be created.

When you create a pod, if you do not specify a service account, it is
automatically assigned the default service account in the same
namespace

Reference.
So all pods are linked to service account anyway (default or specified in spec).
Then API access token is always generated for each service account.
automountServiceAccountToken flag defines if this token will automatically mounted to the pod after it has been created.
There are two options where to set this flag:

*

*In a specific service account
apiVersion: v1
kind: ServiceAccount
metadata:
  name: build-robot
automountServiceAccountToken: false
...

*In a specific pod
apiVersion: v1
kind: Pod
metadata:
  name: my-pod
spec:
  serviceAccountName: build-robot
  automountServiceAccountToken: false
  ...

Answer:

What's the purpose of a pod's service account (serviceAccountName), if
automountServiceAccountToken is set to false?

It may make a difference depending on what processes are involved in pod creation. Good example is in comments in GitHub issue (where this flag eventually came from):

There are use cases for still creating a token (for use with external
systems) or still associating a service account with a pod (for use
with image pull secrets), but being able to opt out of API token
automount (either for a particular pod, or for a particular service
account) is useful.


text:
Q: How can I add shadow to a BottomNavigationBarItem I have used the BottomNavigationBar widget from material.dart. I want to have a background shadow on the selected BottomNavigationBarItem. The desired output is Something like this.
I have written the following code whose output is like this:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shoppingapp/views/screens/cart/cart.dart';
import 'package:shoppingapp/views/screens/profile/profile.dart';

class BottomNavBar extends StatefulWidget {
  const BottomNavBar({Key? key}) : super(key: key);

  @override
  _BottomNavBarState createState() => _BottomNavBarState();
}

class _BottomNavBarState extends State<BottomNavBar> {
  int _selectedIndex = 0;
  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
    });
  }

  static const TextStyle optionStyle =
      TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
  List<BottomNavigationBarItem> items = [
    BottomNavigationBarItem(
        icon: Icon(Icons.home_outlined),
        label: "Home",
        backgroundColor: Colors.black),
    BottomNavigationBarItem(
        icon: Icon(Icons.shopping_bag_outlined),
        label: "Cart",
        backgroundColor: Colors.black),
    BottomNavigationBarItem(
        icon: Icon(CupertinoIcons.heart),
        label: "Wishlist",
        backgroundColor: Colors.black),
    BottomNavigationBarItem(
        icon: Icon(CupertinoIcons.profile_circled),
        label: "Profile",
        backgroundColor: Colors.black)
  ];
  static const List<Widget> _widgetOptions = <Widget>[
    Text(
      'Home',
      style: optionStyle,
    ),
    Cart(),
    Text(
      'Wishlist',
      style: optionStyle,
    ),
    Profile(),
  ];

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.only(
            topRight: Radius.circular(30), topLeft: Radius.circular(30)),
        boxShadow: [
          BoxShadow(color: Colors.black38, spreadRadius: 0, blurRadius: 10),
        ],
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(25.0),
          topRight: Radius.circular(25.0),
        ),
        child: BottomNavigationBar(
          items: items,
          type: BottomNavigationBarType.shifting,
          currentIndex: _selectedIndex,
          showSelectedLabels: true,
          showUnselectedLabels: false,
          selectedItemColor: Colors.white,
          iconSize: 30,
          onTap: _onItemTapped,
          backgroundColor: Colors.white,
        ),
      ),
    );
  }
}

A: You can try using this package Flutter Glow
Flutter Glow example:
GestureDetector(
  onTap: () {
    setState(() {
      iconSelected = !iconSelected;
    });
  },
  child: GlowIcon(
    iconSelected ? Icons.wb_cloudy : Icons.cloud_queue,
    color: flutterColor,
    glowColor: iconSelected ? flutterColor : Colors.transparent,
    size: 64,
    blurRadius: 9,
  ),
 );
),


text:
Q: Does every compact metric space have a finite basis? Let $M$ be a compact metric space. Then the collection $\mathscr{U}=\{B(x,\frac1n):x\in M, n\in\Bbb{N}\}$ forms an open cover of $M.$ Let $\mathscr{B}_0$ be a finite sub-cover extract from $\mathscr{U}$. We can easily prove that $\mathscr{B}_0$ is a (finite) sub-basis for the topology on $M$.
Does $\mathscr{B}_0$ provide a finite basis for the metric topology on $M$?

A: From the comments it appears that what you really want to show is that a compact metric space $X$ is second countable. To do that, for each $n\in\Bbb Z^+$ let $\mathscr{U}_n=\left\{B\left(x,\frac{1}n\right):x\in X\right\}$; $X$ is compact, so $\mathscr{U}_n$ has a finite subcover $\mathscr{B}_n$. Let $\mathscr{B}=\bigcup_{n\in\Bbb Z^+}\mathscr{B}_n$; then show that $\mathscr{B}$ is a base for $X$. This takes a little work with the triangle inequality but isn't too hard.


text:
Q: Proving a one-to-one function with a power set involved Let A = P({1,2,3,4}).
f : A → A defined by f (X ) = X ∩ {1, 4}.
Can I prove that the function is one-to-one as there is one intersection? Or since there are many 1's and 4's within the power list that repeat, does it mean that it is not a one to one function.
I know that the {1,4} will have one intersection with the power set
( {},{1},{2},{3},{4},{1,2},{1,3},
{1,4},      (intersection)
{2,3},{2,4},{3,4},{1,2,3},{1,2,4},{1,3,4},{2,3,4},{1,2,3,4})
I am used to proving that a function is one by one by proving that if f(u)=f(v)  then you must have u=v, this is confusing for me. I believe that it is a one-to-one function but I am not sure how to prove it in this context.

A: Hint:
What is $f(\{1\})$? What is $f(\{1,2\})$
Edit referring to comment:

*

*$f(\{1\}) = \{1\} \cap \{1,4\} = \{1\}$

*$f(\{1,2\}) = \{1,2\} \cap \{1,4\} = \{1\}$

So, you have found two elements $A,B \in P(\{1,2,3,4\})$ such that $A \neq B$ and $f(A) = f(B)$.


text:
Q: IOException : The network adapter could not establish the connection I am trying to connect to an Oracle database from my Java application. I am using oracle.jdbc.driver.OracleDriver, Version : 0/1 to connect to the database. But DriverManager.getConnection() is giving me the "The network adapter could not establish the connection". This is not happening evertime. Its happening sometimes only, may be once in 8-10 times. The stack trace am getting is :
Driver Class : oracle.jdbc.driver.OracleDriver, version 0/1
java.sql.SQLException: Io exception: The Network Adapter could not establish the connection
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:179)
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:334)
at oracle.jdbc.ttc7.TTC7Protocol.handleIOException(TTC7Protocol.java:3678)
at oracle.jdbc.ttc7.TTC7Protocol.logon(TTC7Protocol.java:352)
at oracle.jdbc.driver.OracleConnection.<init>(OracleConnection.java:365)
at oracle.jdbc.driver.OracleDriver.getConnectionInstance(OracleDriver.java:547)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:347)
at java.sql.DriverManager.getConnection(DriverManager.java:316)
at java.sql.DriverManager.getConnection(DriverManager.java:297)

Since I am not getting this everytime, I am not able to guess that there is any connectivity issue. I can see lots of developers have the same problem, but for them it happens everytime. Please help me, since i am literally stuck in solving this problem.

A: This is probably a network issue:

*

*Is there a firewall that's giving you trouble?  Try to telnet to the port. Is the firewall stateful?

*Is the DNS too slow (use IP address instead of hostname, try DNS lookup)

*Do you close the connections? Are you overloading the Listener?

A: I was having a similar problem, I tried using the IP address instead of the host name in the database URL, and it worked for me.
Example jdbc:
...(DESCRIPTION=(ADDRESS.....(HOST=1.1.1.1)..)

A: I would have a closer look and perhaps set a break point in
at oracle.jdbc.ttc7.TTC7Protocol.handleIOException(TTC7Protocol.java:3678)

to see the precise IOException handled.  This will tell you the underlying cause, which can help diagnose the problem.


text:
Q: FoundationDb: What is meaning of FDBException: Transaction is too old to perform reads or be committed I am trying to execute a getRange command in fdbCli but it fails with
FDBException: Transaction is too old to perform reads or be committed
What is the meaning of this particular exception?
Does it mean by query took more than 5 sec to complete?

A: Fdb keeps a list of the transaction started within 5 sec. Also, data nodes only keep versions of the last 5sec. So if the read version is smaller than the last version kept by dataNodes, the dataNodes have no way to answer the request. That's why fdb throws this exception. the trick to evade from such exceptions is to split one huge time taking transaction to many small transactions. I also noticed fdb performs really well if the transaction time < 300ms.

A: Firstly - yes, you are correct (your query took more than 5 seconds to complete).
If the read request's timestamp is older than 5 seconds, the storage server may have already flushed the data from its in-memory multi-version data structure to its on-disk single-version data structure. This means the storage server does not have the data older than the 5 seconds. So the client will receive the error you've mentioned.
NB: You can avoid this problem via the use of a RecordCursor and by using passing a continuation to your query.
More on continuations here.


text:
Q: Get Controller and Action Name whern creating Custom Authorization Policy in .NET Core 6 using IHttpContextAccessor I, am trying to configure a custom Authorization policy in .NET Core 6 with the following logic in a Handler:

*

*Get Controller Name and Get Controller Action which user is trying to access

*If Claim.Type = Controller Name and Value = Controller Action then grant access.

I, am trying to access the Controller Name and Action using IHttpContextAccessor injected into the Handler class. How can I get the controller name and action method name? I found several articles mentioning how to do so in previous versions of .NET Core. But those do not work on .NET 6. It always provides NULL value
Current AccessHandler (Previous Versions of .NET)
using Microsoft.AspNetCore.Authorization;

namespace myApp.Security
{
    public class AccessHandler : AuthorizationHandler<AccessRequirement>
    {
        private readonly IHttpContextAccessor httpContextAccessor;

        public AccessHandler(IHttpContextAccessor httpContextAccessor)
        {
            this.httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
        }
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, AccessRequirement requirement)
        {

            string? controllerName = httpContextAccessor.HttpContext?.Request.Query["controller"].ToString();

            string? actionName = httpContextAccessor.HttpContext?.Request.Query["action"].ToString();

            if (controllerName != null && actionName != null)
            {
                if (context.User.HasClaim(claim => claim.Type == controllerName && claim.Value == actionName))
                {
                    context.Succeed(requirement);
                }
            }

            return Task.CompletedTask;
        }
    }
}

A: Finally found the solution and the process of finding was really satisfying. Here is how you can do it in .NET 6 Core. Modify the Requirement handler as follows:
using Microsoft.AspNetCore.Authorization;

namespace myApp.Security
{
    public class AccessHandler : AuthorizationHandler<AccessRequirement>
    {
        private readonly IHttpContextAccessor httpContextAccessor;

        public AccessHandler(IHttpContextAccessor httpContextAccessor)
        {
            this.httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
        }
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, AccessRequirement requirement)
        {
            string? controllerName = httpContextAccessor.HttpContext?.Request.RouteValues["controller"]?.ToString();

            string? actionName = httpContextAccessor.HttpContext?.Request.RouteValues["action"]?.ToString();

            if (controllerName != null && actionName != null)
            {
                if (context.User.HasClaim(claim => (claim.Type == controllerName && claim.Value == actionName)))
                {
                    context.Succeed(requirement);
                }
            }

            return Task.CompletedTask;
        }
    }
}


text:
Q: Why is my PC breaking my Mbed? - swd Error I am using a nRF51-DK mbed board and programming it from both my mac and PC. However, when I use my PC to compile a program and then download the .hex to the board, I get a Fail.txt file show up in the mbed file system. It reads:

SWD Error

After that, no matter what I do I get fail.txt

TIMEOUT

I move to my mac, boot the mbed board in bootloader mode and then reinstall the latest firmware. After a reboot, the device works fine. When I try to instal any more programs from my PC, it breaks again.
Why is my PC breaking my mbed?
NB: I am using a Microsoft Surface Pro 3 running Windows 10 Pro x64

A: A solution is suggested here:

*

*Plug Board in, wait for solid status LED

*Press and hold reset button and at same time drag blinky on to mass storage device.

*Release reset and program should now load, no error.

I hope that makes sense to you - I have not used Mbed; I simply Googled "SWD Error" and several Mbed related hits popped up.  I was surprised because SWD (Single Wire Debug) is not peculiar to MBed, and expected to need "SWD Error"+ mbed as a search term; it seems this issue is common on mbed perhaps.
Anyway my advice in future is to always start by Googling the exact error message - it works in very many cases!


text:
Q: Cell selection by cell matrix @TimWilliams if I define CellArray matrix as range then it crashes on the code to build the matrix, I followed the answer posted at the link that you have indicated https://stackoverflow.com/a/8320884/11835835
Dim CellsArray(3,3) As Range
For X = 0 To 2
    For Y = 0 To 2
        CellsArray(X, Y) = Cells(X+1,Y+1) _
        .Address(RowAbsolute:=False, ColumnAbsolute:=False)  'it crashes here run-time error 91
    Next Y
Next X

For K = 1 To 2
    ActiveSheet.Union(Range(CellsArray(0, 0), CellsArray(0, K))).Select
Next K

Instead it works if I define CellsArray matrix as string
Dim CellsArray(3,3) As String

but then it crashes on
ActiveSheet.Union(Range(CellsArray(0, 0), CellsArray(0, K))).Select

with run time error 438

A: Try this:
Dim CellsArray(1 To 3, 1 To 3) As Range 'easier to use a 1-based array

For X = 1 To 3
    For Y = 1 To 3
        Set CellsArray(X, Y) = Cells(X, Y) 'Need Set here
    Next Y
Next X

I'm not sure what you want to do here...

Dim rng As Range
For K = 1 To 3
    If rng is nothing then
        Set rng = CellsArray(1, 1)
    Else
        Set rng = Application.Union(rng, CellsArray(1, K))
    End If
Next K
rng.Select


text:
Q: Error de ruta en laravel 5 Estoy tratando de corregir un problema que tengo al acceder a una ruta y tratar de exportar un archivo de excel. La pagina esta en laravel 5 y ha venido presentando algunas fallas por actualizacion y ahora estoy intentando corregir la exportacion del archivo y me indica que no encuentra la ruta; como se ve en la imagen.

En el archivo de rutas tengo definida la siguiente ruta:
Route::post('/Informes/excelPreventivos', 'InformesController@excelPreventivos')->name('Informes.excelPreventivos');

en el controlador:
public function excelPreventivos(Request $request)
    {
        $inicio = $request['fechaInicial'];
        $fin = $request['fechaFinal'];
        $reportes = Reporte_mantenimiento::with('equipo', 'biomedico', 'equipo.clientes')
            ->cliente($request['cliente'])
            ->fecha($inicio, $fin)
            ->get();
        $num = 1;
        foreach ($reportes as $reporte) {
            $data[] = [
                'N°' => $num,
                'N° REPORTE' => $reporte->numeroReporte,
                'CLIENTE' => $reporte->equipo->clientes->nombreCliente,
                'EQUIPO' => $reporte->equipo->nombreEquipo,
                'MARCA' => $reporte->equipo->marcaEquipo,
                'MODELO' => $reporte->equipo->modeloEquipo,
                'SERIE' => $reporte->equipo->serieEquipo,
                'PLACA' => $reporte->equipo->placaEquipo,
                'UBICACIÓN' => $reporte->equipo->ubicacionEquipo,
                'FECHA DE ASIGNACIÓN'=>$reporte->fecha,
                'FECHA DE REALIZACIÓN' => $reporte->fechaRealizada,
                'BIOMÉDICO' => $reporte->biomedico->nombreBiomedico,
                'OBSERVACIONES' => $reporte->observaciones
            ];
            $num++;
        }
        if (isset($data)) {
            Excel::create('Informe Preventivo', function ($excel) use ($data) {
                $excel->setDescription('Informe preventivo');
                $excel->sheet('Informe Preventivo', function ($sheet) use ($data) {
                    $sheet->setAutoFilter('A1:M1');
                    $sheet->freezeFirstRow();
                    $sheet->cells('A1:M1', function ($cells) {
                        $cells->setBackground('#ccf5ff');
                    });
                    $sheet->fromArray($data);
                });
            })->export('xls');
        } else {
            Session::flash('errorMessage', '¡No hay reportes preventivos que correspondan a los filtros escogidos!');
            return Redirect::to('/Informes/preventivos');
        }
    }

y en las vistas tengo lo siguiente:
@extends('app')
@section('content')

        @if(Session::has('errorMessage'))

                <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>
                {{Session::get('errorMessage')}}

        @endif
        {!!Form::open(['route'=>'Informes.excelPreventivos', 'method'=>'POST'])!!}
        @include('Dashboard.Informes.Forms.informe_form')

            {!!Form::submit('Generar',['class'=>'btn btn-primary'])!!}
            {!!Form::close()!!}

@stop

Informes / forms

            {!!Form::label('fechaInicial','Seleccione fecha de inicio del reporte:')!!}
            {!!Form::date('fechaInicial',null,['class'=>'form-control','required'=>'required'])!!}

            {!!Form::label('fechaFinal','Seleccione fecha de final del reporte:')!!}
            {!!Form::date('fechaFinal',null,['class'=>'form-control','required'=>'required'])!!}

            {!!Form::label('empresa','Seleccione la empresa(Opcional):')!!}
            {!!Form::select('cliente',\GeomedicosApp\Cliente::dropdown(),null,
            ['class'=>'form-control','id'=>'empresa','style'=>'width: 100%',
            'placeholder' => 'Selecciona la empresa para generar el informe']) !!}

me gustaria saber en donde estoy fallando o que estoy omitiendo y si hay alguna forma de corregir este direccionamiento?.
muchas gracias por los aportes.


text:
Q: Spatialite for Android NDK Build I am having a little trouble with build an existing project at:
http://code.google.com/p/spatialite-android/

I am using Win7 and Cygwin
I get the source code by cloning using "GIT for Windows". Placing it into: C:\temp\ECLIPSE\workspace\SA1
I download the following:

*

*http://download.osgeo.org/geos/geos-3.2.2.tar.bz2

*ftp://ftp.remotesensing.org/proj/proj-4.7.0.tar.gz
I place these in: C:\temp\ECLIPSE\workspace\SA1\spatialite-android-library\jni
I then start Cygwin and do the following:
$ cd c:/temp/eclipse/workspace/sa1/spatialite-android-library/jni
$ tar xvjf geos-3.2.2.tar.bz2
$ cd geos-3.2.2
$ ./configure --build=x86_64-pc-linux-gnu --host=arm-linux-eabi

Outside of Cygwin, I open in an editor: C:\temp\ECLIPSE\workspace\SA1\spatialite-android-library\jni\geos-3.2.2\source\headers\geos\platform.h
and make couple of changes so it resembles below
/* Set to 1 if you have `int64_t' type */
/* #undef HAVE_INT64_T_64 */

/* Set to 1 if `long int' is 64 bits */
/* #undef HAVE_LONG_INT_64 */

/* Set to 1 if `long long int' is 64 bits */
/* #undef HAVE_LONG_LONG_INT_64 */

/* Set to 1 if you have ieeefp.h */
/* #undef HAVE_IEEEFP_H */

/* Has finite */
#define HAVE_FINITE 1

/* Has isfinite */
/* #undef HAVE_ISFINITE */

/* Has isnan */
#define HAVE_ISNAN 1

Save and close
I then go back to Cygwin and do the following:
$ cd ..
$ tar xvzf proj-4.7.0.tar.gz
$ cd proj-4.7.0
$ ./configure --build=x86_64-pc-linux-gnu --host=arm-linux-eabi
$ cd ..
$ /cygdrive/c/android-ndk-r8/ndk-build

Along with the Compile++ lines the following compiles
StaticLibrary  : libiconv.a
StaticLibrary  : libproj.a

However while it's going through geos it comes up with the following error:
Compile++ thumb  : geos <= TaggedLineSegment.cpp
Compile++ thumb  : geos <= TaggedLinesSimplifier.cpp
Compile++ thumb  : geos <= TaggedLineString.cpp
Compile++ thumb  : geos <= TaggedLineStringSimplifier.cpp
Compile++ thumb  : geos <= TopologyPreservingSimplifier.cpp
Compile++ thumb  : geos <= Assert.cpp
Compile++ thumb  : geos <= GeometricShapeFactory.cpp
Compile++ thumb  : geos <= math.cpp
Compile++ thumb  : geos <= Profiler.cpp
Prebuilt       : libgnustl_static.a <= <NDK>/sources/cxx-stl/gnu-libstdc++/libs/armeabi/
StaticLibrary  : libgeos.a
make: execvp: /cygdrive/c/android-ndk-r8/toolchains/arm-linux-androideabi-4.4.3/prebuilt/windows/bin/arm-linux-androideabi-ar: Argument list too long
make: *** [/cygdrive/c/temp/eclipse/workspace/sa1/spatialite-android-library/obj/local/armeabi/libgeos.a] Error 127
HFisher@Toshiba500 /cygdrive/c/temp/eclipse/workspace/sa1/spatialite-android-library/jni
$

Can someone help with how I can fix this? Any help greatly appreciated!

A: The issue can be solved by making the path to the ndk and the spatialite-android folder shorter.
I moved the ndk to the c:\cygwin folder and renamed it from android-ndk-r8b to ndk.
Likewise I moved the android-spatialite folder to c:\cygwin and renamed it to sla
Then cd into /sla/spatialite-android-library/jni folder and run /ndk/ndk-build -j8
And it compiles :)

A: Try adding the following to the makefiles.
LOCAL_SHORT_COMMANDS := true

A: This appears to be an issue with the NDK.  This error occurs when the argument list provided is too long.  Usually this can be fixed using a options file.  See @ parameter for arm-linux-androideabi-ar.
Searching the internet it appears this issue has bee reported to Google. The only workaround I can offer is to use a Ubuntu VM to compile the native code.


text:
Q: Como configurar um ambiente de desenvolvimento manualmente Estou tentando configurar meu próprio ambiente de desenvolvimento em uma máquina com Windows 10.
A ideia seria instalar Apache + PHP + MySQL. O problema é que a documentação dos softwares são bastante complicadas para iniciantes como eu e tutoriais não me ajudaram muito.
A maior dificuldade de que encontrei foi em instalar o MySQL.
Eu sei que existem diversas opções de ambientes prontos, como o XAMPP, e o instalador do MySQL, mas a minha intenção é fazer manualmente (linha de comando e arquivos de configuração) para entender como tudo funciona.
Se alguém souber explicar ou indicar um local par ler sobre, me ajudaria muito.

A: Primeiro baixe o php
Em http://windows.php.net/download baixe a versão mais recente do php, baixe o primeiro arquivo que é um zip e extraia em uma pasta, neste exemplo vou extrair em uma pasta com o nome php, que criei em c:
Procure um arquivo com o nome php.ini-development e renomeie para php.ini
Agora adicione o php nas variaveis de ambiente
Botão direito em meu computor e escolha propriedades,
na tela que abrir entre em configurações avançadas do sistema, ira abrir outra tela, nela na aba Avançado clique em variaveis de ambiente, na tela que abrir, em variaveis do sistema, selecione Patch e clique em editar, nesta outra tela clique em novo e coloque o C:\php ou o caminho que você extraiu o zip do php, você também pode usar o botão procurar
Para quem estiver usando outra versão do windows, sem ser o 10. Pesquei por "adicionar variavel de ambiente no windows 8 /7/xp"
Pronto, seu php já esta instalado no windows!
Agora só falta o servidor
No caso de um ambiente de desenvolvimento, você não precisa instalar o apache, as versão atuais do PHP já traz um servido embutido.
Crie uma pasta www em c: ou qualquer outro lugar, depois navegue até essa pasta pelo cmd e execute o comando php -S localhost:8080
Pronto seu servido já esta rodando! Basta colocar seus arquivos nesta pasta e acessar pelo endereço localhost:8080
Se você não for usar banco de dados, isso já é o suficiente para começar a desenvolver
Acessando o mysql
No caso do mysql, não vou colocar nenhum link de passo a passo para instalação, acredito que a maioria que você encontrar no google serve, o que muitos se atrapalham não é na instalação, e sim em acessar o mysql depois da instalação.
Uma coisa é instalar o servidor, outra é instalar um client para acessar o servidor mysql, que seria a interface de acesso.
Apos instalar o mysql eu recomendo usar o heidi SQL, que é muito simples, leve e gratuito
http://www.heidisql.com/
Com o heidi aberto, basta colocar localhost no campo hostname e seu usuario e senha que você escolheu na instalação do mysql nos campos abaixo.
Pronto, seu ambiente de desenvolvimente essencial esta pronto.


text:
Q: How to merge new buffer to old buffer in scala?
I try to merge new data to old buffer when refreshing.
Update or insert is accroding the "id" attr.
Could someone tell me how to do it in scala?
def merge(oldBuf: Buffer[java.util.Map[String, Value]], newBuf: Buffer[java.util.Map[String, Value]]) {
      // loop newBuffer{
             // val item = newBuf(n)
             // val id = item.get("id")
             // if same id found in oldBuf:
             //    update new [Value] to the old item in oldBuf
             // else (can not found this id in oldBuf)
             //    add this new item to oldBuf
        //}
          return oldBuf
}

A: If you want to use Java's Map, then try putAll:
import java.util

object Buf extends App {
  val oldBuf = new util.HashMap[Int, String]()
  oldBuf.put(1, "1")
  oldBuf.put(2, "2")
  oldBuf.put(3, "3")
  oldBuf.put(4, "4")

  val newBuf = new util.HashMap[Int, String]()
  newBuf.put(4, "4 new")
  newBuf.put(5, "5")

  oldBuf.putAll(newBuf)
  println(oldBuf)
}

If you have a Scala Map:
import scala.collection._

val oldBuf = mutable.Map("a" -> 1, "b" -> 2)
val newBuf = immutable.Map("a" -> 3, "c" -> 4)

oldBuf ++= newBuf

so there is no difference.
Generally speaking I suggest converting any Java collection to a Scala collection, before you start processing in Scala (if your long term goal is to replace all Java code). If you use Java collections in Scala in your algorithms, they might stay there for good.


text:
Q: Scala or Java Library for fixing malformed URIs Does anyone know of a good Scala or Java library that can fix common problems in malformed URIs, such as containing characters that should be escaped but aren't?

A: I've tested a few libraries, including the now legacy URIUtil of HTTPClient without feeling I found any viable solution. Typically, I've had enough success with this type of java.net.URI construct though:
/**
 * Tries to construct an url by breaking it up into its smallest elements
 * and encode each component individually using the full URI constructor:
 *
 *    foo://example.com:8042/over/there?name=ferret#nose
 *    \_/   \______________/\_________/ \_________/ \__/
 *     |           |            |            |        |
 *  scheme     authority       path        query   fragment
 */
public URI parseUrl(String s) throws Exception {
   URL u = new URL(s);
   return new URI(
        u.getProtocol(),
        u.getAuthority(),
        u.getPath(),
        u.getQuery(),
        u.getRef());
}

which may be used combination with the following routine. It repeatedly decodes an URL until the decoded string doesn't change, which can be useful against e.g., double encoding. Note, to keep it simple, this sample doesn't feature any failsafe etc.
public String urlDecode(String url, String encoding) throws UnsupportedEncodingException, IllegalArgumentException {
    String result = URLDecoder.decode(url, encoding);
    return result.equals(url) ? result : urlDecode(result, encoding);
}

A: I would advise against using java.net.URLEncoder for percent encoding URIs. Despite the name, it is not great for encoding URLs as it does not follow the rfc3986 standard and instead encodes to the application/x-www-form-urlencoded MIME format (read more here)
For encoding URIs in Scala I would recommend the Uri class from spray-http. scala-uri is an alternative (disclaimer: I'm the author).


text:
Q: Expanding a cell formula resolving all its references (precedents) In Excel I have a cell containing a formula referencing other cells, which reference other cells and so on... forming a large tree of references. I'd like to substitute recursively all the occurrences of all the references so that the formula will contain only constants and no references to other cells.
E.g. Supposing I have these cells:
A1=3
A2=4
A3=5
A4=A1+A2
A5=A4/A3+1

is there a way to expand the formula of A5 into something like "(3+4)/5+1"?
I found the Precedents property in VBA which returns the list of precedents (the cells referenced in the formula at the various levels of the whole tree of dependencies). The solution would be to find their occurrence in the formula and substitute them recursively with the formula of the corresponding cells. However doing this syntactically is hard (e.g. think of substituting the occurrence of "A1" in the formula "=A10+A11").
I've been asked why I need this so here's my problem:
My spreadsheet has a lot of financial calculations that I don't understand, with partial results which are spread over various cells. I'm interested only in the final result which is in only one cell and depends on a number of initial variables. If I had to trace all the dependencies it would be a long work. I need to work with different scenarios with different initial values and of course the final result. These scenarios will be set automatically by the solver (so I need to have them all in the same spreadsheet) in order to optimize a function.

A: You can use Replace (from the Home ribbon, choose Find & Select / Replace).
For your example, I would set up the Replace window as:
Find what: A4
Replace with: (A1+A2)


text:
Q: pyparsing dropping space and merging tokens I am trying to parse some verilog code and I am hoping to just parse sections of it. I don't know pyparsing well enough to write a full parser. I am working on a port section. Here it can have optional tags like "input" and "output". So the following are valid ports:
random_signal
input random_signal

The problem I have is someone picked a port name:
input1

When I parse this line, pyparser separates the line into "input" and "1".
Here is what I have:
from pyparsing import alphas, nums
from pyparsing import Literal, Group, Optional, Word

port_name = Word( alphas + nums + "_") | "\\do "
in_type = Literal("input") | Literal("output") | Literal("RFnet") | Literal("inout")
var_real = Literal("var") + Literal("real")
bus_index = Word( nums )
in_bus = Literal("[") + bus_index + Optional(":") + Optional(bus_index) + Literal("]")
in_pin = Group(Optional(in_type) + Optional(var_real) + Optional(Literal("wire")) +
               Optional(in_bus) +
               port_name.setResultsName('port_name', listAllMatches=True))

# Test some ports
in_list = ['random_signal', 'input random_signal', 'input1', 'input input1']
for in_str in in_list:
    print in_str, in_pin.parseString(in_str)

Here is the output:
random_signal [['random_signal']]
input random_signal [['input', 'random_signal']]
input1 [['input', '1']]
input input1 [['input', 'input1']]

I would like input1 to return: [['input1']]
Thanks for you help.


text:
Q: How do I get the interior of the th tag on one line? Here is the fiddle
I would like to get From: textbox To: textbox all on one line.

            Project Name
            Project Number
            Market
            Project Type
            Completion Date
            Square Footage
            Architect
            Manager

From: <input type="text" id="min" name="min" class="form-control numberFilter" /> To: <input class="form-control numberFilter" type="text" id="max" name="max" />

            Project Name
            Project Number
            Market
            Project Type
            Completion Date
            Square Footage
            Architect
            Manager

.numberFilter {
width: 75px;
}

A: Your headings may need a tweak but try this:
.numberFilter {
    width: 15%;
    white-space: nowrap;
    display:inline-block;
}

You can edit the width value to suit, but that is just a guide. You won't be able to fix the width of the input in PX, unless you set the TH / TD widths.

A: You can do that with the help of display: table-row & display: table-cell.
Wrap each of your 2 "cells" (text + input) in a placeholder element (for example, a ), set this wrapper element to display: table-cell and the
 to display: table-row.
Here's the fixed fiddle

A: There are some good answers already.  You may run into cross browser issues with the table-row and table-cell css properties.  If you do, you can just give your input elements a "display: inline" and set the width of the column. Like so:
js fiddle code
<input style="display: inline" />

notice the width set on the th element in the js fiddle code.


text:
Q: Prove that if $C$ is a connected subset of $(X,\tau)$ and $B\subseteq X$ such that $C\subseteq B\subseteq \overline{C}$ then $B$ is connected. Let $C$ be a connected subset of a topological space $(X,\tau)$ and $B\subseteq X$ such that $C\subseteq B\subseteq \overline{C}$. Now it is required to prove that $B$ is connected. The following is my attempt.
Suppose $f:B\to \{0,1\}$ is continuous where $\{0,1\}$ is endowed with its discrete topology. Now since $C\subseteq B$ and $f$ is continuous we have $f(\overline{C})\subseteq\overline{f(C)}$, whence $f(C)\subseteq f(B)\subseteq f(\overline{C})\subseteq \overline{f(C)}$. But $f(C)$ is either $\{0\}$ or $\{1\}$ as $C$ is connected, and $f(C)$ is closed. Thus $f(C)=\overline{f(C)}$. Therefore $f(B)=f(C)$. Thus $f$ is constant. Hence $B$ is connected.
Is the above argument alright? Thanks.

A: With functions another way: by definition $C$ is dense in $\overline{C}$, so $C$ is dense in $B$ as well and $\{0,1\}$ is Hausdorff, and if $f: B \to \{0,1\}$ is continuous, $f|C$ is constant with value $c \in \{0,1\}$. But then $1_c$ and $f$ coincide on the dense set $C$ of $B$, so also on $B$ and $f$ is constant with the same value. Done: $B$ is connected.


text:
Q: Is there a similar of MessageBox of ExtJS in ADF Faces I'am looking for a possibility to achieve a MessageBox in ADF Faces.
Is there a similar of MessageBox of ExtJS in ADF Faces?
Here is an example msg-box
May be someone can direct me to the right way

A: You can have a look at <af:popup> and then use an <af:dialog> within it to get YesNo, OkCancel, YesNoCancel dialogs. Also you can add components like <af:progressIndicator> within an <af:dialog> to get the popup showing the progress.


text:
Q: Bigquery load from Avro gives can not convert from long to int I am trying to load the avro file from google storage to Big query tables but faced these issue.
Steps i have followed are as below.

*

*Create a dataframe in spark.

*Stored these data by writing it into avro.
dataframe.write.avro("path")

*Loaded these data into google storage.

*Tried to load the data into google bigquery by using following command
bq --nosync load --autodetect --source_format AVRO datasettest.testtable gs://test/avrodebug/*.avro
This command leads to give this error.
Error while reading data, error message: The Apache Avro library failed to read data with the follwing error: Cannot resolve: "long" with "int"
So i even tried to use this command by specifying the schema.
     bq --nosync load --source_format AVRO datasettest.testtable gs://test/avrodebug/*.avro C1:STRING, C2:STRING, C3:STRING, C4:STRING, C5:STRING, C6:INTEGER, C7:INTEGER, C8:INTEGER, C9:STRING, C10:STRING, C11:STRING
Here i have only C6,C7 and C8 are having integer values.
Even this also giving the same previous error.
Is there any reason why i am getting error for long to int instead of long to INTEGER
Please let me know is there any way to load these data by casting it.


text:
Q: @reboot crontab has no effect I have this crontab @reboot "/home/pi/Desktop/TV Scraper 2.0/run.sh" set up and for whatever reason it doesn't seem to run the bash file on reboot.
Typing "/home/pi/Desktop/TV Scraper 2.0/run.sh" on the terminal actually runs the script, so I know it's correct.
This is what's inside run.sh just in case:
#!/bin/bash
cd "/home/pi/Desktop/TV Scraper 2.0"
node ./app.js

I've also tried using @reboot root sh "/home/pi/Desktop/TV Scraper 2.0/run.sh" as well, but it doesn't work either.
How can I move forward with this? My knowledge of Linux is very limited. All I need is to have some Node and Python3 scripts run on every reboot. On Windows that's such an easy task: I've tried CRON, rc.local and autostart, nothing works.

A: My guess is that node is not available via cronjob, since its containing directory is not in your PATH environment variable. When you execute the script manually, it's probably available via PATH.
An easy fix for this is to use the full path, which you can get by executing which node. The result should be something like /usr/bin/node. Then you can use that, instead of just node.
For debugging purpose you can also redirect stdout and stderr to a file, so the last line in your script would look like this:
/usr/bin/node ./app.js &>/tmp/cron-debug.log

If that doesn't fix it, i would rename the directory "TV Scraper 2.0" and replace the whitespace characters with something like an underscore. Directory and file names are less likely to cause problems if you avoid whitespaces.


text:
Q: How to merge multiple pdfs (or pngs) into one single page Is there a command line tool to merge multiple graphs (in pdf or png format) to one page pdf, probably each fit a cell in a 2x2 table of that page?

A: I found the answer --- using pdfjam
e.g.
pdfnup --nup 2x2 frag.dat_*pdf


text:
Q: Convert plot offset along the y-axis to a sign function [-1;1] I'm not sure that I clearly enough reflected the essence of a small problem in the title of the topic, but I'll try to reveal its essence in the question itself.
https://www.wolframalpha.com/input/...

We have two functions.
If the function is shifted more to the positive region (up along the $y-axis$), then we "mentally associate the $+1$ sign with it, if it is negative (down the $y-axis$), then we" mentally associate the $-1$ sign with it".
If both the positive and negative regions are approximately the same, then we must switch between $-1$ and $+1$. Is there a continuous function that implements this operation, including in real time mode and those cases when the analytical description of the function is unknown?
EDIT:
Let me be more specific:
I need a function that extracts a constant component of the signal proportional to the displacement along the y-axis.
The signal continuously changes in time, therefore, it is necessary to extract the DC component in real time. For example, from this functions:
https://www.wolframalpha.com/input...


text:
Q: Distribution of each element and molecule as a function of distance from the Sun and as a function of time Are there any graphs that show the distribution of each element and molecule as a function of distance from the Sun?
And maybe even the time-evolution of each distribution over the solar system's lifetime?

A: What you're likely looking for is referred to by the heliophysics community as 'solar wind composition'.
You might be able to model it over longer periods, or greater regions, but for the most point, the data's collected by various spacecraft, so it's a point-in-space-and-time for the most part.  (well, it's a path in space-time, but it's not like we've got 4-dimensional data with good coverage).  You might get some measurements of variations over the solar cycle from spacecraft at L1, like from SOHO or ACE, or even some of the near-earth spacecraft, but all of these are going to be affected by the earth's magnetosphere.
Probably the best place to look for what instruments various heliophysics spacecraft have on them is the Virtual Space Physics Observatory.  The data classification they're using breaks composition down into a few different categories, so using the restriction:

Measurement type contains ('Dust' OR 'Energetic Particles' OR 'Ion Composition' OR 'Neutral Gas' OR 'Thermal Plasma')

returns 393 datasets ... as you want graphs, add:

Resource type equals 'Display(Plot)'

Which returns 30 datasets ... stuff from Cluster, DMSP, GOES, IMP 8, SAMPEX, Ulysses, Voyager 1&2, IMAGE, Geotail, ACE, Doublestar, Wind, MPA, FAST and Genesis.
There may be more composition information that's inferred from spectrometry, but neither that nor the solar wind data is really stuff I know a lot about.
...
Now, given that you're specifically looking for images related to heliophysics data, another place you can try looking is if they've got it in iSWA (Integrated Space Weather Analysis) ... I took a quick look through, and I didn't see anything obvious, but they're adding new data pretty regularly, if it's of interest for space weather purposes.

A: I haven't found any, so apart from warning about absence of evidence being construed as evidence of absence, I might suggest that you are actually looking for a table, rather than a graph? I don't think you'll find much besides chemical compositions of the Sun, planets, solar wind, and outer icy bodies. I don't think the overall chemical composition of any of those have changed much since formation besides fusion in the Sun, either.

A: The current element distribution basically goes back to the origin of the solar system, and hasn't really changed since except for the losses of parts or all of the atmosphere of the inner planets, and migration of the outer planets early in the history of the solar system. The concentration of iron and similar elements is highest on Mercury, lower on Earth, and lower again on Mars. Venus is in between Mercury and the Earth. The lower concentrations of the lightest elements, hydrogen and helium, on the inner planets is presumably due to the heat of the sun, the solar wind, and radiation pressure all driving these atoms out to the outer solar system. The mean density of the asteroids, located beyond Mars, is significantly lower than that of Mars, continuing the trend of a lower proportion of iron and similar elements as we recede from the sun.
Jupiter and Saturn were originally located further from the Sun than Neptune and Uranus and so retained most of their hydrogen and helium, as well as accumulating hydrogen and helium driven off from the inner solar system. Uranus and Neptune lost a lot of hydrogen and helium, but also retained a lot.
Except for these modifications which depend basically on the atomic weights of the elements, the detailed tables of element abundances, which depends primarily on how they are built up in the cores of giant and supergiant stars, are expected to be the same on all the planets as well as on the sun.


text:
Q: How to swap items with pointers I'm writing a little program to help me understand pointers better to finish an assignment I'm working on.
Here's main
#include <stdio.h>

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

typedef struct some_t {
    int x;
} some_t;

some_t *i, *j;

i->x = 1;
j->x = 2;

some_t *tmp;

tmp = i;
*i = *j;
*j = *tmp;

printf("i is %d\n", i->x);
printf("j is %d\n", j->x);

return 0;
}

As soon as I run it I get a segmentation fault and my emacs gud-gdb won't run through the program. I start it but then says 'continuing until next break.'
What I'm ultimately trying to do is I have a bag with pointers to objects (weapons, tools, etc) and a equipment struct (objects that are equipped). When I want to equip one of the objects in the bag I want to just flip the pointers of the objects. So that the pointers in the equipment struct point at the weapon and then the pointer in the bag swaps to pointing at what the previous object replaced.

A: some_t *i, *j defines two pointers, but they don't point anywhere useful. They are uninitialized variables.
Immediately after those definitions you try to dereference these pointers. Since they don't point anywhere meaningful, that's causing your problems. Make sure you point your pointers at something before you use them:
some_t a, b;
some_t *i, *j;
i = &a;
j = &b;

Or something along those lines.
Editorial note: you have a bunch of extra * in your swap routine; you just want to swap the pointers, right?
tmp = i;
i = j;
j = tmp;

A: You are not allocating memory for the pointers to point at. Without this the program doesnt know where pointers i and j are pointing.
You need to allocate memory first and then make the i and J point to it.

i=malloc(sizeof(some_t));  j=malloc(sizeof(some_t));

Also you are not actually swapping pointers.You are de-referencing them and basically copying data from memory location pointed by j to memory location pointed by i. This is okay but when you do *j = *i in the next step you are basically copying same content to memory pointed by j which it already holds.

A: You can't do the following:
typedef struct some_t {
    int x;
} some_t;

some_t *i, *j;

i->x = 1;
j->x = 2;

Here, you have the pointers i and j which do not point to any valid memory.
You need to allocate enough memory, then point your pointers to the allocated memory and only then should you store values.
typedef struct some_t {
    int x;
} some_t;

some_t *i, *j;
i = malloc(sizeof(*i));
j = malloc(sizeof(*j));

i->x = 1;
j->x = 2;

A: You don't need to dynamically allocate space, but you do need to allocate space. Here is an example where you static allocate space.  It also has the change where you swap the pointers (i and j) instead of swapping the dereferenced pointers (i andj):
#include <stdio.h>

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

typedef struct some_t {
    int x;
} some_t;

some_t val1;
some_t val2;
some_t *i, *j;

i = &val1;
j = &val2;

i->x = 1;
j->x = 2;

some_t *tmp;

tmp = i;
i = j;
j = tmp;

printf("i is %d\n", i->x);
printf("j is %d\n", j->x);

return 0;
}


text:
Q: My program is saying that i have 0Mb of ram left So i wrote program to print in console how much i'm using ram, network, processor, etc. But available ram (in Mb) shows 0 when im using only 30% of my 16gb of ram.
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Threading;

namespace Perf_Monitor
{
    class Program
    {
        static void Main(string[] args)
        {
            PerformanceCounter perfCpuCount = new     PerformanceCounter("Processor Information", "% Processor Time", "_Total");
            PerformanceCounter perfMemDowCount = new     PerformanceCounter("Memory", "Available MBytes");
            PerformanceCounter perfNetDowCount = new     PerformanceCounter("Network Adapter", "Bytes Received/sec", "Intel[R] 82579V     Gigabit Network Connection");
            PerformanceCounter perfNetUpCount = new     PerformanceCounter("Network Adapter", "Bytes Sent/sec", "Intel[R] 82579V Gigabit       Network Connection");

            while (true)
            {
                Thread.Sleep(1000);
                Console.WriteLine("CPU Load:            {0}%",     perfCpuCount.NextValue());
                Console.WriteLine("Available RAM:       {0}",     perfCpuCount.NextValue());
                Console.WriteLine("Network Usage Down:  {0}Mbit/s",     perfNetDowCount.NextValue() / 125000);
                Console.WriteLine("Network Usage Up:    {0}Mbit/s",     perfNetUpCount.NextValue() / 125000);
            }

        }
    }
}

This is how it shows up:

A: You have a copy/paste error, using perfCpuCount twice:
Console.WriteLine("CPU Load: {0}%",     perfCpuCount.NextValue());
Console.WriteLine("Available RAM: {0}", perfCpuCount.NextValue());

Should be:
Console.WriteLine("CPU Load: {0}%",     perfCpuCount.NextValue());
Console.WriteLine("Available RAM: {0}", perfMemDowCount.NextValue());


text:
Q: Python Paramiko doesn't show commands output in the right order When I run the following code, I get a distorted result:
######## Make connection

remote_conn_pre=paramiko.SSHClient()
remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy())
remote_conn_pre.connect(ip, port=22, username=username,
                        password=password,
                        look_for_keys=False, allow_agent=False)

remote_conn = remote_conn_pre.invoke_shell()

######## commands read from JSON file (commands)

for command in commands["normal"]:
    print("-- command: " + command)
    remote_conn.send(command + "\n")
    while not remote_conn.recv_ready():
        time.sleep(0.300)
    output = remote_conn.recv(buffersize)
    print(output.decode())

Output result:
-- command: sh run | section dhcp
sh run | sec dhcp

-- command: sh run | i ip route
ip dhcp bootp ignore
sh run | i ip route
ip route 0.0.0.0 0.0.0 vlan 1

As you can see the ip dhcp bootp ignoreresult should be under the "DHCP section" and not onder the "route section".
The correct result should be:
-- command: sh run | section dhcp
sh run | sec dhcp
ip dhcp bootp ignore

-- command: sh run | i ip route
sh run | i ip route
ip route 0.0.0.0 0.0.0 vlan 1

What is going wrong here? I thought about the command not being ready so I've built in the sleep timer. Yet it seems the buffer isn't empty or ready after this.

A: Because you do not wait for the command to finish before sending another. And there's actually no way to do that with SSHClient.invoke_shell (SSH "shell" channel). The "shell" channel is not intended for command automation.
Instead, use SSHClient.exec_command (SSH "exec" channel).
See Wait until task is completed on Remote Machine through Python

If some of your commands are actually not top-level shell commands, but subcommands of the top-level commands, see also:
Execute (sub)commands in secondary shell/command on SSH server in Python Paramiko


text:
Q: Drag without scrolling on a jQueryUI sortable element If I have a fixed-height div with sortable elements and if I drag one to a list below, the div will scroll. I thought I might be able to set overflow: hidden, which hides the scroll bar but still scrolls the div.
It is much easier to describe in this fiddle: http://jsfiddle.net/PrZNr/2/
If I try to drag A1 under B1, the div will scroll which could be frustrating to a user. How might I prevent this behavior?

Item A1

Item A2

Item A3

Item A4

Item A5

Item A6

Item A7

Item A8

Item A9

Item A10

Item B1

Item B2

Item B3

Item B4

Item B5

A: Well, somehow I overlooked the obvious: "scroll" option
I simply need to set scroll to false...
http://jsfiddle.net/PrZNr/3/


text:
Q: OSGI: Using code in another bundle from a fragment I want to add an OSGI fragment to a bundle, here to "org.eclipse.equinox.http.jetty", with a Manifest.mf like this:
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: JettyCustomize
Bundle-SymbolicName: com.company.st.console.jetty.customize
Bundle-Version: 1.0.0.qualifier
Bundle-Vendor: Company
Bundle-RequiredExecutionEnvironment: JavaSE-1.8
Fragment-Host: org.eclipse.equinox.http.jetty

Unfortunately, my code needs code defined in other bundles, here in "org.eclipse.jetty.io". So I add the following line to the manifest:
Import-Package: org.eclipse.jetty.io

Now - in Eclipse - the code compiles. But when I start the application, I get the following exception (MyJettyCustomizer is a class in the fragement that is used by the code in the fragment-host "org.eclipse.equinox.http.jetty" per reflection):
java.lang.ClassNotFoundException: com.company.st.console.jetty.customize.MyJettyCustomizer cannot be found by org.eclipse.equinox.http.jetty_3.4.0.v20170503-2025
    at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:484)
    at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:395)
    at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:387)
    at org.eclipse.osgi.internal.loader.ModuleClassLoader.loadClass(ModuleClassLoader.java:150)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:264)
    at org.eclipse.equinox.http.jetty.internal.HttpServerManager.createJettyCustomizer(HttpServerManager.java:232)
    at org.eclipse.equinox.http.jetty.internal.HttpServerManager.updated(HttpServerManager.java:74)
    at org.eclipse.equinox.http.jetty.internal.Activator.start(Activator.java:62)
    at org.eclipse.osgi.internal.framework.BundleContextImpl$3.run(BundleContextImpl.java:779)
    at org.eclipse.osgi.internal.framework.BundleContextImpl$3.run(BundleContextImpl.java:1)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.eclipse.osgi.internal.framework.BundleContextImpl.startActivator(BundleContextImpl.java:772)
    at org.eclipse.osgi.internal.framework.BundleContextImpl.start(BundleContextImpl.java:729)
    at org.eclipse.osgi.internal.framework.EquinoxBundle.startWorker0(EquinoxBundle.java:933)
    at org.eclipse.osgi.internal.framework.EquinoxBundle$EquinoxModule.startWorker(EquinoxBundle.java:309)
    at org.eclipse.osgi.container.Module.doStart(Module.java:581)
    at org.eclipse.osgi.container.Module.start(Module.java:449)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1628)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1608)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.doContainerStartLevel(ModuleContainer.java:1579)
    at org.eclipse.osgi.container.SystemModule.startWorker(SystemModule.java:264)
    at org.eclipse.osgi.container.Module.doStart(Module.java:581)
    at org.eclipse.osgi.container.Module.start(Module.java:449)
    at org.eclipse.osgi.container.SystemModule.start(SystemModule.java:188)
    at org.eclipse.osgi.internal.framework.EquinoxBundle.start(EquinoxBundle.java:383)
    at org.eclipse.osgi.internal.framework.EquinoxBundle.start(EquinoxBundle.java:402)
    at org.eclipse.osgi.launch.Equinox.start(Equinox.java:115)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.startup(EclipseStarter.java:326)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:239)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:653)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:590)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1499)
    at org.eclipse.equinox.launcher.Main.main(Main.java:1472)

If I remove the code that needs "org.eclipse.jetty.io" from MyJettyCustomizer and remove the line "Import-Package: org.eclipse.jetty.io" again from the manifest, there is no exception on runtime and the class MyJettyCustomizer is correctly loaded.
So is there any possibility that I can use code from another bundle in an OSGI fragment?

A: Do you happen to have com.company.st.console.jetty.customize package in more than one bundle/fragment? It looks like split package issue!


text:
Q: Xamarin not installing packages, error XA5209 & XA5207 I have a problem with Xamarin in Visual Studio.
I am working with Xamarin.Forms and Xamarin.Android. My problem is that that android component of the project do not install themselves. The zip folder is empty and the component folders are empty.
Solutions I tried:
Delete the the ./AppData/Local/Xamarin (in windows) folder which is supposed to force the IDE to download the appropriate packages (does not work)
Downloaded the m2repository_r29, put it in zip folders and give it his hash name (does not work)
Install manually each library : download, unzip and put in right folder (works, but is super long for each library from this source https://learn.microsoft.com/en-us/xamarin/android/troubleshooting/resolving-library-installation-errors#Manually_Downloading_m2repository)
This is a sample of the error message I get:

    Severity    Code    Description Project File    Line    Suppression State
    Error       An error occurred trying to install required android components on Project 'Project.AndroidClient'.
    Project 'Project.AndroidClient' requires the following components installed on your machine:
    Xamarin.Android.Support.Animated.Vector.Drawable
    JavaLibraryReference: https://dl-ssl.google.com/android/repository/android_m2repository_r29.zip-m2repository/com/android/support/animated-vector-drawable/23.3.0/animated-vector-drawable-23.3.0.aar-23.3.0.0
    AndroidResources: https://dl-ssl.google.com/android/repository/android_m2repository_r29.zip-m2repository/com/android/support/animated-vector-drawable/23.3.0/animated-vector-drawable-23.3.0.aar-23.3.0.0
    ...

Please double-click here to install it.

Intallation Errors: XA5209 Unzipping failed. Please download 'https://dl-ssl.google.com/android/repository/android_m2repository_r29.zip:m2repository/com/android/support/animated-vector-drawable/23.3.0/animated-vector-drawable-23.3.0.aar' and extract it to the 'C:\Users\...\AppData\Local\Xamarin\Xamarin.Android.Support.Animated.Vector.Drawable\23.3.0.0\embedded' directory
XA5209 Reason: ...

Please help, I am new to all this and I don't know what to do.

A: Use nugets instead, xamarin is migrating fully from components to nugets on May, 5th


text:
Q: Jquery-method in .NET not executing I'm running Visual Studio 2008 and .NET 3.5
I created a javascript method (window.unbeforeload) with javascript to give users a message when trying to exit the site. Unfortunatly, the same message is displayed every time a user clicks a link that's not redirecting outside of the site.
Solution: to let jquery handle all link-clicks inside the site. But this isn't working.
 <asp:Content ID="ContentHead" ContentPlaceHolderID="head" runat="server">

//lots of other functions

</asp:Content>

Here I tried making any click on a link inside the site create an alert, to no success.
How to go about making Jquery work in my application?
Sideinfo: I have verified that the jquery file exists at  HTML/jquery.js but despite this, Visual Studio 2008 issues a warning of file not found. Another .aspx page with the exact same path to the jquery file does not issue this warning.
UPDATE:
    <%@ Page Language="C#" MasterPageFile="~/Manage/ConceptManager.Master" AutoEventWireup="true" CodeBehind="ConceptManager.aspx.cs" Inherits="DynamicForm.Manage.ConceptManagerPage" %>

<%@ Register src="Controls/Element_MetadataEditor_FieldNode.ascx" tagname="Element_MetadataEditor_FieldNode" tagprefix="uc1" %>

<%@ Register src="Controls/Element_MetadataEditor_TemplateNode.ascx" tagname="Element_MetadataEditor_TemplateNode" tagprefix="uc3" %>

<%@ Register src="Controls/CategoryAttributes.ascx" tagname="CategoryAttributes" tagprefix="usercontrol" %>

<%@ Register Src="Controls/ConfirmDialog.ascx" TagName="DeleteConfirmDialog" TagPrefix="usercontrol" %>
<%@ Register Src="Controls/ConfirmDialog.ascx" TagName="ConfirmDialog" TagPrefix="usercontrol" %>
<%@ Register src="Controls/AddReferenceDialog.ascx" TagName="AddReferenceDialog" TagPrefix="usercontrol" %>
<%@ Register src="Controls/AddIncludeDialog.ascx" TagName="AddIncludeDialog" TagPrefix="usercontrol" %>

<%@ Register Assembly="ExtExtenders" Namespace="ExtExtenders" TagPrefix="ExtExt" %>

<asp:Content ID="ContentHead" ContentPlaceHolderID="head" runat="server">

</asp:Content>

A: I'm utterly baffled. No offense to Peeter above, but that seems like an overly complicated solution when the same can be achieved by doing something like
$(function($){
    $('a').not('[href*="mydomain.com"]')
          .click(function(e){
              // visiting some other domain!
          });
});

The excellent jQuery: In Action book also suggests simply checking for a[href^="http://"] to check for external links, and this is how I'd insist in doing it.
Personally (and because I'm a bit paranoid with this particular bit), I slap the two together as a sort of a catch-all (just in case someone or something throws in an internal absolute URL).
$('a[href^="http://"]').not('[href*="mydomain.com"]')
                       .click(function(e){
                           // visiting some other domain!
                       });

A:

Omg
Omg

Working example: http://jsfiddle.net/peeter/K8cuE/

A: Try changing this:
$(document).live('click',function() {
     $("a").click(function() {
         alert("Hello world!");
     });
 });

to this:
$(document).ready(function() {
     $("a").click(function() {
         alert("Hello world!");
     });
 });

A: You don't need to the live click.
$(function() {
    $("a").click(function() {
         alert("Hello world!");
     });
});


text:
Q: Central limit theorem with Lyapunov condition $Z_1, Z_2,...$ are iid uniformly distributed on $[-1;1]$,
$\lim_{n \to \infty} a_n=0$ and $\lim_{n \to \infty} na_n=\infty$ also $a_n>0$ $\forall n$,
$X_{n,j}= \frac{1}{a_n}I(|Z_j| \le a_n)$ $\forall j = 1,...,n$ where $I$ is the indicator function,
$S_n=\sum_{j=1}^{n}X_{n,j}$.
One needs to show that $(S_n-n)\sqrt{\frac{a_n}{n}} \to N(0,1)$ in distribution.
Easy to show that:
$E[S_n]=n$ if $n$ large enough,
also $Var[S_n]= \frac{(1-a_n)n}{a_n}$ if $n$ large enough,
and the Lyapunov condition is satisfied for $\delta=2$, i.e. $$\lim_{n \to \infty} \sum_{j=1}^{n} \frac{1}{Var(S_n)^2}E[|X_{n,j}-E(X_{n,j})|^4]=0.$$
But then it follows that $\frac{S_n-E[S_n]}{\sqrt{Var(S_n)}}=(S_n-n)\sqrt{\frac{a_n}{n(1-a_n)}} \to N(0,1)$ in distribution. What am I doing wrong?
Reaction to Did's comment:
$Z_n=(S_n-n)\sqrt{\frac{a_n}{n(1-a_n)}}$ and $Y_n=Z_n*\sqrt{(1-a_n)}$, Clearly if $F_{Z_n}(x)$ is a cdf for $Z_n$, then $F_{Z_n}(\frac{x}{\sqrt{1-a_n}})$ is the cdf for $Y_n$. Now we need to prove that $\lim_{n \to \infty}F_{Z_n}(\frac{x}{\sqrt{1-a_n}})=\Phi(x)$ $\forall x$. And here I am stuck.


text:
Q: Error bars / measurement uncertainty in bar plots I'm plotting pH results from an experiment and the measurement uncertainty is ± 0.1.
\documentclass[10pt]{standalone}
\usepackage{pgfplots}
\usepackage{siunitx}
\usepackage{tikz}
\usepackage{mhchem}
\usetikzlibrary{patterns}
\pgfplotsset{compat=1.16}
\definecolor{mygray}{HTML}{c7c7c7}
\definecolor{myblue}{HTML}{4385f5}
\definecolor{myred}{HTML}{ea4136}
\definecolor{myorange}{HTML}{fcbc05}
\begin{document}
\begin{tikzpicture}
  \centering
  \begin{axis}[
    ybar=0pt, enlarge x limits=0.25, legend style={at={(0.5,-0.15)},anchor=north,legend columns=-1,/tikz/every even column/.append style={column sep=0.1cm}}, legend style={draw=none,/tikz/every even column/.append style={column sep=0.3cm}},
height=6cm, width=11cm,
        ymajorgrids, tick align=inside,
        ymin=0, ymax=14,
        ytick={0,2,4,...,14},
        ylabel={pH},
        y axis line style={opacity=0},
        tickwidth=0pt,
        ylabel={pH},
        symbolic x coords={Reference, Aabach, Kleine Emme, Grosse Aa},
       xtick=data,
       nodes near coords,every node near coord/.append style={font=\tiny},
       bar width=13pt,
                  cycle list={
           {fill=mygray,draw=black},
           {fill=myred,draw=black},
           {fill=myblue,draw=black},
    {fill=myorange,draw=black}}
    ]
\addplot coordinates {(Reference,7.3) (Aabach,8.5) (Kleine Emme, 8.2) (Grosse Aa, 8.1)};
\addplot coordinates {(Reference,7.8) (Aabach,8.5) (Kleine Emme, 8.3) (Grosse Aa, 8.3)};
\addplot coordinates {(Reference,7.8) (Aabach,8.4) (Kleine Emme, 7.9) (Grosse Aa, 8.2)};
\addplot coordinates {(Reference,7.8) (Aabach,7.8) (Kleine Emme,7.7) (Grosse Aa,7.8)};
    \legend{NT, DN, SYF, NAF}

                \addplot+ [ %from https://tex.stackexchange.com/questions/470674/adding-error-bars-to-bar-plot and https://tex.stackexchange.com/questions/424758/plotting-error-bars-in-pgf-plots
            error bars/.cd,
                y dir=both,
                y fixed=0.1,
        ] coordinates {
            (Reference,7.3) +- (0,0.1)
            (Kleine Emme,7.9) +- (0,0.1)
        };
  \end{axis}
  \end{tikzpicture}
\end{document}

The problem with the code is that duplicate bars are created:

How can have only four bars per x-tick, each with a error bar?

A: Instead of adding another \addplot command to draw an/the error bar(s) -- this adds the bar you don't want, you need to add the "error bar" stuff to each of the previous \addplot command. To not repeat yourself over and over again you can also add these options to the axis options.
For details have a look at the comments in the code.
% used PGFPlots v1.16
\documentclass[border=5pt]{standalone}
\usepackage{pgfplots}
    \pgfplotsset{compat=1.3}
    \definecolor{mygray}{HTML}{c7c7c7}
    \definecolor{myblue}{HTML}{4385f5}
    \definecolor{myred}{HTML}{ea4136}
    \definecolor{myorange}{HTML}{fcbc05}
\begin{document}
\begin{tikzpicture}
    \begin{axis}[
        ybar=0pt,
        enlarge x limits=0.25,
        % (merged both styles)
        legend style={
            at={(0.5,-0.15)},
            anchor=north,
            legend columns=-1,
            draw=none,
            /tikz/every even column/.append style={column sep=0.3cm},
        },
        height=6cm,
        width=11cm,
        ymajorgrids,
        tick align=inside,
        ymin=0,
        ymax=14,
        ytick distance=2,       % <-- (changed)
        ylabel={pH},
        y axis line style={opacity=0},
        tickwidth=0pt,
        ylabel={pH},
        symbolic x coords={Reference, Aabach, Kleine Emme, Grosse Aa},
        xtick=data,
        nodes near coords,
        every node near coord/.append style={font=\tiny},
        bar width=13pt,
        cycle list={
            {fill=mygray,draw=black},
            {fill=myred,draw=black},
            {fill=myblue,draw=black},
            {fill=myorange,draw=black}%
        },
        error bars/y dir=both,      % <-- added
        error bars/y fixed=0.1,     % <-- added
    ]
        \addplot coordinates {(Reference,7.3) (Aabach,8.5) (Kleine Emme,8.2) (Grosse Aa,8.1)};
        \addplot coordinates {(Reference,7.8) (Aabach,8.5) (Kleine Emme,8.3) (Grosse Aa,8.3)};
        \addplot coordinates {(Reference,7.8) (Aabach,8.4) (Kleine Emme,7.9) (Grosse Aa,8.2)};
        \addplot coordinates {(Reference,7.8) (Aabach,7.8) (Kleine Emme,7.7) (Grosse Aa,7.8)};

        \legend{NT, DN, SYF, NAF}
    \end{axis}
\end{tikzpicture}
\end{document}


text:
Q: Is it possible to determine which php version is most widely used on paid webhosting services? I'm assuming every modern hosting provider gives access to php5 (and i noticed that many have both 4 and 5) but now WHICH php5 is most popular... let's say i'm trying to choose between curl copy handle and curl setopt array (in my previous question)... but curl setopt array is available in php 5.1.3 while curl copy handle is available in earlier versions... so now how do i know if it's worthwile to use thing that works with newer version? How do i know if php 5.1.3 is used widely enough? I'm trying to make my application run on most configurations available.

A: Use the function_exists method to check for which function exists, then use that one.  That way you don't have to worry about which version of PHP is being used.  It's the same idea as the feature-detection vs browser-detection debate in javascript.

A: According to this website, the most popular version of PHP on May 9, 2008 (over a year ago) was PHP 5.2.5. So, you'd probably be OK using 5.1.3 + features.

A: Besides what tj111 mentioned, the PHP version doesn't really mean which functions will or will not be available. Many hosts, specially free hosts, disable features like cURL, mail(), ZipArchive, image* functions, system(), exec(), passthru() etc. If you want to check for dependences, its recommended to check for exactly what you need with function_exists().