How can I forward ALL traffic over a site-to-site VPN on Cisco ASA?

Question: I currently have two Cisco ASA 5100 routers.  They are at different physical sites and are configured with a site-to-site VPN which is active and working.
I can communicate with the subnets on either site from the other and both are connected to the internet, however I need to ensure that all the traffic at my remote site goes through this VPN to my site here.  I know that the web traffic is doing so as a "tracert" confirms this, but I need to ensure that all other network traffic is being directed over this VPN to my network here.

Here is my config for the ASA router at my remote site:
<code>hostname ciscoasa
domain-name xxxxx
enable password ######## encrypted
names
!
interface Ethernet0/0
 nameif NIACEDC
 security-level 100
 ip address x.x.x.x 255.255.255.0
!
interface Ethernet0/1
 description External Janet Connection
 nameif JANET
 security-level 0
 ip address x.x.x.x 255.255.255.248
!
interface Ethernet0/2
 shutdown
 no nameif
 security-level 100
 no ip address
!
interface Ethernet0/3
 shutdown
 no nameif
 security-level 100
 ip address dhcp setroute
!
interface Management0/0
 nameif management
 security-level 100
 ip address 192.168.100.1 255.255.255.0
 management-only
!
passwd ########## encrypted
ftp mode passive
clock timezone GMT/BST 0
clock summer-time GMT/BDT recurring last Sun Mar 1:00 last Sun Oct 2:00
dns domain-lookup NIACEDC
dns server-group DefaultDNS
 name-server 184.108.40.206
 name-server 188.8.131.52
 domain-name XXXX
same-security-traffic permit inter-interface
same-security-traffic permit intra-interface
access-list ren_access_in extended permit ip any any
access-list ren_access_in extended permit tcp any any
access-list ren_nat0_outbound extended permit ip 192.168.6.0 255.255.255.0 192.168.3.0 255.255.255.0
access-list NIACEDC_nat0_outbound extended permit ip 192.168.12.0 255.255.255.0 192.168.3.0 255.255.255.0
access-list JANET_20_cryptomap extended permit ip 192.168.12.0 255.255.255.0 192.168.3.0 255.255.255.0
access-list NIACEDC_access_in extended permit ip any any
access-list NIACEDC_access_in extended permit tcp any any
access-list JANET_access_out extended permit ip any any
access-list NIACEDC_access_out extended permit ip any any
pager lines 24
logging enable
logging asdm informational
mtu NIACEDC 1500
mtu JANET 1500
mtu management 1500
icmp unreachable rate-limit 1 burst-size 1
asdm image disk0:/asdm-522.bin
no asdm history enable
arp timeout 14400
nat-control
global (NIACEDC) 1 interface
global (JANET) 1 interface
nat (NIACEDC) 0 access-list NIACEDC_nat0_outbound
nat (NIACEDC) 1 192.168.12.0 255.255.255.0
access-group NIACEDC_access_in in interface NIACEDC
access-group NIACEDC_access_out out interface NIACEDC
access-group JANET_access_out out interface JANET
route JANET 0.0.0.0 0.0.0.0 X.X.X.X 1
route JANET 0.0.0.0 0.0.0.0 192.168.3.248 tunneled
timeout xlate 3:00:00
timeout conn 1:00:00 half-closed 0:10:00 udp 0:02:00 icmp 0:00:02
timeout sunrpc 0:10:00 h323 0:05:00 h225 1:00:00 mgcp 0:05:00 mgcp-pat 0:05:00
timeout sip 0:30:00 sip_media 0:02:00 sip-invite 0:03:00 sip-disconnect 0:02:00
timeout uauth 0:05:00 absolute
http server enable
http 192.168.12.0 255.255.255.0 NIACEDC
http 192.168.100.0 255.255.255.0 management
http 192.168.9.0 255.255.255.0 NIACEDC
no snmp-server location
no snmp-server contact
snmp-server enable traps snmp authentication linkup linkdown coldstart
crypto ipsec transform-set ESP-3DES-SHA esp-3des esp-sha-hmac
crypto ipsec transform-set ESP-AES-256-SHA esp-aes-256 esp-sha-hmac
crypto map JANET_map 20 match address JANET_20_cryptomap
crypto map JANET_map 20 set pfs
crypto map JANET_map 20 set peer X.X.X.X
crypto map JANET_map 20 set transform-set ESP-AES-256-SHA
crypto map JANET_map interface JANET
crypto isakmp enable JANET
crypto isakmp policy 10
 authentication pre-share
 encryption aes-256
 hash sha
 group 2
 lifetime 86400
crypto isakmp policy 30
 authentication pre-share
 encryption 3des
 hash sha
 group 2
 lifetime 86400
crypto isakmp policy 50
 authentication pre-share
 encryption aes-256
 hash sha
 group 5
 lifetime 86400
tunnel-group X.X.X.X type ipsec-l2l
tunnel-group X.X.X.X ipsec-attributes
 pre-shared-key *
telnet timeout 5
ssh timeout 5
console timeout 0
dhcpd address 192.168.100.2-192.168.100.254 management
dhcpd enable management
!
!
class-map inspection_default
 match default-inspection-traffic
!
!
policy-map type inspect dns preset_dns_map
 parameters
  message-length maximum 512
policy-map global_policy
 class inspection_default
  inspect dns preset_dns_map
  inspect ftp
  inspect h323 h225
  inspect h323 ras
  inspect rsh
  inspect rtsp
  inspect esmtp
  inspect sqlnet
  inspect skinny
  inspect sunrpc
  inspect xdmcp
  inspect sip
  inspect netbios
  inspect tftp
  inspect http
!
service-policy global_policy global
prompt hostname context
no asdm history enable
</code>
Thanks in advance,
Scott
Comment: I've hidden a IP from your route-line, you probably didnt want that out in the open.
Comment: I've also changed your "encrypted" passwords to "#####".  However, you are now in danger of someone having full and unfettered access to your network.  Cisco IOS passwords are a trivial thing to crack.  I WOULD CHANGE YOUR ASA/VPN PASSWORDS IMMEDIATELY...and do not post those lines from your config again.
Comment: Oh man.  I see this post is from May.  Ugh.  I sure hope you've changed your passwords since then.
Answer: From what I can see you're routing 0.0.0.0 0.0.0.0 (everything) to a IP across your VPN. Everything looks correct.
Comment: Thanks for looking at it and yes I believe you're right, however I still have one more issue and that is, although the web traffic is being sent over the VPN to the router here as required, it is not being filtered by our Check Point firewall like everything else on the subnet here! I've changed my client gateway to the router here and the web traffic isn't filtered either, does this mean that I need to put in a tunnel-rule in the routing on either/or routers?? Please help!
Comment: Is the default route pointing at your CheckPoint firewall?  Should it be?


Relationship between three matrices

Question: I think this might be an odd question, and a little vague.  But here goes.
This is related to coordinate transformations.  Three matrices are given: $G_1 , G_2$, and $\Lambda$.  $G_1$ and $G_2$ are symmetric.  (They are metrics, actually.)  $\Lambda$ is the matrix in question.  The three matrices satisfy
$\Lambda^{-1} = G_1^{-1} \Lambda^T G_2$
Is there anything we can say about the properties of $\Lambda$, such as it is symmetric, or it is either symteric or anti-symmetric, or ...?
Thanks.
Answer: If you rewrite this as $$G_1 = \Lambda^T G_2 \Lambda\,,$$
this is just the change-of-basis formula for a symmetric bilinear form. That is, $\Lambda$ is the matrix that interpolates from the expression for the metric in one coordinate system to the expression in another coordinate system. As it stands, $\Lambda$ could be any invertible matrix.

Relationship between three matrices


How to go to the beginning of the file in fstream?

Question: I'm practicing file handling. I made a text file and wrote some characters in it, now I want the cursor to go to the beginning of the file and put a character there using seekp.
Here is the code
fstream ofile;

char ch = 'g';

ofile.open("test.txt", ios::out | ios::app);

ofile.seekp(0, ios::beg);
ofile.put(ch);

ofile.close();

Expected Result:
It writes g at the start of file.
Actual Result:
It appends g at the end.
I tried removing the ios::app tag but ios::out alone truncates the file before writing anything.
Comment: https://stackoverflow.com/questions/10359702/c-filehandling-difference-between-iosapp-and-iosate?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
Comment: Use `ios::in | ios::out`
Comment: possible workaround: https://stackoverflow.com/questions/7300306/c-overwriting-data-in-a-file-at-a-particular-position
Comment: @NeilButterworth That does it! Thanks! :)
Comment: @drescherjm ios::ate truncates the file as well. :-/
Comment: @NathanOliver got it!
Answer: See:
http://en.cppreference.com/w/cpp/io/basic_fstream/open
std::ios::app  seek to the end of stream before each write


setup raid 6 with 12 - 2 TB drives

