Determine the Vectors Which Span R^4

Question: I understand how to determine WHETHER a set of vectors span a space, but I've been given two vectors (1,2,3,4) and (17,17,17,17) and asked to find two more vectors such that the set of all these vectors span $ \mathbb{R}^4 $.
At the moment I'm just going about with kind of a trial and error approach...is there some better way to work this out?
Hints, or suggestions would be greatly appreciated as I want to figure this out without a full solution.
Comment: There are methods but for this particular problem trial and error is a good one. How about starting by adding $(1,0,0,0)$?
Comment: Won't any linearly independent set of four vectors in $\mathbb{R}^4$ span it? So you would just need to find two more vectors that are linearly independent to the first two and each other.
Answer: Try to complete your basis using the vectors of the standard basis: $(1,0,0,0), (0,1,0,0),$ etc. Pick one of them and check if the three vectors you have now are independent. If yes, great, keep the vector you chose and repeat the procedure with the three remaining vectors of the standard basis. If not, discard the vector you chose and try again with another one. Repeat until done.
Comment: I like this answer. I think the two vectors you gave should work right? I checked a matrix of these vectors for independence and got a non zero determinant, but I don't really intuitively understand how you can reach every vector in R^4 with a linear combination of these vectors.
Comment: They'll probably work, yes. If you got a non-zero determinant, you're good to go. I usually don't try to find intuition behing "ugly" vectors such as $(17,17,17,17)$, say haha. It only means that if: $$(x,y,z,t) = a(1,2,3,4) + b(17,17,17,17) + c(1,0,0,0) + d(0,1,0,0),$$ you can find unique $a,b,c$ and $d$ in terms of $x,y,z$ and $w$. It is more algebraic.
Comment: Okay great thanks, but then basically  it means that it's true that any four LI vectors in four dimensions will span R^4 right?
Comment: Precisely! ${}{}{}$
Answer: Put your two given vectors into a $4 \times 2$ row matrix $M$, and apply row operations to covert $M$ into a matrix $M'$ in which the leading nonzero entry of row $2$ is to the right of the leading nonzero entry of row $1$. The row spaces of $M$ and $M'$ are identical. It should now be obvious how to add two row vectors to $M'$ to make a basis. Your original two vectors, together with the two added row vectors, form the basis you want.
Answer: HINT
What basis do you already know that spans $\mathbb{R}^4$?
How can you use this in combination with the vectors that you are already given to get a basis?

Determine the Vectors Which Span R^4


Horizontal form elements

Question: I have described the form, but every element there is located under the previous one. I need to describe the form where all elements will be placed horizontally but not vertically.
This is my form:
function contact_register_form($form, &$form_state) {
  $form['description'] = array(
    '#type' => 'item',
    '#title' => t('Sign up to be notified when your community launches:'),
  );

  $form['email'] = array(
    '#type' => 'textfield',
    '#title' => t('Email'),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Add me',
  );

  return $form;
}

Answer: You can use code similar to the following one, used by the Node module in node_filter_form().
  // Build the 'Update options' form.
  $form['options'] = array(
    '#type' => 'fieldset',
    '#title' => t('Update options'),
    '#attributes' => array('class' => array('container-inline')),
    '#access' => $admin_access,
  );

  // ...

  $form['options']['operation'] = array(
    '#type' => 'select',
    '#title' => t('Operation'),
    '#title_display' => 'invisible',
    '#options' => $options,
    '#default_value' => 'approve',
  );

The key is the line settings the "#attributes" attribute to "container-inline."
That code is for Drupal 7; the equivalent code for Drupal 6 starts with the following code:
  $form['options'] = array(
    '#type' => 'fieldset',
    '#title' => t('Update options'),
    '#prefix' => '
',
    '#suffix' => '
',
  );

Supposing you are using Drupal 6, then your code should be changed to something similar to the following one:
function contact_register_form($form, &$form_state) {
  $form['description'] = array(
    '#type' => 'item',
    '#title' => t('Sign up to be notified when your community launches:'),
  );

  $form['email'] = array(
    '#type' => 'textfield',
    '#title' => t('Email'),
    '#prefix' => '
',
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Add me',
    '#suffix' => '
',
  );

  return $form;
}

I didn't put the description inline, as it would not be correctly rendered because it is using a "item" form field. I also find that inlining the description would cause the form to take too much space. (Imagine what would happen if the inlined description would be longer, and placed in a single line.)
The CSS styles that Drupal 7 adds to container-inline elements are the following.
/**
 * Inline items.
 */
.container-inline div,
.container-inline label {
  display: inline;
}
/* Fieldset contents always need to be rendered as block. */
.container-inline .fieldset-wrapper {
  display: block;
}

They are added from system.base.css.
Comment: And don't forget to apply a `float` in CSS to the `container-inline` class.

Horizontal form elements


Suggestions for a productive hardware setup with excellent virus protection

Question: This question is a little opinion based, but I think it can be based in fact and I would prefer answers backed up with a link to a reputable company if possible.
The problem is at my job, we have "okay" hardware for the developers, laptops running Windows XP (I know) with dual core 2.3 Ghz processor, 2GB of memory and 60 GB hard disk @7200 rpm however, the amount of virus scan and security agents and big brother software on these make them unusable when scans are running. My company insists on running full disk virus scans every monday and "smart scans" every other day.
I appreciate the concern for viruses as much as the next guy, however it is hindering our work and we are looking for a new setup that allows the developers to work unimpeded by scans, yet provides virus protection et al that the company is looking for.
Keep in mind my company is not really willing to change antivirus vendors, so we're looking at a developer oriented solution because most of the business users do not experience these issues.
UPDATE:
Company policy requires that all laptops (which I have) are taken home each evening unless you have an office to lock it in.  Because I am office-less, I have to take it home each evening.
I am willing to listen to any scenario, switch to a desktop, switch to a different OS, any of the above.  Just looking for setups that people currently use, that seem to work for their developers, in particular java developers.
We also run a lot of software on our laptops, an applicatoin server, a database, email client, developer IDE, database IDE and other random things as required.
END UPDATE.
Any suggestions?
Comment: Is disconnecting the computers from the network or running Linux an option?
Comment: The company is unwilling to switch antivirus vendors, but willing to buy new laptops? Is the antivirus that expensive?
Comment: @3dinfluence - We are willing to listen to any OS switch, I'm just looking for possible ideas to alleviate the problem.

@Ernie  We are currently on a 2 or 3 year lease cycle with hardware and the cycle end is fast approaching.
Answer: Maybe a software solution would be better. Does the virus scanner have the option of shutting down the computer when it's done? Maybe at the end of the day the developer can run the virus scanner in lieu of shutting down. When the scanner is done, the user comes in the next day to a freshly scanned computer that's ready to boot up.
Answer: Having an on-access should make it unnecessary to run a scan, though I realise many IT departments insist on using a scheduled scan, possibly because they might be fired if there was a virus outbreak!
All I can suggest is to try and convince your support guys that an on-access scanner alone is adequate. I strongly advise you have at least an on-access scanner. Any modern AV on-access scanner shouldn't cause a significant slowdown. i use AVG here and only notice it when doing big directory replications.
JR
Comment: Just a minor nit:
"Having an on-access should make it unnecessary to run a scan [...]" -- That's true as long as the AV solution is always more current than the virus creators... Since that's rarely the case, it makes sense to "re-scan" files periodically to ensure a new virus wasn't missed on the first access scan.
Comment: @Chris: I would (indeed I do) run a full scan occasionally e.g. over a lunch break. Whether you could trust developers (a race related to Orcs but less evolved :-) to do the same is debatable.
Comment: @John  Did I forget to mention that I'm a developer?  Its funny, we have a similar opinion of our IT counterparts on the hardware side.
Answer: There is no good solution to this problem that I can see- if management insists on auditing that often, you're stuck with it. However, a possible fix could be making it so that developer stations that can't access the internet, only the company intranet, and exempting them from the daily scans, letting only the weeklies run.
If there's an infection loose on the intranet, quarantine the developer subnet and lock it down, and thoroughly disinfect before reconnecting it.
Answer: I don't think you're going to find any economical level of hardware platform that won't show some signs of stress during virus scanning, especially in the realm of laptop computers. Workstation-class machines with 10K or 15K-RPM SAS drives and multi-core processors (to give you faster IO, more IO parallelism, and processing parallelism) are your best bets, but that's going to be expensive.
This is one of those classic "tradeoff triangles". In this case, the points of the triangle are probably "Virus Scanning Frequently", "Users Not Impacted", and "Inexpensive Computers". You can optimize however you want in that triangle, but you're not going to get all 3 things.
You don't want to hear it, but I'd argue that a rethinking of your antivirus strategy is in order.
Answer: How about changing the scan time to 5:00 PM or whatever time the developers generally go home?  Alternatively, how about 12:00 PM, and the Devs all take lunch exactly at noon every Monday?  This assumes that the full scan is worse performance-wise than the Smart scan.
Comment: The are doing a lunch time scan, but they insist on doing a full scan on Mondays which take on the order of 4 hours, roughly.  I'm a java developer, so we have lots of jar files, that it tries to scan each file inside of.
Comment: @Nick I suggested the same in a comment below - but how about getting cable locks for the laptops, so they can be left in the building at night?  That should make them no more or less enticing than the desktops that are already sitting there.  Once you leave the laptops, the scans can be run overnight.
Answer: I've gone with a sort of combination of what the others here have said.
Our weekly Full scans run weekly on Monday's at 3 AM. They should be long done before anyone shows up to start the week.
As for the on-access scan, configure the AV client to ignore the directory structure containing the source code. If the client is also scanning network shares -and- your file servers are also running AV, be sure to exclude share scanning from the clients as well.
Comment: Thanks for the suggestion, however, the company policy requires us to take the laptops with us at close of business, because we work in cubes.  We've thrown around the idea of getting desktops, which I believe someone else mentioned.
Comment: How about cable locks for the laptops?
Answer: I'd suggest some really fast SSDs to alleviate some of the seek overhead from the scans.  Obviously, this would help even more if you could exclude your dev folders from the scan (though I bet IT policy won't allow that).
Answer: The last time a virus nuked my Windows system at work (completely in spite of our antivirus, I might add!), I switched to Ubuntu. It mostly works well and considering that I'm a Unix sysadmin it's well suited to me. Ubuntu comes with a free SSH client and a terminal program that uses tabs for the multiple remote logins I have going at any given moment in time. That, plus some standard internet apps, basic word processing, and Kdevelop for a nice multi-language (including Java) IDE gets me by 90% of the time.
The first big, fat caveat comes from our database client, which neither has a Unix version, nor does it run under the WINE "emulator". This may happen to you. Try dual-booting Ubuntu on your work computer, or using your own laptop to experiment with. This is the only way of knowing if such a solution is right for you or any of the other developers where you work.
The other big, fat caveat is that Linux is NOT immune to viruses. It's not likely that you'll get infected, but it's entirely possible that you can get one through the network, especially if you're running an application and database server locally that is accessible from the network (one of several included firewall solutions would prevent this however). But it is certainly less prone to viruses, and its small market share means that Linux isn't a high priority target for virus writers, and infections are pretty rare. But then, so is the H1N1 Flu. It doesn't mean you have no reason to worry at all.
Answer: Why has nobody questioned the fact that the scans are running during developer work hours yet? Why can't they run overnight? Your problem is most certainly a people one, not a technology one.
Answer: First suggestion would be to switch to a desktop so the scans can be run while the developers aren't trying to work on the machines.
If that doesn't work, next would be to see if it is possible for the developers to remotely connect, over a VPN, to the network late Sunday night from home for a scan to run from say 12:01am Monday morning that should finish by the time they would need to disconnect the laptop from the remote network to bring it in to the office.  I'm not sure how well some of the corporate folks would like this idea but it would have the scans run on the schedule and the laptops are out of the office when the scan is done.


