Postgresql behind firewall: Query takes too long

Question: Here is my setup: two CentOS 5.2 boxes on VMWare ESXi 4.0. The first box ip is 192.168.22.52 on eth0 and 192.168.99.1 on eth1. The second box runs PostgreSQL 8.3 with ip 192.168.99.2 on eth0. Here are iptables for box1, for box2 see comment below.
I have set up port 5432 forwarding on box1 and am able to connect to PostgreSQL on box2 via pgAdminIII or psql from Vista notebook (192.168.22.1, there is no other boxes in this subnet, it has its own switch and is physically isolated). The database I am connecting to has two schemas, one is 'smaller' (basically just one table), another one is bigger (some 30 tables, 100 functions, etc.) So I am able to work with the smaller schema (browse the table and so on) but I when I try to expand the bigger schema - pgAdminIII freezes for 20 min or so.
PostgreSQL log shows there is a query which takes way too long:
2009-06-04 21:04:46 EEST LOG:  00000: duration: 493578.874 ms  statement:
SELECT pr.oid, pr.xmin, pr.*, format_type(TYP.oid, NULL) AS typname,
typns.nspname AS typnsp, lanname, proargnames, proconfig,
        pg_get_userbyid(proowner) as funcowner, description
              FROM pg_proc pr
              JOIN pg_type typ ON typ.oid=prorettype
              JOIN pg_namespace typns ON typns.oid=typ.typnamespace
              JOIN pg_language lng ON lng.oid=prolang
              LEFT OUTER JOIN pg_description des ON des.objoid=pr.oid
             WHERE proisagg = FALSE AND pronamespace = 2200::oid
               AND typname <> 'trigger'
             ORDER BY proname

Both box1 and box2 are clones of the development boxes, and the original network structure was different - box2 was directly accessible without port forwarding and there was no problem accessing the databases whatsoever.
Now, if I run the above query via psql on box2 or 'original' machine, or from box1 connecting to box2, it executes immediately.
During the query is run, tcpdump on the box2 periodically says:
12:45:39.770609 IP 192.168.99.2.postgres > 192.168.22.1.49484: . 8760:10220(1460) ack 1 win 54
12:45:39.968496 IP 192.168.22.1.49484 > 192.168.99.2.postgres: . ack 10220 win 16425
12:45:39.968541 IP 192.168.99.2.postgres > 192.168.22.1.49484: . 10220:11680(1460) ack 1 win 54
12:45:39.968574 IP 192.168.99.2.postgres > 192.168.22.1.49484: . 11680:13140(1460) ack 1 win 54
12:45:39.969250 IP 192.168.22.1.49484 > 192.168.99.2.postgres: . ack 13140 win 16425
12:45:39.969275 IP 192.168.99.2.postgres > 192.168.22.1.49484: . 13140:17520(4380) ack 1 win 54
12:45:39.969408 IP 192.168.22.52 > 192.168.99.2: ICMP 192.168.22.1 unreachable - need to frag (mtu 1500), length 556

Other than that, I do not see much traffic. MTU on all ethN interfaces is 1500. ping -l 1472 -f 192.168.99.1 from the notebook goes through without problems.
I suspect that I am missing something about iptables or network setup and would appreciate your advise.
Comment: Box2 iptables here: http://www.flyupload.com/?fid=173188036
Answer: Some things to try:

Start off by verifying your network
is behaving itself.  Assuming you
have managed switches, look at the
interface statistics for
speed/duplex mismatching or a
mismatched MTU.  Consider checking /
replacing cabling if anything is
running errors (eg: trying to run
GigE over Cat5 instead of Cat5e will
likely give grief).
Run some tests to prove you can get
wire-speed transfers between the two
machines and to the external
machine; netcat, ftp or http
transfers are a good start here (scp
may get CPU bound, and thus, may not
be the best test).
Test the same query locally on the
Postgres server.  If it completes in
an appropriate timeframe, you know
it's not the database.  If it
doesn't complete or takes "too
long", then you have a bad query or
other database problem to debug.
Make sure to consider the storage
I/O side of things; you may be
saturating what your disks are
capable of providing.  Check the
VMware performance graphs to confirm
/ deny.
Assuming that works, disable the
firewall and run the same query
against the postgres server from
"box1".  If that works, the VM->VM
connectivity is likely fine.
Assuming that works, bring the
firewall back up and test again.  If
that works, then your problem is
likely external to that host,
leaving the switch or the external
host to debug.

Good luck.
Answer: You're having an MTU issue, but I'm not sure why. I'm trying to get my head wrapped around your virtual topology here.
So, your Windows Vista notebook is connected to the "local" network, or the Internet network?
I am assuming that your Windows Vista notebook is connected to the Internet and that you're accessing the external-side IP address of "box 1" to use the port-forwarding on port 5432 to get to "box 2". If that's the case, what do you get back when you try to:
ping -l 1472 -f <box 1 IP address>
Edit: Okay-- very good. If you would, run an "ifconfig" on both "box 1" and "box 2" and examine the MTU value on each Ethernet interface. They should all be 1500. (I'm just trying to get a handle on why "box 1" told "box 2" that it couldn't fragment a 556 byte datagram bound for your notebook...)
Edit: Zow. Okay-- that's wild.
If it's not too much to ask, could you post the contents (or links thereto) of your iptables configs into the question? (I'm starting to get stumped here. What you're describing is something that I've done frequently, but I'm not sure how it's breaking down.)
Edit: Back with you now. Okay. I'm getting perplexed at this one now. The iptables configuration doesn't look like it should be causing any problems. I do see that you're forwarding UDP 5432 onto "box 2". You don't need to forward that-- Postgres only uses TCP. That won't hurt anything, though.
During your 20 minute wait, did you see traffic moving between the Vista notebook and "box 2"? Can you reproduce that condition every time you connect?
Not that it makes a huge difference, but on the FORWARD chain on "box 1", I'd typically make the rule that ACCEPTs packets with RELATED,ESTABLISHED set to be the first rule in the chain (to short-circuit processing). I can't think this would have any significant performance impact for you, though.
I hate not knowing the answer to a problem. This is going to keep me awake at night.
Comment: Evan, thanks for guiding me through it. I edited the question to include all the info gathered so far. Still no solution...
Answer: Is it conceivable that one of these machines is trying to inappropriately use IPv6?  That is, have you made sure IPv6 is turned off everywhere it's not supposed to be used, and, if used at all, correctly configured?


How to do scheduled Linux server backup

Question: I need to organize automated backup for databases, websites, ftp, email, etc. at Ubuntu 9.04 and since I've never done it before, I'm looking for places to learn. What needs to be done, what (free) software I could use, tips&tricks, best practices and so on. If you could point me to relevant articles for beginners, I'd most appreciate that
Answer: Backups are always hard to tune properly; especially because people have different needs, and such needs are usually a mix between data 'snapshot' backup, data archiving, server (config) backup, reliable service, etc).
3dinfluence and davey are both right: it's important to try the restore operation (as Joel says), and a set of cron scripts is usually the first things to do; but additional actions have to be done depending on how much data you can "accept to loose", and which level of reliability you need.
So the questions you have to ask yourself are:

the purpose of the backup - "protect" your data/services against:

(local) hardware failure, like disk crashes;
bigger damage, like fire on the building;
user mistake (accidental deletion) or need to retrieve old data;
buggy package releases (upgrading the services is usually tough, etc).

acceptable downtime (and data losses), in case of different type of issue

disk failure? eg. no loss, no downtime(?)
other hardware failure (MB, CPU, etc)? one day of work lost, few hours downtime
fire (and water from the fireman)? one week lost, few days downtime
earthquake or blackout?

Depending on the answer to those questions, you'll see if daily backups are enough, or if you need a warm standby server staying in a different geographical location.
I'm not guru at all on this field, but maybe my example can gives you some idea.
I'm managing a small (debian) server, providing databases (postgresql), subversion repositories, trac sites and some others similar functions; the server is mainly used by our R&D group, so few people (~20 clients for the subversion), and some instruments (~50 clients for the database), but they are working almost 24/24h, 7/7days (especially the instruments, which feed the database with measures).
In case of average issue (like main hardware failure), a downtime of 2 to 4 hours is acceptable (instruments can work locally for a while). So I didn't have (yet) warn standby server, but only a set of local and distant backup and dumps.
So the requirements are not drastic at all: about hundred gigs of data, and less than hundred clients to serve.
The first "line of defense" is provided by the disk redundancy and partitioning
(which not only help in case of disk crashes, but also for further backup or server upgrade)
The machine is equipped with 4 disks (500Gb each).

2 (soft)raid arrays (type 1, on 3 disks):

a small one, dedicated to /boot
and a large one, used by lvm (see below)

2 lvm groups:

one made upon the large raid array (+ 1 non-raid partition on the 4th disk)
another one made with non-raid partitions only (50Gb on each of the first 3 disk, and half of the 4th disk)

finally, the partitions:

/ and /var on two lvm volumes from the large raid; user data are all stored on /var ...
the non-raid extends of the first vgroup are reserved for snapshots (lvm)
/boot directly on the small raid 1 array
/tmp and a special /backup on two lvm (linear volumes) from the second vgroup (non-raid).
the last drive is used, extends on the 3 others are reserved for snapshots.

The second defensive line is the regular backups: they are made from cron scripts, essentially launched every days (eg. hotbackup for svn, trac sites, copy of the db files, etc.) or every week (database dump, svn dump, etc.)
Exact ways of doing each backup depends on the services; for example, subversion provides tools for the (fast) hot backup (using hard links, etc) and textual dump, but a simple rsync is used for the database, made from a lvm snapshot.
All those backups goes on the (local!) /backup partition (to be fast); this partition is usually mounted in read-only; two sudoeable scripts are used to re-bind it in rw mode (beginning of a backup), and back to ro (at the end). A semaphore made upon lockfiles is used to take care of concurrent backups.
Each time that the /backup is switched to ro (and also every 4 hours), a mirroring action is scheduled (using 'at' with a small delay to concatenates changes from the third line).
The mirroring is made (using rsync) to a different server, from which data are archived on tapes (every day, with only one year of retention) and, over the network, to a set of distant terra stations.
To avoid the risk of loosing an entire day of work, at minimal bandwidth cost, a third line is also in place, which consist in doing incremental backup - where it's possible.
Examples:

for subversion, every revisions are dumped in a single (compressed file), from the post-commit and post-revpropschange hook (using svn-backup-dumps)
for the database, using continuous archiving (& PITR concept)