Question: I have two 500GTB 7.2k Sata 2.5in drives, plus twelve 2TB drives, and LSI 9260-8i SAS/SATA Card. I need to have OS on one label the rest for storage.  I am unsure how to build the raid6. It has the LSI MegaRaid utility. Should I build it all as one array with raid 6?  Then it asks if I want to add the array hole to the Span?  What's the best way to handle this?
Comment: Thanks. We ended up using Raid 5 for all 12 drives and adding the array hole to the span.
Answer: You say you have an LSI 8-port internal SAS card.
Unless you also have a SAS expander or enclosure (with an expander), you cannot connect 12 drives to an 8-port card...
If you are connecting these 12 drives to both the LSI card and onboard SATA connectors, you cannot use any kind of hardware RAID setup - use Linux softraid (mdraid) instead.
Comment: The raid6 is for the 12 -2TB drives.  It's a Dell PowerEdge C2100
Answer: Assuming you can manage all these drives with your controller (and that assumption is not a sure thing), then don't build raids with differently sized (or speed) drives. Make a raid with the 2 500GB drives (raid 0 for striping, or 1 for mirroring), and a separate raid (or raids) with the 12 2TB drives.
If you are building raid 5 or 6, remember that the rebuild time on large drives is very long. And gets considerably worse if you're on raid 6 and suffer a double disk failure. Also, during this rebuild, you will suffer a lower performance for any normal IO done to the disk.
Two raid 5s with 6 disks each for your 2TB drives would lose you a bit of redundancy, where a double failure could cost you data if you were unlucky and both failures were on the same raid, but would allow you much better rebuild times.
Don't forget to account for a spare- ideally you would have a hot spare ready to swap in without waiting for a new drive, so your total available raidable 2TB drives would be 11, not 12.
Comment: RAID-5 on 2TB disks is a big no-no.
Read [here](http://www.zdnet.com/blog/storage/why-raid-5-stops-working-in-2009/162) for why.
Comment: I'm perfectly aware of that, but raid 5 is still faster to rebuild than raid 6. There are certainly use cases for that kind of storage, and since the question didn't specifically state their use case (could be a backup disk pool), it's a viable part of the answer.

setup raid 6 with 12 - 2 TB drives


How to get treeview parent and child nodes in dictionary

Question: Please help me to get all checked nodes of treeview in dictionary where key is checked parent node and value is list of checked child nodes using linq query using c# .
Answer: Assuming that you have only single level of child for each parent, you could do create an Extension method as following.
public static class Extensions
{
        internal static IEnumerable<KeyValuePair<string,IEnumerable<string>>> GetSelectedList(this TreeNodeCollection tr)
        {
            var childCollection = new List<string>();
            foreach (var trNode in tr.OfType<TreeNode>())
            {
                if (!trNode.Checked) continue;

                childCollection.Clear();
                childCollection.AddRange(trNode.Nodes.OfType<TreeNode>().Where(x => x.Checked).Select(x=>x.Text));

                yield return new KeyValuePair<string, IEnumerable<string>>(trNode.Text, childCollection);

            }
        }
    }

Now you could use it as following.
var selectedData = treeview.Nodes.GetSelectedList().ToDictionary(x => x.Key, y => y.Value);

Comment: Thank you for your reply. I'll check and Mark it as answer.


TinyMCE 4 Table resize cells by dragging

Question: I was looking for a TinyMCE plugin for table resize cell by dragging and I came to:
http://sourceforge.net/p/tinymce/plugins/163/?page=2
Here there is a working example http://tinymcesupport.com/premium-plugins/resize-table-cells
Unfortunately this is for an old version (I'm using the 4) and also following the migration guide I didn't came to a working version.
I'm not a Java programmer and I don't know if the migration is quite simple with some small changes or more development is necessary.
Thanks
Answer: TinyMCE now supports resizing columns with its 4.3 release. Simply enable the table plugin as shown:

tinymce.init({
  inline: true,
  selector: 'table',
  plugins: 'table'
});
table {
  border-collapse: collapse;

}

th, td {
  border: solid 1px #ccc;
  text-align: center;
  padding: 10px;
}

Make sure the table plugin is activated, then drag the columns to resize them:

      Column 1
      Column 2
      Column 3

      Data
      Data
      Data

Comment: They moved their blog to a new domain and that post doesn't exist anymore. Link updated to point to the 4.3 changelog.


Jackson JSON View - exclude view variables from the output (Spring MBV)

Question: So I am learning Spring MVC framework and have set up Content Negotiation using the MappingJackson2JsonView class, such that when I go to /products, I get the normal HTML view and when I go to /producs.json, I get a JSON of the model - this works great.
My question is, how do I exclude variables from the JSON output? These variables I wish to exclude are set by an Interceptor I've created to add attributes to the model that I display to HTML users;
Interceptor:
public class GlobalVariablesInterceptor extends HandlerInterceptorAdapter {

public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    if (modelAndView != null) {
        ModelMap model = modelAndView.getModelMap();
        model.addAttribute("cp", request.getServletContext().getContextPath());

        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (!(auth instanceof AnonymousAuthenticationToken)) {
            Set<String> roles = auth.getAuthorities().stream().map(r -> r.getAuthority()).collect(Collectors.toSet());
            String userRoles = String.join(",", roles);
            model.addAttribute("roles", userRoles);
            model.addAttribute("authUsername", auth.getName());
        }

    }
}
}

JSON Bean:
@Bean
public MappingJackson2JsonView jsonView() {
    MappingJackson2JsonView jsonView = new MappingJackson2JsonView();
    jsonView.setPrettyPrint(true);
    return jsonView;
}

@Bean
public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
    ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
    resolver.setContentNegotiationManager(manager);
    ArrayList<View> views = new ArrayList<>();
    views.add(jsonView());
    views.add(xmlView());
    resolver.setDefaultViews(views);
    return resolver;
}

any help would be appreciated.
Answer: So, for the benefit of anyone who reads this in the future....
things I tried:

Setting an explicit list of model variables to go
forward, did this in the bean definition in the WebContextConfig.
Didn't work.
Querying the ModelAndView object in the postHandle
method of the interceptor; attempting to see if the View was an
instanceof MappingJackson2JsonView; didn't work.
Querying the HttpServletResponse object of the postHandle method to get its
content type and see if it was application/json (didn't work... null
pointer exception) etc.

The one thing that did work (but is clearly not very 'resilient' code).... query the HttpServletRequest object of the postHandle method, see if the requested URL contains .json (which is the trigger for the JSON view)... if yes, then don't add these extra variables to the model in the first place:
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    if (modelAndView != null) {
        String url = request.getRequestURI().toLowerCase();
        if (!(url.contains(".json") || url.contains(".xml"))) {
            ModelMap model = modelAndView.getModelMap();
            model.addAttribute("cp", request.getServletContext().getContextPath());

            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            if (!(auth instanceof AnonymousAuthenticationToken)) {
                Set<String> roles = auth.getAuthorities().stream().map(r -> r.getAuthority()).collect(Collectors.toSet());
                String userRoles = String.join(",", roles);
                model.addAttribute("roles", userRoles);
                model.addAttribute("authUsername", auth.getName());
            }

        }
    }

}


software to monitor internet usage on an XP PC? (browser + non-browser)