Using a neural network to learn to distinguish blurry images?

Question: Is it possible to train a neural network to detect whether an image is blurry or not?
I'm currently using synthetically blurred images to build the classifier. However, I'm worried that this approach is not valid as we are using synthetic images. What are the challenges of using an approach like this?
Comment: The term of art you're looking for is super-resolution imaging.
Answer: Using synthetically generated images to build the classifier and then applying the classifier to real world images means that there is a high risk of the build data set and the production data set not having the same distribution (i.e. statistical properties), and that is a bad idea. You always want your build data set and your production data set to come from the same distribution.
Using synthetic data is good for proof of concept, but not for building the production version of your classifier.
Answer: 'Is it possible to train a NN to detect...' - stop right there, the answer is always 'Yes.'. At least theoretically - so says the Universal Approximation Theorem. It's not a question of if you can do it, but finding out how to do it well and without burning through ten GPUs a day.
Enough being obtuse though; it's practically doable as well. You most likely want some kind of adversarial-style setup - train a recognition network to recognize a sharp image as true and the synthetically blurred one as a fake.
You could attach it to a generator network that blurs real images to more or less get an arbitrarily large training set. Really quite similar to a VAE-GAN, except you want to extract the discriminator from the GAN component.
Comment: Why should it be framed as a GAN problem? Couldn't it be just framed as supervised binary classification?
Comment: It's only GANnish if you're including the automated blurring process as part of the architecture. And I'd call it more of an analogy/proof-of-concept - VAEs are often blurry, VAE-GANs are not blurry where it matters, ergo there are networks (GAN discriminators in VAEGANs) capable of smartly recognizing blurriness.
Comment: The first statement should be clarified: NNs can theoretically approximate any function. However, the real issue is whether the function is captured in the data. What if I want to predict from an image the name of the person who took the photo? No chance.
Comment: True. I've actually deliberately added 'detect' in the quote above to account for that as it implies there is *something detectable* in the data.
Comment: It's been shown to be practically impossible to get a neural net to add two numbers, so I'm not convinced of the UAT argument.
Comment: Was it now? If you're going off of Minsky's example, that a) is only definitely true for non-deep networks, and b) not only he knew that, but he mentioned that *in the very same book*. RNNs not only can be trained to add, I've heard a claim they were *Turing-complete*.


Problema em retornar Struct em C

Question: Estou fazendo um programa simples em C que recebe nome,matricula e duas notas dos alunos porém ao retornar o valor digitado do struct na funçao Mostrar ele não retorna nada
#include <stdio.h>

#define N  2

typedef struct {
  char nome[30];
  int matricula;
  float nota1;
  float nota2;
} Aluno;

void Mostrar(Aluno a) {
  printf("%s\n","teste");
  printf("nome = %s\n",a.nome);
  printf("matricula = %d\n",a.matricula);
  printf("nota = %f\n",a.nota1);
  printf("nota2 = %f\n",a.nota2);
}

int main() {
  Aluno a;
  Aluno alunos[N];
  int i;

  for (i = 0; i < N; i++) {

    printf("Digite o nome do aluno");
    fflush(stdin);
    gets(alunos[i].nome);

    printf("Digite a matricula do aluno");
    scanf("%d", &alunos[i].matricula);

    printf("Digite a nota 1 do aluno");
    scanf("%f", &alunos[i].nota1);

    printf("Digite a nota 2 do aluno");
    scanf("%f", &alunos[i].nota2);
  }

  Mostrar(alunos[N]);

  return 0;
}

Answer: Uma coisa não use a função gets,  gets é do mal. Prefira scanf.
Outra coisa você declarou alunos como um vetor de dois elementos, alunos[0] e alunos[1]. Só que no seu código você estava tentando exibir alunos[N] que é o mesmo que alunos[2] que não existe.
O que fiz foi trocar o gets por scanf e mostrar o valor de alunos[0] e alunos[1].
    int main() {
        Aluno a;
        Aluno alunos[N];
        int i;

        for(i=0;i < N; i++) {
            printf("Digite o nome do aluno");

            // Modifiquei aqui.
            scanf("%s",&alunos[i].nome);

            printf("Digite a matricula do aluno");
            scanf("%d",&alunos[i].matricula);

            printf("Digite a nota 1 do aluno");
            scanf("%f", &alunos[i].nota1);

            printf("Digite a nota 2 do aluno");
            scanf("%f",&alunos[i].nota2);

        }

        // Modifiquei aqui.
        Mostrar(alunos[0]);
        Mostrar(alunos[1]);

        //Ou então pode usar essa sintaxe. Para usar comente as duas utimas linhas e descomente a próxima linha.
        //for(int i=0; i < N; i++) { Mostrar(alunos[i]);}

        return 0;
    }

Comment: True, muito obrigado , poRÉM se meu vetor tivesse tamanho 10, teria que escrever 10 vezes o alunos[0],alunos[1] e etc? Ou tem outro jeito de pegar todas as posições do vetor? Porque eu tentei alunos[N] e nao consegui
Comment: o normal no caso de passar uma estrutura para uma função é usar a passagem por referência; assim, a declaração da função "Mostrar" ficaria `Mostrar(Aluno*)`, e a chamada seria `Mostrar(&alunos[0])`, ou `Mostrar(&alunos[i])`, etc
Comment: Use um laço for: `for(int i=0; i < N; i++)  { Mostrar(alunos[i]);}`
Comment: @zentrunix: Isso. Se quiser editar a resposta fique a vontade.

Problema em retornar Struct em C


How to force Windows Server 2008 R2's SMTP server to generate NDRs for non-existing local users?

Question: I have a Windows Server 2008 R2 server with the SMTP service enabled, which provides mail relay to another server for some applications.
Sometimes, a message comes in with a wrong "To:" address, consisting of only a single word without a SMTP suffix, i.e. someone instead of email@example.com.
When this happens, the server treats the message as being addressed to its own fake local domain, i.e. email@example.com, and drops it into its "Drop" folder.
There is, of course, no user named someone on the server, and that address is obviously invalid; and yet, the server still drops the message there, instead of sending a NDR because someone without any domain suffix is not a valid SMTP address.
How can I force this server to send a NDR when such a message is received?
Answer: It looks like the behaviour you describe is default for the SMTP service in IIS and can't be changed:
http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/6bb0d71f-d3d7-4f59-aa01-4d5c022274a4.mspx?mfr=true
Answer: Rather than add an additional somedomain.com domain in the SMTP configuration, you should just have editing the default domain and changed it to somedomain.com. There's no reason why you need to leave the default domain as it is. You might even be able to delete it, just leaving the one you created.
Comment: Ah, I see what you're getting at. It looks like the behaviour you describe is default for the SMTP service in IIS and can't be changed:

 http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/6bb0d71f-d3d7-4f59-aa01-4d5c022274a4.mspx?mfr=true
Comment: The server is handling relay for *all* Internet domains, and as such it doesn't have one or more destination domains, but only a global smart host. The defaul domain is there only because the server created it automatically and won't let me delete it.
Comment: Looks like you're right. If you post it as an answer (or edit this one), I'm going to accept it.
Answer: If the SMTP service is accepting recipient addresses without a domain part, it is doing so in violation of RFC 2822 Section 3.4.1. In this case, the server should not send an NDR but reject the RCPT TO: command right away due to a malformed recipient address.
You might consider opening a support case with Microsoft PSS on this to get it fixed.
Comment: @Massimo no, I am not. I've referred to the wrong specs - RCPT TO syntax is [defined in 2821](http://tools.ietf.org/html/rfc2821#section-126.96.36.199) and seems to allow specifying the local address part only, although frankly I cannot see any use for it and it has not been allowed in the original SMTP RFC 821.
Comment: Are you sure this is a RFC violation? Because this is Windows Server 2008 R2, and as IIS's SMTP server component has been around for *quite* a while, I'd guess it has always behaved this way...


super prefix in Swift

Question: So total noob to Swift/programming so excuse the seemingly obvious question;
Could someone explain to me the functionality of the super prefix?
Does it allow for the override to retain the functionality of the parent class?
The tutorial I am working on tells me its used to let the parent class know when the child class is called? Not sure i fully understand this.
Thanks in advance for the help!
import UIKit

class ViewController: UITableViewController {
    var pictures = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()

        let fm = FileManager.default
        let path = Bundle.main.resourcePath!
        let items = try! fm.contentsOfDirectory(atPath: path)

        for item in items {
            if item.hasPrefix("nssl") {
                pictures.append(item)
            }
        }
    }
}

Comment: Share link to this tutorial.
Comment: "Does it allow for the override to retain the functionality of the parent class" ... Yes.
Answer: Imagine that UITableViewController did some stuff in viewDidLoad that was necessary for its operation, much like how your view controller does. When you override the inherited method, yours gets called instead of the super class's. Now you have a chance to do your initialization, but you've deprived the super class of the opportunity to do its initialization.
To remedy this, you would call the super implementation yourself. A lot of UIKit view cycle methods (view(Will|Did)(Load|Layout|Appear)) don't strictly need to be called, because the super class implementations do nothing, but some do. Omitting them could lead to funky results, hence why it's usually good practice to make a habit out of calling the super class implementations of such methods.
Comment: Thanks! I suspected as much.