These increments are saved using the same concept as for the daily and weekly copy (to the local backup partition first, and with a small delay, on the second host). Of course, the daily copy and weekly dump scripts have to take care of the rotation of the increments.
Notice that this third line is really close to a warn standby server (well, it's a necessary step toward this concept).
Finally, the config of the server itself (to monimize the work if a new one has to be setup).
As I wasn't convince by the ghosting solution (new machine will have different hardware, disk config, etc.), I'd setup a dedicated subversion repository, on which I put every script or config file that I've manually edited (directly, or indirectly via a user-interface). So the root of the filesystem (/) is a working copy.
In addition, a cron task scheduled daily is responsible to save the list of installed packages (dpkg), the partitions tables (fdisk), raid and lvm setup and so on.
BTW, it's certainly the weakest point: the server config is on a subversion repos, served by the "same" host. Anyway, it's fairly easy to use one of the repository backup (either a fast backup or the dump) from a different machine (even a windows one), if needed.
In addition, I also try to conscientiously make lvm snapshots before touching any script (or package upgrade) on the main system.
But the lifetime of those lvm snapshot should be as short as possible, due to the big penalty introduced on the other services.
Well, I hope it can help, or at least gives ideas...
Answer: There are many options out there depending on your goals, infrastructure, and media preferences.
First you'll probably need to figure out how to setup cron jobs no matter what solution you end up going with.  It's what runs scheduled tasks on *nix.
As for the backup itself I tend to go with rsnapshot as it's simple enough to setup and does what I need.  Amanda and Bacula are both great solutions but involve databases and other things which complicate the backup and recovery.  I tend to avoid complicated things when I need something reliable such as in the case of backup.  Rsnapshot uses rsync over ssh to transfer the data between systems so it's secure and efficient.  It then uses hardlinks so that you have many point in time snapshots of the filesystem you're backing up.
Databases have to be treated a bit special b/c you either need to lock the tables while you're running your backup job or dump the database tables to another location where you then backup using what ever method you choose.  This can be done with a tool like mysqldump if you're using MySQL. This dump is normally automated using a cron job.
Comment: Definitely have to give rsnapshot another +1 before even reading the whole post that was what I was thinking.
Answer: Most folks I know use Bacula for this purpose.
http://www.bacula.org/en/
They have pretty decent documentation, but here's an article that walks you through some basics.
http://www.linux.com/archive/feature/132562
Answer: Curtis Preston wrote the O'Reilly book on backups he has website and  blog.   He has some sections on Linux backups and on rsync based tools.
Mondo Rescue is an all in one free image backup/restore tool (apt-get install mondo)
G4l is also an option. These two are good for backing up a single box.
Amanda is a centralised backup solution.
I'd say that your data is the important thing, to back up, use more than one means e.g. rsync to a remote box + cpio to a usb stick.  Everything else can be rebuilt you can switch from ubuntu to Fedora and take your data with you, it just takes more work, you can never get back lost data so make doubly sure that you have the data covered.
Whatever you choose. Do some restores and get comfortable doing them. There is nothing worse than having to restore a system in the middle of the night and then finding out the hard way that you got something wrong and your backups are mince!
Answer: Good answers on backup policies already. I've come to love a simple backup tool: Backup Manager.
Backup Manager is very lightweight (just some scripts, really), and easy to configure. It knows how to backup SVN repositories, MySQL databases and can run specific commands to backup other systems that you can't just copy files to backup. It stores backup data in standard file formats (tar, zip, etc) and can save them to many different storage areas: local disks, FTP servers, scp, Amazon S3... possibly encrypting them using a GPG key on the way. Another important point is that it's already packaged in Debian and Ubuntu.
Definitely a simple and efficient way to start out, although you may want something more advanced in the end.
Answer: It's very good to save backups on Amazon S3.
For backups I recommend use duplicity and DT-S3-Backup bash script.
DT-S3-Backup was designed to automate and simplify the remote backup process using duplicity and Amazon S3.  After the script is configured, you can easily backup, restore, verify and clean without having to remember lots of different command options.

How to do scheduled Linux server backup


Intersection of a closed and a dense subset of a Compact Hausdorff space be empty?

Question: Suppose that $X$ is a compact Hausdorff space. Let $\{X_i\}_{i \in \mathbb{N}}$ be a sequence of dense open subsets of $X$. Let $E$ be a closed subset of $X$. Can it happen that $\left(\cap_{i \in \mathbb{N}}X_i\right)$ has empty intersection with $E$?
First by Baire Category theorem, $\left(\cap_{i \in \mathbb{N}}X_i\right)$ is dense in $X$. Moreover, since $E$ is closed, it is compact. If the intersection were empty, then $E \subset \cup_{i \in \mathbb{N}}X\setminus X_i$. But, this doesn't yield any contradiction.
A hint would be greatly appreciated.
Thanks for the help!!
Answer: Yes, the intersection can be empty. Suppose that $X=[0,1]$, with its usual topology. Take $E=\{0\}$ and $X_n=(0,1]$, for each natural $n$.
Comment: You can also take a Cantor set $C$ and $X_n = [0,1] \setminus C$. Then $C$ is closed and uncountable! Since $C$ is nowhere dense, $X_n$ is dense.


How to change activity while get 401 status code in Interceptor Android

Question: When I am getting 401 status code in API then I have to open login activity. I don't want to put change activity logic in every API's onError method. I want a global method which used for all the API's.
So for that, I created one Interceptor
public class MyInterceptor extends BaseActivity implements Interceptor {

@Override
public Response intercept(Chain chain) throws IOException {
    Response response = chain.proceed(chain.request());

    if (response.code() == 401) {

        throw new RuntimeException(" Here you got 401 from API !");
    }

    return response;
}
}

Here I add this Interceptor
OkHttpClient.Builder builder=new OkHttpClient.Builder()
            .addNetworkInterceptor(new Interceptor() {
                @Override
                public okhttp3.Response intercept(Chain chain) throws IOException {
                    Request newRequest = chain.request().newBuilder()
                            .addHeader("Content-Type", "application/json")
                            .addHeader("User-Agent", "MyApp-Android-App")
                            .build();
                    return chain.proceed(newRequest);
                }
            })
            .addNetworkInterceptor(new StethoInterceptor())
            .addNetworkInterceptor(new MyInterceptor())
            .addNetworkInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));

Now, where should I add change activity call method. One more thing I am calling API using RxRetrofit. I want a global method for handling this 401 response. Can you please provide me any solution where should I put Activity change method call?
Comment: I did [this](https://gist.github.com/Sanjay-Prajapati/5c592f6f360fe5fe39927bbc39da70e4) way. checkout my Gist.
Comment: Did you find solution?
Comment: No, still I don't find any proper solution but as of now, I implemented as per my question. so in MyIntercepter class, I extend the BaseActivity I called the method of BaseActivity which clear the user data and navigate to the login screen. For navigating to login activity i used application level context.
Comment: @bdevloperI found a solution you can check my Gist which I mentioned below in answer. Sorry for late response I was not active since a long time.
Answer: create interceptor class
class HeaderInterceptor implements Interceptor
    {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request orignal = chain.request();
///--------------------------
            String token="your auth token"; //retriving depend upon you
//---------------------------

            Request request =orignal.newBuilder().header("Authorization", "Bearer "+ token)
                    .header("Accept", "application/json")
                    .header("Content-Type", "application/json").
                            method(orignal.method(), orignal.body())
                    .build();

            Response response =  chain.proceed(request);
            Log.d("MyApp", "Code : "+response.code());
            if (response.code() == 401){
                //handle it as per ur need
                return response;
            }
            return response;
        }
    }

now add interceptor
.....
                .addInterceptor(logging).addInterceptor(new HeaderInterceptor())
                .build();
    ..


What's the best way to check the version of a library on Ubuntu

Question: I am sure there are several ways to do this, but is there a tool built into Ubuntu or a recommended way to check the version of any given library you have installed on an ubuntu server?
Answer: First off. Sometimes when people talk about libraries they are talking about .deb packages that provide libraries to other packages. We'll deal with that case first. The other context you hear the term library used in is the traditional .so shared object sense. We'll deal with that second.
apt-cache depends <package_name> will return a list of packages that are dependencies for <package name>. Packages are not necessarily congruous with libraries (i.e., libraries in the sense of linkable .so files), but in Debian and Ubuntu libraries are generally packaged as lib<something>. If you do a dpkg -l |grep <library package name> you can find which package containing which libraries is installed.
kelliott@mis-ke-lnx:~$  apt-cache depends perl
perl
  Depends: perl-base
  Depends: perl-modules
  Depends: libbz2-1.0
  Depends: libc6
  Depends: libdb4.7
  Depends: libgdbm3
  Depends: zlib1g
kelliott@mis-ke-lnx:~$ dpkg -l |grep libc6
ii  libc6                                    2.11.2-10                         Embedded GNU C Library: Shared libraries
ii  libc6-dev                                2.11.2-10                         Embedded GNU C Library: Development Libraries and Header Files

Or you can go the other way. If you're wondering what package required the package libwww-perl you can use this handy little perl script to return a list of libwww-perl reverse dependencies that are also installed.
#!/usr/bin/env perl
use strict;
use warnings;

use AptPkg::Cache;
my $cache = AptPkg::Cache->new;

my $pkg = $ARGV[0]
    or die 'supply a package name as the first arg';

my @acrd = split /\s+/, `apt-cache rdepends $pkg`;

my $state;
for (@acrd) {
    unless ( $_ eq 'Reverse' or $_ eq 'Depends:' ) {
        $state = $cache->{$_}->{'CurrentState'};
        print "$_\n" if $state eq 'Installed';
    }
}

Now the .so shared object files are a little different. I like to use a combination of ldd and apt-file. Let's say I'm interested in the object files linked against ls:
kelliott@mis-ke-lnx:~$ ldd /bin/ls
    linux-vdso.so.1 =>  (0x00007fff8b05d000)
    libselinux.so.1 => /lib/libselinux.so.1 (0x00007fcfb7e24000)
    librt.so.1 => /lib/librt.so.1 (0x00007fcfb7c1c000)
    libacl.so.1 => /lib/libacl.so.1 (0x00007fcfb7a14000)
    libc.so.6 => /lib/libc.so.6 (0x00007fcfb76b3000)
    libdl.so.2 => /lib/libdl.so.2 (0x00007fcfb74af000)
    /lib64/ld-linux-x86-64.so.2 (0x00007fcfb8057000)
    libpthread.so.0 => /lib/libpthread.so.0 (0x00007fcfb7292000)
    libattr.so.1 => /lib/libattr.so.1 (0x00007fcfb708e000)
kelliott@mis-ke-lnx:~$ apt-file search libattr.so.1
    ia32-libs: /lib32/libattr.so.1
    ia32-libs: /lib32/libattr.so.1.1.0
    libattr1: /lib/libattr.so.1
    libattr1: /lib/libattr.so.1.1.0
kelliott@mis-ke-lnx:~$ dpkg -l |grep libattr1
    ii  libattr1                                 1:2.4.44-2                        Extended attribute shared library