Question: Is there any (ideally open source) software for Windows that can be used on a PC, to monitor the usage of internet from that PC?   It would need to include both browser and non-browser sources (e.g. a service that sync's calendar to gmail).
So any software on your PC that uses would need to be configured to point to this local internet monitoring software/proxy.  The monitoring software/proxy then would be configured to point to the company proxy server (address, port & credentials).
Things that come to mind that might be close but not really focused on solving this might be perhaps: Charles Proxy, Fiddler 2, SQUID?
The idea would be it could give you a daily/weekly/monthly report of internet upload/download usage on a per program/process/service basis for the PC it is being run on.
thanks
PS The scope is only monitor Internet usage for the PC that the software is running on.  It's just aimed at tracking my own Internet usage at work on my PC from the point of view of the various software I have that does sync to Internet.
Answer: Is this for a specific computer or all computers? You could use a turnkey firewall like smoothwall or related appliance software in front of your proxy (or replace your proxy). That would give you reports based on IP of anything that was going out of your network, often by protocol, for the cost of a small server. Failing that you could use a virtual machine, but I wouldn't recommend it unless you have a dedicated VM server.
This would also centralize your monitoring and make it more flexible rather than having the hassle of individual monitoring on each machine and taking up resources on each system due to a monitoring program and it would be more transparent to the user(s).
Comment: The scope is only monitor Internet usage for the PC that the software is running on.


Java For loop is looping before my input is being asked for

Question: When I run my program my for loop outputs the line "Enter a game score?" twice before I am able to input sometimes, have a made a silly error while constructing it.
import java.util.Scanner;

public class Project {

public static void main (String[] args){

Scanner scan = new Scanner(System.in);
System.out.println("What is your name?");
    String playername = scan.nextLine();

    System.out.println("How many games will you be entering?");
    int numofgames = scan.nextInt();

    /* Creating the arrays*/
    String[] game = new String[numofgames];
    int[] scores = new int [numofgames];
    int[] mins = new int [numofgames];

    /* Creating a temp array to store the game data before splitting*/
    String[] temparray = new String[numofgames];

    /*Getting the users game data and storing it into the temp array*/
    for (int count=1; count <= numofgames; count++){
        System.out.println("Enter a game score?(Game name:Scores:Mins)");
                temparray[count] = scan.nextLine();

    }}}

Comment: Please enter valid compileable code.
Answer: The function scan.nextInt() does not discard the newline character after you hit 'Enter'. So it stays in the buffer and is read when scan.nextLine() is called. Just empty the buffer after scan.nextInt()
int numofgames = scan.nextInt();
scan.nextLine(); // remove newline from buffer

You should also fix your loop boundaries:
for (int count=0; count < numofgames; count++) {
...
}


probability application

Question: 1) A disease has hit a city. The percentage of the population infected $t$ days     after the disease arrives is approximated by $$p(t) = 12te^{\frac{-t}{7}} \qquad \mbox{for} \qquad0\leq t \leq 35.$$
After how many days is the percentage of infected people a maximum? What is the maximum percent of the population infected?
The maximum percent of  the population  infected    is  ______  %
2) A container contains 12 diesel engines.  The company chooses 5 engines at random and will not ship the container if any of the engines chosen are defective.  Find the probability that a container will be shipped even though it contains 2 defectives if the sample size is 5.
For the first problem, the number of days at which the percentage is at maximum is 7. Clearly, if I substitute this to $p(t)$ I will get the maximum percentage. My problem is how did they get the answer of 7 days? How do I deal with this kind of problem? Is there a specific formula? I'm trying to figure it out but can't.
Also for the second problem I made use of the hypergeometric formula that is $$p(x) = \frac{\left[C(k,x) \cdot C(N-k, n-x)\right]}{C(N,n)}$$ where $N$ is the size of population, $k$ is the number of successes in the population, $x$ is the number of successes in the sample and $n$ is the sample size. I used this and I got a different answer. The answer should have been 0.318 but I got a different one. Please help.
Comment: For the first question [if you've taken calculus] use the first derivative of $p$ to find critical points.
Comment: That's right.  It is a general result.
Comment: Great! that was what i was thinking. So there's no particular formula for statistics in this problem right?
Comment: As far as I can tell, no.
Answer: Mode of gamma distribution. For (1), recognize that $p(x)$ is the PDF of a gamma distribution with shape parameter 2 and scale parameter 7. Look at the Wikipedia article. Its mode is $x = (2-1)7 = 7.$ (The bound 35 is so far out as to be irrelevant to the discussion.)
Application of hypergeometric to acceptance sampling. For (2), I used the hypergeometric PDF programmed into R as follows:
<code> dhyper(0, 2, 10, 5)
 ## 0.3181818
</code>
So it seems you have made a mistake.
Hint: What is ${10 \choose 5}$
and what is ${12 \choose 5}?$
Answer: The gradient (or "slope") at a local maximum, minimum, or point of inflection, will equal zero.
We have $p(t) = 12 t e^{-t/7}$ , so then by differentiation (using the chain rule): $\frac{\mathrm d p(t)}{\mathrm d t} = 12 e^{-t/7} - \dfrac{12 t}{7} e^{-t/7}$.
Solving for $t$ when $\frac{\mathrm d p(t)}{\mathrm d t}=0$ gives us $t=7$.   This exists within our interval $0\leq t \leq 35$, thus all we need do is check is that it is indeed a maximum.
$$p(7) \approx 30.9 \\ p(6) \approx 30.6 \\ p(8) \approx 30.62$$

For the second problem the container will be shipped if the two defective containers are among the seven not inspected.   By counting distinct ways to select places for defectives, the probability of this is: ${^{7}{\rm C}_{2}}\big/ {^{12}{\rm C}_{2}} = \frac{7\times 6}{12\times 11}$
Using the hypergeometric formula, this is $p(0) = \dfrac{{^{5}{\rm C}_{0}}\;{^{12-5}{\rm C}_{2-0}}}{ {^{12}{\rm C}_{2}}}$
Comment: Thanks! I was just thinking maybe there's some statistics involved because my first choice's been using calculus. How about for the second one? Any suggestion? I really made a different answer from the key. :(
Comment: I will read on that. How about for the second problem? is my formula right? @BruceTrumbo
Comment: I just read it. Now I know where I went wrong. I was thinking of getting $p(5)$ instead of $p(0)$.
Comment: By now both @GrahamKemp and I have gotten around to (2). Different approaches, same answer. Can you see why both are correct?
Comment: @marg_ocruz: Correction. gamma shape parameter is 2. Please do read about it as indicated above ('I will read on that.' in response to my deleted comment, corrected here, and now elaborated in my Answer.)

probability application


Array lengths different using strlen and full array not printing?

Question: I am trying to copy a string plaintext into another string ciphertext in C so that they have the same length and array characters. I cannot seem to get the strings' lengths or content to match. Any guidance would be much appreciated!
I have tried to use strlen when initializing ciphertext to be of the same size as plaintext, and then copy each character of plaintext into ciphertext and print both strings as well as their lengths.
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

bool is_number(int input);

int main(int argc, string argv[])
{
    //checking that user provides only one input argument
    if (argc != 2)
    {
        printf("Usage: ./caesar key\n");
        return 1;
    }
    //check that user key input is an integer
    for (int i = 0, l = strlen(argv[1]); i < l; i++)
    {
        if(is_number(argv[1][i]) == 0)
        {
            printf("Usage: ./caesar key\n");
            return 1;
        }
    }

    //prompts user for message
    string plaintext = get_string("plaintext:  ");
    char ciphertext[strlen(plaintext)];
    printf("length p: %lu\n", strlen(plaintext));
    printf("length c: %lu\n", strlen(ciphertext));
    for (int i = 0; plaintext[i] != '\0'; i++)
    {
        ciphertext[i] = plaintext[i];
        //printf("p[i] = %c\n", plaintext[i]);
        //printf("c[i] = %c\n", ciphertext[i]);
        //printf("i= %i\n", i);
    }
    printf("ciphertext: %s\n", ciphertext);
}

//checks if a char is a number
bool is_number(int input)
{
    if(input < '0' || input > '9')
    {
        return 0;
    }
    else
    {
        return 1;
    }
}

When I run this code, my string lengths do not match and ciphertext does not print all of its characters or prints random extra characters.
command line example:
$ make caesar
clang -fsanitize=signed-integer-overflow -fsanitize=undefined -ggdb3 -O0 -std=c11 -Wall -Werror -Wextra -Wno-sign-compare -Wno-unused-parameter -Wno-unused-variable -Wshadow    caesar.c  -lcrypt -lcs50 -lm -o caesar
$ ./caesar 1
plaintext:  hello
length p: 5
length c: 6
ciphertext: hell

Comment: BTW, good use of enabling many warnings.  Consider `-pedantic`
Answer: Undefined behavior (UB)
printf("ciphertext: %s\n", ciphertext); attempts to print ciphertext assuming it is a string (sequence of characters including and ending with a null character) which it is not.
strlen(ciphertext) requires a string.
In C, recall a string must contain a null character, else it is not a string.  Many str...() functions require a string.

Code could attempt
printf("ciphertext: %.*s\n", (int) strlen(plaintext), ciphertext);

to print an array of characters up to a null character or to the length or string plaintext.
strlen(ciphertext) is just wrong as ciphertext lacks a null character.

Or consider
char ciphertext[strlen(plaintext) + 1];  // 1 more
size_t i;
for (i = 0; plaintext[i] != '\0'; i++) {
    ciphertext[i] = plaintext[i];  // ciphertext is not yet a _string_.
}
ciphertext[i] = '\0'; // Now ciphertext is a _string_.

Also note:
printf("length p: %lu\n", strlen(plaintext)); is amiss as strlen() returns a size_t , not necessarily an unsigned long.
Use a matching specifier and type.
// printf("length p: %lu\n", strlen(plaintext));
printf("length p: %zu\n", strlen(plaintext));

Tip: the 2 below are functionally equivalent, the 2nd is idiomatic in C.
for (int i = 0, l = strlen(argv[1]); i < l; i++)
for (int i = 0; argv[1][i]; i++)
// of better
for (size_t i = 0; argv[1][i]; i++)

`


How many fielders are allowed on offside in cricket?

Question: I'm aware that there are few fielding restriction on leg side, for example that there should not be more than 5 fielders on leg side. But is there similar restriction to offside as well? Can I place all my 9 fielders in off side? I have checked the The fielder Law | MCC - Lord's Cricket Ground but there was nothing mentioned about off side fielding restrictions.
Answer: The only restriction in the Laws of Cricket is that in Law 28.4:

At the instant of the bowler's delivery there shall not be more than two fielders, other than the wicket-keeper, behind the popping crease on the on side.

This means you could have 9 fielders on the on side if you wish, so long as 7 of them are in front of the popping crease, or if you wish, all 9 fielders on the off side, either in front of or behind the popping crease.
Individual formats and tournaments may introduce further restrictions; for example, the restriction to having no more than 5 fielders on the on side is part of the Playing Conditions for both One Day Internationals and T20 Internationals:

28.4.1 At the instant of delivery, there may not be more than 5 fielders on the leg side.

but that is not part of the Laws of Cricket. I don't believe that any ICC tournaments have a restriction on the number of off side fielders, but you would need to refer to the Playing Conditions for the specific tournament you are interested in if you want a definitive answer.
Comment: Thanks. Does that mean that in ODI also, I can have 9 fielders on off side as per current Laws of cricket?
Comment: "I don't believe that any ICC tournaments have a restriction on the number of off side fielders"


Custom Twig filter not found when called

Question: I'm trying to create my own Twig filter. I followed this tuto Symfony Official Book.
But I get this error The filter "avatar" does not exist in src/Acme/Bundle/StoryBundle/Resources/views/Story/storyList.html.twig
Here is my AvatarExtension.php
<?php

namespace AppBundle\Twig;

class AvatarExtension extends \Twig_Extension
{
    public function getFilters()
    {

        return array(
            new \Twig_SimpleFilter('avatar', array($this, 'avatar')),
        );

    }

    public function getName()
    {
        return 'avatar_extension';
    }

    public function avatar($user)
    {
        if ($user->getPicture() && $user->getPicture() != '') {
            return $user->getPicture();
        } else {
            return '/images/default-avatar.jpg';
        }
    }
}

And my AppBundle/Resources/config/services.yml
services:
    app.twig.avatar_extension:
        class: AppBundle\Twig\AvatarExtension
        tags:
        – { name: twig.extension }

The template using the filter is not in the same bundle as the Twig extension, but since it is a service, it shouldn't be a problem.
Here is how I call it : {{ story.author|avatar }}
Do you have any idea what the problem might be ?
EDIT
# Twig Configuration
twig:
    debug:            "%kernel.debug%"
    strict_variables: "%kernel.debug%"
    globals:
      uploadTmpDir: %upload.tmp.relative.dir%

Comment: Is the services.yml indented like that? If so you need to indent the `- { name: twig.extension }` another 4 spaces.
Comment: Yep, looks strange that your services.yml file is compiling, i thought you'd get a "You cannot define a sequence item when in a mapping" exception.
Comment: The services.yml file is properly indented. Indentation broke when I posted it here
Comment: try clearing your cache
Comment: check the service is correctly loaded by `php app/console container:debug|grep 'app.twig.avatar_extension'` then check that you haven't already registered another twig extension with the same name. Hope this help.
Comment: In a standard installation of a symfony2.6 project, the app bundle don't have the dependency injection manager class, if is so you must follow [this](http://symfony.com/doc/current/cookbook/bundles/extension.html) guide. Let me know.
Comment: @Matteo the command issued this : `app.twig.avatar_extension                                          AppBundle\Twig\AvatarExtension`

I have other services registered in the AppBundle, and it works fine

@DerickF I tried clearing my cache but I still got the problem
Comment: All looks ok, very strange...
Comment: As workaround you can try to use the [default twig filter](http://twig.sensiolabs.org/doc/filters/default.html) as follow: `{{ story.author.picture |default('/images/default-avatar.jpg') }}`
Comment: you have the twig section in your `config.yml` files? can you post it?
Comment: I edited the original post with the twig config in config.yml
Answer: Ok I found the solution. Here is the services.yml
app.twig.avatar_extension:
        class: AppBundle\Twig\AvatarExtension
        tags:
            - { name: twig.extension }

And here is the ExtensionClass:
<?php

namespace AppBundle\Twig;

class AvatarExtension extends \Twig_Extension
{
    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('avatar', array($this, 'avatarFilter')),
        );
    }

    public function avatarFilter($user)
    {
        if ($user->getPicture() && $user->getPicture() != '') {
            return $user->getPicture();
        } else {
            return '/images/default-avatar.jpg';
        }
    }

    public function getName()
    {
        return 'avatar_extension';
    }
}

I guess the function name must have the Filter suffix


Can send post request with curl but cannot from a node server

Question: I can make a post request to a REST api endpoint of a web service with curl successfully but couldnt do so with request module in node.js. Instead, I always get error CONNECTION ETIMEDOUT.What is the problem?
curl command:
curl -i --header "Content-Type: application/json" -XPOST 'http://<endpoint_url>/urls' -d '{
  "callback": "http://www.example.com/callback",
  "total": 3,
  "urls": [ {
     "url": "http://www.domain.com/index1.html"
     }, {
     "url": "http://www.domain.com/index2.html"
     }, {
     "url": "http://www.domain.com/index3.html"
     }
  ]
}'

code:
function sendRequestToEndPoint() {

  const sample = {
    "callback": "http://www.example.com/callback",
    "total": 3,
    "urls": [ {
      "url": "http://www.domain.com/index1.html"
      }, {
      "url": "http://www.domain.com/index2.html"
      }, {
      "url": "http://www.domain.com/index3.html"
      }
    ]
  }
  const options = {
    method: 'post',
    //headers: {
    //  'Content-Type': 'application/json',
    //  'Accept': 'application/json',
    //},
    url: 'http://<endpoint_url>/urls',
    json: sample
    //body: JSON.stringify(sample) // also tried this with headers on
  };

  console.log(sample);
  request(options, (error, response, body) => {

    console.log(response)
  });
}

Update: Turned out that it was because the api url I used is not correct.
Answer: this code works,
you need to Stringify your json object using JSON.stringify , and use the methode write of the object request to send the sample json object
, http = require('http')
, bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
 extended: false
}));
var sample = JSON.stringify({
"callback": "http://www.example.com/callback"
, "total": 3
, "urls": [{
        "url": "http://www.domain.com/index1.html"
  }, {
        "url": "http://www.domain.com/index2.html"
  }, {
        "url": "http://www.domain.com/index3.html"
  }
 ]
 });
var options = {
hostname: 'localhost'
, port: 80
, path: '/test/a'
, method: 'POST'
, headers: {
    'Content-Type': 'application/json'
    , 'Content-Length': sample.length
 }
 };
 app.get('/', function (req, res) {
 var r = http.request(options, (response) => {
    console.log(`STATUS: ${response.statusCode}`);
    console.log(`HEADERS: ${JSON.stringify(response.headers)}`);
    response.setEncoding('utf8');
    response.on('data', (chunk) => {
        console.log(`BODY: ${chunk}`);
    });
    response.on('end', () => {
        console.log('No more data in response.');
    });
 });
 r.on('error', (e) => {
    console.log(`problem with request: ${e.message}`);
 });
 r.write(sample);
 r.end();
 res.send('ok');
});

a link for more details about http.request nodejs.org http.request(options[, callback])
Answer: use querystring  to stringify your json data,
var querystring = require('querystring');
...
sample = querystring.stringify(sample);

look at this answer How to make an HTTP POST request in node.js
Comment: hi, I tried using `querystring` on `sample` and it turned `sample` to `callback=http%3A%2F%2Fwww.example.com%2Fcallback&total=3&urls=&urls=&urls=`. and it didnt work.
Comment: plus, i think the endpoint is expecting `application/json`, so maybe theres no need for `querystring`?


Converting nvarchar to int, isnumeric returning 0 on a number

Question: I have a temporary table with datatype NVARCHAR which I need to migrate to a table with datatype INTEGER.
I have two NVARCHAR tables which need to be INTEGER, one is working and the other is giving an error,

Conversion failed when converting the nvarchar value '9824
  ' to data type int.

I tried removing that extra space using LTRIM and RTRIM but ISNUMERIC() is still giving 0 and the error stays the same.
This is the code resulting in an error,
SELECT CAST(table_name AS integer)
FROM OLTP.table

What I've tried:
SELECT ISNUMERIC(REPLACE(Revenue, ' ', '')), Revenue, ISNUMERIC(REPLACE(LTRIM(RTRIM(Revenue)), '  ', ' '))
FROM OLTP.ExtractedData

Sample Data
(No column name)    Revenue (No column name)
0   9824    0
0   5661    0
0   3250    0
0   2959    0
0   2511    0
0   2072    0
0   2056    0
0   1705    0
0   1704    0

Answer: You probably have a linebreak in there, TRIM/RTRIM don't trim those.
declare @value nvarchar(10) = '1234
'

select ISNUMERIC(Replace(CHAR(9), '', @value))
select ISNUMERIC(Replace(CHAR(10), '', @value))
select ISNUMERIC(Replace(CHAR(13), '', @value))
select ISNUMERIC(Replace(CHAR(32), '', @value))

Answer: Instead of cast() use `try_cast()
SELECT TRY_CAST(table_name AS integer)
FROM OLTP.table

Comment: This produces `NULL`, which happens if the data is not an integer, but it is.
Answer:   SELECT  PARSE(column_name AS int )  from table

Answer: I would check the length. This will give you an idea if how many special characters you are looking for.
SELECT LEN(Revenue)
FROM OLTP.ExtractedData

Then use SUBSTRING and ASCII to find out what the character is.
SELECT
  ASCII(SUBSTRING(Revenue, 5, 1))
FROM OLTP.ExtractedData


Why does a locally scoped variable that hasn't been defined reference the instance variable of the same name?

Question: I came across an odd bug in my code that revealed an interesting behavior of ruby.  Hopefully someone can explain why it behaves this way.
I had a class with an instance variable @foo and a method that referenced a locally scoped variable foo.  I refactored part of the method out accidentally leaving the reference to foo; the variable no longer defined in the scope.  It ended up pointing to @foo instead.  Changing foo made changes to @foo and vice versa.
Simplified version:
EDIT : added ImOutOfNames.
class ImOutOfNames
    attr_accessor :foo # the culprit!
end

class Bar < ImOutOfNames
    def initialize
        @foo = "that is a tasty burger"
    end

    def bar_method_1
        foo = "Come on Yolanda, whats Fonzie like?"
        bar_method_2
    end

    def bar_method_2
        puts foo
    end
end

And the output of bar_method_1 and bar_method_2 was "that is a tasty burger".  I was expecting there to be an error, for example running the above code gets
NameError: undefined local variable or method

I even had a more senior developer come take a  look and he was somewhat baffled and confirmed the behavior.
Is this an expected behavior and I misunderstood how @variables work or is there something wrong?
Comment: Very odd.  There isn't an `attr_reader :foo` hiding in there somewhere, is there?  You're not misunderstanding anything.  If `def foo; @foo end` isn't defined (explicitly or via `attr_reader` or `attr_accessor`), `foo` should not be returning `@foo`
Comment: aha!  I just checked and there is indeed an attr_accessor :foo.
Comment: nice :)  gotta watch those magic methods.  Hook one of those answers up with a point :-P
Comment: I don't have enough reputation to give points yet :(
Answer: Your previous buggy code probably at an attr_accessor  definition that created a method foo that accessed to your instance variable,
You can have the same behavior if your code is like this:
class Bar

  attr_accessor :foo

  def initialize
    @foo = "that is a tasty burger"
  end

  def bar_method_1
    foo = "Come on Yolanda, whats Fonzie like?"
    bar_method_2
  end

  def bar_method_2
    puts foo
  end
end

The attr_accessor call defines two methods in your object;
def foo
  @foo
end

def foo=(value)
  @foo = value
end

So in your case, when no local variable was defined, the method was used, but as you did not call attr_accessor in this example you posted the method was not defined and there was no local variable to use on bar_method_2 so the call fails.
Comment: This makes sense, thank you!

I went back and checked and there was an attr_accessor in its parent class.
Answer: Do you have an attr accessor for your @foo instance variable? That's one way this could happen.
I'd recommend not using the same name for a locally scoped variable, in general, but you can find out if it's coming from some method with
self.method(:foo)

or if it's even defined with
defined? foo

Using the ruby runtime to your advantage definitely reduces the mysticism and magical nature of some code.


Conversion of scientific notation to long numbers using c#?

Question: I need to convert 8.9148E+19 to numeric format using c#
I have already tried using  Double.Parse(3.58E+14, System.Globalization.NumberStyles.Float) but it is rounded up the value, but not returned the actual number.
Comment: I think you're actually talking about the formatting when converting the double to a string. If you want to show all the digits, try `double.ToString("N")` or `double.ToString("F0")` - e.g. `Console.WriteLine(double.Parse("8.9148E+19").ToString("F0"));`
Comment: What do you mean? You want to display as a string not in scientific notation or just do calculations?
Comment: When I tried `var a = Double.Parse("8.9148E+19", System.Globalization.NumberStyles.Float); Console.WriteLine(a);` I got "8.9148E+19". How did *you* look at the value?
Answer: You should use Parse from decimal.
var parsed = decimal.Parse("8.9148E+19", System.Globalization.NumberStyles.Float);

Answer: If you want to check and convert the exponent value use this:
//your value
string val = "8.9148E+19";
//create a dummy
double dummy;
//check if ist valid
bool hasExponential = (val.Contains("E") || val.Contains("e")) && double.TryParse(val, out dummy);
if (hasExponential)
{
    //if it is valid parse it
    decimal d = decimal.Parse(val, NumberStyles.Float);
}


Finding subfields of an Extension Field

Question: Let a $\in$ C be a root of the polynomial $X^4+ 1 \in Q[X]$ Consider
the field extension Q(a) of Q.
Find three fields $K_1, K_2,K_3$ such that $Q \subset K_i \subset Q(a)$ for i=1,2,3.
I found out 2 fields namely, Q(i) and Q(√2) contained in Q(a).
I couldn't find the third one.
Iam not sure how to proceed further.
Comment: Indeed, $\Bbb Q(i\sqrt{2})$ is the third one, see the duplicate.
Answer: In general, if you have two extensions $\mathbb{Q}(\alpha)$ and $\mathbb{Q}(\beta)$, and you know they are different, then $\mathbb{Q}(\alpha\beta)$ is also different from the previous two.
Indeed, $\mathbb{Q}(\alpha\beta)\neq \mathbb{Q}(\alpha)$ since their compositum is $\mathbb{Q}(\alpha,\beta)\neq \mathbb{Q}(\alpha)$, and likewise $\mathbb{Q}(\alpha\beta)\neq \mathbb{Q}(\beta)$.

Finding subfields of an Extension Field


Carregar cidades através de um estado X, através de um arquivo.js

Question: Tenho o seguinte código HTML

              Estado Natural
              <select name="estado_natural" id="estado_natural" class="u-border-1 u-border-custom-color-1 u-input u-input-rectangle u-radius-9 u-white" required>
                <option value="estado_natural">SELECIONE</option>
                <option  value="AC">AC</option>
                <option  value="AL">AL</option>
                <option  value="AP">AP</option>
                <option  value="AM">AM</option>
                <option  value="BA">BA</option>
                <option  value="CE">CE</option>
                <option  value="DF">DF</option>
                <option  value="ES">ES</option>
                <option  value="GO">GO</option>
                <option  value="MA">MA</option>
                <option  value="MT">MT</option>
                <option  value="MS">MS</option>
                <option  value="MG">MG</option>
                <option  value="PA">PA</option>
                <option  value="PB">PB</option>
                <option  value="PR">PR</option>
                <option  value="PE">PE</option>
                <option  value="PI">PI</option>
                <option  value="RJ">RJ</option>
                <option  value="RN">RN</option>
                <option  value="RS">RS</option>
                <option  value="RO">RO</option>
                <option  value="RR">RR</option>
                <option  value="SC">SC</option>
                <option  value="SP">SP</option>
                <option  value="SE">SE</option>
                <option  value="TO">TO</option>
              </select>

E queria retornar no próximo select input somente as cidades do estado selecionado, vi algumas formas de fazer passando por um db, mas como não são todas as cidades do país disponíveis, precisava fazer a requisição através de um arquivo json que possuo nesse formato:
{
  "erro": false,
  "cidade": {
      "197": {
        "nome": "ABADIA DE GOIAS",
        "estado": "GO"
      },
      "25669": {
        "nome": "ZACARIAS",
        "estado": "SP"
      },
      "3407": {
        "nome": "ZE DOCA",
        "estado": "MA"
      },
      "27414": {
        "nome": "ABADIA DOS DOURADOS",
        "estado": "MG"
      },
      "2032": {
        "nome": "ABADIANIA",
        "estado": "GO"
      },
      "28254": {
        "nome": "ABAIRA",
        "estado": "BA"
      },
      "7600762": {
        "nome": "ABAPA",
        "estado": "PR"
      },
      "28463": {
        "nome": "ABARE",
        "estado": "BA"
      },
      "16305526": {
        "nome": "ABRE CAMPO",
        "estado": "MG"
      },
      "226": {
        "nome": "ABRE-CAMPO",
        "estado": "MG"
      },
      "28595": {
        "nome": "ABREU E LIMA",
        "estado": "PE"
      },
      "6892123": {
        "nome": "ZORTEA",
        "estado": "SC"
      }
  }
}

Como os Códigos de cada cidade são específicos, não conseguir implementar através do IBGE.
Também tenho outros select's que são condicionais e utilizam o mesmo padrão de arquivo json, a minha pergunta é, da pra puxar essas opções condicionais direto pelo arquivo ou realmente preciso passar para um sql? Estou fazendo tudo por php e js.
Answer: Está utilizando JS puro ou algum framework como VUEJS? Você pode utilizar a propriedade Watch, Ela fica monitorando a variavel atrelada ao campo, quando você selecionar um estado ele irá gerar uma requisição buscando as cidades daquele estado:
watch: {
id_estado(newVlr) {
if (this.id_estado != null) {
const payload = {
id_estado: newVlr,
tabela: 'cidades',
};
let th = this;
axios.post('/admin/funcao/buscarDados', payload).then((response) => {
th.cidades= response.data.dados;
});
}
},
}
documentação para JS puro: https://cgi.cse.unsw.edu.au/~cs2041/doc/MDN_javascript_reference/Web/JavaScript/Reference/Global_Objects/Object/watch.html
documentação para VUEJS por exemplo:
https://vuejs.org/guide/essentials/watchers.html
Comment: Mas eu preciso que funcione nos navegadores comuns e mobile, pela documentação desse watch ele não tem muita utilidade fora do firefox
Comment: Não procede meu caro, tem utilidade em todos os navegadores e mobile também, da uma lida melhor na documentação
Answer: Dessa maneira?
html:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title></title>

        Estado Natural
        <select name="UF" id="UF" class="u-border-1 u-border-custom-color-1 u-input u-input-rectangle u-radius-9 u-white" required>
        </select>

        Cidade
        <select name="cidade" id="cidade" class="form-control input-lg">
            <option value="">SELECIONE</option>
        </select>

script.js (atualizado) (javascript com jQuery)
$(document).ready(function(){

carregar_dados_json('UF');

function carregar_dados_json(elemento, grupo)
{
 var html_do_select = '';
 var estados = []; //array para filtrar estados sem repetição
 $.getJSON('https://api.npoint.io/cca1afd7773c92c72f42', function(data){

  html_do_select += '<option value="">SELECIONE</option>';
  $.each(data.cidade, function(key, value){
  if ($.inArray(value.estado, estados) == -1) {
        estados.push(value.estado);

    if(elemento == 'UF')
     {
          html_do_select += '<option value="'+value.estado+'">'+value.estado+'</option>';
     }
  }
  if(elemento == 'cidade')
   {
     if(value.estado == grupo)
     {
       html_do_select += '<option value="'+value.nome+'">'+value.nome+'</option>';
     }
   }
  });
  $('#'+elemento).html(html_do_select);
 });
}
$(document).on('change', '#UF', function(){
     var UF = $(this).val();
     if(UF != '')
     {
        carregar_dados_json('cidade', UF);
     }
     else
     {
        $('#cidade').html('<option value="">SELECIONE</option>');
     }
    });
});

Link com novo exemplo atualizado aqui.
Comment: funcionou em partes, ele tem um problema se o arquivo.json tiver mais dados ele mostra todos os estados de forma repetida, para cada cidade vai retornar o estado dela, teria como remover isso?
Comment: Sim, mas precisaria entender como, de fato, é seu arquivo.json. Você pode atualizar a pergunta com o novo json ou informá-lo aqui.
Comment: Atualizei, pouca coisa mas é basicamente isso, tem bastante cidades e todas tem o dado UF, o problema desse código é que pra cada cidade ele retorna o estado dela, ai se tiver 200 cidades do estado de sp, no campo de inserir o UF, ele insere o estado de SP 200 vezes tbm.
Comment: se preferir "https://api.npoint.io/cca1afd7773c92c72f42" só trocar o link no jsfiddle
Comment: Nesse caso você precisa criar uma condição na qual os estados sejam adicionados ao array de forma a não se repetirem. Atualizei a resposta acima.
Comment: agora foi hehe, mas eu ainda to pegando o id da cidade na base da gambiarra, teria alguma ideia de como retornar o valor delas diretamente pelo input? exemplo, seleciono o nome dela mas receber o retorno somente o id.
Desculpa perguntar tanto, não to tão acostumado com js, agradeço muito a ajuda bixo
Comment: Não entendi exatamente o que precisa. Mas se minha resposta ajudou na solução do problema anterior, clique no botão para aceitá-la como correta. Você pode fazer uma nova pergunta pontuando a nova questão..
Comment: o id da cidade seria esse numero no arquivo.json (nesse caso "197")
`{"cidade": { "197": {"nome": "ABADIA DE GOIAS","estado": "GO"}}}`
Comment: Qual input? Não seria através do select? Você pode obter o ID através do parâmetro key. Vá até o [fiddle](https://jsfiddle.net/vucs65xa/) de exemplo e abaixo do trecho `estados.push(value.estado);` adicione o código `console.log(key)`;
Comment: Se eu entendi bem o que você quer, pode ser feito [dessa forma](https://jsfiddle.net/natbco7f/).
Comment: Tu acha que daria pra ordenar em ordem alfabética?
Comment: Olá Léo Souza, nesse momento, devido a falta de tempo, não consigo te passar uma solução mais elegante, mas você pode tentar a seguinte: https://jsfiddle.net/ocpus4xd/


How to add assetbundle js/css add only in one page in yii2?

Question: I have added fullcalendar js/css in vendor/bower folder. I want to add this into just one page.
I read abt AssestBundle on this link - http://www.yiiframework.com/doc-2.0/guide-structure-assets.html
But this add in all the pages.
Answer: In Yii 2 framework asset bundles is recommended way of working with js / css. It's not limited to just adding to all pages. You can use it only in specific view.
Example of asset bundle for JsTree plugin:
<?php

namespace backend\assets;

use yii\web\AssetBundle;

class JsTreeAsset extends AssetBundle
{
    public $sourcePath = '@bower_components/jstree/dist';

    public $js = [
        'jstree.min.js',
    ];

    public $css = [
        'themes/default/style.min.css',
    ];

    public $depends = [
        'yii\web\JqueryAsset',
    ];
}

In this example, @bower_components alias is used, in order to get it working you also need to register it in application bootstrap file (in advanced application template this file is common/config/bootstrap.php):
Yii::setAlias('bower_components', dirname(dirname(__DIR__)) . '/bower_components');

Then, in view where you need to use it, call register() method of this asset bundle and pass current view:
use backend\assets\JsTreeAsset;

...

JsTreeAsset::register($this);

The files in default asset bundle (AppAsset) which included in application templates are loaded in every view because it's registered in application layout and layout is applied to all views.


Autoreleasepool in background queue for Realm

Question: In the example project of RealmCocoa:
<code>// Multi-threading
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    RLMRealm *otherRealm = [RLMRealm defaultRealm];
    RLMResults *otherResults = [Dog objectsInRealm:otherRealm where:@"name contains 'Rex'"];
    NSLog(@"Number of dogs: %li", (unsigned long)otherResults.count);
});
</code>
In the website docs:
<code>dispatch_async(dispatch_queue_create("background", 0), ^{
    @autoreleasepool {
        Dog *theDog = [[Dog objectsWhere:@"age == 1"] firstObject];
        RLMRealm *realm = [RLMRealm defaultRealm];
        [realm beginWriteTransaction];
        theDog.age = 3;
        [realm commitWriteTransaction];
    }
});
</code>

Why doesn't the example project have autoreleasepool?
Should the example project's code also include an autoreleasepool?
Which one of these usage is more appropriate?
Answer:
Why doesn't the example project have autoreleasepool?

It's an oversight.

Should the example project's code also include an autoreleasepool?

Yes.

Which one of these usage is more appropriate?

The latter. As Realm's documentation on threading states, all use of Realm from background threads should be contained within explicit autorelease pools.
Comment: I think it'd be better if the documentation has some "for dummies" section to explain these things in more basic words. Because when I first read it, I didn't understand the exact meaning. Thanks for the answer!


Reload Activity to re-switch between fragments

Question: I have a TabLayout with three fragments, on the first tab i want to switch between two fragment depending on a condition, i used if statement but still the fragments are not switching it only retains its initial fragment. The following is the case scenario and a code snippet of what am doing.
MY app allows user to decide if they are to login at first use or not, and my main activity is the launcher, the main activity's(Containing a TabLayout and three Fragment) adapter checks if the user is logged in or not.
if (user != login) {
  load fragment A
}else{
  load fragment B
}

I have an option somewhere where user can log in while using the app,
if user clicks on login button, it loads a fragement for user to login, once the user is logged in, the fragment still retain the state of user not logged in i.e its still loading fragment A, but then i can see all user login details in the app.
this point is still active

if (user != login) {
   load fragment A
}

Code Snippet
@Override
public Fragment getItem(int position) {
    Fragment f;
    switch (position) {
        case NEWS_POST:
            if(fbid != null){
                f = new NewsFragment();
            }else{
                f = new NewsAllFragment();
            }

Comment: please provide more detail, your issue is incomplete
Comment: Add a bit more code, the part where you are using `FragmentManager` to `add/replace` the current `Fragment`. Also add breakpoints where you are initializing `NewsFragment` and `NewsAllFragment` to check if it is actually being called.
Comment: You should be storing a loggedIn boolean or some key in your preference to check if you want to know if the user has logged in or not
Answer: First you should use SharedPreferences to check user is logged in or not.
Moreover you can use this code in your fragments to check if this fragment is visible or not. and if visible you can do your required task getting boolean logged in information from shared preferences.
private static boolean m_iAmVisible;

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    m_iAmVisible = isVisibleToUser;

    if (m_iAmVisible) {
        Log.d(localTAG, "this fragment is now visible");
    } else {
        Log.d(localTAG, "this fragment is now invisible");
    }
}

Here see i have a fragment in which i am using viewPager, in onCreateView Method
final View x = inflater.inflate(R.layout.consumer_tab_layout, null);
        tabLayout = (TabLayout) x.findViewById(R.id.tabs);
        viewpager_for_tabs = (ViewPager) x.findViewById(R.id.viewpager_for_tabs);

        bottom_tv1 = (TextView) x.findViewById(R.id.bottom_tv1);
        bottom_tv2 = (TextView) x.findViewById(R.id.bottom_tv2);
        bottom_tv3 = (TextView) x.findViewById(R.id.bottom_tv3);
        bottom_tv4 = (TextView) x.findViewById(R.id.bottom_tv4);
        bottom_tv5 = (TextView) x.findViewById(R.id.bottom_tv5);

        /**
         *Set an Apater for the View Pager
         */
        viewpager_for_tabs.setAdapter(new MyAdapter(getChildFragmentManager()));
        viewpager_for_tabs.setOffscreenPageLimit(5);

        /**
         * Now , this is a workaround ,
         * The setupWithViewPager dose't works without the runnable .
         * Maybe a Support Library Bug .
         */

        viewpager_for_tabs.setOnPageChangeListener(myOnPageChangeListener);
        bottom_tv1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateBottomTabTextViews(bottom_tv1, R.drawable.d1);
                viewpager_for_tabs.setCurrentItem(0, false);
            }
        });
        bottom_tv2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateBottomTabTextViews(bottom_tv2, R.drawable.d2);
                viewpager_for_tabs.setCurrentItem(1, false);
            }
        });
        bottom_tv3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateBottomTabTextViews(bottom_tv3, R.drawable.d3);
                viewpager_for_tabs.setCurrentItem(2, false);
            }
        });
        bottom_tv4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateBottomTabTextViews(bottom_tv4, R.drawable.d4);
                viewpager_for_tabs.setCurrentItem(3, false);
            }
        });
        bottom_tv5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateBottomTabTextViews(bottom_tv5, R.drawable.d5);
                viewpager_for_tabs.setCurrentItem(4, false);
            }
        });

        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                tabLayout.setupWithViewPager(viewpager_for_tabs);

            }
        });

        return x;