super prefix in Swift


Using localstorage.clear() but exclude 1 item

Question: I have a lot of items in localstorage, and I want to clear them all...except 1 item, we'll call it "X".
Is there a way to call localstorage.clear() but exclude X?
Answer: Store the value you'd like to keep in another variable, then use localStorage.clear()
Example:
var myItem = localStorage.getItem('key');
localStorage.clear();
localStorage.setItem('key',myItem);

Example was taken from this SO post.
Comment: ... and of course add the variable back to the localStorage once you've cleared it.
Comment: Thank you! Good idea, quality post.


Google Maps Directions List Jquery Mobile/HTML5

Question: I have the start and end cordinates stored on client device with HTML5 localstorage.To diplay him the route between start and end i have to use google maps driving list(not a map..just the directions in text format) The application is in jquery mobile.

can i add that driving list in my listview with id myList?
 function gotDirections(geo){
        var directionsService = new google.maps.DirectionsService();
        var directionsDisplay = new google.maps.DirectionsRenderer();
        directionsDisplay.setPanel(document.getElementById("myList"));
        var storedlati=localStorage.getItem("text1");
        var storedlongi=localStorage.getItem("text");
        var destilati=localStorage.getItem("text2");
        var destilongi=localStorage.getItem("text3");
        var request = {
            origin:google.maps.LatLng(storedlati,storedlongi),
            destination:google.maps.LatLng(destilati,destilongi),
            travelMode: google.maps.TravelMode.DRIVING
        };
        directionsService.route(request, function(result, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                directionsDisplay.setDirections(result);
            }
        });

    }

Comment: What is "google maps driving list"?  Is it just the content of the panel you want (like [this](http://www.geocodezip.com/v3_GoogleEx_directions-draggableA.html) but without the map)?  Or is there something additional?
Comment: i want the list on the right on the link you gave :)
Answer: In that case, just set the directions panel on the directionsRenderer, not the map; and don't create the map. Like this Example
Comment: As you can see from the code i have given above i have set it to directionsRenderer only var directionsDisplay = new google.maps.DirectionsRenderer();
        directionsDisplay.setPanel(document.getElementById("myList"));
Comment: Then perhaps a link to a live version of yours would be helpful.  The one I posted works.


How do I transition from a classical education to a jazz education in piano and theory?

Question: I've been learning piano theory from a classical standpoint on-and-off for about 8 years of my life, and I feel as though I haven't gotten anywhere.
I compose and improvise in my spare time, but I have little to no education and I feel as though I play the same things over and over again, due to the fact that I know nothing of chord progressions and/or improvisational techniques.
I have an appointment with a jazz teacher tomorrow, but I'd very much appreciate any tips and such on how to transition and grow, please! I'd still like to pursue composing and improvisational piano, thanks!
Comment: It's nearly a year on now.  How did the lessons go?  What would YOU now tell us are the differences between classical and jazz?
Answer: The first tip I can offer is to listen to the teacher you're seeing tomorrow!
But remember, theory is a set of descriptions, not a set of instructions.  Work from the music. Listen, imitate, then (if you like) analyse.
Comment: The best way to learn jazz is to listen, apply, then analyze. Once you can analyze while listening, you've already done a big step. +1


Inserting data to a CLOB type in oracle

Question: i have created a table
create table test_clob(
  value clob
);

if i try to do an insert on this table with the data size grater than 4000 bytes i get following error
SQL Error: ORA-01704: string literal too long
01704. 00000 -  "string literal too long"
*Cause:    The string literal is longer than 4000 characters.
*Action:   Use a string literal of at most 4000 characters.
           Longer values may only be entered using bind variables.

I don't how to use the bind variables...
Comment: How are you trying to insert the data?  What language/ API are you using to interact with the database?  Where is the data itself coming from?
Comment: well i was just experimenting it on sql developer
Comment: is there a way to do it using sql
Comment: Using plain SQL with string literals?  No, not really.  You can use PL/SQL and the `DBMS_LOB` package.
Comment: eventually i will be using it in PL-sql ,, thanks justin
Answer: You can use to_clob function to insert large text  in oracle database.
Example like:String have more then 4000 char.then
use query:
insert into tableName(fieldName)values(to_clob('charCount=>4000')||to_clob('after 4000 char but not more  then 4000'));
Ex: if I have 6000 char then 4000 in first to_clob and next 2000 char next to_clob:
Answer: TO_CLOB converts NCLOB values in a LOB column or other character strings to CLOB values. char can be any of the data types CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. Here is the Oracle official documentation about TO_CLOB. To insert the data into CLOB column, use the below query.
insert into tableName(
    column_name
) values (
    to_clob('charCount=>4000') || to_clob('after 4000 char but not more then 4000')
);

Inserting data to a CLOB type in oracle


Enable all languages for multilingual site

Question: I notice I can add languages one by one on this page
mysite.com/admin/config/regional/language/add
Is there an easy way for adding all languages?
Maybe there is a command with drush?
Answer: No - there is no drush command for this and you would want to do this one by one because you're going to need to upload your specific po translation files from Drupal.org (one reason its not practical to make this an option with the base install for n languages)


drop table com tabela temporária dando erro

Question: qryCIDtemp.SQL.Text := 'drop table if exists #tempCID';  //apaga a tabelas temporária

O Delphi me retorna a seguinte mensagem em tempo de execução:

Invalid use of keyword
Token: if
Line Number: 1.

Se alguém puder me ajudar fico muito grata.
EDIT:
Teste com a sugestão da resposta abaixo:
Fiz como sugeriu:
 qryCIDtemp.SQL.Text := 'if object_id('#tempCID','U') Is not null drop table #tempCID'; //apaga a tabelas temporária

e também não funcionou. Agora o erro é de compilação. o delphi me retorna:

Missing operator or semicolon. Statement expected, but expression of
  type 'String' found.

Tem outra ideia?
Comment: Tente: `IF OBJECT_ID('#tempCID') IS NOT NULL DROP TABLE #tempCID`
Comment: As mensagens de erro não foram retornadas pelo SQL Server mas sim pelo Delphi.
Answer: Você precisa usar o comando:
IF OBJECT_ID('#tempCID') IS NOT NULL DROP TABLE #tempCID

Porém, para que isto funcione no Delphi, você precisa utilizar a seguinte String, escapando as aspas simples com outra aspa simples ':
 qryCIDtemp.SQL.Text := 'IF OBJECT_ID(''#tempCID'') IS NOT NULL DROP TABLE #tempCID';

Answer: Essa sintaxe if exists pode não funcionar no SQL-Server, é uma sintaxe nova a partir do SQL SERVER 2016, você pode fazer assim:
IF OBJECT_ID('#tempCID', 'U') IS NOT NULL DROP TABLE #tempCID

OBJECT_ID é uma função que torna o id de um objeto, e caso seu retorno seja null, o objeto (tabela no caso) não existe, por isso o IS NOT NULL
Comment: também não funcionou.
Comment: retorna algum erro? Como você está executando o comando? não aparece essa parte no seu código
Comment: Seu problema deve ser as aspas, tem que colocar duplas aspas assim: `'IF OBJECT_ID(''#tempCID'') IS NOT NULL DROP TABLE #tempCID'`
Answer: Na função OBJECT_ID, para tabelas temporárias é necessário sempre citar o nome do banco de dados tempDB:
-- código #1
IF Object_ID(N'tempDB..#tempCID', N'U') is not null
  DROP TABLE #tempCID;

Ao encapsular o comando acima no programa em Delphi fique atenta aos apóstrofos:
qryCIDtemp.SQL.Text := 'IF Object_ID(N''tempDB..#tempCID'', N''U'') is not null DROP TABLE #tempCID';


Pressing keys by python not working at all(win7)

Question: I tried using WScript.Shell and
shell.SendKeys('w'), tried using pyautogui.KeyDown/KeyUp or just win32 features, but none of them pressing anything. I had the same problem on win10, but I fixed it somehow, any ideas?
Answer: By the way, it is working using win32api.keybd_event() directly, but let me now if you know, why win32 shell and pyautogui is not.


What HTML Editor Should I Use?

Question: I'm a college student and have taken several web development and web design courses.  Over the last few years I have used the following:
PHPStorm
Visual Studio Code
Notepad++
SublimeText3
Atom
Amongst all of those, I don't really have a preference.  I lean towards Jetbrains since as a student I get full access via student license.  But those other editors/IDE's work fine too.  If you were in my shoes which would you opt to use more frequently?
Comment: This question is either too broad, opinion based or requires discussion and so is not suitable for Stack Overflow. If you have a specific, answerable, programming issue, please provide full details.
Answer: I'm a front-end developer, I mostly use VScode it's powerful with lots of features. You can customize it as per your needs.
It has a huge library of extensions which are really handy.
I think VScode is best for web developers. Whatsoever.

What HTML Editor Should I Use?


How to identify email without orignal envelop id

Question: I am using Office 365 as email server.
I have already checked my server supports Dsn
I have implemented code in given in example.
Problem is that "Original-Envelope-Id" is always null.
I am sending unique Message id while sending through mailkit smtp client and receiving through imap client.
Is there some alternative to check message id of delivery notification email.
Like sending some headers which I can receive in delivery email.
ASP.NET MailKit SMTP response
Comment: Can you provide a sample delivery status notification email that has a null Original-Envelope-Id? There are, afaik, no other headers that you can check or set.
Comment: I have emailed you email logs of smtp and imap
Answer: It looks like the delivery agent in your case decided to attach a text/rfc822-headers MIME part to the message instead of specifying the Original-Envelope-Id in the message/delivery-status MIME part content.
What you need to do is locate the TextRfc822Headers mime part and then check the headers.Message.MessageId property instead.


Remainder when dividing by 990: Chinese Remainder Theorem

Question: What is the remainder when the number
$101102103104105...996997998$
is divided by 990?
(The digits of the number are just the digits of all the integers from 101
to 998 inclusive, written side-by-side.)
I think I would have to use chinese remainder theorem and factor 990.
990= $2$$\cdot$$3^2$$\cdot$$5$$\cdot$$11$
Do I just create a system of 4 modular equations with different modulos as the factors listed above?
Comment: I wouldn't bother with $2$ and $5$, instead doing $10$, and doing that just by writing down the answer.
Answer: First, note that $1000\cong 10\pmod{990}$. Then, $$1000^2\cong 100\pmod{990}$$ so $$1000^3\cong 1000\cong 10\pmod{990}$$ We can show by an easy induction that $1000^k\cong 10\pmod{990}$ if $k$ is odd, and $1000^k\cong 100\pmod{990}$ if $k$ is even (both for $k\geq 1$). Then, the number in question, which we can rewrite as $$\sum_{k=0}^{897} (998-k)1000^k = 998+\sum_{i=0}^{448} (997-2k)1000^{2i+1}+\sum_{j=0}^{447} (996-2k)1000^{2j+2}$$ is congruent to $$998+\sum_{i=0}^{448} 10(997-2k)+\sum_{j=0}^{447} 100(996-2k) \\ = 998+10(448+1)(997-448)+100(447+1)(996-447) \\ = 998+10\cdot 449\cdot 549+100\cdot 448\cdot 549$$ We can calculate the remaining modular division by hand to find that this is congruent to $548\pmod{990}$.
Comment: Note that dividing the number mod $11$ or mod $99$ is about as complex as dividing it mod $990$, since you are still left with sums that look like the ones above. Therefore, I believe that the Chinese remainder theorem does not make this problem simpler.
Comment: Can we use the CRT? If we let this number=x then we get three congruences. $x \equiv k mod 10$, $x \equiv k mod 9$, $x \equiv k mod 11$. We then solve for k
Comment: Sure, but calculating $k$ divided by $11$ is by itself almost as complicated as calculating it divided by $990$ (in consideration of the fact that we will have a sum similar to the above). I don't see CRT as making this problem simpler.


Not able to run my selenium script in parallel from code deployed on remote server

Question: From local machine  i am able to run my selenium script in parallel on local selenium grid but scripts are not running when running from code deployed on remote server.
I was trying to run multiple selenium scripts in parallel on local selenium grid. The scripts work fine when I trigger the scripts from my local machine but when I deploy the same code on a remote server and trigger the scripts the scripts are failing.
Comment: You should insert an error message / stacktrace then, so we can help better.
Comment: And probably you should show the code. You have to make the problem reproducible, otherwise it's usually hard to help
Comment: Expalin properly
at least the Error
Comment: When I deploy the code on a remote server and try to run the scripts in parallel the scripts are working in some browsers and get stuck in others. I am using RemoteWebDriver.
Comment: DesiredCapabilities cap = DesiredCapabilities.firefox();

   cap.setCapability("browser", "Firefox");
   cap.setCapability("browser_version", "42.0");
   cap.setCapability("os", "Windows");
   cap.setCapability("os_version", "7");
   cap.setCapability("resolution", "1024x768");
   cap.setCapability("browserstack.debug", "true");
   cap.setCapability("browserstack.local", "true");
   //          cap.setBrowserName("firefox");
   //          cap.setPlatform(Platform.WINDOWS);
   driver = new RemoteWebDriver(new URL("http://22.214.171.124:4444/wd/hub"), cap);
  }