kelliott@mis-ke-lnx:~$ file /lib/libattr.so.1
/lib/libattr.so.1: symbolic link to `libattr.so.1.1.0'
kelliott@mis-ke-lnx:~$ file /lib/libattr.so.1.1.0
/lib/libattr.so.1.1.0: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, stripped

As you can see our good friend ls has quite a few libraries linked against it. libattr.so.1 handles file attributes if I remember correctly. Doing an apt-file search against it shows that it was installed by two packages ia32-libs and libattr1 (one for 32bit and one for 64bit). And on my system it looks like the libattr1 package (at version 1:2.4.44-2) installed the libattr.so shared object file, which upon further investigation is at version 1.1.0.


Logging internet usage in Server 2008?

Question: We are running Windows Server 2008, with each client connecting to the internet through a Draytek router. Each client is setup with OpenDNS which blocks most websites.
There are a few limitations to OpenDNS blocking in terms of the sites the staff need to go on. For example they have a Facebook page so we can't really block Facebook. There has been an issue with staff sending various messages on Facebook to other staff, as well as on eBay etc.
We have had people in for disciplinary action over these messages and the management team would like to be able to show the staff the log if any future problems come up. It has also been added to the employment contracts that their internet usage within the company network is monitored.
Ideally, we would like to have a log of which users visited which sites. I know I can view the log within OpenDNS but that doesn't show me which user visited the site.
Is there any reasonably priced software available that would do this on a Windows 2008 Server with roaming profiles? The log would show the time, date, user and website visited.
Thanks,
Danny
Answer: I think your best bet is to proxy your users internet traffic through something like Microsoft's ISA Server. Another option would be an open source solution like Squid. And then to get good reporting, use something like Red Line Software's SurfCop or Internet Access Monitor. Both spit out executive friendly reports.
There's literally thousands of options out there, but they all generally involve directing user traffic through a proxy. You can user web traffic through the proxy with Group Policy.
None of these options require the use of roaming profiles.

Logging internet usage in Server 2008?


If $f$ is in $L^{p}$, prove that $\lim \int_{x}^{x+1} f(t) dt = 0$

Question:
If $f$ is in $L^p$, prove that $\lim_{x \to \infty} \int_{x}^{x+1} f(t) dt = 0$

It is easy to think that integration must be vanish as $x \to \infty $ but I cannot write them with math.
Suppose not. Then there exist $P$ such that if $p\geq P$ then $\int_{p}^{p+1} f(t)dt >0$. So with $p_1=P$ and $p_k=p_{k+1}-1$,
$\lim_{n \to \infty}\sum_{k=1}^{n}\int_{p_k}^{p_{k+1}}f(t)dt$ should be $>\infty$(I think)
Please help. Thank you!
Answer: Thanks to zhw for catching an oversight.
Write $\mathbb{R} = \bigcup_n [n,n+1)$ and then
$$\int_\mathbb{R} |f|^p = \sum_n \int_{[n,n+1)} |f|^p,$$ and
hence $$\int_{[n,n+1)} |f|^p \stackrel{n\to\infty}{\longrightarrow} 0.$$
If $p=1$, we are finished, otherwise suppose $p>1$.
Since $$\left(\int_{[a,b)} |f|\right)^p = \left(\int_{[a,b)} |f|1\right)^p \le \int_a^b |f|^p  \left( \int_a^b 1^{p \over p-1} \right)^{p-1},$$ we have
$$\int_{[n,n+1)} |f| \le \int_{[n,n+1)} |f|^p .$$
Comment: Then my proof is correct?
Comment: No. Your contrapositive is incorrect.
Comment: Now I understand what you answered. It can be regarded as convergence of series right?
Comment: Yes. In fact, absolutely convergent.
Comment: We don't know $f\in L^1(\mathbb {R}).$ We're given only $f\in L^p((\mathbb {R})$ for some $p.$
Comment: @zhw.: Good catch. Thanks.
Comment: @copper.hat I think the Hölder's inequality line is not correct. Shouldn't it be this way? $\left(\int_{[a,b)} |f|\right)^p = \left(\int_{[a,b)} |f|1\right)^p \le \int_a^b |f|^p  \left( \int_a^b 1^{p \over p-1} \right)^{p-1},$
Comment: @SolidSnake: Thanks for catching that.
Answer: Use Holder to see
$$(1)\,\,\,\,|\int_x^{x+1}f\,| \le \int_x^{x+1}|f| = \int_x^{x+1}|f|\cdot 1 \le (\int_x^{x+1}|f|^p)^{1/p}\cdot (\int_x^{x+1}1)^{1/q}=(\int_x^{x+1}|f|^p)^{1/p}.$$
Because $f\in L^p, \int_x^{x+1}|f|^p \to 0$ by the dominated convergence theorem. That shows $(1) \to 0$ as desired.
Answer: You haven't got the correct negation of the limit hypothesis. Remember that the opposite of

$f(x) \to b$ as $x \to \infty$ if for every $\varepsilon>0$ there is an $n$ such that $\lvert f(x)-b \rvert < \varepsilon$ for all $x>n$

is

$f(x) \not\to b$ as $x \to a$ if there is an $\varepsilon>0$ such that for every $n$ there is an $x>n$ for which $\lvert f(x)-b \rvert > \varepsilon$.

In other words, for some "bad $\varepsilon$", I can find "bad $x$" as large as I like, which don't do the thing I want.
(Remark: this is rather difficult to think about. It's easier to think to yourself "I can make a sequence $(x_n)$ so that $f(x_n)$ either doesn't converge, or converges to something other than $b$.")
In this case, suppose the limit is not zero. Then there is $\varepsilon>0$ such that
$$ \left\lvert \int_x^{x+1} f \right\rvert > \varepsilon \tag{1} $$
for $x$ arbitrarily large. Hence there is an infinite increasing sequence $(x_n)_{n=0}^{\infty}$ for which $x_{n+1}-x_n>1$ (so the intervals of integration are disjoint), and (1) holds. But then
$$ \infty > \frac{1}{\varepsilon^p}\int_{-\infty}^{\infty} \lvert f \rvert^p \geqslant \sum_{n} \int_{x_n}^{x_{n+1}} \left\lvert \frac{f}{\varepsilon} \right\rvert^p  $$
Now, Hölder's inequality says
$$ \int_A \lvert f \rvert \leqslant (\mu(A))^q \int_A \lvert f \rvert^p, $$
so the next inequality is
$$ \sum_{n} \int_{x_n}^{x_{n+1}} \left\lvert \frac{f}{\varepsilon} \right\rvert^p \geqslant 1^{-q}\sum_{n} \frac{1}{\varepsilon} \int_{x_n}^{x_{n+1}} \lvert f \rvert \geqslant\sum_{n} \frac{1}{\varepsilon} \left\lvert \int_{x_n}^{x_{n+1}} f \right\rvert > \sum_n 1 = \infty, $$
which gives a contradiction.
(This generalises to any measurable dissection of $\mathbb{R}^n$ in the same way, for example. Or, indeed, any sufficiently non-degenerate measure space with infinite measure.)
Comment: Thank you. I should check again.


how to use Drupal menu system AND OR

Question: I'm trying to display all content labeled under my taxonomy terms with ids 1 and 3. Both terms work fine so that If I point my browser to
www.mysite/?q=taxonomy/term/1 or www.mysite/?q=taxonomy/term/3
But trying to use drupals built-in AND/OR feature using the urls below gives me a "Page not Found" error.
www.mysite/?q=taxonomy/term/1+3
www.mysite/?q=taxonomy/term/1,3
Any ideas?
thanks
Comment: After more digging around I've found this. (In D7, you can no longer specify paths such as "taxonomy/term/1,2", "taxonomy/term/1+2","taxonomy/term/2/2" or "taxonomy/term/2/all". Function taxonomy_term_page (D7) does not parse the string as it did in D6.)
Comment: ...But I'd still like to know an easy way to get the same results since it was possible in version 6
Answer: Install the views module and then go to <code>?q=admin/structure/views</code>.
You will find a disabled view created by default named "Taxonomy term" with an ID equal to taxonomy_term.
Enable this view; it will override the default taxonomy page. Configure the view to match your case, and click save.

how to use Drupal menu system AND OR


Imprimir mais de uma cópia em javascript

Question: Eu consigo fazer uma impressão sair automaticamente em 3 cópias? Igual nessa janela abaixo.
window.onload = function() {
    window.print();
}

Answer: Não, isso não é possível.
Mas você pode ver isso como uma coisa boa.
Imagine se fosse possível e você acidentalmente ou um site mal intencionado enviasse um parâmetro para imprimir um número muito alto de páginas e um usuário desavisado clicasse em OK para imprimir sem notar na quantidade.
Answer: De acordo com a documentação do window.print() não há parâmetro adicional para esta função. Logo, não é possível enviar mais cópias. Uma solução (que não é muito legal) é você chamar 3 vezes o método:
window.onload = function() {
  window.print();
  window.print();
  window.print();
}


Computing the integration $\lim_{n\to \infty}\int_{-1}^1 \frac{nf(x)\ dx}{1+n^2 x^2}=\pi f(0)$

Question: I don't have any idea that how to start this problem.

Let $f:[-1,1]\to \mathbb{R}$ be a continuous function. Then show that
  $$ \lim_{n\to \infty}\int_{-1}^1 \frac{nf(x)\ dx}{1+n^2 x^2}=\pi f(0) $$
Comment: have you omitted a limit?
Comment: This definitely varies with respect to $n$. You meant to add $\lim_{n \to \infty}$
Comment: Yeah I made the change. Thanks, @LordSharktheUnknown
Answer: Hint: Consider
\begin{align}
\int_{|x|\leq n^{-1}} \frac{nf(x)}{1+n^2x^2}\ dx+ \int_{n^{-1}\le|x| \le 1 } \frac{nf(x)}{1+n^2x^2}\ dx.
\end{align}
Comment: an excellent hint, +1
Answer: Hint
We first change variables using $y = nx$ to get
$$\begin{align}
\lim_{n \to \infty}\int_{-1}^1 \frac{n}{1+n^2 x^2}f(x)\,dx
&=\lim_{n \to \infty}\int_{-n}^n \frac{f(y/n)}{1+y^2}\,dy
\\&=\int_{-\infty}^\infty\frac{f(0)}{1+y^2}\,dy \tag{Prove this!}
\\&=f(0)\int_{-\infty}^\infty\frac{1}{1+y^2}\,dy
\\&=\pi f(0)
\end{align}$$
The critical proof step has been left to OP, since OP merely asked for help starting the problem!


How to track from which site user came from to my rails app?

Question: I want to store url of user's referral website after sucessfull registration. In this case I can't use request.referer because user can visit few pages on my website before registration. But I need previous website url, for example http://google.com or http://facebook.com/somepage_id or whatever. I know that Google Analytics or Intercome can collect this data but I want something simple. Preferably without external APIs or libraries if this possible.
Answer: There is ruby gem called 'ahoy', which can be used for this.
When someone visits your website, Ahoy creates a visit with lots of useful information.

traffic source - referrer, referring domain, landing page, search
keyword
location - country, region, and city
technology - browser, OS, and device type
utm parameters - source, medium, term, content, campaign

Please find the link for more information,
Ahoy
Answer: When user reach your site create UserSession which will store request.referer also it has user_id. And during registration bind UserSession to created User by filling user_id. In this case you will get site from which user came + you can get some additional info from UserSession(user-agent, date, visited pages and etc.)


VirtualBox Ubuntu LAMP Stack development, with SVN and CruiseControl/phpUnderControl?

Question: I've got a Windows 7 machine upon which I do both PHP/MySql Dev, and .NET/C#/Sql Server coding.  Due to a recent re-install, I thought it might be an ideal time to try and keep my machine a bit cleaner rather than install both Apache and IIS, etc.
I installed VirtualBox, with Ubuntu 10.04 as the guest OS, with the plan to move my PHP development from my old Windows/Apache/MySql platform onto this virtual image.  In addition to this, I want to add CruiseControl/phpUnderControl to my PHP development process.
So far I've got Ubuntu 10.04 installed with a LAMP stack, plus Netbeans for PHP, MySQL Workbench, etc, which is effectively the same as my old Windows dev set up, but I've now also installed SVN and CruiseControl (I've not installed phpUnderControl yet, but that is the next step).
My question is, can I use this virtual image as both my "local" development environment and as a build server, so that I don't need to clutter my native windows machine with MySql/PHP related software (meaning I can keep it nice and clean for .NET development)?
I imagine I'd need the virtual webserver to be able to serve both a "local" dev version of any given project I'm working on, as well as a staging version, which would build using cruisecontrol/svn commits?
Or should I separate my dev and build servers, perhaps keep the local development in windows, and only use the virtual image for the build server? or perhaps have two separate virtual machines for different purposes?
I'd appreciate some advice on the best way to set this up.  One of the projects I want to work on is quite complex so I want to make sure I get this up in the right way before I start the project, so that I can ensure the project is well maintained with versioning, unit tests and continuous integration, should I ever need to involve other developers on the project.
Answer: If you are looking to keep your Windows box clean of MySQL/PHP tools then I'd strongly recommend the two VM approach. One desktop linux distribution for development with LAMP etc on it for the quick code/debug turnaround and one that mirrors your real server install (with the addition of svn etc) for your test builds.
This gives you huge benefits for both having a nice dev environment and more importantly having a test server that will reflect operation of your code on the live server. This way you can keep your dev environment VM up to date with the latest updates for the distribution (kernel, tools, etc) and hold the build VM at whatever application versions are on the live machine. This takes a lot of the guesswork out of "is it the new version of library X or my code?".
If you want to go slightly overkill you'd actually want 3. One for dev, one for SVN/continuous integration and one that exactly mirrors your server so you can test deployment/system configuration.
Comment: I did consider the multiple box approach, but wasn't sure if it was overkill to have 3 instances running simultaneously, but you've convinced me of its benefits.
Answer: If you are considering having your VM for dev why not set it up exactly as you would setup your staging/production environment?
Furthermore you can setup your VM to host the code repository, and the web server, and then connect your tools that are local to your host machine (Windows). That way you can develop on your Windows box, connected to the VM.
This gives you the ability to do everything in your local environment while simulating the server environment in your VM.
VirtualBox does networking really well too, and you should be able to make your Windows host connect via the network to the server as if it were really another node on the network.
Comment: Yeah, I've been impressed how easy it has been to get a working virtual machine on the network - I set up a fixed IP for the VM I've set up so far, so i could access it from my native machine, there's no reason why I couldn't set up multiple VMs with the same approach.  I think I'll go with the 3 machine approach, one for developing, one as an SVN/CI build server, and one to mirror the live environment.
Comment: What VM tools would you recommend to use for development?


Git Command Line Tool Not Installed Windows

Question: I'm using a VM as a build machine for a cordova packager that is pulling a cordova plugin from git to add to the app. I have installed git on the vm and added it to the path.
When it tries to add the plugin from git I get the error in the jenkins console:
<code>Error: "git" command line tool is not installed: make sure it is accessible on your PATH.
</code>
I'm not sure what else I can do to help jenkins find the git file, I can remote on to the vm and run git commands from the command line fine.
Answer: You have to declare the Git installation on your Jenkins server (in the global configuration for the Master, or on the slave configuration):

(my example is for Linux but it's the same principe for Windows)
Please confirm it solves your issue :)
Answer: Have you tried to turn it off and on again?
Sorry, but, for real, close your console and open it again so the path get updated. It may help.
Answer: Managed to work out what the issue was. Whoever set up the jenkins slave in the first place created the PATH in the config page, so the PATH it was using had nothing to do with the path on the actual build machine, and changing that had no effect on where it looked for the git installation.


A passagem de objetos em Java simula passagem por referência?

Question: Todo mundo fala que Java passa por valor, inclusive Objetos. Estes são passados por cópia e não é possível reatribuí-los a um novo objeto dentro do método. O problema é que é possível alterar valor de objetos dentro do método. Isso não caracteriza a simulação de passagem por referência (feita com ponteiros em C++)?
Exemplo de Código Java
class Objeto {

    public int valor;

    public Objeto(){

        this.valor = 2;
    }
}

public class Passagem {

    public static void main(String[] args) {

        Objeto obj = new Objeto();

        System.out.printf("Valor inicial: %d\n", obj.valor);

        metodo(obj);

        System.out.printf("Valor após o método: %d\n", obj.valor);

        metodoNovo(obj);

        System.out.printf("Valor após o método com novo objeto: %d\n", obj.valor);

    }

    // Simula a passagem por referência alterando o valor do objeto
    // mas não o local de memória para qual aponta
    static void metodo(Objeto obj){

        obj.valor = 5;
    }

    //Tenta alterar o objeto em si
    static void metodoNovo(Objeto obj){

        obj = new Objeto();

        obj.valor = 10;
    }
}

O valor do objeto pode ser diretamente alterado pelo primeiro método. Já na segundo não é possível reatribuir ele a um novo objeto, até mesmo porque o método espera receber um Objeto constante - para alterar um objeto em si a lógica diz que teriamos que ter um objeto para um objeto.
O exemplo em C++, que se comporta da mesma maneira:
Exemplo de Código em C++
#include <iostream>

using std::cout;
using std::endl;

class Objeto{

    public:
        int valor;

        Objeto(){

            this->valor = 2;
        }
};

void funcao(Objeto *obj){

    obj->valor = 5;
}

void funcaoNovo(Objeto *obj){

    obj = new Objeto();

    obj->valor = 10;
}

int main()
{
    Objeto *obj = new Objeto();

    cout << "Valor inicial: " << obj->valor << endl;

    funcao(obj);

    cout << "Após função: " << obj->valor << endl;

    funcaoNovo(obj);

    cout << "Após função que atribui novo objeto: "
        << obj->valor << endl;
}

O resultado dos dois códigos é o mesmo.
Só é possível alterar o objeto em si no código C++ se a função esperar receber o endereço do próprio objeto, como em:
Função C++ que Altera o Objeto
void funcaoNovo(Objeto **obj){

    *obj = new Objeto();

    (*obj)->valor = 10;
}

main para a função acima
int main()
{
    Objeto *obj = new Objeto();

    cout << "Valor inicial: " << obj->valor << endl;

    funcao(obj);

    cout << "Após função: " << obj->valor << endl;

    funcaoNovo(&obj);

    cout << "Após função que atribui novo objeto: "
        << obj->valor << endl;
}

Onde será possível ver que a reatribuição deu certo.
Baseado nessas comparações, é certo dizer que em Java existe também uma simulação de passagem por referência? Não é possível alterar o objeto (o local para onde aponta), mas é possível alterar seus valores, pois a função (ou método) chamador altera diretamente o valor dos valores nos objetos.
Nota: Em C também é possível fazer o mesmo teste. Uma dada função funcao(int *ptr)
não consegue atribuir o ptr a um novo malloc dentro dela. Somente o valor pode ser alterado e é considerado uma simulação de passagem por referência.
Minha maior dúvida:
Em C++ o objeto em si não altera o valor original.
void funcaoNovo(Objeto *obj){

    Objeto *novo = new Objeto();

    novo->valor = 10;

    obj = novo;
 }

Aqui o obj não é alterado fora da função. Da mesma forma que em Java.
Ou seja não é possível reatribuir um objeto também pois C++ não pode alterar o objeto passado por cópia também. Entretanto pode alterar o valor contido no objeto (aqui há a simulação), desde que não tente se alterar o objeto.
Isso é chamado de simulação de passagem por referência, pois a função chamadora modifica os dados contido Objeto e não o Objeto em si. Java não tem passagem por referência (exceto com arrays), mas não seria correto dizer que há uma simulação dessa passagem no valor para qual o objeto referencia, ou seja eu consigo uma simulação ao referenciar os valores?
Pois vejo que ambas as passagens são semelhantes - permitem a função alterar valores de fora do escopo (incluindo múltiplos valores), sem permitir a reatribuição do ponteiro (referencia em Java).
Comment: Não sei se entendi sua edição, mas em Java quando se quer modificar objetos inteiros o comum é envolvê-los num "*wrapper*" (um objeto com referência pra outro objeto) e compartilhar esse *wrapper* com todas as partes interessadas. Assim, se uma delas mudar a instância do objeto, as outras obterão o novo objeto ao acessar o *wrapper* (desde que não salvem uma cópia local do objeto em si). Isso é mais ou menos semelhante ao ponteiro para ponteiro, só que um pouco mais limitado.
Comment: Para se alterar um ponteiro, alocando ele em um novo espaço de memória, em C++ (ou C) é preciso exatamente a mesma coisa: um ponteiro para ponteiro. Um ponteiro como parâmetro de função só garante alterar o valor que o objeto (ponteiro) contém (ou para onde aponta), não o objeto em si. Similarmente uma referência em Java, consegue alterar valores, para qual aponta, dentro da função que surtirão efeito fora dela. Da mesma forma que um ponteiro (analogamente à referência) o faz.
Answer: "Referências" e "passagem por referência" são duas coisas distintas. Diferentemente de C/C++, em Java toda variável que se refere a um objeto complexo o faz por meio de uma referência, não um ponteiro e não um tipo valor.
C/C++
Os três principais meios de se manipular objetos:
Objeto valor; // Um objeto no stack
Objeto* ponteiro = &valor; // Um ponteiro para um objeto no stack ou no heap
Objeto& referencia = valor; // Uma referência para um objeto no stack ou no heap

A maneira de utilizá-los é diferente: com os tipos valor e as referências, pode-se acessar os membros do objeto diretamente, enquanto com os ponteiros é necessário "derreferenciá-los":
cout << "Valor inicial: " << valor.valor << endl;
cout << "Valor inicial: " << (*ponteiro).valor << endl;
cout << "Valor inicial: " << referencia.valor << endl;

// Atalho para ponteiros (derreferenciação e acesso num único operador)
cout << "Valor inicial: " << ponteiro->valor << endl;

Ao passá-los para uma função, o tipo valor provoca uma cópia de todo o objeto:
void prop1(Objeto arg) {
    arg.valor = 5; // Não afeta o objeto original
}

void redef1(Objeto arg) {
    Objeto novo;
    novo.valor = 10;
    arg = novo; // Não afeta o objeto original
}

O ponteiro não copia o objeto, mas como ele simplesmente "aponta" pra algum objeto, mudar seu valor simplesmente o fará apontar para algum outro objeto - não afetando o objeto original:
void prop2(Objeto* arg) {
    arg->valor = 5; // Afeta o objeto original
}

void redef2(Objeto* arg) {
    Objeto* novo = new Objeto();
    novo->valor = 10;
    arg = novo; // Não afeta o objeto original
}

Já a referência "refere-se" ao objeto original. Qualquer mudança na mesma afetará sim o original, seja mexendo nas suas propriedades, seja reatribuindo-o:
void prop3(Objeto& arg) {
    arg.valor = 50; // Afeta o objeto original
}

void redef3(Objeto& arg) {
    Objeto novo;
    novo.valor = 100;
    arg = novo; // Afeta o objeto original
}

Alternativa:
Objeto& referencia2 = *(new Objeto()); // Uma referência para um objeto no heap

void prop4(Objeto& arg) {
    arg.valor = 50; // Afeta o objeto original
}

void redef4(Objeto& arg) {
    Objeto* novo = new Objeto();
    novo->valor = 100;
    arg = *novo; // Afeta o objeto original
}

Exemplo no Ideone. Disclaimer: não tenho quase nenhuma experiência prática com C/C++, não veja o código acima como uma boa maneira de se programar nessas linguagens (inclusive, tenho quase certeza de que tem ao menos um vazamento de memória nesse código...).
Java
Em Java, os tipos valor e ponteiros não existem, e uma referência tem algumas coisas em comum com cada um dos três:

A sintaxe da variável é parecida com a do tipo valor:
Objeto referencia;

A da construção com a do ponteiro:
= new Objeto();

E a semântica do resultado final é parecida (mas não idêntica) com a da referência:
Objeto referencia = new Objeto();

Entretanto, referências são passadas por valor:
void prop(Objeto arg) {
    arg.valor = 5; // Afeta o objeto original
}

void redef(Objeto arg) {
    Objeto novo = new Objeto();
    novo.valor = 10;
    arg = novo; // Não afeta o objeto original
}

O que isso quer dizer, no final das contas, é que em Java toda variável de um tipo complexo contém não o próprio objeto, mas uma referência (que pode ou não ser implementada através de um ponteiro - ver essa resposta para mais detalhes) para o objeto real - que só existe no heap. Essa referência pode ser copiada para outras variáveis, o que faz com que elas também passem a referenciar o mesmo objeto.
Acessar um objeto por qualquer uma de suas referências tem o mesmo efeito. Entretanto, as referências em si são independentes umas das outras. Elas são cópias umas das outras. E mexer numa cópia não altera a original. É por isso que atribuir um valor a uma referência (i.e. fazê-la apontar para um outro objeto) não tem qualquer efeito nas demais referências para aquele objeto - que continuam apontando para o objeto original.
Comment: @jsbueno Você chegou a testar esse experimento que propôs? Eu poderia fazer isso mas: 1) não tenho tempo, nem disposição, nem estou tão ansioso pra provar que estou correto, já citei várias fontes que corroboram o que eu falo, se quiser contestá-las todas é um direito seu; 2) meu senso comum diz que ele não se comportaria desse jeito - pois se tal função redefinir a referência, a variável externa será afetada, isso está bem visível no exemplo do ideone. Se tudo o que a referência passasse fosse o endereço do referido, como a função alteraria o referente? Isso não faz o menor sentido pra mim.
Comment: "por meio de uma referência, não um ponteiro"  E quando uma referência não é um ponteiro?  Só o açucar sintático do C++ que permite acesso aos membros do objeto sem o uso dos operadores para ponteiro do C. Mas a informação armazenada na variável de referência é a mesma. Acho que sua resposta mais confunde nesse aspecto do que esclarece.
Comment: @jsbueno "quando uma referência não é um ponteiro?" Em Java, nunca! As implementações antigas da JVM (classic e HotSpot) usavam *handles*, que eram um ponteiro fixo para outro ponteiro variável ([fonte](http://stackoverflow.com/a/1574285)). As recentes (Sun/Oracle, não sei quanto às [muitas outras](http://en.wikipedia.org/wiki/List_of_Java_virtual_machines)) usam ou um tipo chamado `oop` (uma classe que encapsula um ponteiro) ou um chamado `narrowOop`, um inteiro de 32 bits que precisa ser convertido em um ponteiro real antes de acessar um objeto ([fonte](http://stackoverflow.com/a/18135446)).
Comment: "REferencias" e "ponteiros" são dois nomes para a mesma coisa. A diferença entre ambas é que o C++ tem uma sintaxe diferente para lidar com as duas. Enquanto que por limitações historico/técnicas a sintaxe para lidar com dados de uma função tendo em mãos um ponteiro é distinta em C, C++ unifica essa sintaxe, e cria a 'referência'.
Comment: Experimente escrever uma função que aceite dois parâmetros: um ponteiro para uma estrutura, e uma referência para a mesma. faça uma chamada para essa função, passando um ponteiro e uma referência para a _mesma_ estrutura.  Agora abra seu programa com um depurador e veja passo a passo quais são os valores efetivamente passados para a função: do lado de lá chega _o mesmo_ número (um endereço de memória) de 32 ou 64 bit conforme o caso. Ponteiro/referência só faz diferença para a sintaxe necessária para manpulação dos campos.
Comment: Algumas referências (sem trocadilho :P) adicionais: [FAQ do ISO C++ sobre Referências](https://isocpp.org/wiki/faq/references). [Outra pergunta no SOen](http://stackoverflow.com/q/57483/520779) que faz uma análise comparativa extensiva da diferença entre esses dois conceitos.
Answer: Quase todas as linguagens orientadas a objeto - (se não todas) de fato passam sempre os objetos "por referência" - Isso é -tudo o que os métodos ou funções que recebem objetos como parâmetros recebem é uma referência ao objeto original que é normalmente representada internamente por um endereço de memória (um ponteiro) - embora em algumas linguagens de mais alto nível, como Java e Python, ao contrário de C++, o fato de seu método receber um endereço de memória seja tão transparente ao programador a ponto de ser "invisível".
Isso por que quando você acessa atributos ou métodos do objeto, nessas linguagens, a sintaxe é a mesma - ao contrário de C e C++ onde você tem que escrever seu código de um jeito se tem o "valor" da estrutura de dados/objeto ou com outra notação se tem uma "referência".  Na prática é como se nessas linguagens você sempre tenha uma referência ao objeto - mesmo no lugar onde ele é declarado e criado.
E por que então você não pode alterar o objeto em si que é referido? Por que o nome da variável que recebe o objeto  está na função ou método alvo - e aponta para um objeto específico. Se você aponta o nome para um outro objeto, o método que chamou seu código não tem como saber disso.  Por outro lado, se você faz alterações no objeto recebido, está de fato alterando o mesmíssimo objeto que quem chamou o método atual está "vendo".
Na verdade, fora de C, nem faz muito sentido você ficar se preocupando se está passando por "referência" ou "valor" na maior parte do tempo - vocẽ precisa saber que está passando um objeto de um lado para o outro.
Comment: Java não duplica objetos, mas duplica **referências**. C/C++ também duplicam ponteiros, quando os mesmos são passados por valor. Isso é algo que eu próprio não entendia bem, até iniciarmos essas discussões (esta pergunta e mais as duas que eu linkei), mas agora está bastante claro pra mim: passar um ponteiro pra uma função **não é** passagem por referência, e sim passagem por valor. Só que é *o ponteiro* que é passado por valor, não *a coisa para a qual ele aponta*. Por isso não duplica os objetos em si. Mas chame 100 funções passando um ponteiro, e 100 cópias *desse ponteiro* serão feitas.
Comment: Boa resposta, só discordo que a distinção seja irrelevante fora de C/C++ - C# é uma linguagem moderna, e ela emprega essa distinção em alguns casos (ex.: `Struct`s são um objeto complexo mas são um "tipo-valor", e portanto sua passagem acarreta numa cópia; existem também o `ref` e o `out` que pelo que eu saiba [pouco; não tenho experiência com C#] modificam a forma de passagem).
Comment: Bom, também não conheço C#, mas ele não se desvincula completamente de C e C++ (nem no nome) - se ele insiste em tornar endereços de memória menos transparentes, como você coloca, é mais um reflexo dessa herança. (que não digo que não possa acarretar ganhos de performance em algumas construções específicas, mas as custas da facilidade de uso da linguagem)
Comment: Ao contrário da sua primeira afirmação, em Java, C#, Delphi, Ruby, VB.Net... o padrão é passar o argumento por valor, e não por referência; e Java sequer suporta a passagem de argumentos por referência (em Java todo argumento, independentemente do seu tipo, é sempre passado por valor). Há que se ter em mente que *"tipos por valor e tipos por referência"* é diferente de *"passagem por valor e passagem por referência"*. Os links citados na resposta do @mgibsonbr esclarecem isso.
Comment: Caffé: não conheço tão bem as outras linguagens, mas Java **com certeza** não duplica todo objeto passado por um método - que é o principal "side effect" de "passagem por valor".
Comment: Acho que você está confundindo passagem por referência com a necessidade de uso de operadores especiais para acessar os campos de um objeto na função chamada.


Get item as soon as it inserted in dynamodb in python

Question: Looking for example
We insert single record in dynamodb
We need to retrieve that item as soon as it inserted in dynamodb database using python
Just like get record seeking continuously for latest item in db once it inserted it will retrieved from db
Comment: Use dynamodb streams.
Comment: @jarmod That seems like an answer, why not add it as such? :)
Comment: @Maurice I didn't want to steal the opportunity to answer for luk2302 but yes, agree, so I have added an answer.
Comment: You typically want an event-based solution without having to poll the database which means using [DynamoDB Streams](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.html) and [Lambda](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.html) functions, but you can also write a Python client that [polls streams](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodbstreams.html).
Answer: You typically want an event-based solution without having to poll the database which means using DynamoDB Streams and Lambda functions.
You can, however, also write a Python client that polls DynamoDB Streams.
Comment: I have done this but in first execution i got data record but after terminate python program i got error KeyError: 'NextShardIterator'

                      response = client.get_records(ShardIterator=shard_iterator, Limit=1)
Comment: You should create a new post and include the minimal code needed to illustrate the problem. Maybe the documentation is incorrect and rather than NextShardIterator being null, which is what the docs say, it is simply absent if there's no continuation?
Comment: response sharedit-- {'Records': [], 'ResponseMetadata': {'RequestId': '74a9ea37-9a97-41d0-9a46-9dc526b2b27c', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Mon, 23 May 2022 14:22:18 GMT', 'content-type': 'application/x-amz-json-1.0', 'x-amz-crc32': '2531396130', 'x-amzn-requestid': '74a9ea37-9a97-41d0-9a46-9dc526b2b27c', 'content-length': '14', 'server': 'Jetty(9.4.18.v20190429)'}, 'RetryAttempts': 0}}
Comment: Thanks for adding the response. Given that the `Records` list is empty, I'd say that the boto3 docs are misleading at best. I think you should change your code to first of all test `if NextShardIterator in response:` to handle it being absent.


Como verificar o erro "SQLSTATE[42S22]: Column not found: 1054 Unknown column"

Question: Gostaria de saber como posso verificar esse erro em meu código "SQLSTATE[42S22]: Column not found: 1054 Unknown column"
private $indoperacionais;
public function RetornaIndoperacionais($ano){

    if($ano == '2016'){
        $_base = "pla_est_2016";
    }else{
      $_base = "pla_est";
    }

    $Query = ("SELECT i.codiniciativa,
    te.nome as nome_tema,
    iniciativas as cod_te,
    p.observacoes as per_obs,
    te.sequencia as tem_sequencia,
    p.sigla as per_sigla,
    p.nome as nome_perspectiva,
    p.codperspectiva as cod_perspectiva,
    o.sequencia as sequencia_obj,
    o.codobjetivo as cod_obj,
    o.nome as nome_obj,concat(p.sigla, ' ', te.sequencia,
    '.', o.sequencia, '.',i.sequencia) as codigo,i.nome as nom_iniciativa,
    i.sequencia as iniciativa_sequencia,
    i.metas,i.responsavel,i.indicadores,
    ifnull((SELECT a.percentual FROM $_base.avaliacoes a WHERE a.status = 'A' AND a.codiniciativa = i.codiniciativa AND year(a.data) = 2016 AND month(a.data) = 1 ORDER BY a.data DESC LIMIT 1),
    ifnull((SELECT a.percentual FROM $_base.avaliacoes a WHERE a.status = 'A' AND a.codiniciativa = i.codiniciativa AND year(a.data) <= 2016 AND month(a.data) < 1 AND curdate() >= '2016-01-01' ORDER BY a.data DESC LIMIT 1), 0)) as '01',
    ifnull((SELECT a.percentual FROM $_base.avaliacoes a WHERE a.status = 'A' AND a.codiniciativa = i.codiniciativa AND year(a.data) = 2016 AND month(a.data) = 2 ORDER BY a.data DESC LIMIT 1),
    ifnull((SELECT a.percentual FROM $_base.avaliacoes a WHERE a.status = 'A' AND a.codiniciativa = i.codiniciativa AND year(a.data) <= 2016 AND month(a.data) < 2 AND curdate() >= '2016-02-01' ORDER BY a.data DESC LIMIT 1), 0)) as '02',
    ifnull((SELECT a.percentual FROM $_base.avaliacoes a WHERE a.status = 'A' AND a.codiniciativa = i.codiniciativa AND year(a.data) = 2016 AND month(a.data) = 3 ORDER BY a.data DESC LIMIT 1),
    ifnull((SELECT a.percentual FROM $_base.avaliacoes a WHERE a.status = 'A' AND a.codiniciativa = i.codiniciativa AND year(a.data) <= 2016 AND month(a.data) < 3 AND curdate() >= '2016-03-01' ORDER BY a.data DESC LIMIT 1), 0)) as '03',
    ifnull((SELECT a.percentual FROM $_base.avaliacoes a WHERE a.status = 'A' AND a.codiniciativa = i.codiniciativa AND year(a.data) = 2016 AND month(a.data) = 4 ORDER BY a.data DESC LIMIT 1),
    ifnull((SELECT a.percentual FROM $_base.avaliacoes a WHERE a.status = 'A' AND a.codiniciativa = i.codiniciativa AND year(a.data) <= 2016 AND month(a.data) < 4 AND curdate() >= '2016-04-01' ORDER BY a.data DESC LIMIT 1), 0)) as '04',
    ifnull((SELECT a.percentual FROM $_base.avaliacoes a WHERE a.status = 'A' AND a.codiniciativa = i.codiniciativa AND year(a.data) = 2016 AND month(a.data) = 5 ORDER BY a.data DESC LIMIT 1),
    ifnull((SELECT a.percentual FROM $_base.avaliacoes a WHERE a.status = 'A' AND a.codiniciativa = i.codiniciativa AND year(a.data) <= 2016 AND month(a.data) < 5 AND curdate() >= '2016-05-01' ORDER BY a.data DESC LIMIT 1), 0)) as '05',
    ifnull((SELECT a.percentual FROM $_base.avaliacoes a WHERE a.status = 'A' AND a.codiniciativa = i.codiniciativa AND year(a.data) = 2016 AND month(a.data) = 6 ORDER BY a.data DESC LIMIT 1),
    ifnull((SELECT a.percentual FROM $_base.avaliacoes a WHERE a.status = 'A' AND a.codiniciativa = i.codiniciativa AND year(a.data) <= 2016 AND month(a.data) < 6 AND curdate() >= '2016-06-01' ORDER BY a.data DESC LIMIT 1), 0)) as '06'
    FROM $_base.perspectivas p
    LEFT JOIN iniciativas te ON p.codperspectiva = te.codperspectiva
    LEFT JOIN objetivos o ON iniciativas = iniciativas
    LEFT JOIN iniciativas i ON o.codobjetivo = i.codobjetivo WHERE p.codperspectiva = '5' AND p.status = 'A' AND te.status = 'A' AND o.status = 'A' AND i.status = 'A'ORDER BY p.sequencia ASC,te.sequencia ASC,
    o.sequencia ASC,CAST(i.sequencia AS DECIMAL) ASC" );

    //echo "
"; print_r($Query); exit;

    //while ($_indoperacionais = mysql_fecth_array($Query));
    try {
            $this->search = $this->MySql->prepare($Query);
            //$this->search->bindParam(":nome", $this->indoperacionais);
            $this->search->execute();

        } catch(PDOException $e) {
            die($e->getMessage());
        }

        $_result = $this->search->fetchAll(PDO::FETCH_ASSOC);
        return $_result;

   }
}

<?php
 /* codigo para gerar os paramentros  */
    $ano        = $_POST["ano"];
    $_perspectiva = $_POST["perspectiva"];

    if ($_POST["semestre"] == "primeiro") {
        $_parametros = array (
        "ano" => $ano,
        "mes1" => 1, "mes2" => 2, "mes3" => 3,
        "mes4" => 4, "mes5" => 5, "mes6" => 6,
        "nomeMes1" => "Janeiro", "nomeMes2" => "Fervereiro", "nomeMes3" => "Março",
        "nomeMes4" => "Abril", "nomeMes5" => "Maio", "nomeMes6" => "Junho",
        "perspectiva" => $_perspectiva);
    }else if ($_POST["semestre"] == "segundo") {
        $_parametros = array (
        "ano" => $ano,
        "mes1" => 7, "mes2" => 8, "mes3" => 9,
        "mes4" => 10, "mes5" => 11, "mes6" => 12,
        "nomeMes1" => "Julho", "nomeMes2" => "Agosto", "nomeMes3" => "Setembro",
        "nomeMes4" => "Outubro", "nomeMes5" => "Novembro", "nomeMes6" => "Dezembro",
        "perspectiva" => $_perspectiva);
    }else {
        $error = "ERRO";
    }

    //Instanciando a classe
    $_model = new model_Indoperacionais();
    $_indoperacionais = $_model->RetornaIndoperacionais($ano);

        // "
"; print_r ($_indoperacionais);exit;
          echo '
'.$_perspectiva ["perspectiva"].'
';
          echo '
'.$ano ["ano"].'
';

     foreach($_indoperacionais as $_indoperacional){
          echo '
';
          echo ''.$_indoperacional['nome_tema'].'	';
          echo ''.$_indoperacional['indicadores'].'	';
          echo ''.$_indoperacional['responsavel'].'	';
          echo ''.$_indoperacional['metas'].'	';
          echo ''.$_indoperacional['codiniciativa'].'	';
          echo '
';
        //print_r($_parametros);
     }
    ?>

Answer: O erro que está sendo exibido é Column not found, isso significa que algum campo que tem na consulta sql, não tem na tabela do banco de dados. Faça uma comparação e remova esse campo da consulta.
Espero ter ajudado


How find positive integers $a,b$ such $a \mid b^2$, $b \mid a^2$, $(a+1) \mid (b^2+1)$.

Question: Find all postive integer $a,b$ such that
$$a \mid b^2, \quad b \mid a^2$$
and
$$(a+1) \mid (b^2+1)$$
It is clear that $a=b=1$ is a solution. It is also true that
$$(a,b)=(n^2,n^3),n\in N^{+}$$
is a solution. What other solutions exist?
Answer: Certainly all pairs $(a,b)$ with $a=b^2$ satisfy all three conditions: $a \mid b^2$, $b\mid a^2=b^4$ and $a+1=b^2+1$.
Answer: Let $b^2=ca$. By the given data $ca\mid a^4$ and $(a+1)\mid (ca+1)$ which is equivalent to $c\mid a^3$, $(a+1)\mid (c-1)$. Let $c=d(a+1)+1$, $d\in \mathbb{N}_0$. Now since $a^3\equiv-1\pmod{a+1}$, we have that $\frac{a^3}{c}\equiv-1\pmod{a+1}$ or $\frac{a^3}{c}=e(a+1)-1$ for $e\in\mathbb{N}$.
It follows that $a^3=(d(a+1)+1)(e(a+1)-1)$, which after multiplying and dividing by $a+1$ than we get $a^2-a+1=de(a+1)+(e-d)$ than it's $e-d\equiv a^2-a+1\equiv 3\pmod{a+1}$, so we have $e-d=k(a+1)+3$, $$de=a-2-k\tag{*}$$ for $k\in\mathbb{Z}$
Now we have 3 cases.
Case 1. $k\not\in\{-1,0\}$. From $(*)$, we have $de<\lvert e-d \rvert -1$, which is possible for $d=0$,so $c=1$ and $b^2=a$. Hence $(a,b)=(t^2,t)$
Case 2. $k=-1$. From $(*)$, we have that $a=d+1$. Now $c=a^2$ and $b^2=a^3$, and hence $(a,b)=(t^2,t^3)$.
Case 3. $k=0$. From $(*)$, we get $a=d^2+3d+2$. Now we have $c=d(a+1)+1=(d+1)^3$ and $b^2=ca=(d+1)^4(d+2)$. It follows that $d+2=t^2$ for $t\in\mathbb{N}$, which gives $(a,b)=(t^2(t^2-1),t(t^2-1)^2),t\geq 2$.
Comment: Why does $ca\mid a^4$ imply $c\mid a$?  (What if, e.g., $c=4, a=2$?)
Comment: @StevenStadnicki I wanted to write $ca\mid a^4$ implies $c\mid a^3$ ,fixed.


How to implement listview using Usercontrol and a flowlayout panel?

Question: I am trying to place Usercontrols on a flowlayout panel that act as a listview in C# (windows forms) . How can I implement selecting items here ?
Click event is not working when the user clicks on the controls of Usercontrol..
Any ideas ?
Answer: <code>private void flowLayoutPanel1_ControlAdded(object sender, ControlEventArgs e)
        {
            e.Control.Click += new EventHandler(Clicked);
        }

        private void Clicked(object sender, EventArgs e)
        {
            //click event code goes here
        }
</code>
Comment: let me try it..I want to change the backcolor when the usercontrol is clicked, which tells user that it is selected...


GIT author authentication

Question: Our company is looking into modernize our version control and generally we would like to use git. I've use distributed version control before but only with personal project and opensource project (where there is some sort of user management) (Mercurial on Google code and Bazaar on LaunchPad). I am not sure about how can we authenticate author of each commit if we are using GIT on our own repository. I am not talking about the authentication for push but for commit.
So let say ..
1. I clone the repo and check out a branch.
2. I change my user.name to my worker and make changes and finally commit.
3. I change my user.name back and push (with my ssh account for example).
4. There I can blame all the changes to my coworker.
Will this be a problem? How do we get around to tame this problem?
I am sure there is something out there but I guess I am not looking for the right info so it would be very helpful if you guys can give me some basic overview on this.
Thanks
Comment: Is this an actual problem? I've been working at a fairly large company where we use git for version control and gerrit for code reviews. Never has the question of spoofed commit authors/committers popped up. Sometimes people mistakingly put themselves as the author when doing a cherry-pick, but that's usually caught during code review.
Comment: Thanks for answering. It is not a problem now as we are still evaluating. It is corporate policy and paranoia that is in the play here. Also, I sense that they will not like that we have to rely solely on code reviewer (as mistake can happen in case of complex branch where many people have hand on).
Answer: You cannot regulate the creation of commits, since that happens on each user's workstation, in their own local copy of the repository.
You can do some checks (with hooks) in the central repository, and require that incoming commits bear the name of the connecting user.  However, this is a bad idea.
Consider the case where one user might need to reuse someone else's work, but doesn't want to merge it.  He might cherry-pick someone else's commit, or rebase their branch onto his own.  In this case, it is correct that the authorship information match the original commits, and restricting incoming commits to have an author name that matches the user pushing them would break this workflow.
I would worry about this only if it becomes a problem.  It comes down to trust: if you don't trust a developer, why do they work for you?
Comment: You can always require signing commits with a user's private key. But I would say this is all over the top. You can use server-side hooks to make sure users are restricted to committing a given name/email only, but as cdhowie rightly points out this makes it difficult to commit other people's work in certain workflows.
Comment: Actually it is not company I own and there are about a hundred of people here so the corporate infrastructure and certain management persons concerns about accountability.
Comment: @NawaMan If you want the flexibility and agility of Git, then you can't impose this restriction.  If your company wants to centrally manage everything and impose restrictions, then don't use a decentralized VCS.  Or, require code reviews for Git pushes.
Comment: @MikeWeller That would fail in rebase/cherry-pick scenarios too, unless we are authenticating the *committer* field and not the *author* field.  (And since the commit itself changes, the signature would be invalidated anyway.)
Comment: I haven't used git commit signing, but I would assume in that case you could use the signing information to know who actually made the commit. If someone claims to have been impersonated, you look at the signing info.
Comment: @MikeWeller I see -- so cherry-picked commits would have to be resigned.  That would work, if authentication is indeed required.
Comment: Thanks you all. I will look into the signing commit.

GIT author authentication


Reading with MySqlDataReader

Question: Hello I'm having problem to read with MySqlDataReader. I've tried to change while() to if() and it worked then. So I'm doing something wrong with while (Reader.Read()). Thanks for answer. ( The other question today is fixed, someone that commented helped me xd )
using (MySqlCommand cmd = new MySqlCommand
      ("SELECT * FROM `citationer`",  mysqlCon))
{
    try
    {
        MySqlDataReader Reader = cmd.ExecuteReader();
        while (Reader.Read()) // this part is wrong somehow
        {
            citationstexter.Add(Reader.GetString(loopReading)); // this works
            loopReading++; // this works
        }
        Reader.Close();
    }

    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

Comment: Can you provide the exception details please. It seems fine to me.
Answer: Your problem is the use of the loopReading parameter to GetString.
This parameter should be the zero-based column ordinal (the column number), but you're incrementing it for every row you read.
See here for more info:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getstring.aspx
You should use 0 for the first column of your citationer table, 1 for the second column, etc.
Also, it's good practice to use
  using(MySqlDataReader Reader = cmd.ExecuteReader())
  {
    ...
  }

just like you did for the mySqlCommand object to save a memory leak (but this is not your problem.)

Reading with MySqlDataReader


Why does my JS file not get loaded?

Question: I am a beginner with Drupal. I want to include a JavaScript file using a custom module.
I created the .libraries.yml file, hello_world.libraries.yml.
hello_world_js:
  js:
    js/basic.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupalSettings

The module .info.yml file (hello_worl.info.yml) contains a reference to the library.
name: Hello World
type: module
description: Say Hello World
package: Custom
core: 8.x
libraries:
  - hello_world/hello_world_js

The JavaScript code in the basic.js file is the following one.
(function($,Drupal){
  Drupal.behaviors.addAccessionBehavior = {
    attach: function(context, settings){
      $(".query_button").click(function(){
        console.log("works");
      });
    }
  };
})(JQuery, Drupal);

When I click on a button using the .query_button CSS class, nothing happens and I don't know what the problem is.
Answer: If you look in a JavaScript console you can get more information. You probably have an error in your console that says JQuery is not defined. This is  because you declared JQuery but the variable is jQuery. So this:
})(JQuery, Drupal);

Should be this:
})(jQuery, Drupal);

Also, when you want to test if your file has been attached, you should add a debugging command directly into behaviors.attach(), rather than a sub-function that requires a click (as you've done). So you can test if your script has been added like this:
Drupal.behaviors.addAccessionBehavior = {
  attach: function(context, settings){
    console.log("works");
    $(".query_button").click(function(){
      // Do stuff on click
    });
  }
};

This will log something on page load, which tells you that the script has loaded (and contains required variables).
Answer: Module info files have no libraries key. That key is only for themes.
You need to attach the module library yourself. Read the docs; there are numerous ways to attach the library at the right place to be loaded at the right time, depending on where you need the JS to fire.
Finally fix this typo: JQuery with uppercase J is wrong. It needs to be jQuery with lowercase j.

Why does my JS file not get loaded?


an estimate for condition number: $\kappa(C^{-1}A)\leq \kappa(C^{-1}B)\kappa(B^{-1}A)$

Question: I'm currently reading through "Domain Decomposition Methods" by Tosseli and Widlund and in the appendix I found the following Theorem:
Let A, B, C be symmetric positive definite matrices. Let $\kappa(M) = \lambda_\mathrm{max}(M)/\lambda_\mathrm{min}(M)$ be the spectral condition number. Then the following holds: $$\kappa(C^{-1}A)\leq \kappa(C^{-1}B)\kappa(B^{-1}A)$$
I think one can proof this using Rayleigh-quotients to estimate the eigenvalues of $C^{-1}A$, $C^{-1}B$ and $B^{-1}A$ to get an estimate.  I tried this for a while, but I'm getting nowhere with that.
Does anyone know a proof for this or can give me the general idea to prove this or something? Thanks.
Answer: As $\kappa(M)=\|M\|\|M^{-1}\|$, where $\|\cdot\|_2$ is the induced $2$-norm (i.e. the largest singular value of a matrix, which is also the largest eigenvalue when the matrix is positive definite), the statement in question is just a direct application of the submultiplicativity property $\|XY\|\le\|X\|\|Y\|$ of matrix norms.
Comment: oh yes, you're very right. I guess I was just thinking way too complicated ... Thank you!
Comment: I have another question on this: Why does this estimate say  "a good preconditioner of a good preconditioner remains a good preconditioner"?


Como procurar texto parcial em uma lista de strings?

Question: Eu tenho uma lista com vários elementos de texto, e eu gostaria de saber como eu posso encontrar um desses elementos procurando por uma parte do texto e não pelo texto exato.
Exemplo:
Lista = ['Jorge Henrique','Matheus Oliveira Santos','Sopa de batata doce','Algorítimos maravilhosos']

Agora imagine que eu quero encontrar o elemento que contém 'de bat'
que no caso seria 'Sopa de batata doce'.
Como eu posso fazer para encontrar dessa forma em Python e salvar em uma variável?
Answer: Você pode usar o operador in para verificar se uma string é uma substring de outra.
Só não ficou claro se você quer apenas uma das strings da lista (a primeira que encontrar, por exemplo), ou se quer todas que possuem a substring.

Se quiser apenas uma das strings, uma forma de fazer é:
elemento_encontrado = None
busca = 'de bat'
lista = ['Jorge Henrique', 'Matheus Oliveira Santos', 'Sopa de batata doce', 'Algorítimos maravilhosos']
for s in lista:
    if busca in s: # se "de bat" está contido na string
        elemento_encontrado = s
        break

if elemento_encontrado:
    print(elemento_encontrado) # Sopa de batata doce

Neste caso, eu paro assim que encontrar algum caso válido (o uso do break interrompe o loop, ou seja, ele para no primeiro caso que encontrar e nem olha para o restante). Depois eu só verifico se foi realmente encontrado alguma string e a imprimo.
Você ainda pode usar um bloco else no for, que é chamado caso ele não seja interrompido pelo break (ou seja, se nenhum caso for encontrado):
for s in lista:
    if busca in s: # se "de bat" está contido na string
        elemento_encontrado = s
        break
else:
    print('Nenhum elemento encontrado')

Agora se quiser todas as strings que contém a substring desejada, pode usar uma list comprehension para retornar uma lista com todos os casos:
busca = 'a'
lista = ['Jorge Henrique', 'Matheus Oliveira Santos', 'Sopa de batata doce', 'Algorítimos maravilhosos']
# obtém uma lista com todas as strings que contém "a"
encontrados = [ s for s in lista if busca in s ]
print(encontrados) # ['Matheus Oliveira Santos', 'Sopa de batata doce', 'Algorítimos maravilhosos']

A linha encontrados = [ s for s in lista if busca in s ] é a list comprehension, e é equivalente ao for abaixo:
encontrados = []
for s in lista:
    if busca in s:
        encontrados.append(s)

Mas a list comprehension é mais sucinta e pythônica.
Comment: muito obrigado, resolveu meu problema aqui
Answer: Ola,
Existem os Operadores de associação do Python in e not in, que são usados para testar se uma sequência é apresentada em um objeto. Você pode checar mais sobre eles aqui
Para sua solução você pode fazer o seguinte
resultado = [valor for valor in lista if 'de bat'  in valor ]


How to append additional sets of fields to html form

Question: Example: let's say we have a form with 3 fields: pc, part_id, part_details. Sometimes you will want to add additional parts to database when adding pc, so part_id and part_details should be duplicated(part_id and part_details should be corresponding). What I want is the best way to append this two fields to the form?
I know if you just want to duplicate one field you can name the field like this:
<input type="text" name="part_id[]">

Then we can easily get the post data as array. But now we are duplicating more than one field, if we use the approach above at the post end the two/multiple arrays will not be relevant. The approach described here seems to be a good one http://www.quirksmode.org/dom/domform.html, but the fact that names are changing all the time makes it complicated to use the post data as well.
There is another possible approach described here Multiple Forms With Input Fields With The Same Name Attribute? Good Or Bad? . It gives an idea to duplicate the entire form. I am not sure if I understand it correctly, but when I try putting two identical forms in the same page and submit one of them, only data from this form will be submitted, the other one will be ignored. Also it is not suitable for my scenario as not all the fields should be duplicated.
So what is the best way to accomplish this duplicating job?
Answer: You can use another level of indexing:
<input type="text" name="pc" />

<input type="text" name="parts[0][part_id]" />
<input type="text" name="parts[0][part_details]" />

<input type="text" name="parts[1][part_id]" />
<input type="text" name="parts[1][part_details]" />

<input type="text" name="parts[2][part_id]" />
<input type="text" name="parts[2][part_details]" />

The fields for each part (id and details) can be easily generated using jQuery.
Comment: This seems to be a good idea, I will come back after testing, thanks
Comment: After actually work on it, I found the answer by sahbeewah saves much more time. This answer here makes it easy to manipulate the data in the next step, but its take's more time to generate this fields in the frontend by javascript. Anyway, upvote for this answer since it opens my eyes.
Answer: In the link you gave, they didn't duplicate the form, just the elements inside the form which is fine. If all you are adding is multiple parts to a single PC then there shouldn't be a problem. The parts will be linked via array indices (you can rely on the ordering).
The first instance of part_id[] will correspond to the first instance of part_details[]. This should be distinguishable in your server-side language. In PHP for instance, part_details[2] will correspond to part_id[2] etc.
Comment: This should be a viable approach, but I still don't get what they were trying to do. I am just looking for a more ideal way with less worry about the server side data manipulation
Comment: Uh, it is not going to get any cleaner than that. The next (wasteful) step up would be to generate a custom JSON object upon submission and submit the JSON as the data instead.
Comment: You were right, your approach is better, it saves time in javascript to duplicate the fields.


How do I override the default sorting when filtering a view by Taxonomy terms?

Question: My current settings …
In Drupal 6, I currently have a view that filters and sorts nodes by the following criteria:

The taxonomy term is very general, and nodes can either be assigned to "Referenzen" only, or any of its sub-nodes. This is done for the basic structuring of the site. Here, in this view though, I only want to "load all nodes with 'Referenzen' assigned", regardless of their sub-term.

The problem …
"Wichtig" ("important") is an integer value that defines the primary sort criteria for me. I do not care whether a reference is filed under "Media" or "Consulting", or any other sub-term.
However, the nodes are finally displayed like this:
Node 1   Important:  100   Taxonomy: Referenzen
Node 2   Important:    0   Taxonomy: Referenzen
Node 3   Important: -100   Taxonomy: Referenzen
Node 4   Important:  100   Taxonomy: Referenzen – Media
Node 5   Important:   80   Taxonomy: Referenzen – Media

As you can see, the "Important" factor comes second when sorting the nodes, and the taxonomy grouping comes first.
How can I change this behavior, so the following is achieved:
Node 1   Important:  100   Taxonomy: Referenzen
Node 4   Important:  100   Taxonomy: Referenzen – Media
Node 5   Important:   80   Taxonomy: Referenzen – Media
Node 2   Important:    0   Taxonomy: Referenzen
Node 3   Important: -100   Taxonomy: Referenzen

The executed query
SELECT node.nid AS nid, node.title AS node_title, node.language AS node_language, node_data_field_image.field_image_fid AS node_data_field_image_field_image_fid, node_data_field_image.field_image_list AS node_data_field_image_field_image_list, node_data_field_image.field_image_data AS node_data_field_image_field_image_data, node.type AS node_type, node.vid AS node_vid, node_revisions.teaser AS node_revisions_teaser, node_revisions.format AS node_revisions_format, node_data_field_important.field_important_value AS node_data_field_important_field_important_value, node_data_field_date.field_date_value AS node_data_field_date_field_date_value
FROM node node
INNER JOIN term_node term_node ON node.vid = term_node.vid
LEFT JOIN content_field_image node_data_field_image ON node.vid = node_data_field_image.vid
LEFT JOIN node_revisions node_revisions ON node.vid = node_revisions.vid
LEFT JOIN content_field_important node_data_field_important ON node.vid = node_data_field_important.vid
LEFT JOIN content_type_story node_data_field_date ON node.vid = node_data_field_date.vid
WHERE (term_node.tid = 2) AND (node.language in ('***CURRENT_LANGUAGE***')) AND (node.status <> 0)
ORDER BY node_data_field_important_field_important_value DESC, node_data_field_date_field_date_value DESC

The exported view
… can be downloaded here:

http://cl.ly/1c2c0X3f1Q2L3Y3x3l3w

MySQL Query Browser
… however tells me that those that have the "Wichtig" field not set have the value NULL and therefore are sorted last. All newly created nodes get "Wichtig" set as 0, however all old ones still have NULL.

So what can I do to make those with NULL have the value 0 instead and how can I prevent this for new articles in the future?
Comment: do you have a relationship setup in this view?
Comment: Can you post the executed query and an export of the view?
Comment: @uwe999 No, I don't, it's fairly simple.
Comment: @Berdir I updated my question.
Comment: Does the same thing happen when you run the query manually from Query Browser, or similar tool?
Comment: @MPD Updated with some info.
Comment: So, does your manual query match up with the views output you show?  I don't understand what your actual problem is (view sort ignoring **wichtig** or that you need **NULL** to be counted as **0**).
Comment: @MPD The MySQL query matches the view output. The problem seems to be `NULL`, which is sorted below `-100`. It should be sorted between `-100` and `100`, thus counted as `0`.
Answer: Maybe the MySQL IFNULL() function could be the solution. It allows you to check the selected field value and give it a custom one when null.
In your SQL statement, instead of
node_data_field_important.field_important_value AS node_data_field_important_field_important_value

you should have:
IFNULL(node_data_field_important.field_important_value,0)  AS node_data_field_important_field_important_value

Try the modified SQL statement in your MySQL Query Browser and see if it works.
I'm an old database administrator, but a Drupal beginner, so I don't really know how to put this function in a View using the web interface. Do you?
I'm searching a way to add custom SQL to views (because as a beginner I'm interested too) and found something about hook_views_query_alter(). It belongs to Views 2 API.
You should use that hook to change the corresponding array value using your exported view code as reference for array indexes. I have no time to try it, but probably this is the right way.
IMHO another way should be taking the exported view code, modify it manually adding the IFNULL() MySQL function on the field name and then reimport it into a new view. I'm not sure that Drupal will write a correct SQL query or that it won't discard some SQL it doesn't expect... This should be the same as using the hook above, but in a rude and not to so elegant manner...
Hope it helps.
Comment: Changing this does the trick in SQL! Now I only need to port it to the view, so everything's displayed correctly. I consider myself a Drupal beginner, so I really don't know how to do that.
Comment: you could use http://drupal.org/project/views_php module to be able to enter PHP code to do a custom sort. I can't give you the exact code, this is the help text for the code you need to write "The comparison code must return an integer less than, equal to, or greater than zero if the first row should respectively appear before, stay where it was compared to, or appear after the second row."
Comment: I guess I see what the problem is now. I introduced the "Wichtig" field after already creating several nodes. Thus, for those created earlier, there is no "Wichtig" stored (i.e. it's `NULL`), and all new ones automatically get `0` as value. I guess I'll only need a query to update all my old records to change `NULL` to `0`. You as a database administrator can surely come up with something?
Comment: If that is the case, you can just run a regular update query like this:

UPDATE node_data_field_important SET field_important_value=0 WHERE field_important_value IS NULL;

You'd better try it first on a copied version of the node_data_field_important table.
Comment: ...Or make a backup copy of the table first.
Beware that those null values come from inserted (and updatable) values in a table and not from the LEFT JOIN query, that put null where it doesn't find any correspondence.
Comment: Thanks -- I didn't get your notice earlier because the system didn't give me a notification (you have to use `@slhck` for this). Based on the fact that your code got my sorting to work, I guess the `UPDATE` query should work as well, I can't try it for another couple of days, but thank you anyway!
Answer: if you want to alter views query to overwrite the default shorting
function modulename_views_query_alter(&$view, &$query){
if ( $view->name == 'test_merchandise' ) {
 //here you will get the whole $query object and alter only the place you want change
 $query->orderby[0] = "substring(node_data_field_date_field_date_value,1,4) DESC";
 print_r($query);
}
}
Answer: If I understand well your question, why not validate the "Wichtig" ("important") field before be stored to store 0? If is possible, I think that you have several alternatives to validate fields:
Rules module has form support to validate fields: http://drupal.org/node/298487 (see Form support)
also, with hook_form_alter (or hook_form_FORM_ID_alter) you can validate fileds with custom modules:
http://api.drupal.org/api/drupal/developer--hooks--core.php/function/hook_form_alter/6
http://api.drupal.org/api/drupal/developer--hooks--core.php/function/hook_form_FORM_ID_alter/6
this guide show you how to validate fields in custom forms http://drupal.org/node/751826
also Form API Validation allows to you validate fields: http://drupal.org/project/fapi_validation
if I am not wrong and is useful my answer, I have some experience validating with rules and hook_form_alter, so if is necessary, I can add more information inside this answer.
Comment: I see now that for new nodes, the value is `0` automatically. It seems that `NULL` only exists for those that were written *before* I introduced the custom field. So I guess I don't need any custom validation. Still, thanks for the hints!
Comment: then, I think that if you have access to database, you can replace with `0` where is `null` for respective nodes.


How to achieve Dynamic Menu items list based on User Rights Array?

Question: I have an application where all menu items are coming from my below file. I want that users should see only those menus who are in their rights array ?. Below is sample spinet out of whole code.
 {
        state: 'master',
        short_label: 'M',
        name: 'MASTER',
        type: 'sub',
        icon: 'ti-direction-alt',
        children: [
          {
            state: 'roles',
            name: 'Roles',
            type: 'sub',
            children: [
              {
                state: 'add-roles',
                name: 'Add Roles',
                // target: true
              },
              {
                state: 'edit-roles',
                name: 'Edit Roles',
                // target: true
              }
            ]
          },

Answer: If I've understood right you want this to create a menù that the user can see. So, in this example, the user will only see two entry named "Add Roles", and "Edit Roles", right?
Create a Menù class like this :
export class MenuEntities {
   public state: string;
   public name: string;
   public target: boolean;
}

Create an array of MenuEntities parsing the Json. I've assumed that the configuration is in this lines of code :
children: [
              {
                state: 'add-roles',
                name: 'Add Roles',
                // target: true
              },
              {
                state: 'edit-roles',
                name: 'Edit Roles',
                // target: true
              }
            ]

Create the array and map the json res :
public menuEntities: MenuEntities[] = [];
// I let you do the logic to parse the json to this array.

Once you have it you are up to go. Simply loop in the .html file to this array and you got a menù :

States : {{entity.states}}

Name : {{entity.name}}

Note: I can edit this answer if you post more code, but this logic works fine


How to code binary (0/1) predictor variables in regression? Numeric versus factor

Question: I am developing a regression model and most of my variables are 0/1 variables.
Should these variables be treated as factor variables in the model or can they just be left as numeric 0,1?
Comment: Do you need intercept in the model ? Is intermediate value between 0 and 1 possible ? Is 0 < 1 or does not matter - they are just categories ?
Comment: It won't matter if they're factors or numeric. The most that might change is the reference category.
Answer: In linear regression, if they are independent variables and 1 and 0 are the only possible outcomes, then either way is fine.
Modeled as binary, but specified it as if it's continuous (data and syntax are of Stata 12):
. sysuse auto
. reg mpg foreign

      Source |       SS       df       MS              Number of obs =      74
-------------+------------------------------           F(  1,    72) =   13.18
       Model |  378.153515     1  378.153515           Prob > F      =  0.0005
    Residual |  2065.30594    72  28.6848048           R-squared     =  0.1548
-------------+------------------------------           Adj R-squared =  0.1430
       Total |  2443.45946    73  33.4720474           Root MSE      =  5.3558

------------------------------------------------------------------------------
         mpg |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
     foreign |   4.945804   1.362162     3.63   0.001     2.230384    7.661225
       _cons |   19.82692   .7427186    26.70   0.000     18.34634    21.30751
------------------------------------------------------------------------------

Modeled as factors:
. reg mpg i.foreign

      Source |       SS       df       MS              Number of obs =      74
-------------+------------------------------           F(  1,    72) =   13.18
       Model |  378.153515     1  378.153515           Prob > F      =  0.0005
    Residual |  2065.30594    72  28.6848048           R-squared     =  0.1548
-------------+------------------------------           Adj R-squared =  0.1430
       Total |  2443.45946    73  33.4720474           Root MSE      =  5.3558

------------------------------------------------------------------------------
         mpg |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
   1.foreign |   4.945804   1.362162     3.63   0.001     2.230384    7.661225
       _cons |   19.82692   .7427186    26.70   0.000     18.34634    21.30751
------------------------------------------------------------------------------

It's worth noticing that if modeled as a continuous variable (though bear in mind it's actually binary), the reference group is always whatever coded as 0. In some statistical software, however, binary variables modeled as factors may have its reference group swapped to whatever = 1. The ANOVA and F statistics will not be affected but the regression coefficients can change (due to reference group being reassigned.) Check the output carefully.
Comment: For those puzzled, specific syntax here is Stata syntax. Underlying principle is generic
Comment: Thanks @Nick, sorry for being sloppy. I edited the answer.
Comment: `if modeled as continuous, the reference group is` Pardon me, how can a continuous (scale, numeric) variable have a _reference group_ at all?
Comment: @ttnphns, thanks and that's true. I meant to say model that binary variable in the software without specifying it as a factor. I guess the "statistical continuous" and "software configuration continuous" got mixed up. I have slightly revised the answer.
Answer: In R, it doesn't matter if they are factors or numeric variables. But be sure to indicate that you're doing a logistic regression by indicating family=binomial in, for example, a general linear model or mixed effects model.
Without indicating this, the assumed variance of the distribution will differ. In a binomial family, the variance (dispersion parameter) is taken to be 1, unlike in gaussian family.
Comment: Thanks, I was referring to a linear regression model (failed to specify), are there still variance effects?
Comment: The variance assumptions are more flexible with general linear models vs linear models. Almost all linear models will have a corresponding general linear model implementation. So, since you are specifically predicting binary variables, you want to specify this and therefore should use GLM vs LM.
Comment: Sorry did not specify this but my target variable is not binary it is continuous (modeling cost), most of my independent variables are binary