And in adapter getitem Methods
@Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                        return new fragment();

                case 1:
                    return frag2.getInstance();
                case 2:
                   return frag3.getInstance();
                case 3:
                   return frag4.getInstance();
                case 4:
                    return frag5.getInstance();
            }
            return null;
        }

In this was i just have to pragmatically call Button onClick using performClick() method for views and it will automatically replace my fragment.
Better solution would be to change current item of viewPager Have a look at this solution pager.setCurrentItem( num )
If you want to show different fragments on a single tab of viewPager then apply Boolean condition in getItems() method of your fragment adapter. then call viewPager.setCurrentItem(int) function.
Make sure your Fragment adapter extends FragmentStatePagerAdapter class
Comment: i am getting if user logged in or not from shared preference, it works fine if i reload the app, but while still using the app it retains its initial fragment when user is logged in, which is a really bad user experience.
Comment: There must be some code that will check is user logged in and doing some task. In that piece of code you can replace your fragment like this http://stackoverflow.com/a/18940937/6634982. Anf if you are using viewpager you use setPage function
Comment: I have a code that check if user is logged in, and i am using view pager with three tabs, i only want to replace the first tab with any of two different fragment pending on if the user is logged in or not. since you already have the idea the issue am having, how can i solve it. Thanks.


Limiting distribution of scaled sum of squared Poisson RVs