Answer: You Should use RemoteWebDriver and not WebDriver the difference is WebDriver works on local machine but when you execute your application from a distant machine you need to use RemoteWebDriver


recompress .gz file without unzipping to a temp file first

Question: I have test.gz file that I wish to recompress(using better compression ratio):

  gunzip test.gz
  gzip -8 test

can this be done?
Comment: This doesn't really seem like a programming question.
Answer: You can pipe the output of the first one into the second one, e.g.
gzip -cd test.gz |gzip -9vv > test-recompressed.gz

Note that you'll have to recompress to a separate new file I think.
Also higher gzip numbers don't really give much benefit for a lot of compute time, so this may not be worthwhile. If you really need better compression try xz which is widely supported nowadays.
Comment: Yes, you certainly need need to recompress to a new file, since if you tried `> test.gz`, then `test.gz` would be immediately deleted and recreated by the `>` before the commands are even run.
Comment: Ah, right - thanks. I wondered if the first gzip might get the inode reference before that happened but you're right, the shell would get there first. In either case you wouldn't save space on disk.
Comment: @Rup: will this work on .tar.gz file also?  I noticed that the resulting .tar.gz file is smaller
Comment: Yes, this will work for any gzipped data, tar or not.
Answer: It could be done by:
tar -cvf files.tar /path/to/file0 /path/to/file1 ; gzip -9 files.tar

Or you could use:
tar cvf - /path/to/file0 /path/to/file1 | gzip -9 - > files.tar.gz


What is IOptions in AspNetCore Identity 2.0?

Question: I am trying to understand how Identity comes together. I would like to implement Dapper instead of Entity Framework, but I feel in order for me to be able to support in future I need to understand what is going on.
As such I downloaded the 2.0.0 release from Identity Repository here: https://github.com/aspnet/Identity/releases and started looking around.
The part that I am stuck on right now is IOptions<IdentityOptions> that is required to be passed in by UserManager. Looking at the IdentityOptions class itself, I understand that those are configurations for things such as PasswordOptions and etc. So I need to instantiate and set those up and then bind them.
However, the part that I don't understand is IOptions interface. It seems to be a wrapper, but why is it there, what is the purpose of it? Why not just create IdentityOptions on its own, why does it needs to be wrapped inside the IOptions interface?
Comment: documentation https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration#using-options-and-configuration-objects
Answer: As I understand it, IOptions is the interface to retrieve any configured object and its underlying properties. For example, you have multiple Options objects under IdentityOptions class. Instead of instantiating them all, one by one, you would plug your IdentityOptions into DI pipeline by adding your options class into service collection object. This way you can call access any of the Options object (from IdentityOptions class) anywhere through constructor injection.
The point to remember is that all "Options" objects under IdentityOptions are itself classes. So to avoid all manual instantiating, you can use DI pipeline by wrapping IOptions around your Options class.
hope this helps.


If $G'/G''$ and $G''/G'''$ are cyclic then $G''=G'''$

Question: Prove that, if $G'/G''$ and $G''/G'''$ are both cyclic then $G''=G'''$.
I was expecting this proof would be similar to the proof of

$$G/Z(G)~~~~ \text{is cyclic} \Rightarrow G~~~ \text{is abelian}$$

I tried in that way but i could reach nowhere.
Any help would be appreciated.
Thank You.
Comment: Well, I've seen $K(G)$, $[G,G]$ and $G'$ for the commutator subgroup. Possibly some I've forgotten.
Comment: This is trickier than I expected. Notice that it does not work with $G/G'$ and $G'/G''$, as with $G=S_4$ we get $G'=A_4$ and $G''=V_4$, so $G/G'\cong C_2$, $G'/G''\cong C_3$ but $G/G''\cong S_3$. It has to be used in the proof that the top group is already a commutator subgroup of something.
Comment: Is $G'$ the commutator subgroup of $G$?
Comment: @Babak S : Thanks for Your Edit. :) COuld you please give some hint regarding this problem.
Comment: @DanielFischer Yes, Yes. $G'$ is commutator subgroup of $G$. I was expecting that it is standard Notation.So, did not mention it
Comment: @JyrkiLahtonen Yes Yes. I have no hope. I tried to confirm myself by some example but it is getting more complicated :(
Answer: By the third isomorphism theorem, we may as well assume that $G''' = 1$.
So we are given that $G'/G''$ and $G''/G''' = G''$ are cyclic, and we want to show that $G'' = 1$, or rather that $G'$ is abelian.
We will use the fact that for a subgroup $H$ of $G$, the quotient $N_G(H)/C_G(H)$ is isomorphic to a subgroup of $\operatorname{Aut}(H)$.
Since $G''$ is normal, we have $G = N_G(G'')$.
Then by the fact we just mentioned, $G/C_G(G'')$ is isomorphic to a subgroup of $\operatorname{Aut}(G'')$.
But $G''$ is cyclic, so $\operatorname{Aut}(G'')$ is an abelian group.
Thus $G/C_G(G'')$ is abelian, and so $G' \subset C_G(G'')$.
But this means that $G'' \subset Z(G')$.
From here the proof follows from the fact

$$ N \subset Z(G), ~ G/N ~~ \text{cyclic} \Rightarrow G~~ \text{is abelian} ,$$

the proof of which is basically the same as the proof of the fact about $G/Z(G)$ you mentioned.
Comment: All terms in the derived series are characteristic and hence normal in $G$.
Comment: May I know why we can just assume $G'''=1$?
Comment: Can the third isomorphism theorem be applied? Is $G'''$ necessarily normal in $G'$?
Comment: Good to know, @DerekHolt.
Answer: Exercise~4.4.10 verifies action by conjugation of $G/G^{\prime\prime}$ on the cyclic group $G^{\prime\prime}$. Observe that the kernel of the associated homomorphism into the abelian group $\text{Aut}\left(G^{\prime\prime}\right)$ (see Proposition~4.4.16) is $Z\left(G\right)/G^{\prime\prime}$ and $\left(G/G^{\prime\prime}\right)/\left(Z\left(G\right)/G^{\prime\prime}\right)\cong G/Z\left(G\right)$ is isomorphic to an abelian subgroup of $\text{Aut}\left(G^{\prime\prime}\right)$. Then $G^{\prime}/Z\left(G\right)\leq\left(G/Z\left(G\right)\right)^{\prime}=Z\left(G\right)$ so the complete preimage of $G^{\prime}/Z\left(G\right)$ is $G^{\prime}=Z\left(G\right)$. It follows that $G^{\prime\prime}=1=G^{\prime\prime\prime}$.
Consider a group $K$ so $K^{\prime}/K^{\prime\prime}$ and $K^{\prime\prime}/K^{\prime\prime\prime}$ are cyclic, and $K^{\prime\prime\prime}$ is non-trivial. Then $G=K/K^{\prime\prime\prime}$ satisfies the hypotheses $G^{\prime}/G^{\prime\prime}$ and $G^{\prime\prime}$ are cyclic, and $G^{\prime\prime\prime}=1$. That is, $1=G^{\prime\prime}=K^{\prime\prime}/K^{\prime\prime\prime}$ so $K^{\prime\prime}=K^{\prime\prime\prime}$. Thus the result.
References to Dummit and Foote, Abstract Algebra, 3rd Ed.


How do I programmatically test if it's possible to connect to the X server specified in $DISPLAY

Question: This is a bit of a middle-ground between programming and server-admin, but this seems ultimately the most relevant place for it.
I'm looking for a way to determine if the variable '$DISPLAY' is advertising an XServer we can actually connect to, that is, if all the authentication and whatnot is in place to permit further things to execute.
I'm ideally looking for something shell-end tool that returns true/false, which can be used in a build-script to determine if the other tests in it ( which I don't control ) should be run or not.
The tests at present simply check for the env variable "$DISPLAY", and if it's there, will try to connect, and when the connection doesn't work, the tests assume failure of the test, not simply the display is not connectible.
I just need to be able to do
if [[ ! can_connect_to_X ]] ; then
    unset DISPLAY
fi

In order to stop these tests having severe mental problems.
In an ideal situation, the tool required to do this should come provided with the X Client libraries itself, so as not to incur special dependencies, and to be able to assume if the utility is not there we can't connect to any display.
Answer: You can try with the xset command :
if [[ ! $(xset -q) ]]; then
   # the X server is not reachable
else
   # the X server is reachable
fi

Comment: Although I ended up using it in a more complex way, xset appears to be more likely installed than xdpyinfo.
Comment: http://git.overlays.gentoo.org/gitweb/?p=proj/perl-overlay.git;a=commitdiff;h=a6d565109aff334347e022c74593a409936dcb1a
Comment: `xset q 2> /dev/null >&2` to avoid any output
Answer: I am guessing there is a better solution.  But you can always just use a small tool like xclock and check the exit status.
if [[ ! xclock ]]; then
  exit 1
fi
pkill xclock

But man, that is ugly :-)
Less Hacky, put the following in checkX.c:
#include <X11/Xlib.h>
#include <stdio.h>

int main()
{
    Display *display;
    if( ! (display=XOpenDisplay(NULL) ) ) {
        return(1);
    }
    return 0;
}

Then:
gcc -lX11 checkX.c -o checkX
chmod +x checkX

Lastly:
if ./checkX; then
   echo "We are good to go!"
fi

Comment: Yeah, that is the first thing I considered, but I wanted something that didn't visually create a window :/. I even considered doing xclock& and then killing it.
Comment: xclock -geometry 1x1 is about the best I can do to eliminate visual intrusion :/, but it also allocates a task-space on the task bar :(
Comment: That is the first X program I have ever written in C, so, not sure if it is entirely reliable :-)
Comment: And not the most portable thing ;-)
Comment: That is pretty awesomely handy, just unfortunately, my constraints are somewhat tighter. Truth to be told, I'm writing an ebuild(gentoo), so I have to virtually do /everything/ in shell, and assume that apps will be there before hand and I cant just add binary blobs ahead of time to 3rd party apps :)
Answer: Heres a possible WayToDoIt, not sure how good it is though.
  x_works(){
     # If there is no xdpyinfo
     # Bash will return 127
     # If X cant connect, it returns 1
     # If X can connect, it returns 0
     xdpyinfo 1>/dev/null 2>&1
     WORKS="$?"
     return $WORKS
  }

  if x_works; then
   ...

This appears to be working.
Comment: On my Fedora 11 machine I'm getting:

$ xdpyinfo 1

usage:  xdpyinfo [options]

Anyway, I think that it sounds like a good idea to use the xdpyinfo program.
Comment: the '1' there is stderr redirect for bash ;) , not a xdpyinfo param :)


Using media query inside a CSS in the "@media" expression

Question: I read in manual that is possible to use CSS media query like:
<link href="mypdf.css" type="text/css" rel="stylesheet" media="mpdf" />

but I need to use it inside a unique CSS stylesheet, using media query. Actually, @media screen and @media print are working, but seems that mpdf is ignoring @media mpdf. I didn't find any example including this tag, so maybe I'm wrong and media query doesn't work that way in mPDF.
@media print { dl {  page-break-inside: avoid;  }    }
@media mpdf  { dl {  page-break-inside:inherit;     }    }

Moreover, we need to do this cause mPDF is duplicating content inside DL tags when using "page-break-inside: avoid;".
Please, any suggestions?
Thank you
Comment: There is no such media query to target mpdf only - it is third party plugin and as such not a web standard
Comment: Well, in fact that's the target. Only mPDF processor should interpret this CSS, as you can read here https://mpdf.github.io/real-life-examples/pdf-from-every-page-of-website.html
However, I need to do the same but inside an unique CSS file, and "@media mpdf" is being ignored .... so that's why asked about here.
Comment: So just link a new external stylesheet for your mpdf overrides and don't try to create a non-standard @media query
Comment: I must say mPDF is not a plugin, it's a PHP package that doesn't work with simultaneous media stylesheets. It need an UNIQUE block for CSS, so if I try to use various stylesheets, they must be appended to only one, so that's the need to use @media query.
Comment: As you've said it's external software that uses non standard techniques so either follow their techniques or write something yourself to parse the media queries you want, don't just expect it to work because you want it to
Comment: Well, I asked here looking for an expert in mpdf cause there are not enough documentation about media query in their site and I was doubting if I was missing some information and about if what I asked were possible. You answered me from a CSS/HTML expert point of view, but not really the knowledge I was looking for. So thanks anyway for your comments.
Comment: Does mPDF supports these page-break-inside tags in the way you like? The CSS support is limited (https://mpdf.github.io/css-stylesheets/supported-css.html) You could test with some simpler CSS whether the @media query is working.
Comment: Thank you Klap-in. I read that page before posting here, but as for sure you noticed, in that page doesn't seems page-break-inside were not supported by mPDF. The worst thing is that doesn't mention @media tag anywhere, so I finished here cause a mPDF member told me to ask here, instead of answer my question in github.com. Anyway, I take my time to try as you proposed, with a simpler CSS and making a "trial and error", I have no choices  ;)
Comment: After reading a lot more and driving me crazy about media query support in mPDF, I found this thread in their own forum at github ...
https://github.com/mpdf/mpdf/issues/758
That say it all. Documentation is not clear at this respect, so even who answered and closed at first time the issue doesn't know exactly how it works!!  :(
Answer: Could it be that you need to set the configuration variable CSSselectMedia to your media query name 'mpdf'.
// require composer autoload
require __DIR__ . '/vendor/autoload.php';
$mpdf = new \Mpdf\Mpdf();
$mpdf->CSSselectMedia = 'mpdf';
...

for more detail: https://mpdf.github.io/reference/mpdf-variables/cssselectmedia.html
The example from https://mpdf.github.io/real-life-examples/pdf-from-every-page-of-website.html is using it too.
Comment: Thank you!!! Very complete info and links. I'll try your recommendation (can't vote cause my reputation is <15)  , sorry


how to rotate a JFreeChart in iText pdf

Question: I have created a servlet to handle the save of a JFreeChart displayed in a JSP to a PDF file.
The code I am using so far is:
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jfree.chart.JFreeChart;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.DefaultFontMapper;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;

public class ChartPrintServlet extends HttpServlet {

    private static final long serialVersionUID = -2445101551756014281L;

    protected void doPost ( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        JFreeChart jFreeChart = (JFreeChart) request.getSession().getAttribute("jFreeChart");
        String url = "";
        int height = 1024;
        int width = 1152;

        if (jFreeChart == null)
        {
            url = "/do/error";
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
            dispatcher.forward(request, response);
        }
        else
        {

            AbsencesGanttChartPostProcessor postProc = new AbsencesGanttChartPostProcessor();
            postProc.processChart(jFreeChart, null);
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "attachment; filename=\"absences.pdf\"");
            OutputStream out = response.getOutputStream();

            try
            {
                Rectangle pagesize = new Rectangle(width, height);
                Document document = new Document(pagesize.rotate(), 30, 30, 30, 30);
                PdfWriter writer = PdfWriter.getInstance(document, out);
                document.open();
                PdfContentByte cb = writer.getDirectContent();
                PdfTemplate tp = cb.createTemplate(height, width);
                Graphics2D g2 = tp.createGraphics(height, width, new DefaultFontMapper());

                Rectangle2D r2D = new Rectangle2D.Double(0, 0, height, width);
                jFreeChart.draw(g2, r2D);
                g2.dispose();
                cb.addTemplate(tp, 0, 0);
                document.close();
            }
            catch (DocumentException de)
            {
                System.err.println(de.getMessage());
            }
            finally
            {
                out.close();
            }
        }
    }

    protected void doGet ( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        doPost(request, response);
    }
}

I have swapped the height and width everywhere in order to get the PDF to look half-decent, but what I really want is to be able to create a PDF as if it were in landscape mode.
If I try
Graphics2D g2 = tp.createGraphics(height, width, new DefaultFontMapper());
g2.rotate(90)