Question: Let $Y_1,Y_2,...$ be $\text{iid}$ Poisson random variables having mean $1$. Define
$$U_n = \sqrt{\frac{1}{n}\sum\limits_{i=1}^n Y_i^2}.$$
How to determine the limiting distribution of the sequence $U_1,U_2, ...$?
I know that the weak law of large numbers can be used to deal with the  $n^{-1}\sqrt{\sum Y_i^2}$, but not how to deal with the $n^{-1/2}$ case.
Comment: I am asking how to determine the limiting distribution of the sequence of U's
Comment: Which exercise from which book is this? If it is.
Answer: The central limit theorem (at least some version of it) tells us that with
$$
  U_n^2 = \frac{1}{n} \sum_{i=1}^n Y_i^2
$$
the following converges in distribution to a standard normal $Z$ for large $n$,
$$
  \sqrt{n} \frac{U_n^2-\mu}{\sigma^2} \overset{d}{\longrightarrow} Z
$$
with $\mu=\text{E}[Y^2]$ and $\sigma^2=\text{Var}[Y^2]=\text{E}[Y^4]-\text{E}[Y^2]^2$. Therefore, the limiting distribution of $U_n$ is going to be
$$
  U_n\ \overset{d}{=}\ \sqrt{\mu + \frac{\sigma^2}{\sqrt{n}} Z}