then the PDF just prints a white, blank page.
What is the correct way with the itext / Java awt APIs to go about rotating the entire document (including the JFreeChart underneath) when creating a PDF?
Comment: Pop the image in a dialog & I think you will discover the problem has nothing to do with PDF (i.e. the code is broken before that point).  For better help sooner, post an [SSCCE](http://sscce.org/) (that uses J2SE exclusively).
Answer: First this: your referring to my name in your code. I'd like you to use itextpdf instead. See http://lowagie.com/itext2
Now for your question. There's an easy way to achieve what you want, and there's a more difficult way.
You only use three parameters in this method: cb.addTemplate(tp, 0, 0); which means that you only want iText to do a translation (zero up, zero to the right). If you also want a rotation, you need to use the method with seven parameters, six of which define the transformation matrix. This is simple algebra; it's explained in my book "iText in Action", but most of the developers I know don't like doing math and they say this is the difficult way.
The easy way, is to wrap tp inside an Image object, and rotate the image:
Image img = Image.getInstance(tp);
img.setRotationDegrees(90);

There's also a setRotation() method that takes radians as a parameter.
Additional notes:

Don't worry about the Image class rasterizing your content. A PdfTemplate wrapped inside an Image object will result in a Form XObject, it won't be changed into an Image XObject.
Be careful not to rotate your image 'outside your page'. You may need to take into account the pivot point.
Comment: Thanks for the helpful comments, however the underlying image seems to be unchanged. I have pasted the modified code above with some screenshots
Comment: The missing items were part of [edit/2](http://stackoverflow.com/revisions/13864220/2), since [revised](http://stackoverflow.com/posts/13864220/revisions).
Comment: OK, I found them, but now the question is even less clear. The way I interpret that edit is: Bizmark creates a chart with a width or X and a height of Y. It seems that he wants the chart to be redrawn entirely when he rotates the chart. That doesn't make much sense, I'm inclined to downvote the question without further clarification.
Comment: Well, yes, I was looking for a way to redraw it, why else call rotate on the graphic? Essentially I would like the PDF to be created as if it were in landscape when the chart was originally displayed (in a browser) as portrait so the user does not have to print it in landscape or otherwise fiddle with the layout after opening the PDF.
Answer: You rotate your Graphics counterclockwise around the top left corner, and doing so moves everything out of the drawing area. This is why you just get the blank page. You need to apply translation also to shift graphics back into the painting area. Translate y downwards by the width of you image:
        g.rotate(Math.PI / 2);
        g.translate(0, width);

Also, Graphics2D.rotate expects radians, not degrees.
After that, JFreeChart should draw the transformed chart if you pass transformed Graphics2D for it.
Comment: That's probably because you rotated the image outside the visible area of the template. I think you would see the syntax to draw the chart if you opened the PDF in a tool that allows you to see the content stream.
Comment: translate by -width worked for me. Also remember if you are writing the rotated/translated image somewhere, you will have to switch the height and width dimensions.

how to rotate a JFreeChart in iText pdf


How to find where an input occurs within a list in python?

Question: I'm building a simple hangman game right now, and I want to be able to identify where in a list a user guesses a specific letter. For example, if the word list was [D,R,A,G,O,N] -- and the user guesses A, I want to be able to get a return that would say 4...this is my failed code so far
import random

word_list = ['red', 'better', 'white', 'orange', 'time']
hidden_list = []
selected_word = random.choice(word_list)
letters = len(selected_word)
selected_word_list = list(selected_word)
game_playing = True

print('My word has ' + str(letters) + ' letter(s).')

print(selected_word_list)

for i in selected_word_list:
    hidden_list.append('_')

while game_playing:
    print(hidden_list)
    guess = input('What letter do you want to guess?')
    if guess in selected_word_list:
        print('Nice guess!')
    else:
        print('Nope!')

Comment: you want index ? for A it should be 2 or 3 ?
Answer: # vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']

# index of i item is printed
for i in vowels:
    print('The index of:', i+" "+str(vowels.index(i)))

Answer: You can use the index function of  a list
e.g.
>>> word_list.index('white')
2

But if the guess is not in the list, you will get a ValueError. You need to handle this exception.
Comment: This is what I was looking for! Thanks for your help.
Comment: Happy to help. Please upvote and accept the answer!
Answer: A faster alternative to list.index is you could construct a dictionary of letter: index pairs using enumerate:
yourlist = list('DRAGON')
yourdict = {letter: idx for idx, letter in enumerate(yourlist)}

guess = input('What letter do you want to guess?')
result = yourdict.get(guess.strip()) # Avoids KeyError on missing letters

if result is not None:
    print("You got it!", result)
else:
    print("Nope!")

For short lists, list.index is completely fine and you won't notice the performance gain of the dict, but for really long lists, it makes a difference:
Short List

list

python -m timeit -s 'x = list(range(50))' 'x.index(49)'
1000000 loops, best of 3: 0.584 usec per loop

dict

python -m timeit -s 'x = dict(enumerate(list(range(50))))' 'x.get(49)'
10000000 loops, best of 3: 0.0733 usec per loop

# at this level, you really won't notice the difference on a GHz processor

Long list

list

python -m timeit -s 'x = list(range(500000))' 'x.index(490000)'
100 loops, best of 3: 4.91 msec per loop

dict

python -m timeit -s 'x = dict(enumerate(list(range(500000))))' 'x.get(490000)'
10000000 loops, best of 3: 0.0884 usec per loop

Note that for large numbers of items, dict scales really well


Erro: The requested client requires the gRPC extension | gRPC + App Engine + Firestorm

Question: Bom dia, estou desenvolvendo uma aplicação que vai receber dados via post e vai inserir em um banco de dados firebase/firestore, local eu consegui fazer rodar com sucesso, mas quando subo para o ambiente do google (App Engine) ele da o seguinte erro.
Fatal error: Uncaught Google\Cloud\Core\Exception\GoogleException: The requested client requires the gRPC extension. Please see https://cloud.google.com/php/grpc for installation instructions. in /srv/vendor/google/cloud/Core/src/ClientTrait.php:75 Stack trace: #0 /srv/vendor/google/cloud/Firestore/src/FirestoreClient.php(137): Google\Cloud\Firestore\FirestoreClient->requireGrpc() #1 /srv/index.php(11): Google\Cloud\Firestore\FirestoreClient->__construct(Array) #2 {main} thrown in /srv/vendor/google/cloud/Core/src/ClientTrait.php on line 75

Eu consegui instalar a gRPC local mas não encontro como habilitar lá no meu app engine.
Se alguém tiver uma luz...
desde já agradeço!
Answer: Create a php.ini file in se same place of your index.php file exist and add this code inside of php.ini:
; enable the gRPC extension
extension=grpc.so
; for debugging purposes only
display_errors=On


Applied JS to Drupal theme doesn't work correctly, but it works fine outside Drupal

Question: Applied this JS http://jsfiddle.net/tbq8eo8b/10/ to webforms. As you can see in fiddle, it calculates total amount. When in Drupal, it gives 0 no matter what amounts you select, it always prints 0. What's wrong?
Drupal code:
(function ($) {
Drupal.behaviors.bartik = {
attach: function(context, settings) {

/*Add your js code here*/
    var $selects = $("select").change(function (e) {
        var total = 0;
        $selects.each(function() {
            var val = this.value.match(/\$(\d+)/);
            total += val ? +val[1] : 0;
        });
        $(".total").val(total);
    });

}

};
}(jQuery));

Also console prints:
TypeError: $ is not a function
$("select").change(function ()

Comment: Try changing `Drupal.behaviors.bartik` with `Drupal.behaviors.something_unique`. You sure there is an input field with `total` class? Also, you will need to use more precise selectors.
Comment: First thing, it should be `$("select", context)` as your top-level selector. Second thing, are you sure it is run after form is ready and prepared? Third thing: How you debugged it? Does it find selects at all? Are select's values in the format you expect them to be? and so on...
Comment: I changed it, but same. Under input.total it still prints 0.
Comment: What about questions from my comment? Have you tested these things?
Comment: I applied the context part. Still same. It prints 0 in the input that has class .total Also updated question with Console errors. Thanks for helping.
Comment: Try removing `$` before select variable in `var $select` and `$selects.each(function() {` as there is no need to add `$` before variables in javascript, also as you are using `$` for jQuery so may be adding before variable is causing problem.
Comment: I updated the thread. The errors are gone now. Thanks for helping though.
Comment: Please don't hide the information that was needed to answer this question. Answer works, to some extent at least, so give future users a chance to benefit from it, too.
Answer: }(jQuery));

should be
})(jQuery);

in your last line of code.
Comment: Yes, I already fixed that, didn't change anything though.
Comment: @OptimusPrime At least it will remove the console error *$ is not a function* and your script will be executed at all. Please don't [chameleon](http://meta.stackexchange.com/q/43478/225745) your question now.
Comment: No, error is still there and same.
Comment: @OptimusPrime are you sure your browser refreshed js files?
Comment: I'm sorry. You were right, the errors are gone, But it still prints zeros, but in the jsfiddle the script works fine. What is Drupal preventing from working it right? Why it still prints zeros instead of total amount? Thanks for helping.
Comment: @OptimusPrime I think now it's time for you to ask a follow-up question. Your script changed, it started to run, so it is significantly improved :) Try to find an answer to **"Does it find selects at all? Are select's values in the format you expect them to be?"** and ask new question - then we will be able to help you further.
Comment: It will be basically a duplicate question then. If it wouldn't find selects it wouldn't be printing anything in .total field. Now it prints zeros, so it finds it. And the same exact script in fiddle link does work correctly. What I did in Drupal was just wrap it up.
Comment: @OptimusPrime nope, you are wrong. `var total = 0;` does not require any selects to be executed, and `.each` over no elements will leave that `0` in place. So we still don't know if any selects are found in `$selects.each(` line. I know that "common logic" suggest that if `.change` works, there need to be some selects in `$selects`. But I'm not sure if there really are any.
Comment: I'm lost now. So what should I ask in next question? What would be the correct question title?


A basic question on real analysis (limit)

Question: What is the value of the expression $$\lim_{\lambda\to\infty}\sum_{k=0}^{\lfloor{\lambda t}\rfloor} e^{-\lambda} \frac{\lambda ^k}{k!}$$ Will it depend on $t$? $t$ just controls the number of terms which is infinity as $\lambda\to\infty$.
Answer: The sum is $P(S_\lambda\leqslant\lambda t)$, where the distribution of the random variable $S_\lambda$ is Poisson with parameter $\lambda$. By the (weak) law of large numbers, the limit when $\lambda\to\infty$ is $0$ if $t\lt1$ and $1$ if $t\gt1$. By the central limit theorem, it is $\frac12$ if $t=1$.


How can I make a form visible and maximize it to fill a secondary monitor without it activating?

Question: I have an application which is designed for multiple monitors. It starts up, and we try to avoid activating windows that do not need to be activated, because the user only does keyboard input in one place, and each time we Activate a new form on a secondary monitor, it grabs keyboard focus, something we wish to avoid.
Our in-house base TForm class has a method like this, which is using the Win32 ShowWindow function directly, avoiding the VCL framework's internal visibility change system which grabs focus:
procedure TOurForm.ShowWithoutActivate;
begin
    ShowWindow(Self.Handle, SW_SHOWNOACTIVATE);
    Self.Visible := true;
end;

If I just did this, it would grab focus:
 Self.Visible := true; // TWindow.Visible = true, will grab focus, plus make window visible.

This works, but the next thing I'd like to be able to do is set Maximized state so that the
form will maximize itself on the Monitor that it is currently on.  How do we get it onto a particular monitor?  The same way it always worked, with modification of the Left and Top properties of the Form. We have to take care that if we store Left/Top/Width/Height on form, and then restore it, that the results are still valid when we reload it. That is NOT what I'm asking about.
I'm specifically asking about how to maximize the form now that I have "showed" it using the above custom function.  One hack begets another hack. Here is how far down this rabbit hole I've gone:

When a TForm, which is also a TWinControl's private field FShowing is false, setting Form.Maximized has no effect.
When a TForm has its TWinControl.FShowing field set true, setting the windowState to wsMaximized also causes the form to activate.

Is it possible to both make this form visible and make it take the window state I want it to take without activating?  If I can't do this, then users are going to lose their keyboard focus when I show this form on a secondary monitor, something that I really want to avoid.
What I tried is to use Win32 ShowWindow API to do SW_SHOWMAXIMIZED:
  ShowWindow(Self.Handle, SW_SHOWMAXIMIZED);

The above seems to grab focus (activate).
Answer: When you create the top-level window set the extended window style to
WS_EX_NOACTIVATE | WS_EX_APPWINDOW

WS_EX_NOACTIVATE stops the window activating.  This also makes it disappear from the taskbar, so you need WS_EX_APPWINDOW to fix that problem.
Call ShowWindow(hWnd, SW_MAXIMIZE) and the window will be maximized but not activated.
You need to be able to activate the window once it is visible, so in the WM_ACTIVATE handler (the irony!) you need to clear the WS_EX_NOACTIVATE flag thus:
case WM_ACTIVATE:
    {
        DWORD exstyle = GetWindowLong(hWnd, GWL_EXSTYLE);
        if (exstyle & WS_EX_NOACTIVATE)
        {
            SetWindowLong(hWnd, GWL_EXSTYLE, exstyle & ~(DWORD)WS_EX_NOACTIVATE);
        }
    }

Apologies for the C++.  This should be simple to translate into Delphi.
Comment: It translates very easily into any language, thanks!
Answer: EnumDisplayMonitors API enumerates the monitors and their coordinates on the joint desktop, area into which a particular monitor maps to its specific position.
To find out which monitor is "current" you would want to compare the current window position against monitor coordinates rcMonitor/rcWork. Or, you have MonitorFromPoint and friends to help you.
Once to decided which monitor you want, you can either move your window (MoveWindow, SetWindowPos) to monitor's work area, or use this rectangle in response to WM_GETMINMAXINFO message to send the window to this position as a part of standard maximization.
To add to this, this small C++ application [1, 2, 3] demos the concept mentioned above, shows monitor information, and changes position where the window would be maximized to.
Comment: So rather than calling Win32 `ShowWindow( Win32Handle, SW_SHOWMAXIMIZED)` I should maybe call SetWindowPos?
Comment: With `SetWindowPos` you have the option of specifying the corrdinates (which can be those you want, or instead you can use maximization flag). `ShowWindow` with maximization option will request min/max info from your window - you can handle it there and provide coordinates to maximize to, which can be "current monitor work area" or anything else at your discretion.


Salvar estado após vincular elementos html

Question: Criei uma pergunta aqui no SOpt onde minha dúvida era como vincular elementos HTML em um drag and drop.
A resposta que tem lá é excelente e resolveu completamente minha dúvida.
Mas agora tem mais uma coisa... Como que eu posso salvar o estado dessas divs vinculadas? Porque da forma que está, se o usuário der um f5 na página, as divs são desvinculadas...
Como que eu poderia resolver isso?
Comment: Você precisará de um banco de dados para persistir os dados. Assim, quando o usuário modificar algo você grava no banco e quando ele apertar `F5` você irá buscar as informações no banco para exibir conforme ele havia personalizado.
Answer: Bem, não sei se é a melhor prática, mas resolvi tentar e obtive um sucesso.
Fiz um exemplo com o salvamento em localStorage.
Entre os dados salvos estão:

Posição x e y do .panel;
Posição x e y da .div;
Informação para saber se as divs estão vinculadas ou não;

E criei um botão para desvincular também.
Código completo:

<button id="desvincular" >Desvincular</button>

Drop here!

Ese é um modelo simples, para aplicações simples, mas é funcional e de fácil adaptação. Não o usei os Jsfiddle nem nada do tipo, pois por algum motivo, dá uns bugs, então você pode copiar o código e testar na sua máquina que funciona.
Comment: Deixa eu te perguntar, caso eu queria salvar em banco de dados... Como podemos fazer?


Stacking different elements in a Windows.Forms.Button

Question: I am developing a windows forms application in c#. I am creating a large amount of buttons in loops, and I wish for both an image (icon), and text to be displayed on a button. I have experimented with alignment, but I require the image to be on the very top of the Button, and the text to be below the image. My current code is:
button1.Image = im;
button1.ImageAlign = ContentAlignment.TopCenter;
button1.Text = "CS: GO";
button1.TextAlign = ContentAlignment.MiddleCenter;

This produces this image, which is clearly not what I want:

I cannot resize the Button, as the text is user defined, and subject to change in length.
Answer: Try the following:
button1.TextAlign = ContentAlignment.BottomCenter;

if this doesn't fit your needs there's another Property:
button1.TextImageRelation = TextImageRelation.ImageAboveText;

if I am right this will override some of your alignments.
Comment: Yeah, but that positions it at the bottom of the button. For a couple of reasons, I need it anchored below the image.
Comment: @jezza This should solve it :P - just keep the rest centered and it'll be fine :D
Comment: Yes! Thank you very much, perfect. Also, thank you to whoever made edits to my question, I understand why it should of been windows forms.


Is there a built-in way to fetch a single ActiveRecord attribute from the database (ignoring the in-memory value)?

Question: Big caveat: we're using Rails 2 at my company. So I'm looking for an answer (if one exists) from ActiveRecord 2.
Is there a method already included in ActiveRecord to fetch the most up-to-date value of an attribute from the database, without calling reload or overwriting the current in-memory value?
For example:
p = Person.find(123)

# Now the in-memory value is "Joe", which would be overwritten
# if I called reload
p.nickname = "Joe"

# I want something like this to execute the equivalent of:
# SELECT 'nickname' FROM persons WHERE id = 123;
nickname_from_db = p.get_current_value(:nickname)

I realize what I'm asking would be very simple to implement myself; I just don't want to reinvent the wheel if there's already an ActiveRecord method that does what I'm asking.
Answer: You can use the select option.
Person.find(123, :select => "nickname")
Comment: Yeah, I was thinking this... so there's no more "direct" method, then? (I guess I'm just clarifying that there isn't, e.g., an instance method that wraps this.)
Comment: Person.find(p, :select => :nickname)
Comment: No. `nickname` is just a value and Rails doesn't know where it comes from. So you have to ask the *thing* where it came from for getting the current value: `Person`.
Comment: @BenjaminM: I didn't mean an instance method on `String`, but rather on `Person`. I.e., if I had a `Person` object, `p`, I thought maybe there'd be a method like `p.fetch_latest("nickname")` and that method would internally call `Person.find(p.id, :select => "nickname")`. Anyway, I'm guessing there isn't any such method; so I'll just do as this answer suggests.
Answer: You can access the dirty attributes to get the previous value of the attribute
>> p = Product.first
>> p.name # foo
>> p.name = 'bar'
>> p.changes['name'] # ['foo', 'bar']

Comment: This is nice, but I'd like to get whatever the value currently is in the database *now*, not what it was when I first fetched the record. Does that make sense?
Comment: I don't really understand. If you need to know the value as it is right now in the database, simply do another database query using acitve record?!
Comment: @BenjaminM: Yes of course; I was only asking this question because, as we all know, there are lots of handy convenience methods in ActiveRecord and Rails in general; so rather than write my own little helper function to do this (as in Kaeros's answer) I was just checking whether it already existed first.


Creating a python win32 service

Question: I am currently trying to create a win32 service using pywin32. My main point of reference has been this tutorial:
http://code.activestate.com/recipes/551780/
What i don't understand is the initialization process, since the Daemon is never initialized directly by Daemon(), instead from my understanding its initialized by the following:
mydaemon = Daemon
__svc_regClass__(mydaemon, "foo", "foo display", "foo description")
__svc_install__(mydaemon)

Where svc_install, handles the initalization, by calling Daemon.init() and passing some arguments to it.
But how can i initialize the daemon object, without initalizing the service? I want to do a few things, before i init the service. Does anyone have any ideas?
class Daemon(win32serviceutil.ServiceFramework):
    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

    def SvcDoRun(self):
        self.run()

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)

    def start(self):
        pass

    def stop(self):
        self.SvcStop()

    def run(self):
        pass

def __svc_install__(cls):
    win32api.SetConsoleCtrlHandler(lambda x: True, True)
    try:
        win32serviceutil.InstallService(
            cls._svc_reg_class_,
            cls._svc_name_,
            cls._svc_display_name_,
            startType = win32service.SERVICE_AUTO_START
            )
        print "Installed"
    except Exception, err:
        print str(err)

def __svc_regClass__(cls, name, display_name, description):

    #Bind the values to the service name
    cls._svc_name_ = name
    cls._svc_display_name_ =  display_name
    cls._svc_description_ = description
    try:
        module_path = sys.modules[cls.__module__].__file__
    except AttributeError:
        from sys import executable
        module_path = executable
    module_file = os.path.splitext(os.path.abspath(module_path))[0]
    cls._svc_reg_class_ = '%s.%s' % (module_file, cls.__name__)

Comment: I am not sure I understand the question. Can you give us an example of what you want to do that the above code doesn't allow?
Answer: I just create a simple "how to" where the program is in one module and the service is in another place, it uses py2exe to create the win32 service, which I believe is the best you can do for your users that don't want to mess with the python interpreter or other dependencies.
You can check my tutorial here: Create win32 services using Python and py2exe
Answer: I've never used these APIs, but digging through the code, it looks like the class passed in is used to register the name of the class in the registry, so you can't do any initialization of your own.  But there's a method called GetServiceCustomOption that may help:
http://mail.python.org/pipermail/python-win32/2006-April/004518.html

Creating a python win32 service


Let A and B be subsets of R, prove that int(A ∪ B) ⊂ int(A) ∪ int(B)

Question: $x\in int(A \cup B)$ implies that there exists $\epsilon>0$ such that $(x-\epsilon, x+\epsilon)\subset(A \cup B),$
hence, $(x-\epsilon,x+\epsilon)\subset A  \cup  (x-\epsilon,x+\epsilon)\subset B$, implies $x\in int(A)\cup int(B)$.
Is this true?
And how to prove that $int(A ∪ B)$ ⊂ $int(A)$ ∪ $int(B)$?
Comment: You can (easily) prove the reverse inclusion, not this one, which doesn't generally hold.
Answer: This is false. If $A$ is the set of all rational numbers and  $B$ is the set of all irrational numbers then $A$ and $B$ have no interior but the interior of $A \cup B$ is $\mathbb R$.
Comment: Thank you. But for general solution, how do I prove that int(A ∪ B) ⊂ int(A) ∪ int(B)?
Comment: @JASMINE In general, this inclusion is not true as shown by this answer. Only the reverse inclusion is true in general. [See](https://math.stackexchange.com/questions/3350947/int-s-cup-int-t-subseteq-ints-cup-t?rq=1).


iOS - UICollectionView still have spacing between cells after set to 0

Question: Im getting small spaces between cells when setting everything to 0. All I did in the cellForItemAtIndexPath is setting backgroundColor for each cell.
Here's my code:
//collectionView frame
_collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 150) collectionViewLayout:layout];