$$
The only real difficulty here is to determine the 2nd and 4th moment of $Y$. Luckily, because $Y$ is Poisson with mean 1 we can use Dobinsky's formula:
$$
  \text{E}[Y^i] = \frac{1}{e}\sum_{k=0}^{+\infty} \frac{k^i}{k!}
$$
which for $i=1,2,3,4$ gives 1, 2, 5, 15 respectively. Therefore $\mu=2$ and $\sigma^2=15-2^2=11$.
Comment: I do not quite follow... Don't you mean $U_{n}^2 = n^{-1} \sum Y_{i}^2$?
Comment: Didn't you mean "$\sigma$" instead of "$\sigma^2$" in the denominator of the second formula?  That would change the third formula, too.  It's hard to see how Dobinsky's Formula is any help, unless you can point to an alternative way of computing the Bell numbers.


Java: static variable declaration best practices

Question: I have developed a Java Program which contains certain static variables that are used in all the classes.
Now, I want to store those variables at a single platform, which I can refer to call from any class rather than declaring them again & again.
I have researched on the internet and found some good solutions like declaring them in an interface and implementing that interface in my classes.
Also, I can write a separate class and call those variables using the object of that class.
Can anyone suggest the better solution? or which one is better between these two? please explain :)
Comment: "I want to store those variables at a single platform" what do you mean?
Comment: If they're *static* variables, with the second solution you don't need an *instance* of that class.
Comment: Why don't you create a class with all static variables?
Comment: Like I want to declare them once so that I do not have to declare or initialize it in every class
Comment: Do you know how `static` variables work ?
Comment: I am actually looking for the solution which is the best practice to avoid re-declaration of those variables. So implementing a constant interface is a good practice? or shall I follow something else?
Comment: Have you thought about using enums?
Comment: No, is that a good approach to use enum? as far as
I have searched, the interface will share all the variables that are not even not required by the calling class which is bad practice. Enum avoids that practice.
Answer: It kind of depends on what you mean by "variables" if you mean global mutable state, you should probably either use a Singleton pattern, or even better,  redesign your application in such a way as to eliminate global mutable state. (Encapsulation)
If all your static variables are final, or effectively final (for instance loaded from environment variables at run time), then wrapping them in a class (with a private Constructor, since you do not want to be able to create objects of the class that only has static members) is probably the best solution.
Interfaces are designed to describe behavior, rather than state, so unless you have a contract described in it, it doesn't seem useful to have it as an interface, and could potentially lead to confusion down the road.
Comment: Impressive. I have some variables whose value will be assigned in the class but I want to declare them once with initialization. They are not final. So what should I follow from above?
Comment: If they are not final, you should use the [Singleton pattern](https://en.wikipedia.org/wiki/Singleton_pattern), since that gives you some control over critical sections and concurrency.

That being said I would really recommend against using global mutable state, as it is generally considered an anti-pattern.
Answer: 1:- Create an enum class like this,
    public enum YourClassName{

 // these are your three varible
VARIABLE1("val1"), VARIABLE2("val2"), VARIABLE3("val3"),;

private String value;

YourClassName(String value) {
    this.value=value;
}

public String getValue() {
    return value;
}

public void setValue(String value) {
    this.value = value;
}

}
2:- Once you have an enum class with some variable then you can call from every class like this,
 YourClassName.VARBIABLE1.getValue();

this will help you and i think its a good way.
Comment: It will make it more complicated, I am using public static String VARIABLE just want to call this variables .Setters and getters will make it more complex
Comment: Take care of java naming conventions. Class name should start with upper case character. Enum values like your *varable1* should be upper case
Answer: You can refer to static variables from any class... (assuming they are not private): just do ClassName.variable.
The better option is to not use static variables as global variables. Use getters and setters to pass values.
The interfaces solution is hacky and I have used it before - but that is also not ideal. Implementing a constants interface is considered bad practice.
Comment: @DevX I assumed the OP was talking about https://stackoverflow.com/questions/320588/interfaces-with-static-fields-in-java-for-sharing-constants
Comment: What do you mean by implementing a constant interface, because you dont have to implement that interface to access those static variables, just asking for my clarity
Comment: So where should I declare them? Shall I create a new class for constants and declare my variables there?
Comment: @DevX No, you don't have to, but that's what OP is trying ("declaring them in an interface and implementing that interface in my classes")
Comment: @sleepToken yes that is what I thought but not sure why is he looking to implement that because in most scenarios we have a separate interface for constants and hardly implement them ever
Comment: @Devx can you please elaborate your answer? I am finding it useful
Comment: @Jawad-Dev you can [see](https://stackoverflow.com/a/60488979/1722792) the answer explanation
Answer: Well to further work on @sleepToken answer there can be multiple ways to what you are looking to do. Again these approaches may depend on the design and at times may totally be different than what is being followed in the code base that you are working on.
For instance in most cases I have seen a convention that constants are defined in an Interface in java and that interface is hardly ever implemented. You can have multiple of these interfaces as well. Like one interface for storing constants related to user and may be another for the constants related to the system

IUserConstants.java
ISystemConstants.java

Now this is totally up to you to decide the names and what these interfaces will hold. Since these are constants you will define in them they are supposed to be public and static and at times you will make them final as well but make sure that you know the difference between runtime and compile time constants. Again this is something you will have to decide about.
Further more public static final are redundant for interfaces. This link just got my attention.
You can check this sample interface
public interface IConstants{
public static final int TIME=10;
public static final String CONFIG_STRING=SomeClass.LoadValue();
}

Another approach I have seen is to use an abstract class that contains all the constants which are static and public and if you want to make sure that it is not further used for implementation you can use a private constructor although I am not sure why this was used because at times legacy code that comes in front hardly makes sense.
public abstract class IConstants
{

  public static final int TIME = 10;
  public static final String CONFIG_STRING = SomeClass.LoadValue();constant

  private IConstants()
  {
    throw new AssertionError();
  }
}

I hope this helps you


DropDownList não funciona dentro de DetailsView

Question: Tenho um DetailsView com vários campos e um DropDownList que deve atualizar o campo sexoAnimal com Macho (M) ou Fêmea (F).
Adicionei um ControlParameter no SqlDataSource, o parâmetro pega o valor selecionado no DropDown.
Se eu deixo o DropDownList dentro do DetailsView, ele dá esse erro:

Não foi possível encontrar o controle 'sexoDrop' em ControlParameter 'sexoC'.

Se eu tiro ele pra fora do DetailsView (exemplo: em baixo), ele atualiza o campo Sexo normalmente.
O que posso/devo fazer para funcionar dentro do DetailsView?
Cód DropDown:
<asp:DropDownList ID="sexoDrop" runat="server">
    <asp:ListItem Value="M">Macho</asp:ListItem>
    <asp:ListItem Value="F">Fêmea</asp:ListItem>
</asp:DropDownList>

Parâmetro:
<asp:ControlParameter Name="sexoC" ControlID="sexoDrop" PropertyName="SelectedValue" />

Comment: Poderia postar um trecho maior de código do seu APSX e tbm do seu source ASPX.cs q faz a chamada dos métodos?
Comment: @tchicotti, está tudo sendo feito no .aspx, usando os componentes DetailsView com SqlDataSource.
Answer: Conforme eu respondi na tua outra pergunta: Como usar o valor do SelectedValue do DropDownList?
Uma forma de fazer isso é recebendo o DropDownList do DetailsView e fazendo a lógica de update dentro do code-behind. Nunca utilizei o SqlDataSource, mas pelo erro que está dando o problema é que o DropDownList não esta acessível para o SqlDataSource.
Da mesma forma que no code-behind é necessário realizar um dvId.FindControl("sexoDrop"), será necessário realizar o mesmo no SqlDataSource. Agora como fazer isso eu não sei, pois nunca utilizei este controle.


showint thumbnails issue

Question: I am unexperienced in ways of PHP and MySQL, but I am trying to build an image upload website following a tutorial of Kevin Skoglund. Everything was fine up to a point where my images are supposed to show on a page in a html table.
I got everything from my database (image size, type, name, caption), but instead of image thumbnail I get broken link.
Here is relevant html

    <img src="../<?php echo $photo->image_path(); ?>" width="100" />
    <?php echo $photo->filename; ?>
    <?php echo $photo->caption; ?>
    <?php echo $photo->size_as_text(); ?>
    <?php echo $photo->type; ?>

Here is php that defines image path
protected $upload_dir="images";
public function image_path() {
return $this->upload_dir.DS.$this->filename;

}
Site root defined:
defined('SITE_ROOT') ? null :
    define('SITE_ROOT', DS.'wamp'.DS.'www'.DS.'projekat');

this is folder structure
this is end result
Thanks for taking time to read and help with my problem in advance.
Answer: EDIT:
return $photo->image_path() as
 projekat/public/images/filename.jpg

and display
 <img src="/<?php echo $photo->image_path(); ?>"

In html, you can use beginning '/' to indicate root. So if you have stored your relative path in database as
  $path = relative/path/to/file

you can use
src = "/<?php echo $path?>"

Comment: Didn't work, thanks for fast reply anyways. Is it possible that since I worked in windows and tutorial is done on mac that I have something like folder permissions, or something trivial like that stoping thumbnails from showing.
Comment: I hope you have firebug.It will show some error in your console. Check if it shows source does not exist or something similar.
Comment: and BTW, you are storing relative paths right !?. If you are storing absolute paths like 'C:/www/something' it wont work when you go live or when you test in different OS. If you are not storing relative paths, do that, and i think it will solve your problem
Comment: I know, but for a starters, I would like to show them at least locally.
Comment: The error comes from the fact that you are using '../some_path', which means go back one level. But , that is with respect to your php file. So, when you are using the same in html ... it will go back one level from the document root, which I guess is C:/wamp/www/, in your case. You need to address this to solve your error.
Comment: solved it by changing

return $this->upload_dir.DS.$this->filename; to

return $this->upload_dir."/".$this->filename;
Comment: thanks for your interest in helping me, i appreciate it a lot <3
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/25997/discussion-between-goran-stosic-and-arundex)

showint thumbnails issue


How are false positives possible? Since shouldn't mathematical methods be "exact"?

Question: That is, it's not possible to have true as false, but isn't that basically what a false positive or a false negative does? That it gives a prediction of a condition existing, when it does not?
So how is this possible?
Comment: See [here](https://en.wikipedia.org/wiki/Map%E2%80%93territory_relation)
Comment: 1. I roll a six-sided die but don't how you which face landed uppermost. The die is symmetric and I rolled it a long way.  I ask you to predict the face that's uppermost. You can use mathematical methods ... so you should get the right answer every time, right? (How could you possibly get it wrong? Shouldn't mathematical methods be exact?)  $\:$  2. Let's predict next years weather (say the maximum temperature and rainfall for every day of 2019) using mathematical methods. How can we ever get it wrong? Shouldn't mathematical methods be exact?
Answer: False positives and false negatives arise in the context of binary decision problems in statistics, where you have an underlying unknown binary state, and you use data to predict that unknown state.  A "false positive" means that you have predicted that a particular "positive" state is true, but it turns out you are wrong.  In deductive mathematical problems outside of statistics, the observed information may be sufficient to logically imply the true underlying state, in which case it should be possible (in theory at least) to predict this state exactly.  Statistical problems arise when the data is insufficiently informative to logically imply the true underlying state of nature, and so we make inferences using probability theory and statistical methods, and our predictions are inexact - they have some chance of being wrong.
Perhaps a useful re-framing of your question is: What is the mathematical/statistical procedure that is able to predict unknown states of nature exactly, from limited statistical data, without any false positives.  If you are aware of such a procedure, it will be of great interest to people, and you should feel free to share it with us.  If you are unable to find or create such a procedure, then I think that gives you your answer.


Changed Comment Module and database table - how to revert changes?

Question: Yesterday, I posted this thread which was subsequently locked for being too localized. I think this is much more searchable (and I still need help!) but I'm sorry for the bad thread.
Like mentioned in that thread, I changed different files in the comments module folder and added columns to the database table. This sort of disabled comments, both the settings in page content settings and their appearance on the page normally.
I tried to fix this by: uploading a completely new 'comments' folder (I have a back up if that was a bad idea) from a new copy of the core, and deleted those table fields. Still no sign of fixing any of the problems I created.
How do I return the comments to their normal setting so I can approach the altering I was planning on doing the right way this time?
Answer: First: Do not hack core!
To restore your site to a stable state, revert to the default theme, back-up your database and the sites/ sub-directory and anything below it.  Then download a fresh copy of the core and install it. Finally, restore the sites/ sub-directory, your database, and the theme.
Having extra tables in the database that Drupal does not know about does not do any harm, but you may drop those tables that you created yourself before backing up the database.
Comment: To backup the database, it is best to use the Backup and Migrate module (linked to in my answer).  It discards certain tables (such as *cache* and *sessions* you don't want to re-import to your restored site.  When you do this, you should test for potential problems after completing every step of the restoring process.  I.e. test first after installation of core, then again after restoring `sites`, and then again after importing the database.  If there still is problems, you need to describe these problems in detail in order to get help here.  You should edit your question to add such detail.
Comment: When you say backup my database, this just means I save it (SQL file) and take it all down for the installation of the fresh core? There won't be any problems when I import that old database?
Comment: I installed new core, replaced the 'sites' folder, and replaced that new database with the old one, and I'm getting the exact same problems.
Comment: I had an earlier version of the database that I just used after reinstalling. Still copying updates everything over. I'll let you know how it goes soon.
Comment: Perfect, everything is back to normal. Can you send me in the right direction in terms of figuring out how to post/store comments with custom parameters (which can be gathered on the page) so I can display only the comments for that "page"? By this I mean I have a page that takes in parameters and I want a different set of comments for each possible parameter/id.
Comment: http://drupal.stackexchange.com/questions/70195/storing-additional-parameters-for-comments if you get a chance - Thanks again!


Sylius how to override the CoreBundle Checkout process

Question: I'm working on a project and I'd like to ask for a clean/best way to override the steps in the
Sylius\Bundle\CoreBundle\Checkout\CheckoutProcessScenario
I'd like to preserve the custom mechanics of the whole process just add a custom step at the end and remove the finalize step.
    $builder
        ->add('security', 'sylius_checkout_security')
        ->add('addressing', 'sylius_checkout_addressing')
        ->add('shipping', 'sylius_checkout_shipping')
        ->add('finalize', 'sylius_checkout_finalize')
        ->add('payment', 'sylius_checkout_payment')
        ->add('purchase', 'sylius_checkout_purchase')
    ;

What's the best form of doing so? If it's extending the bundle and overwriting it I'd like some help with that of at least some information to point me in the right direction - currently I'm not getting any results on my own.
I've read the docs on the bundle itself but it doesn't explain how to override the built in process.
I've also read the symfony cookbook on extending resources:
http://symfony.com/doc/2.0/cookbook/bundles/inheritance.html#overriding-resources-templates-routing-translations-validation-etc
and:
http://symfony.com/doc/current/cookbook/bundles/override.html
If anyone has some experience on the topic and would like to share thier insights I'd be very gratefull. Thanks in advance.
Answer: You could change the service class to a custom one.
You can overwrite the parameter sylius.checkout_scenario.class.
app/config/config.yml:
<parameter key="sylius.checkout_scenario.class">
    Your\Class
</parameter>

Answer: I've done it a bit different but still the point was good :)
What I've done is use the service compiler to override it with my own class and override the original file. The basics are explained here:
http://symfony.com/doc/current/cookbook/bundles/override.html
in the Services & Configuration section :)
Then I just had to include the compiler pass
// src/Acme/ShopBundle/AcmeShopBundle.php
namespace Acme\ShopBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;

use Acme\ShopBundle\DependencyInjection\Compiler\CustomCompilerPass;

class AcmeMailerBundle extends Bundle
{
    public function build(ContainerBuilder $container)
    {
        parent::build($container);

        $container->addCompilerPass(new CustomCompilerPass());
    }
}

Inside the compiler pass I just extended the base file and overwrote the function I needed. Droppin it by in case anyone needs to pointed in the right direction.


Como obter o último dia útil do mês?

Question: Há alguma biblioteca brasileira de feriados confiável que a gente consiga integrar e obter o último dia útil de algum mês?
De qualquer modo, se não houver tal biblioteca, como eu poderia obter o último dia de semana de algum mês? (Formatado em um Calendar ou um Date.)
Exemplo de código necessário
Calendar hoje = Calendar.getInstance();
Calendar ultimoDiaUtil = getUltimoDiaUtil(hoje);

Comment: Você pode obter o último dia do mês somando -1 dia à uma data que represente o primeiro dia do mês seguinte. E se quiser o último dia de semana, é só voltar os dias até encontrar uma sexta (caso o último dia já não seja). Em no máximo duas iterações você consegue o dia desejado.
Comment: Deve ser simples você manter um arquivo de configuração (um XML talvez) com os feriados nacionais e estaduais. Na interação que o @Renan mencionou, basta ignorar as datas que cairem em um feriado configurado. Fontes confiáveis de informações sobre feriados são [1](http://www.brasil.gov.br/cidadania-e-justica/2014/01/divulgada-lista-de-feriados-e-pontos-facultativos-de-2014) e [2](http://pt.wikipedia.org/wiki/Feriados_no_Brasil).
Comment: @Renan sua solução é muito boa, desde que o autor não precise considerar os feriados, pq não implementa ela?
Comment: @Math porque eu sou um zero a esquerda em Java e não conheço os tipos de data e hora do framework. Se fosse .NET ou Javascript eu poderia ajudar mais. Se alguém quiser dar uma resposta completa abaixo com a minha ideia, fiquem a vontade :)
Answer:
Você pode obter o último dia do mês somando -1 dia à uma data que represente o primeiro dia do mês seguinte. E se quiser o último dia de semana, é só voltar os dias até encontrar uma sexta (caso o último dia já não seja). Em no máximo duas iterações você consegue o dia desejado.

Funciona desde que não considere os feriados.
Se quiser considerar os feriados, mapeie-os e adicione mais uma condição no loop verificando se a data não é um feriado, se for um feriado continue decrementando até que a condição não seja satisfeita e caia fora do while.
Implementando a ideia do @Renan mais a parte do código que verifica se é feriado:
public static void main(String[] args) {
    DateFormat DATE_FORMAT = new SimpleDateFormat("dd/MM/YYYY");
    Calendar hoje = Calendar.getInstance();
    Calendar ultimoDiaUtilDoMes = getUltimoDiaUtilDoMes(hoje);
    System.out.println(DATE_FORMAT.format(ultimoDiaUtilDoMes.getTime()));
}
public static Calendar getUltimoDiaUtilDoMes(Calendar calendar) {
    //muda a data da variável para o último dia do mês
    calendar.add(Calendar.MONTH, 1);
    calendar.set(Calendar.DAY_OF_MONTH, 1);
    calendar.add(Calendar.DATE, -1);
    //enquanto for sábado, domingo ou feriado
    while(calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY ||
            calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY ||
            ehFeriado(calendar)) {
        //decrementa a data em um dia
        calendar.add(Calendar.DATE, -1);
    }
    return calendar;
}
public static boolean ehFeriado(Calendar calendar) {
    Calendar feriado = Calendar.getInstance();
    //considerando 30 de abril como feriado
    feriado.set(calendar.get(Calendar.YEAR), Calendar.APRIL, 30);
    if(calendar.get(Calendar.DAY_OF_YEAR) == feriado.get(Calendar.DAY_OF_YEAR)) {
        return true;
    }
    else {
        return false;
    }
}

Retorna:

29/04/2014

Pois no meu código disse que hoje é feriado, portanto ele mostrou a data de ontem.
Para a comparação feita no código:
calendar.get(Calendar.DAY_OF_YEAR) == feriado.get(Calendar.DAY_OF_YEAR)

dar certo é necessário que o ano do feriado seja setado como o mesmo ano da data que vai comparar, assim:
feriado.set(
    calendar.get(Calendar.YEAR), //ano de feriado igual ao ano de calendar
    Calendar.APRIL, //constante estática da classe Calendar
    30);

pois o calendar.get(Calendar.DAY_OF_YEAR) retorna um inteiro que diz qual é o dia daquele ano, portanto caso seja setado 30 de abril de um ano qualquer daria diferença de um dia se comparar a data de um ano bissexto com a mesma data de um ano não bissexto.
Para considerar os feriados cuja a data varia de ano para ano deve-se descobrir a conta que é feita e implementá-la por exemplo em um método ehFeriadoQueVaria() e adicioná-lo no while().
Edição para referência futura:
Agenda de Feriados disponibilizada pelo Google em formato XML.
Comment: @Renan Posso dizer que carnaval não é feriado em SP, pois já trabalhei no carnaval e não ganhei nada mais por isso, rs..
Comment: `Não me lembro de nenhum feriado que vai no final do mês`  Carnaval e semana santa podem cair em final de mês. O Reveillon até onde lembro é feriado facultativo no Brasil. E do jeito que a coisa vai, o Dia das Bruxas (31 de Outubro) daqui a pouco vira feriado. Isso são os nacionais - pode ainda haver feriados estaduais ou municipais que caiam em último dia de mês. Fora isso, +1
Comment: @Renan você merece metade dos pontos que eu ganhar, rsrs.. vou editar. PS: até onde sei Reveillon não é feriado, dia 1º de janeiro que é. Realmente carnaval e feriados regionais podem ser um problema.
Comment: @Renan na verdade carnaval só é feriado no Rio e na Bahia, no restante do país é facultativo, semana santa é feriado mesmo, e varia de ano para ano, seria necessário uma bela de uma conta (se é que existe) para calculá-los. Feriados regionais geralmente não mudam de data, então não seria nenhum problema.
Comment: Carnaval e semana santa são baseados na lua. Parecem aleatórios, mas é uma conta conhecida. Posso confirmar que o Carnaval é feriado em todos os estados do Nordeste ao menos, até onde sei. Originalmente era um feriado católico e era um dos poucos que a Ditadura não conseguiu remover do calendário oficial em eras passadas, para se ter uma ideia da importância dele...
Comment: Muito interessante pessoal. Realmente a ideia dessa iteração tornou o cálculo bem rápido mesmo. E a ideia de colocar em um XML é uma boa também. Acho que não compensa ficar tentanto fazer cálculos para encontrar... acho que é melhor para cada ano adicionar um arquivo com as informações mesmo...
Comment: Pessoal, aproveitando as interessantes idéias desse post, encontrei uma agenda que eu diria ser confiável, com os feriados do Brasil (nacionais apenas) já em XML. A agenda disponibilizada pelo [Google](https://www.google.com/calendar/feeds/pt-br.brazilian%23holiday%40group.v.calendar.google.com/public/basic). Se fosse necessário adicionar feriados regionais, bastaria baixar o arquivo, importar em uma agenda personalizada e depois exportar novamente. Faltaria agora os métodos para ler o XML e retirar as informações...
Answer: Calendar c = Calendar.getInstance();
    //alterar para o mes de abril
    c.set(Calendar.MONDAY, Calendar.APRIL);
    //pega o ultimo dia do mes de abril
    int ultimoDia =c.getActualMaximum(Calendar.DAY_OF_MONTH);

Comment: e pra pegar o último dia útil?
Answer: Para não seguires códigos muito grandes e complexos, te sugiro, este código feito por mim, e te sugiros que sigas os tutorias no próprio site da Oracle!
import java.time.LocalDate;

public class testee {

    public static void main(String[] args) {
        System.out.println("primeiro dia do mês: " + principioDoMes(LocalDate.now()));
        System.out.println("ultimo dia do mês: " + fimDoMes(LocalDate.now()));
    }

    private static LocalDate principioDoMes(LocalDate l) {

        String local = l.toString();
        int ano = Integer.parseInt(local.split("-")[0]);
        int mes = Integer.parseInt(local.split("-")[1]);

        return LocalDate.of(ano, mes, 1);
    }

    private static LocalDate fimDoMes(LocalDate l) {
        return principioDoMes(l.plusMonths(1)).minusDays(1);
    }
}

Como obter o último dia útil do mês?


Expected Statement

Question: Hello i'm working on a test Website where I want a User to be able to look at entries in a Database, the User can Choose if he wants the Data from Customers, the Adress, or the Order.
When i open it, ist says expected statement on wend at line 82.
Here is my Code:
     <form action="DB_HTML_Styled.asp" method="get">
  <%
  response.flush
%>

          <select name = "f_operator" onchange"">
            <option value = "1" <% if l_operator = "1" then response.write("selected") end if %>>Kunde</option>
            <option value = "2" <% if l_operator = "2" then response.write("selected") end if %>>Auftrag</option>
            <option value = "3" <% if l_operator = "3" then response.write("selected") end if %>>Ort</option>

<%  Set l_DBCon = Server.CreateObject("ADODB.Connection")
    l_DBCon.Open "db_amill136_test"
    Dim l_rs
    Set l_rs = Server.CreateObject("ADODB.Recordset")
select case l_operator
case "1"
    l_query = "select * from t_kunde"
case "2"
    l_query = "select * from t_auftrag"
case "3"
    l_query = "select * from t_ort"
case "4"

%>

<%=l_query%>
  <%
    l_rs.Open l_query, l_dbcon
    while not l_rs.EOF  %>

<%if l_operator =  "1" then %>

      <%=l_rs("f_vorname")%>

      <%=l_rs("f_name")%>

      <%=l_rs("f_kundennr")%>

      <%=l_rs("f_ortnr")%>

    <%else if l_operator =  "2" then%>

      <%=l_rs("f_auftragsnr")%>

      <%=l_rs("f_menge")%>

      <%=l_rs("f_rabatsatz")%>

      <%=l_rs("f_datum")%>

      <%=l_rs("f_kundennr")%>

    <%else if l_operator =  "3" then%>
      <%=l_rs("f_ortnr")%>

      <%=l_rs("f_ort")%>

      <%=l_rs("f_plz")%>

<%end if
        l_rs.MoveNext
      wend

    l_rs.Close
    Set l_rs = Nothing

    l_DBCon.Close
    set l_DBCon = Nothing
%>

    </form>

Answer: As it stands, you would need three "end if" statements before the wend because you have three separate "if" statements within the "while".
Instead of using "Else If" (with a space) use "ElseIf" (without a space) so you only need the one "end if".
Alternatively, you may wish to tidy up those nested ifs by using a Case instead.
Comment: Thank solved my Problem. I deleted the spaces, and added a end select ins line 87.

Expected Statement


Can we bound the lower and upper asymptotic density of these subsets of $\mathbb N$?

Question: Suppose we partition the powers of $2$ into two sets in the following manner:
$$A = \{1\}, \quad B = \{2,4,8,16,\dots\}$$
Now suppose that, for each odd positive integer $t$, we select either $tA$ or $tB$, and form the union $S$ of all sets selected in this way. For example, if we always choose $tA$, then the resulting set is
$$S_1 = 1A\cup 3A\cup 5A\cup\cdots = \{1,3,5,7,9,\dots\},$$
while if we always choose $tB$, the resulting set is
$$S_2 = 1B\cup 3B\cup 5B\cup\cdots = \{2,4,6,8,10,\dots\}.$$
These sets consist of all odd and all even integers, respectively; they each have natural density $\frac 12$.
On the other hand, we might form a "mixed" union. A tame example is
\begin{align*} S_3 = \left(\bigcup\limits_{t\equiv 1\text{ mod }4} tA\right) \cup \left(\bigcup\limits_{t\equiv 3\text{ mod }4} tB\right) &= 1A\cup 3B\cup 5A\cup 7B\cup\cdots \\ &= \{1,5,6,9,12,13,14,\dots\}, \end{align*}
which again can be shown to have natural density $\frac 12$. A more wild example is
\begin{align*} S_4 = \left(\bigcup\limits_{\substack{t\text{ odd} \\ \lfloor\log_2 t\rfloor\text{ even}}} tA\right) \cup \left(\bigcup\limits_{\substack{t\text{ odd} \\ \lfloor\log_2 t\rfloor\text{ odd}}} tB\right) &= 1A\cup 3B\cup (5A\cup 7A)\cup (9B\cup\cdots\cup 15B)\cup\cdots \\ &= \{1,5,6,7,12,17,18,19,21,22,23,24,\dots\}. \end{align*}
This set has no natural density; in particular, $\frac{|S_4\cap\{1,2,\ldots,n\}|}{n}$ oscillates between $\frac 7{18}$ (when $n=2^{2k}$) and $\frac{11}{18}$ (when $n=2^{2k+1}$).
My question:
Is it true that, no matter how we build $S$, its lower (resp., upper) asymptotic density will be less than or equal to (resp., greater than or equal to) $\frac 12$? This strikes me as a very reasonable conjecture, but I cannot figure out how to prove it.
Answer: We can prove the conjecture true by first considering the logarithmic density of a set $T$ of positive integers, which is
$$
\lim_{x\to\infty} \frac1{\log x} \sum_{m\in T\cap[1,x]} \frac1m.
$$
Proposition: Any set $S$ formed as described in the OP has logarithmic density $\frac12$.
Proof: Let $x\ge1$, and consider any odd integer $t\le x$. Note that
$\displaystyle
\sum_{m\in tA\cap[1,x]} \frac1m = \frac1t,
$
while
$$
\sum_{m\in tB\cap[1,x]} \frac1m = \frac1t -\frac1{2^kt}
$$
where $k$ is the largest nonnegative integer with $2^kt\le x$. Consequently, whether $C_t=A$ or $C_t=B$, we have
$$
\sum_{m\in tC_t\cap[1,x]} \frac1m = \frac1t +O\biggl( \frac1x \biggr).
$$
It follows that
$$
\sum_{m\in S\cap[1,x]} \frac1m = \sum_{\substack{t\le x \\ t\text{ odd}}} \sum_{m\in tC_t\cap[1,x]} \frac1m = \sum_{\substack{t\le x \\ t\text{ odd}}} \biggl( \frac1t +O\biggl( \frac1x \biggr) \biggr) = \frac12\log x + O(1),
$$
which implies the proposition. $\quad\square$
While the existence of a set's logarithmic density does not imply the existence of its natural density, it does imply bounds on the set's upper and lower natural densities. Suppose, for example, that the lower natural density of $S$ exceeds $\frac12$. This implies that there is a constant $\alpha>\frac12$ such that $\#(S\cap[1,x]) > \alpha x$ when $x$ is sufficiently large, say $x>x_0$. It follows by partial summation that we would have
\begin{align*}
\sum_{m\in S\cap[1,x]} \frac1m &= \int_{1-}^x \frac1u \,d\#(S\cap[1,u]) \\
&= \frac{\#(S\cap[1,x])}x - 0 + \int_1^x \frac{\#(S\cap[1,u])}{u^2}\,du \\
&> O(1) + \int_{x_0}^x \frac\alpha u\,du = \alpha\log x+O(1),
\end{align*}
which would contradict the logarithmic density of $S$ equaling $\frac12$. An analogous argument works for upper densities.
(In the last calculation, the second expression is a Riemann–Stieltjes integral, and the third expression follows from it via integration by parts; however, one can directly verify that the first and third expressions are equal by dividing the domain of integration in the third expression into subintervals on which $\#(S\cap[1,u])$ is constant, and then integrating and simplifying the resulting telescopic sum.)
Comment: Could you please elaborate on why $\sum_{m\in S\cap[1,x]} \frac1m = \int_1^x \frac{\#(S\cap[1,u])}{u^2}\,du$?
Comment: @Aig: I think there may be an omission there; I believe $\int_1^x \frac{\#(S\cap[1,u])}{u^2}\,du = \sum_{m\in S\cap[1,x]} (\frac1m-\frac 1x)$. Still, the difference can be swept into the $O(1)$ term in the next step.
Comment: @Greg Martin: Thank you! I'd seen the definition of logarithmic density before, but never knew what could be done with it. Marked as resolved.
Comment: I now fully understand the answer, thank you @GregMartin and tuna


(simple problem) finding the distribution for given constraints

Question: For even number $N$, I have three constraints to be satisfied for $C_{n}$ as follows.
\begin{align}
&1)~\sum_{n=0}^{N}C_{n}=1\\
&2)~\sum_{n=0}^{N}n~C_{n}=\frac{N}{2}\\
&3)~~C_{n}=C_{N-n} ~~\text{for}~n\le\frac{N}{2}
\end{align}
Is it possible to find the distribution of $C_{n}$ that satisfies the above equations? How can I find the distribution?
Comment: $C$ is the binomial distribution with $N$ trials and probability 1/2.
Comment: How many linear equations on $C_n$ do you get? Can you write the corresponding linear system and its matrix? Can you solve this system? Look at simple cases, $N=2;4$. What happens for larger $N$?
Answer: Long answer: Your question is equivalent to asking for solutions of the matrix equation $\left(\begin{array}{ccccccccc} 1 & 1 & \ldots & & & &\ldots & 1 &1 \\ 1 & 2 & 3 & \ldots & && n-2 & n-1 & n \\
1 & 0 & 0 & \ldots& &\ldots & 0 & 0 &-1 \\
0 & 1 & 0 &\ldots& &\ldots  & 0  &- 1 & 0 \\
 & & & \vdots &&\vdots & & & \\
0&\ldots & & 1 & 0& -1 & &\ldots & 0\end{array}\right)C=\left(\begin{array}{c}1 \\ \frac{N}{2} \\ 0 \\ \vdots \\ 0\end{array}\right)$.
You have $\frac{N}{2}+2$ constraints for $N+1$ variables, so you will have a range of solutions. However if by distribution you mean that the $C_n$ are the pmf of some distribution then you also need all of your $C_n$ to be non-negative which may narrow it down. Ultimately your answer will be of the form "any convex combination of the distributions $\{C^{(i)}\}_{i=1}^k$, where $k=\frac{N}{2}-1$". Eyeballing the equations though $C_{\frac{N}{2}}=1$ is a solution, as is $C_{N-n}=C_n=\frac{1}{2}$ for any $0\leq n<\frac{N}{2}$. And you can show that the rank of the matrix is $\frac{N}{2}+1$, and that these solutions are linearly independent, so this is the basis of solution vectors.
Short Answer: You're basically asking for all of the symmetric distributions on $\{0,1,\ldots,N\}$ (your second condition is actually redundant given the first and third). What are the building blocks of such distributions? $C_{N-n}=C_n=\frac{1}{2}$ for all $0\leq n<\frac{N}{2}$, and $C_{\frac{N}{2}}=1$. Can any solution be made from a convex combination of these distributions? Yes.