...

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //The cell sizes are divided by the width of the collectionView.
    return CGSizeMake(_collectionView.frame.size.width/12, _collectionView.frame.size.width/12);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 0.0f;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 0.0f;
}

My collection view looks like this. You'll see that there are black lines between some cells. What is causing this? How can I remove the lines?

Any help is greatly appreciated. Thanks in advance.
Comment: I too faced this issue. I believe this happens because of a bug in autolayout. That 1px gap between the cells cant be removed, unless you do some crazy hack!!!
Comment: did you try ceil(_collectionView.frame.size.width/12)?
Answer: I too faced this problem. Thanks to @tenric for pointing out and yes for me was because the width is not divisible by the number of desired columns. My solution as follow:
var itemWidth: CGFloat {
    get {
        return floor(view.frame.size.width / 7)
    }
}

And because I'm using AutoLayout, I just adjust the gap to the width of the collectionView as follow (refer to widthAnchor):
collectionView?.topAnchor.constraint(equalTo: headerSeparator.bottomAnchor).isActive = true
collectionView?.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
collectionView?.bottomAnchor.constraint(equalTo: footerSeparator.topAnchor).isActive = true

let gap = view.frame.size.width - (itemWidth * 7)
collectionViewWidthConstraint = collectionView?.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -gap)

Answer: because both width and height are not divisible by 12,so it would remain some empty pixel point.To avoid this,both width and height of collectionView should be multiples of 12.
Comment: I did change the size is each cell to 26.6666667 (320/12) and still this is happening. But thank you for your answer.
Answer: I was going crazy over this too. I wanted a generic solution since I had 3 cells per row for iPhones and 4 cells per row for iPads and the UICollectionView was covering the entire width of the screen and the width is different between all devices.
I ended up making the combined width of the cells on a row wider than the device screen by using ceil(frame.width / itemsPerRow). I then calculated the total width of the cells on a row and compared with the screen width (view.frame) to get the width overflow the cells would create. Knowing the overflow I set the trailing constraint of the UICollectionView to be negative the overflow. This means the UICollectionView is actually going to overflow the screen width with a pixel or so, but in my case this was not an issue. Hopefully the code below will help clarify and give you an idea of how this could be solved.
// calculating cell width
let frame = view.frame
let cellWidth = ceil(frame.width / itemsPerRow)

// adjust UICollectionView to avoid space between cells
let totalCellsWidth = cellWidth * itemsPerRow
let overflow = totalCellsWidth - frame.width
let adjustedConstraint = -overflow
collectionViewsTrailingConstraint.constant = adjustedConstraint


Passing instance variables to DSL based on instance eval

Question: I'm trying to write a DSL to wrap Mongoid's aggregation pipeline (i.e. Mongo DB).
I've made a module that when included, adds a class method that accepts a block, which it hands to an object that passes requests to Mongoid (via method missing).
So I can do:
class Project
  include MongoidAggregationHelper
end

result = Project.pipeline do
  match dept_id: 1
end

#...works!

"match" is a method on Mongoid's aggregation pipeline, which is intercepted and passed on.
BUT instance variables set outside the block are not available, since its being executed in the context of the proxy class.
dept_id = 1

result = Project.pipeline do
  match dept_id: dept_id
end

#...fails, dept_id not found :(

Any way to pass/redefine external instance variables in with the block?
Below is the trimmed code:
module MongoidAggregationHelper
  def self.included base
    base.extend ClassMethods
  end

  module ClassMethods
    def pipeline &block
      p = Pipeline.new self
      p.instance_eval &block
      return p.execute
    end
  end

  class Pipeline
    attr_accessor :cmds, :mongoid_class
    def initialize klass
      self.mongoid_class = klass
    end

    def method_missing name, opts={}
      #...proxy to mongoid...
    end

    def execute
      #...execute pipeline, return the results...
    end
  end
end

Comment: Can you try `def pipeline(*args, █)` and `Project.pipeline dept_id: dept_id do`?
Comment: Good suggestion @MrYoshiji, in the production code I do that and it works.  I would like to avoid having to pass the variables in as an options hash however, and use the previously declared variables if theres some what to do it.
Comment: I posted an answer with an alternative
Comment: Hi juwiley, I did not find `match` method in Mongoid. Can you please tell me where did you find this method?
Comment: @Kuldeep its buried deep within the Mongoid driver.  Thats the rationale for writing this wrapper, one day Mongoid will/should expose the API in a cleaner way.  You can get to it via YourModel.collection.aggregate
Answer: You can do the following: (unlimited amount of arguments, kinda have to use a Hash)
# definition
def pipeline(*args, &block)
  # your logic here
end

# usage
dept_id = 1
result = Project.pipeline(dept_id: dept_id) do
  match dept_id: dept_id
end

Or you can use named arguments, if you know how many arguments you need to execute the DSL:
# definition
def pipeline(dept_id, needed_variable, default_variable = false, &block)
  # your logic here
end

# usage
dept_id = 1
result = Project.pipeline(dept_id, other_variable) do
  match dept_id: dept_id
end

Comment: Wish I could do this seamlessly without having to pass anything in, but looks like its not possible


Recursive Definition of a Series

Question: I have a series such as the one below:
\begin{equation}
2^n(\sum\limits_{i=2}^{n+1}i)\text{ for all $n \geq 1$}
\end{equation}
I need to write a recursive definition for it. Here's what I have so far:
\begin{equation}
  sum(n)=\begin{cases}
    n, & \text{if $n<1$}.\\
    recurse, & \text{otherwise}.
  \end{cases}
\end{equation}
I'm not entirely sure what the recursive step would be or if the return for a value less than 1 should be n. Can anybody help me out? Thanks!
Comment: I think it means $sum(0)=0$, $sum(n\geq1)=2^n\sum_{i=2}^{n+1}i=2sum(n-1)+2^n\cdot(n+1)$.
Comment: What? I don't understand your comment.
Comment: I posted it below.
Answer: $$\begin{align}
sum(0)&=0\\
sum(n\geq1)&=2^n\sum_{i=2}^{n+1}i \\
&=2\cdot\left(2^{n-1}\sum_{i=2}^{n}i\right)+2^n\cdot(n+1)\\
&=2\cdot sum(n-1)+2^n\cdot(n+1)
\end{align}$$
Or,
\begin{equation}
  sum(n)=\begin{cases}
    n, & \text{if $n<1$}.\\
    2\cdot sum(n-1)+2^n\cdot(n+1), & \text{otherwise}.
  \end{cases}
\end{equation}
Comment: Could you by chance put it in the form I started with? I'm having a hard time following what you wrote.
Comment: I edited your post a bit for readability. I hope you don't mind.
Comment: @CameronWilliams Thanks.
Comment: @Nic And I also added your style too. Is it better now?
Comment: @Nic Using the recursive definition, $S(0)=0$, $S(1)=2\cdot0+2^1\cdot(1+1)=2\cdot2=4$, $S(2)=2\cdot4+2^2\cdot(2+1)=8+4\cdot3=20$.
Comment: @KayK. Can you explain how you got the $4$ in $S(2)=2*4...$?
Comment: @Nic $S(2)=2\cdot S(1)+2^2\cdot(2+1)=2\cdot4+2^2\cdot(2+1)$.
Comment: @KayK. Thanks!!

Recursive Definition of a Series


Query no Sequelize separando Mês e Ano

Question: Olá, pessoal. Desculpe se minha pergunta parecer meio boba, mas estou começando agora e fazer essa query tá dando um nó na minha cabeça kkk
Seguinte, estou construindo um sistema para gerenciar os vales (adiantamentos) da empresa. Já criei o sistema de login usando o express-session e está funcionando legal. Só que agora preciso criar uma página que a pessoa veja todos os vales dele no mês atual. Por exemplo: Se eu entrasse hoje (15/08/2020), eu veria todos os vales que eu pedi em Agosto de 2020. Fazer a query procurando pelos vales correspondentes ao id do usuário eu já consegui tranquilo da seguinte forma:
const finantialController = {
financeiro: async (req,res)=>{
    try {
        const vales = await Vales.findAll({
            where:
                {
                userId: req.session.user.id,
                },
            include: [{model:User}]
        })
        res.render('finantial/financeiro', {vales: vales})

Esse trecho do código tá funcionando lindamente, mas eu não sei como armazenar a data atual (talvez vou ter que fazer isso através do datetime) e como separar o mês e o ano da minha database e comparar com o datetime. Eu já tenho os timestamps na database, então eu usaria a coluna "createdAt". Já li a documentação, já tentei algumas formas, já pesquisei bastante mas infelizmente não cheguei em nenhuma solução. Se puderem me ajudar eu agradeço muito!
Answer: Tá um pouco confuso mas vou tentar ajudar! a variável vales deve retornar um array com as colunas referentes ao ID informado, certo?!
para pegar o mês e o ano você pode utilizar o Date passando o valor do createAt:
const date = new Date("2020-05-06 05:20:30")
console.log(date.getMonth(), date.getYear())

Mesma coisa para pegar o ano e mês atual, basta remove o "2020-05-06 05:20:30"
Feito isso você vai ter as datas da tabela e atual. depois você pode fazer uma comparação percorrendo o array com um MAP e comparando os valores com IF.
Comment: Cara, muitíssimo obrigado! Vc me deu uma ótima ideia e consegui resolver fazendo o seguinte:
Criei uma variável TODAY que recebe a data de hoje, depois criei uma MONTH que recebe today.gethMonth(), depois outra chamada year que recebe today.getYear().
Então criei uma função (SAMEMONTHANDYEAR) que primeiro filtra pelo mês, depois pelo ano e retorna esse valor.
E aí peguei aquele array ali VALES e apliquei um filter com a função. Deu certinho.
Muito obrigado, man!
Comment: Disponha! se você puder marcar como resposta útil eu ficaria feliz

Query no Sequelize separando Mês e Ano