Edit button in teasers

Question: i'm using display suite and views in one of my teaser content type and i'm trying to add an EDIT button right in the teaser, but i can't find the function to do this. So i came here to ask for help. Can you help me? Thank you
Answer: The edit function is usually provided in teasers with contextual links.
Activate the optional core module, and when the teaser is displayed, a contextual links icon will be displayed at the upper right corner of the rendered teaser.
Comment: Hello Triskelion, I have contextual link enabled and still nothing (no edit link) in the teaser. Can you provide some more details? Thank you
Comment: Have you given yourself the permission to _Use contextual links_ under `admin/people/permissions`? Also, the link only appears on _mouse over_ the teaser.
Comment: Still not working :/
Comment: Just a note: If you have "Devel Theme developer" module enabled, the Contextual link will not be shown
Answer: Once you are using Display Suite module, you can simply create a new "Custom Field" and use the "Code field"(Add Code field) to generate the apropriate code to edit. Enable the Entities to Node and in the field code add this code and hit save:
EDIT

PS: As you can see, i'm using a token to generate the edit path of the node, so you need to have token module enabled. Make sure that you are adding this in the teaser display
Comment: Better answer found here @ http://drupal.stackexchange.com/a/130579/9150

This will check the user permission also.
Answer: In Views add filed 'Content: Edit link' and on teaser field go to 'Rewrite results > Rewrite the output of this field' in box use 'Replacement patterns' below and write something like [your-teaser-field-replacement]...[edit_node].
Instead '...' you can use anything or just space.
Rearrange fields and set 'Content: Edit link' field above your teaser field.
On filed 'Content: Edit link' check 'Exclude from display'.
You can use css to set button instead text on edit link.
More info on THIS and THIS link...
Comment: There is no _Teaser_ field. He is using rendered content and individual fields like _Edit link_ will not display.
Comment: With your sugestion, I can't find the 'Content: Edit link' in the View fields. I'm using the last version of Views module

Edit button in teasers


Remove b2body from cocos2d sprite

Question: Is there a way to remove b2body associated with a sprite? The sprite should appear on screen but with out physics.
I am using cocos2d Box2d.
Answer: We give sprite as userdata of the b2body. So if you want to remove the body which has specific sprite as a userdata then you have to go through all the body which are at moment present in world and then one by one compare with them and if you find that then remove that corresponding body.
let say you want to delete the body corresponding to CCSprite* temp;
<code>for(b2Body *b = _world->GetBodyList(); b; b=b->GetNext()) {
if (b->GetUserData() != NULL) {
            CCSprite *sprite = (CCSprite *)b->GetUserData();
            if (sprite==temp) {
               world->destroyBody(b);
               break;
            }
}
</code>
Comment: I have joint attached to that body. I think this is the reason, the body is not destroyed.
Comment: Yes, first of all,you have to delete everything related to the body and then remove that body. If you will not do that then there is a possibility of getting exc_bad_access error signal.

Remove b2body from cocos2d sprite


Will a dataset with multiple labels perform better than with binary labels?

Question: Suppose I have a dataset comprised of garbages. Will a model perform better if I only label the dataset with biodegradable or non-biodegradable?
Or will it be better if I label them with plastics, paper, cardboard, glass, and organic?
In fact, I also plan to further increase the number of labels for example, the plastic label with be comprised of a large number of brands of plastic wrappers, etc.

I think that having a large number of labels is detrimental to computational performance in both training and evaluation since for example, Linear Discriminant Analysis will not lead to much reduced dimensionality due to the nature of the subspace spanned by the centroids on each label.
Neural networks would have a very wide top softmax layer and I am pretty sure that would require a wider architecture.
Aside from model issues, I could easily suffer from class imbalances. Is there any merit to having multiple labels ?
Comment: What's the purpose of your model? Do you just need to identify if the garbage is biodegradable or not?
Comment: @Lynn yes. It is a biodegradable/non-bio task which I think can be extended to several labels under biodegradable/non-bio. The motivation is that, I think that same plastic wrappers from same brands must be clustered in a Gaussian fashion. I am thinking that classifying these Gaussians would be better than having a binary classification of bio/non-bio
Answer: Generally speaking, having classes that are not naturally ordered creates a more difficult prediction/probability estimation problem.  When a binary problem turns into a multinomial/polytomous problem the task is more difficult as more model parameters exist, the effective sample size decreases, and the sample size required to achieve a given predictive reliability increases.
If some of the classes are connected, i.e., types of plastic, you can gain information and predictive reliability by using a Bayesian model that has prior distributions for parameters such that you borrow information (assume some similarity of effects) across connected categories.  This reduces the effective number of parameters.  Sometimes this can be done with Bayesian hierarchical random effects models.
When you can assume that all levels of the outcome variable are ordered, everything changes.  The effective sample size increases and the number of parameters that matter does not increase with increasing number of outcome categories.  Models such as the proportional odds ordinal logistic model come into play.
Comment: Unlike your original setup, ordered classes would classes for which there is consensus among experts that the characteristic of interest is ordered by severity of outcome, impact of outcome, size, darkness, or some other metric.  Many ordinal analysis methods exist for such dependent variables.
Comment: Good day professor, may I ask what you meant by "ordered classes"? For example, if the dataset are images of coins (the front and back of the coin have separate labels), are they more "unordered" compared to dataset of different animals?
Answer: If the data is clustered in the way you describe in your comment, then for the two-class problem you are likely to have a non-linear decision boundary. As linear models can't model non-linear decision boundaries, they are unlikely to perform well here. However, an appropriately sized non-linear model such as a neural network should be able to model this (for more on linear vs non-linear models see Paul Fornia's answer to "Linear vs Nonlinear Machine Learning Algorithms"). If the NN is wide and/or deep enough it will effectively learn the cluster groupings during training.
Correction (in response to @kjetil's comment): You could still use a linear model if the features can be transformed to a higher-dimensional space in which the decision boundary is linear (e.g. by using feature interactions or squaring, cubing etc features).
Transforming your data to a multi-class problem may give you multiple linear decision boundaries, which should help improve a linear model, if for some reason you are restricted to using linear models.
Your point on class imbalances prompted another thought. By separating the classes into sub-classes you may lose information that is common between the subclasses. For instance, consider classes of 'hard plastic' and 'soft plastic', which probably have similar values for some attributes. If they are separate classes the model may treat these shared attributes as "not useful" and ignore them. Conversely the model may place too much importance on differences between 'hard plastic' and 'soft plastic' which are not useful for bio/non-bio classification.
Comment: But linear models can model non-linear boundaries, see for instance https://stats.stackexchange.com/questions/249060/is-the-decision-boundary-of-a-logistic-classifier-linear, https://stats.stackexchange.com/questions/533517/what-is-the-relation-between-linear-classifier-and-linear-decission-boundary-or
Comment: @kjetilbhalvorsen - thanks for pointing out my sloppy over-simplification. I've added a correction to my answer to address this.


How to create a suggested articles block that uses taxonomy?

Question: I've been trying to create a view that uses taxonomy to generate suggested articles to users.
I wanted these articles generated according to their relation with the taxonomy term of the current article the user is reading.
How can I make this work?
Comment: Since this one uses views, this is probably a more suitable dupe: http://drupal.stackexchange.com/questions/27844/how-to-create-a-list-of-similar-nodes-in-drupal-7-views-3
Comment: http://drupal.org/project/similarterms or see http://drupal.stackexchange.com/questions/32682/a-nice-way-to-build-a-related-content-algorithm
Answer: Have a look at the Similar by Terms module. Here are some more details about it (from its project page):

This Drupal module attempts to provide context for content items by displaying a view block with links to other similar content. Similarity is based on the taxonomy terms assigned to content. Views are available based on similarity within each of the defined vocabularies for a site as well as similarity within all vocabularies.
What does this really mean? How should you use this module?

Create a freetagging vocabulary called "Tags" assigned to the content types on which you'd like to display the "Similar" view block.
Enable the view block called "Similar entries from the Tags vocabulary".
Add keyword tags to the content.

You can also create own views and add similar by term Nid argument, sort handler and similarity as field. Now when you go to the page for a tagged content item, a block will show up displaying other content in descending order of common tags (terms).

Note: a stable version of this module is available for both D7 and D8!


Autocomplete suggestions not shown after all chips removed (md-chips + md-autocomplete)

Question: In my example (https://jsfiddle.net/vv18yjzo/7/) the autocomplete suggestions should be shown, as long as the md-chips input is focused. This works well when I enter a few items.
However, when all available items are added and then removed, the autocomplete suggestions are empty / hidden. I have to enter a new search text to see the autocomplete suggestions again.
HTML:
<md-input-container class="md-block">

    Categories

    <md-chips ng-model="vm.selectedCategories"
        md-autocomplete-snap
        md-require-match="true"
        md-on-add="vm.onCategoryAdded($chip, $index)"
        md-on-remove="vm.onCategoryRemoved($chip, $index)">

        <md-autocomplete
            md-selected-item="vm.autocomplete.selectedItem"
            md-search-text="vm.autocomplete.searchText"
            md-selected-item-change="vm.onSelectedItemChanged()"
            md-search-text-change="vm.onSearchTextChanged()"
            md-items="item in vm.searchCategories()"
            md-item-text="item.name"
            md-min-length="0"
            md-select-on-match="true"
            md-match-case-insensitive="true"
            md-no-cache="true"
            placeholder="Choose categories">

            {{item.name}}

        </md-autocomplete>

        <md-chip-template>

                {{$chip.name}}

        </md-chip-template>

    </md-chips>

</md-input-container>

JS:
(function () {
    'use strict';

    angular
        .module('app', [
            'ngMaterial',
            'ngMessages'
        ])
        .factory('CategoriesService', CategoriesService)
        .controller('CategoriesCtrl', CategoriesCtrl);

    function CategoriesService($q, $timeout) {

        var that = {
                find: find
            },
            categories = [
                { name: 'a' },
                { name: 'ab' },
                { name: 'abc' },
                { name: 'abcd' },
                { name: 'abcde' },
                { name: 'abcdef' }
            ];

        function find(search, selectedCategories) {
            var deferred = $q.defer(),
                result = categories.filter(function(category) {
                    return (-1 === selectedCategories.indexOf(category) && -1 !== category.name.indexOf(search));
                });

            $timeout(function() {
                deferred.resolve(result);
            }, 100);

            return deferred.promise;
        }

        return that;
    }

    function CategoriesCtrl($scope, CategoriesService) {
        var vm = this;

        vm.selectedCategories = [];
        vm.autocomplete = {
            selectedItem: null,
            searchText: null
        };

        /* ... */

        vm.searchCategories = function() {
            return CategoriesService.find(vm.autocomplete.searchText.toLowerCase(), vm.selectedCategories);
        };

    }

})();

Example: https://jsfiddle.net/vv18yjzo/7/
Answer: There seems to be a weird bug with the autocomplete searchtext, if you remove an item it just unsets the searchtext variable, which then breaks the autocomplete events.
Check this working fiddle https://jsfiddle.net/mgsLkf89/3/
vm.onCategoryRemoved = function($chip, $index) {
  if (!vm.autocomplete.searchText)
    vm.autocomplete.searchText=null;
};

Comment: Thanks Michael, just figured that out by myself, too.


Python - regex to remove quotes from entire line in CSV file

Question: I've seen a lot on here about how to remove quotes from within a line in a CSV file, but that's not quite the problem I have. Using something like
with open(path), 'wb') as myfile:
  writer = csv.writer(myfile)

I need to create rows consisting of the values of 3 variables. That leads to a line like this:
newline = var1 + " " + var2 + " " + var3

I want a result like value1 value2 value3, but instead it gives me "value1 value2 value3". I tried it without the spaces in between as well and all that did was mess up the formatting without removing the quotes. I also tried adding quoting = CSV_NOQUOTE (or something like that) to the writer declaration, but that caused an error about missing escapechars until I added in \n's, and even then it didn't get rid of the quotes. I've been scouring the pages here on SO for about an hour trying to find something but nothing I've found has worked. Could anyone please offer any advice? Thanks!
EDIT: To tie in the title, at this point I'm frustrated enough with it that I'm OK with a workaround to just get rid of the quotes with regex instead of preventing them from forming at all. I just don't know much about Python's regex, I've used it very minimally, and I'm not sure how to do basically the equivalent of a sed s/ command with it.
Comment: are you trying to create a space separated file or a comma separated file? Also the documentation: http://docs.python.org/2/library/csv.html is pretty clear on how to change the quote characters
Comment: @Cfreak just space separated, no commas in it
Comment: The docs are also very clear on how to change the delimiter.
Comment: I'm honestly not sure why this was put on hold, I displayed several things I attempted and explained what was wrong... at least I still got a working answer out of it
Comment: I voted to close it for a few reasons. 1. The question likely won't be found by someone trying to change the delimiter because you made it about regex. 2. Regexes are not a solution to this problem which indicates you don't (or didn't) really understand the problem. 3. The documentation which I already linked is very clear on how to change the delimiter. SO isn't a place to regurgitate the documentation.
Answer: You didn't show the line where you actually used writer to write a line to the file.  One mistake people make sometimes is to assume that writerow accepts something other than an iterable of values.
The following code (python 2):
import csv
with open("out.dat", "wb") as myfile:
    writer = csv.writer(myfile, delimiter=" ", quoting=csv.QUOTE_NONE)
    var1, var2, var3 = 3.14, 2.1728, "Fred"
    writer.writerow([var1, var2, var3])

produces
~/coding$ cat out.dat
3.14 2.1728 Fred

Comment: I believe that was it, thanks :) I figured it was some little mistake like that, this is just the first time I've ever worked with this stuff so I'm a little shaky still on some things
Answer: One option for writing CSV files is to just avoid the  csv module entirely:
output = [var1, var2, var3]

with open('output.csv', 'wb') as fo:
    fo.write(','.join([str(x) for x in output]) + '\n')

Of course you can do this with a list of lists (or any iterable) to write out multiple lines:
outlist = [[var1, var2, var3], [var4, var5, var6]]

with open('output.csv', 'wb') as fo:
    for out in outlist:
        fo.write(','.join([str(x) for x in out]) + '\n')

If you wanted spaces as a separator you can use ' '.join() instead.


Why do the assemblies in the Expression Blend SDK not support Application Library Caching?

Question: Admittedly, creating extmap.xml files is relatively simple:
http://msdn.microsoft.com/en-us/library/dd833069(VS.95).aspx
But while many third-party libraries provide extmap.xml files with their assemblies (for instance, Telerik thankfully does), the Blend SDK doesn't (looking in my C:\Program Files (x86)\Microsoft SDKs\Expression\Blend\Silverlight\v4.0\Libraries).  I don't see any reason at the moment for that being the case.
Is it just a simple oversight?  Is there some reason those particular assemblies shouldn't be included in app library caching?  Is it a support issue and they're not supported being outside the xap?
Admittedly, the 5 dll's we're using from that SDK only total about ~420KB (before compression) in our xap, but I'd like to move them out if there's no technical or support reason not to do so. :)
Comment: Help me understand the context.  Have you tried selecting the Project -> Silverlight Project Settings -> Use Application Library Caching option and the DLLs are still put into the main XAP?  Which controls are the culprits?
Comment: @Nissan: any assemblies lacking matching extmap.xml files will still be put in the main xap - see the MSDN page I linked to for details.
Answer: There is no technical reason not to do so.  The tookit dlls originally came without extmap files as well but as you say its fairly easy to create them.
Technically the applications use them in exactly the same way, the app will download and load all the zipped dlls before it executes the app just as it would load all the dlls embedded in a Xap normally.
You just need to be careful to avoid going back to the days of dll hell.  It can be tricky to host multiple Xaps in the same ClientBin folder that use different versions of the dlls.  Hence you should really be prepared to build and release an entire ClientBin folder together.
Of course there is nothing stopping you using multiple folders to avoid version issues but that would reduce the caching benefit.
Comment: Good point - at the moment we only have one xap file, so I don't have any conflicting-version issue to worry about currently, but it's good to think about when/if we add more xap's. :)  Thanks!


Installing GDAL on Ubuntu

Question: I am not able to install gdal on Ubuntu using latest anaconda for python 3.6 How do I fix it? I get foll. error:
UnsatisfiableError: The following specifications were found to be in conflict:
  - gdal -> numpy 1.8* -> python 2.6* -> openssl 1.0.1*
  - python 3.6*
Use "conda info <package>" to see the dependencies for each package.

Answer: It seems that you try to install gdal with python 2.6 while your anaconda is python 3.6.
To install gdal (or any package) with a specific python version, create a conda environment:
$ conda create -n <myenvname> python=<version>

then activate the environment:
$ source activate <myenvname>

and then, install gdal:
$ conda install gdal

Answer: If you are not able to use conda, this install worked for me for python 3:
sudo apt-get update && apt-get install -y \
  binutils \
  libproj-dev \
  gdal-bin \
  libgdal-dev \
  python3-gdal \
  python3-pip \
  python-numpy \
  python-dev

pip install pygdal>=2.1.2,<2.1.3

Good luck, this library is not an easy one to work with!

Installing GDAL on Ubuntu


Can the function y=5 be injective or surjective for all x ∈ integers?

Question: I have a practice exam and I get kind of confused about:
Is the constant function
y = 5 ,     ∀ x ∈ Z [All integers]
Is this function Injective or Surjective?
Comment: What is the definition of injective? What is the definition of surjective? Can you find an example to show that $y$ is not injective, or an example to show that $y$ is not surjective?
Comment: My guess is that the confusion is not about the definition of injective/surjective, but about how functions are defined.  To clarify this potential misunderstanding, the function being defined is a function that takes any integer as an input and always outputs the number $5$.
Comment: it is not injective, and it may or may not be surjective, depending on your interpretation. It is not surective as a function $Z\to Z$, but it is surjective as a function $Z\to\{5\}$ (most likely the former is intended and you either overlooked it, or it is assumed to be understood from the context).
Comment: I get the point that y always going to be 5.But, why wolfram alpha states y=5 Neither injection, nor surjection?
Comment: because it is neither [injection](http://en.wikipedia.org/wiki/Injective_function), nor [surjection](http://en.wikipedia.org/wiki/Surjective_function).
Comment: Is there any indication in the question what the codomain is supposed to be?  For instance, is $f: \mathbb{Z} \to \mathbb{Z}$?
Answer: Injective means different elements get mapped to different elements. But, both $1$ and $2$ get mapped to $5$ by this function, so it can't be injective.
Surjectivity depends on the codomain of the function, as noted in the comments.


Sqlite connection string in perl

Question: I am using below sqlite connection string in perl to connect sqlite database and getting following below error

Can't set DBI::db=HASH(0x2c34194)->{PRAGMA journal_mode}: unrecognised attribute name or invalid value

my $driver   = "SQLite";
my $database = "C:\\Sample\\Sample_Sqlite\\Activities.db3;PRAGMA journal_mode=WAL;";

my $dsn = "DBI:$driver:dbname=$database";
print $dsn;
my $dbh = DBI->connect(
    $dsn,
    { RaiseError => 1 },
) or die $DBI::errstr;

Answer: Reading the section on PRAGMA in the DBD::SQLite documentation, it looks like you're setting the PRAGMA at the wrong time. It shouldn't be part of the connection string, but an SQL command that is run once you have connected.
my $driver   = "SQLite";
my $database = "C:\\Sample\\Sample_Sqlite\\Activities.db3";

my $dsn = "DBI:$driver:dbname=$database";
print $dsn;
my $dbh = DBI->connect(
    $dsn,
    { RaiseError => 1 },
) or die $DBI::errstr;

$dbh->do('PRAGMA journal_mode=WAL');

Update: It's probably also worth noting that the journal_mode setting is persistent. So you only need to set it once, and then you can drop it completely from your connection code.
Comment: The only persistent journal mode is `wal`, btw. The others still need to be set for every connection.
Comment: Totally I have 64 rows in my database, with this statement I can able to retrieve only two rows.
Comment: @TulasiKumarGM: I don't see how the journal mode would affect the number of rows a query returns. What makes you think you have 64 rows in your table?
Comment: @TulasiKumarGM: But, anyway, your question was about connecting to the database. I think I've fixed that problem for you. If you have further problems, you should ask separate questions about them.
Comment: I copied db3 file in one of my local folder and tried to open using Sqlite Studio, so here I can able to see only two rows.
if I copy a .db3 and .db3-wal in one of my local folder and tried to open using Sqlite Studio, so here I can able to see all 64 rows.
so here while connecting .db3, I need to consider .db3-wal also

Sqlite connection string in perl


How to map ubercart attributes to CCK fields?

Question: The reason I am trying to map ubercart attributes to CCK fields because I can then use these CCK fields to display price list using views for many use cases.
Is there any fields references module which can do this?
Comment: I'd rather try to do it thru views (try Relationships) or add the necessary relationships via a custom module.
Answer: If you really want fields and do not want to use your price in your views (though Ubercart is really compatible with views), you can use Rules to fill the value of a "hidden" (I recommend you use field permission for that) CCK numeric field.
Once you've created the field for your product content type, set the rule like this :

Event : Content is created
Condition : Is of type your product content type
Condition : Entity has field your numeric hidden field
Action : Add a variable : get your price value
Action : Convert data type : make it numeric
Action : Set a data value : set your hidden field value.

(Maybe this 3 last actions can be done in only 1 with "set a data value", it's worth trying it)
Comment: hi @Gregory Kapustin,

Thanks a lot, sure I will try it out
Comment: Any news here ?
Answer: If you are using drupal 7, then you can use module Ubercart Field attributes.
As mentioned in the project page of the module,

This module links Ubercart's attribute system to Drupal core's fields API and allows to automatically create product attributes from fields and options from the multi-values.

If you are using drupal 6, then there is module Ubercart CCK Attribute.


Understanding and modifing a theorem from Fulton's "algebraic curves"

Question: I am reading Theorem 2 in chapter 3.2 in Fulton.
It says that $mult_p(F)=\dim_k (m_p(F)^n/m_p(F)^{n+1})$ for a sufficiently large $n$. Reading the proof I understood that we eventually play a game of exact sequences, I want to understand what happens if $n$ is not sufficiently large and what does sufficiently large mean.
Say we call $mult_p(F)=k$ (the book uses m, but I am using k to differentiate with the ideals $m_p$)
 So we want to find the dimension of $\mathbb{C}[x,y]/(F,I^n)$. Then the book proceeds with saying that if $F$ has multiplicity k then the polynomial can be written as $F=F_k+ F_{k+1}+\cdots$ thus if we have $ F * G \in I^n$ then $G \in I ^{n-m}$.
That is great and we can make the exact sequence
$$0 \rightarrow \mathbb{C}[x,y]/I^{n-m} \rightarrow \mathbb{C}[x,y]/I^n \rightarrow \mathbb{C}[x,y]/(F,I^n) \rightarrow 0$$
Then from there their proof is very straight. What I observed is that for "n" to be sufficiently large it must be larger than k ie the multiplicity of the point. ( I think I am correct here but feel free to correct me)
My question is if we say that n is smaller than the k. In that case I think the thing that will change is that we do not need a G anymore thus we will get that
$F \in I ^n$ because the smallest term of F is $F_k$ but k is larger than n so we have the inclusion. Thus the exact sequence that we will obtain is
$$0  \rightarrow \mathbb{C}[x,y]/I^n \rightarrow \mathbb{C}[x,y]/(F,I^n) \rightarrow 0$$
To compute the dimension of $\mathbb{C}[x,y]/(F,I^n) $ we get
$\dim \mathbb{C}[x,y]/(F,I^n) = \dim \mathbb{C}[x,y]/I^n +1$ but this does not seem to add up. If someone is familiar with Fulton and the argument can possibly guide me I would appreciate it. Thank you
Answer: Problem 3.13 deals with precisely what happens when $0\le n<k$. You've got the right idea essentially.
It has been dealt with concisely here.
Comment: Good find! In the future, when you find a question that is answered by another question on the site, please suggest a duplicate via the "flag" link at the bottom of the post.
Comment: I'll keep it in mind, thanks.


botoes alinhamento como fazer

Question: Pessoal os botoes estao desalinhado o que posso fazer estou usando o bootstrap
http://jsfiddle.net/a6Lt5Lgx/10/

    <form  name="materia" method="post" action="cad_Materia.php">

                    Disciplina:
                    <input class="form-control"  placeholder="Informe a diciplina" name="disciplina" type="text" required x-moz-errormessage="Disciplina não informada.">

                    Carga Horaria:
                    <input class="form-control" placeholder="Informe a carga horaria" name="cargaHoraria" type="text" required x-moz-errormessage="Carga Horario não informada." >

                    Bibliografia:
                    <input class="form-control" placeholder="Informe a bibliografia " name="bibliografia" type="text" required x-moz-errormessage="Bibliografia não informada." >

                    Codigo:
                    <input class="form-control" placeholder="Informe o codigo " name="codigoMat" type="text" required x-moz-errormessage="Codigo não informada.">

                        <input class="btn btn-primary" type="submit" value="cadastrar">
                        <input class="btn btn-warning" type="submit" value="Alterar" style="width: 86px; height: 34px" onclick="action='alt_Materia.php'" title="Informe (Disciplina/Carga Horaria/bibliografia) a Alterar e (Codigo) cadastrado"/>
                        <input class="btn btn-danger" type="submit" value="Deletar" style="width: 86px; height: 34px"  onclick="action='del_Materia.php'" title="Informe (Disciplina/Codigo) e clique aqui"/>

    </form>

Comment: Não duplique perguntas, sane os problemas indicados na original sempre.
Answer: Está afastado devido ao formato da tabela criada ,

. Você adicionou uma terceira coluna que ficou alinhada após as caixas de texto. As colunas, abrimos com a tag .
Eu coloquei o botão deletar na mesma coluna do botão Alterar, apenas para ilustrar por enquanto, retirando as tags  e 	 nessa parte do código:
    <input class="btn btn-primary" type="submit" value="cadastrar">
    <input class="btn btn-warning" type="submit" value="Alterar" style="width: 86px; height: 34px" onclick="action='alt_Materia.php'" title="Informe (Disciplina/Carga Horaria/bibliografia) a Alterar e (Codigo) cadastrado"/>
    <input class="btn btn-danger" type="submit" value="Deletar" style="width: 86px; height: 34px"  onclick="action='del_Materia.php'" title="Informe (Disciplina/Codigo) e clique aqui"/>

Atualizei seu html aqui: http://jsfiddle.net/a6Lt5Lgx/16/
Comment: Sugiro a leitura [deste link](http://meta.pt.stackoverflow.com/questions/846/sauda%C3%A7%C3%B5es-e-agradecimentos)
Comment: Danilo, por favor visite o link acima, ele justifica porque estou removendo saudações e agradecimentos.
Comment: Entendido! @diegofm

botoes alinhamento como fazer


Testar se a imagem existe

Question: Pessoal utilizo o Intervention no Laravel 5.5 e utilizo as rotas dele com os filtros para gerar as imagens dinamicamente. Gostaria de saber como eu posso testar na classe do filtro e a imagem que passei ela existe no disco, caso não eu carrego uma imagem padrão do site. Obrigado
Comment: Só php: http://php.net/manual/en/function.file-exists.php ou http://php.net/manual/en/function.is-file.php
Comment: @Miguel eu tentei estes 2 métodos, mas como estam em servidores diferentes eles não funcionam. As imagens estam no servidor do backend e o frontend esta em outro servidor.
Comment: Você tem que alterar sua pergunta dizendo que as imagens estão em locais diferentes e que acessa da.seguinte.forma tem como editar?
Comment: @VirgilioNovic então acho que a pergunta esta correta. Pois o filtro esta no mesmo servidor que as imagens. Mas o servidor que vai acessar as imagens via URL esta em outra maquina. Esta resposta que dei abaixo foi a forma que achei no servidor de Frontend. Mas vou postar agora a forma que consegui fazer direto no servidor das imagens.
Answer: Não sei se é o melhor jeito mas fiz assim:
@if(strtoupper($file_headers = @get_headers('http://www.meuservidor.com.br/miniatura/'.$item['imagem'])[0])=='HTTP/1.1 200 OK')

Assim funcionou perfeitamente, mas com certeza tem o custo de 1 conexão a mais com o servidor por imagem. Se alguém souber um jeito melhor gostaria de saber. Principalmente se tiver como fazer isto direto no servidor de imagem seria TOP. Obrigado
Answer: Consegui resolver criando uma nova rota onde eu checo se o arquivo existe e se não existe eu coloco o arquivo padrão e depois encaminho para a rota padrão do Intervention. Deu certinho Desta forma.
Definição da rota:
Route::get('/imagecache/{template}/{filename}', 'ApiController@imagecache')->where('filename','[ \w\\.\\/\\-\\@\(\)]+');

Controller da rota:
public function imagecache($template, $filename)
{
    if(!Storage::disk('public')->exists($filename)){
        $filename='images/noimage.jpg';
    }
    return response()->redirectTo('/imagecache/'.$template.'/'.$filename);
}

Testar se a imagem existe


Internal Server Error "Invalid command 'RewriteCond%{REQUEST_FILENAME}"

Question: 500  Internal Server Error.
Need help for my website.
.htaccess ---------

[Sat May 09 01:35:16.765194 2015] [core:alert] [pid 671798] [client 126.96.36.199:50570] /home/username/public_html/.htaccess: Invalid command 'RewriteCond%{REQUEST_FILENAME}', perhaps misspelled or defined by a module not included in the server configuration

please help me
Comment: [500 Internal Server Error Image](http://1.bp.blogspot.com/-twrDz4IJxnk/VU2vCh9mvzI/AAAAAAAAAas/gUPODvG8g3A/s1600/Capture.PNG)
Comment: Try reading the error message and looking at the file it relates to.
Answer: Not sure if this is a typo, but you are missing a space in your RewriteCond :
RewriteCond %{REQUEST_FILENAME} file.
------------^
Also you need to enable the rewrite module for Apache :
a2enmod rewrite
Finally you need to activate the rewrite engine within your Apache config, before any other Rewrite directive :
RewriteEngine On
Comment: RewriteEngine On did it for me, easy to overlook in some .htaccess files


Show that $ 3^n$ is not $\mathcal{O}(2^n)$

Question: To show that $2^n$ is $\mathcal{O}(3^n)$ is straightforward. On the other hand, if we want to show the opposite that $3^n$ were $\mathcal{O}(2^n)$, then we would have $3^n\le C·2^n$ for all sufficiently large $n$. This is equivalent to $C\ge (\frac{3}{2})^n$, which is clearly impossible, since $(\frac{3}{2})^n$ grows without bound as $n$ increases.
Question:is it clearly impossible based on the question because $C$ is supposed to be constant in the definition of Big-$\mathcal{O}$?
Comment: This is correct.
Answer: This is too long for a comment, but worth pointing out. Rosen's approach for analyzing asymptotics is nice, because it doesn't rely on Calculus techniques. So in that sense, it is more accessible. On the other hand, the Calculus techniques are quite nice for showing things like $f(n) \not \in \mathcal{O}(g(n))$.
Fix $k \geq 0$, and suppose that $f, g : \mathbb{Z}_{\geq k} \to \mathbb{R}$ satisfy that the following limit exists:
\begin{align}
L := \lim_{n \to \infty} \left| \frac{f(n)}{g(n)} \right|.
\end{align}
We have the following:

If $L = 0$, then $f(n) \in o(g(n))$. That is, $f(n) \in \mathcal{O}(g(n))$ and $f(n) \neq \Theta(g(n))$. Put another way, $f(n) \in \mathcal{O}(g(n))$ and $g(n) \not \in \mathcal{O}(f(n))$.
If $0 < L < \infty$, then $f(n) = \Theta(g(n))$. Put another way, $f(n) \in \mathcal{O}(g(n))$ and $g(n) \in \mathcal{O}(f(n))$.
If $L = \infty$, then $f(n) \in \omega(g(n))$. That is, $f(n) \not \in \mathcal{O}(g(n))$, but $g(n) \in \mathcal{O}(f(n))$.

Computing limits is sometimes much easier than trudging through these tedious inequalities.


Split Large File into several smaller files using BCP Utility by line number

Question: I was hoping somebody might be able to help me out here or point me in the direction of some resources that could shed some light.
I am using BCP utility to generate a large CSV file (~200 million lines) from SQL server.
I was wondering if it is possible to have BCP split the file (say every 10 million lines) while processing so that instead of having one large file I end up with 20 smaller ones?
I know I could split the file after I create it, but this takes up quite a bit more storage space as I would duplicate the original file.
Any help would be greatly appreciated!
Thanks very much in advance.
Mick
Comment: Possible duplicate? http://stackoverflow.com/questions/17632236/exporting-sql-server-table-to-multiple-part-files
Comment: Ah thank you Vlad.  This provides insight, but this talks about chunking files by byte size.  I was hoping somebody would have an idea on how to do this by line number.  I understand if it may not be possible to do it with BCP.
Comment: What about this suggestion (from that same page)? `bcp "SELECT * FROM MyTable WHERE Id BETWEEN 0 AND 10000000" queryout …  `
Comment: Yes Vlad.  Between that info and the info from Mike below I am on my way!  You have also been most helpful.
Answer: Here's an option for you. Use a while loop that will iterate through dynamic sql to generate the bcp code that is executed by xp_cmdshell. You should be able to take my code below and change it to your liking.
As an example, I included a print out of the bcp code generated by the SQL code below.  Hope this is a viable solution for you.
declare @c int = 1 --file version
declare @s int = 1 --predicate begin int
declare @e int = 10000000  --predicate end int

while @s <= 200000000
begin

    declare @sql varchar(8000)
    print @sql

    select @sql =
    'bcp select * from [your_table] where <your_id> >= ' + convert(varchar(10),@s) + ' and  [your_id] <=' + convert(varchar(10),@e) + ' out [your_file_name]' + convert(varchar(10),@c) + '.txt -c -t, -T -S' + ' [your_directory]'

    exec  master..xp_cmdshell @sql

    set @s = @e + 1
    set @e = @s + 9999999
    set @c = @c + 1

end

Print out of @sql executed by exec  master..xp_cmdshell @sql
bcp select * from [your_table] where <your_id> >= 1 and  [your_id] <=10000000 out [your_file_name]1.txt -c -t, -T -S [your_directory]

bcp select * from [your_table] where <your_id> >= 10000001 and  [your_id] <=20000000 out [your_file_name]2.txt -c -t, -T -S [your_directory]

bcp select * from [your_table] where <your_id> >= 20000001 and  [your_id] <=30000000 out [your_file_name]3.txt -c -t, -T -S [your_directory]

bcp select * from [your_table] where <your_id> >= 30000001 and  [your_id] <=40000000 out [your_file_name]4.txt -c -t, -T -S [your_directory]

bcp select * from [your_table] where <your_id> >= 40000001 and  [your_id] <=50000000 out [your_file_name]5.txt -c -t, -T -S [your_directory]

bcp select * from [your_table] where <your_id> >= 50000001 and  [your_id] <=60000000 out [your_file_name]6.txt -c -t, -T -S [your_directory]

bcp select * from [your_table] where <your_id> >= 60000001 and  [your_id] <=70000000 out [your_file_name]7.txt -c -t, -T -S [your_directory]

bcp select * from [your_table] where <your_id> >= 70000001 and  [your_id] <=80000000 out [your_file_name]8.txt -c -t, -T -S [your_directory]

bcp select * from [your_table] where <your_id> >= 80000001 and  [your_id] <=90000000 out [your_file_name]9.txt -c -t, -T -S [your_directory]

bcp select * from [your_table] where <your_id> >= 90000001 and  [your_id] <=100000000 out [your_file_name]10.txt -c -t, -T -S [your_directory]

bcp select * from [your_table] where <your_id> >= 100000001 and  [your_id] <=110000000 out [your_file_name]11.txt -c -t, -T -S [your_directory]

bcp select * from [your_table] where <your_id> >= 110000001 and  [your_id] <=120000000 out [your_file_name]12.txt -c -t, -T -S [your_directory]

bcp select * from [your_table] where <your_id> >= 120000001 and  [your_id] <=130000000 out [your_file_name]13.txt -c -t, -T -S [your_directory]

bcp select * from [your_table] where <your_id> >= 130000001 and  [your_id] <=140000000 out [your_file_name]14.txt -c -t, -T -S [your_directory]

bcp select * from [your_table] where <your_id> >= 140000001 and  [your_id] <=150000000 out [your_file_name]15.txt -c -t, -T -S [your_directory]

bcp select * from [your_table] where <your_id> >= 150000001 and  [your_id] <=160000000 out [your_file_name]16.txt -c -t, -T -S [your_directory]

bcp select * from [your_table] where <your_id> >= 160000001 and  [your_id] <=170000000 out [your_file_name]17.txt -c -t, -T -S [your_directory]

bcp select * from [your_table] where <your_id> >= 170000001 and  [your_id] <=180000000 out [your_file_name]18.txt -c -t, -T -S [your_directory]

bcp select * from [your_table] where <your_id> >= 180000001 and  [your_id] <=190000000 out [your_file_name]19.txt -c -t, -T -S [your_directory]

bcp select * from [your_table] where <your_id> >= 190000001 and  [your_id] <=200000000 out [your_file_name]20.txt -c -t, -T -S [your_directory]

Comment: This is exactly what I was looking for and I think it will do nicely!  Thanks very much for taking the time to help me.


JavaScript - innerHTML Mult. Ids

Question: I am very new to javascript and am trying to fill to multiple divs by ID.
So far I have:
function run() {
  var xhttp = new XMLHttpRequest();

  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
    obj = JSON.parse(xhttp.response);

    for (var i = 0; i <= obj.length; i++) {
    document.getElementById("posttitle"+i).innerHTML = obj[i]['title'];
    };

    for (var i = 0; i <= obj.length; i++) {
    document.getElementById("posttext"+i).innerHTML = obj[i]['content'];
    };

    }
  }
  xhttp.open("GET", "http://xxxx", true);
  xhttp.send();
}

HTML Setup

I can fill in the div for poststext[i] or posttitle[i] individually but when I run them together only the first only in the function works/fills in the Ids. What am I missing? Thanks!
Comment: @rodrigo-silveira Surely you're joking.
Comment: Well your elements are numbered starting at 1 but your loop starts at 0. Have you checked the developer console for errors?
Comment: Updated. I miscopied that piece of HTML from code but I still doesn't want to add to both divs.
Comment: The first thing to learn is how to open the browser's error console. The error messages are printed there. It helps a lot in debugging things like this.
Comment: The problem is that the URL you're using doesn't exist: ```http://xxxx => ERR_NAME_NOT_RESOLVED```
Answer: I believe its because you have <= which will try to grab a non existent element.
for (var i = 0; i < obj.length; i++) {
    document.getElementById("posttitle"+i).innerHTML = obj[i]['title'];
    document.getElementById("posttext"+i).innerHTML = obj[i]['content'];
};

Answer: Try this and remove the ";" after the for
for (var i = 0; i <= obj.length; i++) {
document.getElementById("posttitle"+i).innerHTML = obj[i]['title'];
document.getElementById("posttext"+i).innerHTML = obj[i]['content'];
}

JavaScript - innerHTML Mult. Ids


Why did artificial turfs affect the game play of India and Pakistan?

Question: A follow up to this question.
Introduction of artificial turfs are blamed for India and Pakistan no longer being the force in international hockey that they once were. (India won the Olympics gold from 1928 to 1956 and 1964, with Pakistan winning in 1960 and 1968). But after introduction of artificial turfs, their only gold was in 1980 Moscow Olympics, which was in a weakened field due to boycotts.
I understand that an even surface provided by the artificial turf would help a game play which focused on speed and long passes, but how would it inversely affect the game play based on dribbling and short passes?
Answer: There are many reasons why India suffered with the introduction of artificial turfs.  I was watching a program where the former Indian hockey players and the Experts were giving reasons why, the Indian players were failing to play well as a unit on the artificial turfs.
These were the points they mentioned in the show.

Unavailability of the synthetic turfs across the country. This can be attributed to the fact that laying these turfs will need huge investments, which Indian hockey federation never was able to manage. So the players come to play in the international matches after playing most of their games in academies on non-synthetic turfs. So they fail to play well as they need to have better control of the ball with the stick.
The coaches in the academies seem to still adopt non modern methods of training which will affect the players' game. The strategies, on which the game played, as they opined, were obsolete. So what they told was that the Indian coaches need to understand the game as it is now and train the players.

So in nutshell they were saying that the inability of the Indian hockey federation to cope to the changes done by the FIH as the main reason for Indian Hockey's decline.

The change in turf had a huge impact in a negative way as the Indian
  Hockey federation was not able to take measures to adapt to the changes.

We should also not forget the kind of corruption that existed in IHF. That might also be one of the reasons why we had horrible teams in the past competing in major tournaments.


Fast Java library for language detection of Tweets?

Question: According to this bug, Twitter's search API has been broken with regard to Language for at least 2 years: http://bit.ly/GQ244g so it seems unlikely they're going to fix it.
I've looked at the libraries mentioned on the other language detection threads, and they all look great and offer 95%+ accuracy. The question is, which one to use for Tweets?
I suspect that Tweets may be challenging because they're composed of language plus hashtags, which are typically in English. Additionally, my primary concern is performance. I don't mind losing a few Tweets if I can perform the filtering faster.
So my question is for those who have done language detection on Tweets: What library did you use, and what performance did you observe?
Answer: Did you try language-detection? It claims 99% precision for 53 languages. However, given that tweets are generally short I'm afraid that you can just dream of such a high precision...  You should try to generate your own language profiles out of twitter training data and with a subset of languages if possible (you need to do a bit of research on this). I don't know much about performances and it might be better if you can write your own tests.
EDIT:
Take a look at this Python project as well, you might want to try some integration with your java code base: https://github.com/shuyo/ldig
Answer: Take a look at Apache Tika.
Can be useful for a bunch of other things beyond just language detection:
http://tika.apache.org/1.5/detection.html#Language_Detection
Answer: You may use Microsoft's translator webservice from Java. https://datamarket.azure.com/dataset/1899a118-d202-492c-aa16-ba21c33c06cb (its free for 2.000.000 words per month and offers language detection)
Comment: Thank you for that suggestion. The primary concern I have with using any online webservice to do this (including Google's) is that the network latency alone is going to push performance beyond the acceptable range. I'm really looking for a Java library that I can run locally.
Comment: Then a very hard task waiting for you
Answer: You should use JLangDetect. I cannot recommend anything more than this.


What are the boundaries for subsets of $\mathbb{Q}$ in $\mathbb{R}$? Empty sets?

Question: Let $E := \{ p \in \mathbb{Q} : 0 < p < \sqrt 2 \}$.
(1) $\sqrt 2$ is not an inner point of $E$ because $\forall \delta \in \mathbb{R} : \sqrt 2 \not \in \bigcup_{x \in I} B(x, \delta) \subset E \subset \mathbb{Q} \subset \mathbb{R}$ and $\sqrt 2$ is not an outer point because $\forall \delta \in \mathbb{R} : \sqrt 2 \not \in \bigcup_{x\in I_{2}} B(x, \delta) \subset E^{c} \subset \mathbb{Q} \subset \mathbb{R}$. So $\sqrt 2$ is a boundary point of $\mathbb{Q}$ in $\mathbb{R}$.
(2) Notice that $0 \in \mathbb{R}$ and $0 \in \mathbb{Q}$. Since $\forall \delta > 0 : 0 \in \bigcup_{x\in I_{3}} B(x, \delta) \subset E \subset \mathbb{Q} \subset \mathbb{R}$ so $0$ is an inner point. $0$ is also an outer point because $\forall \delta > 0 : 0 \in \bigcup_{x \in I_{4}} B(x, \delta) \subset E^{c} \subset \mathbb{Q} \subset \mathbb{R}$. No boundary point.
[conlclusion, investigating]
Can you declare the borders in some other numbers such as complex numbers or some other way? I think one cannot do it but is there some result about it?
Comment: @gary: By definition a boundary point of a subset $S\subseteq X$ is a point whose every neighborhood intersects both $S$ and $X\setminus S$ (not $\operatorname{int}(S)$ and $\operatorname{ext}(S)$).
Comment: The boundary of $E=\{p\in\mathbb{Q}:00$ intersects both $intS$ and $ExtS$, then , since $intS$ is empty, p could not be a boundary point, right?
Answer: Associated with a subset $E$ in a topological space $X$ there are three subsets of $X$ which are pairwise disjoint and cover $X$. They are

the set of interior points of $E$ or $\operatorname{int}E$, which consists of the points having a neighborhood which is contained in $E$,
the set of exterior points of $E$ or $\operatorname{ext}E$, which consists of the points having a neighborhood which is contained in $X\setminus E$, and
the set of boundary points of $E$ or $\partial E$, which consists of the points whose every neighborhood intersects $E$ and $X\setminus E$.

Let's see what these sets are in the case of $E=\{p\in\mathbb{Q}:0<p<\sqrt{2}\}\subseteq\mathbb{R}$.
First take any point $x<0$. Then $(x-|x|,x+|x|)\subseteq(-\infty,0)\subseteq\mathbb{R}\setminus E$, which means $x$ is an exterior point of $E$.
Then take any point $x>\sqrt{2}$ and denote $r=x-\sqrt{2}>0$. Then $(x-r,x+r)\subseteq(\sqrt{2},\infty)\subseteq\mathbb{R}\setminus E$. Again $x$ is an exterior point of $E$.
Finally take any point $x\in[0,\sqrt{2}]$ and a neighborhood $U$ of $x$. The neighborhood $U$ contains an interval $(x-r,x+r)$ for some (small) $r>0$. Because $x$ is in $[0,\sqrt{2}]$, this interval $(x-r,x+r)$ intersects the interval $(0,\sqrt{2})$, and we know that if the intersection of two open intervals is nonempty, then it (being an open interval) contains both a rational and an irrational number. Furthermore the rational numbers in $(x-r,x+r)\cap(0,\sqrt{2})$ are in $E$ and the irrational numbers are in $\mathbb{R}\setminus E$. We have shown that every neighborhood of $x$ intersects both $E$ and $\mathbb{R}\setminus E$, which means $x$ is a boundary point of $E$.
The conclusion is that $\operatorname{int}E=\emptyset$, $\operatorname{ext}E=\mathbb{R}\setminus[0,\sqrt{2}]$ and $\partial E=[0,\sqrt{2}]$.
Answer: The closure of $E$ in $\mathbb{R}$ is $[0,\sqrt 2]$ and the interior of $E$ in $\mathbb{R}$ is empty. So the boundary of $E$ in $\mathbb{R}$ is the closed interval $[0,\sqrt{2}]$.
Comment: I find the last implication hard-to-understand bacause I cannot understand the quantifier between the last two statements. Is it right "The closure of $E$ in $R$ is $[0, \sqrt 2]$ **so** the interior of $E$ in $R$ is empty."? If yes, we have found only one of the three disjoint sets, namely the interior. You are apparently making a conclusion about the boundary without acknowledging the exterior.
Comment: No. I said "$\bar{E}=[0,\sqrt{2}]$ **and** $E^\circ=\phi$", not "$\bar{E}=[0,\sqrt{2}] \Rightarrow E^\circ=\phi$". That $E^\circ=\phi$ should be clear, because $E$ contains no nonempty open ball in $\mathbb{R}$ as its proper subset.
Comment: the complement of open sets is closed. Exterior, interior and boundary are disjoint. Closure and interior do not need to be disjoint. Closure - Interior = Boundary. Yes, you are correct here.
Answer: I think the word you're looking for is boundary. The boundary of a set $A \subset X$ (in $X$) is defined as $\overline{A} \setminus A^\circ$ and it's sometimes written $\partial A$. In your example the boundary of $E$ in $\mathbb{Q}$ is $\{0\}$ as $(0,\sqrt{2})\cap \mathbb{Q}$ is open in $\mathbb{Q}$ and $E$ has $0$ as a limit point.
Comment: yes but the question was about subsets of $Q$ in $R$, not about subsets of $Q$ in $Q$.


Salvar diferença entre arrays em um novo array

Question: O Script abaixo retorna a intersecção entre os arrays dentro de um novo array, eu queria salvar a diferença, no caso o que não pertence, como modificar esse script ?
SCRIPT:
values = []

a = [('SRV', 'CLIENT'),('SRV1', 'CLIENT'),('SRV2', 'CLIENT')]
b = [('SRV', 'CLIENT'),('SRV1', 'CLIENT'),('SRV3', 'CLIENT')]

gap = []
for row in a:
    if row[0] not in b:
        gap.append(row)

OUTPUT:

[('SRV', 'CLIENT'), ('SRV1', 'CLIENT')]

VISUALIZAR CÓDIGO
OBJETIVO

[('SRV2', 'CLIENT')]
Answer: Usando uma lógica parecida com a sua temos:
def diff(a, b):
        b = set(b)
        return [row for row in a if row not in b]

print(diff(a,b))

Mas acho mais simples:
gap = list(set(a)-set(b))
print(gap)

Comment: A lógica seria a mesma se os arrays fossem assim ? [u('SRV', 'CLIENT'),u('SRV1', 'CLIENT'),u('SRV2', 'CLIENT')] o exemplo representa um array preenchido com um select de um DB.
Comment: Estranho array dessa forma, ai não é array, explica melhor
Comment: Quando percorro um for dentro do array a saída é assim (u'campo',u'campo1',u'campo2')
Comment: O banco é db2,e uso as libs ibm_db e ibm_db_dbi


Is Sun's XML Instance Generator (xmlgen.jar) still available? If so, where?

Question: Since Oracle took over Sun... this specific resource has apparently vanished.  I tried the Wayback Machine but that didn't work out.  Is there still a copy/archive of the Sun XML Instant Generator tool out there on the 'net?
Answer: It's good I never delete any of my bookmarks!
It is and it was a part of Sun Multi-Schema XML Validator (now - Oracle...). It's still available, but it's a nightly build from March 2006. I was not able to find anything newer than that. The source code is available as well in SVN, confirming that it is an old tool.
It can be downloaded from java.net.
Current sources, thanks to Kohsuke, are available on github. Easy to build, it's just Maven project.
Comment: The current version of msv is on github.
Comment: Since there tends to be random account closures at github, I forked a copy, too. https://github.com/starlocke/msv
Comment: Java.net is dead and I couldn't find a built jar elsewhere.


What does it means &sa=U&ei?

Question: I have a website, today looking at the log, I found some request to a page from my server with appended this variable &sa=U&ei.
Could you tell me guys what &sa=U&e could mean? Could be an attempt to find Nullable Scrips? Could be a security threat?
&sa=U&ei=XuRBT92UFseYhQf_w7HeBQ&ved=0CNYBEBYwYw&sig2=Rt1Cr_FCPD1-6VYu__Oavg&usg=AFQjCNFlHVaDQL--kgDbOn2vNgUqwUOsTA

The error in my log is:

A potentially dangerous Request.Path value was detected from the client (&)
Answer: http://www.bleepingcomputer.com/forums/topic442637.html

But nevermind. I found the offending culprit. Seems that for some
  reason my "GoogleEnhancer" became "incompatible" with Firefox. It
  worked fine even before I updated to 10, but go figure. And it wasn't
  the whole add-on, it was the "Use Google Classic" radio button turned
  on. I got this add-on after Google started making their search engine
  so... oh, what's the word I'm looking for... umm... oh, yeah...
  crappy!

http://www.ausforces.com/showthread.php?6595-Google-is-acting-odd...

I figured out what it is... I have an add-on called google enhancer
  which obviously hasn't been updated properly of late. Disabled it and
  it worked fine. Well that was a waste of a thread. Thanks for the help
  though guys.

So, the unnecessary part of the request is created by an outdated add-on for Firefox, nothing serious. The visitors with that add-on have more problems than your website :)
Comment: Thanks Cheery, I suspect the same! Thanks for your answer!
Answer: Practically, it could just be simple url request.
And the random texts you are seeing could be an autogenerated random string to maintain sessions. As there seems nothing wrong with the URL, and those sa and ei simply means, that these get variables are assigned some values, which would then be used in your application, for may be session management or other purpose.
From the face of it, it doesn't appears to be any hackable stuff.

What does it means &sa=U&ei?


Setting Core Data property value with float type

Question: In a test iPhone app I am developing, I am trying to set the value of a float field in my Core Data model. The compiler is giving me an incompatible type error even though both the data type specified in my method is a float and the data type in model is a float.
This is the first project where I am using Core Data instead of SQLite 3.
<code>- (void)insertNewObject:(NSString *)titleTxt withAmount:(float)amount andDueDate:(NSDate *)due {
[newManagedObject setValue:amount forKey:@"amountDue"];
</code>
Answer: You'll have to make an NSNumber with the float.
Comment: I thought it'd be something of that nature. Thanks for the quick response.


Possible to access HealthIndicator methods as endpoints?

Question: By implementing HealthIndicator you can add custom health checks using Spring Boot and its actuator module.
These checks are listed all together using the /health endpoint.
Is it possible to request these custom health endpoints, for example /health/myCustomCheck?
Answer: The short answer is no. That is not provided by the actuator. You can verify this by calling the /mappings endpoint and seeing that only /health is mapped.
Now the long answer is you could add your own endpoint that invokes your custom health indicator. This isn't too hard to do. Spring will pick up any beans of type Endpoint for you and map them. A rough example would be something like this
@Bean
public Endpoint<Object> customHealthEndpoint(final MyHealthCheck health) {

    return new Endpoint<Object>() {

        @Override
        public String getId() {
            return "myHealthCheck";
        }

        @Override
        public Object invoke() {
           return health.health().getStatus();
        }

        @Override
        public boolean isEnabled() {
            return true;
        }

        @Override
        public boolean isSensitive() {
            return false;
        }

    };
}

You can then call /myHealthCheck and get back {"status":"UP"}.


Bootstrap tooltip hidden by parent div

Question: I'm using Bootstrap tooltips on my web app and they were being cut off by it's parent div.

To solve this I added data-container="body"
Hello

This solved the problem but a new problem came with it.
When I click on the anchor and navigate the tooltip won't disappear.
Has anyone come across this? Is there a simple way to solve this?
EDIT - JSFiddle similar to my problem http://jsfiddle.net/m9AX5/5/ except in my case the parent div doesnt get removed.
Comment: Instead of image, provide a demo of your code, it will be very useful for understanding your problem. You can use [JSFIDDLE](http://jsfiddle.net/).
Comment: $(".show_tip").tooltip({container: ''}); try this
Comment: @tejashsoni111 I couldn't make my own but this is quite similar to my problem http://jsfiddle.net/m9AX5/5/ except my parent div doesnt disappear.
Answer: It happens because the mouseleave isn't detected.
One solution is to hide tooltip on click action:
$('#button').on('click', function () {
  $(this).tooltip('hide')
})

Example:
http://jsfiddle.net/m9AX5/6/
Hope it helps.
Answer: As Andre mentioned, the mouseleave event isn't fired, so the tooltip doesn't get removed.
To do the same thing as hiding the tooltip, you can simply trigger the mouseleave event manually (Updated JSFiddle).
$(this).trigger('mouseleave');

While you haven't explained what happens when you click the element in your case, I would guess it's because the element was removed and the mouseleave event is never triggered. In this case, you should write an event listener and trigger the mouseleave element manually:
$('#anchor').click(function(){
    $(this).trigger('mouseleave');
}

Bootstrap tooltip hidden by parent div


Pulling CiviCRM data into a custom Drupal module based on checksum/hash link

Question: I have a CiviCRM contribution page that allows an individual to renew a membership on behalf of an organization. When we email them from CiviMail with a checksum link to the page, it will prefill their information in the form automatically and have the membership renewal associate correctly to the organization.
How can I pull the organizational information into a custom Drupal module (e.g. a block that displays in the sidebar, for example)? I would like to have a text block that displays some information about the org and potentially names of people who are related to the org by relationships in CiviCRM. I won't have a problem doing that with Views and/or the CiviCRM API in a custom Drupal module, but I'm not sure how to get the org's ID in this scenario, to know which info to display.
Answer: I am assuming you want to show the organization information of logged in contact.
So I would do following:

Get the contact id of logged in contact (or anonymous user who used a checksum link, via the cid field in the URL, as @petednz noted).
Get the current employer id
then retrieve address of current employer
Comment: Since you are using a checksum, drupal considers the current user is 'anonymous'. So for any Views block using 'current user' for the contextual filter won't work. But the checksum url does provide the id=xx so a bit of php in your Views contextual filter could get you what you need
Comment: Thanks, both. The anonymous user case was what I was stumped on, and I've expanded that issue in a followup question: http://drupal.stackexchange.com/questions/140841/how-to-ensure-civicrm-checksum-cid-are-valid-in-custom-drupal-module


show that $\lim _ {R \rightarrow \infty} R^{-p} \int_{R<\left|x\right|<2R}\left|u(x)\right|^p dx=0$

Question:
Consider $\mathbb{R}^n$ with Lebesgue measure, $n\geq2,\ 1<p<n$ and $p^*=\frac{np}{n-p}$. If $u\in L^{p^*}(\mathbb{R}^n$), show that $$\lim _ {R \rightarrow \infty} R^{-p} \int_{R<\left|x\right|<2R}\left|u(x)\right|^p dx=0$$

I have tried to solve this question but, I couldn't conclued it, let me share my solution:
It is enough to show that the integral is finite. Since $p^*=\frac{np}{n-p}$, after some calculations $p=\frac{p^*n}{p^*+n}$. Then $\int_{R<\left|x\right|<2R}\left|u(x)\right|^p dx=\int\left|u(x)\right|^{\frac{p^*n}{p^*+n}} dx\leq (\int \left|u(x)\right|^{p^*}dx )^\frac{n}{n+p^*}({\int 1dx})^\frac{p^*}{n+p^*}$ by Hölder's İnequality. We know that the first integral is finite since $u\in L^{P^*}(\mathbb{R}^n$). I think the second itegral is $R^\frac{p*}{n+p*}$. But then what is the limit?
Answer: You are almost done. So in total you get $$\lim _ {R \rightarrow \infty} R^{-p} \int_{R<\left|x\right|<2R}\left|u(x)\right|^p dx \le c\cdot\lim _ {R \rightarrow \infty}R^{\frac{p*}{n+p*}-p}$$ with $$c = \left(\int_\Bbb R \left|u(x)\right|^{p^*}dx \right)^\frac{n}{n+p^*}$$
But $\frac{p^*}{n+p^*} - p < 0$ hence $$\lim _ {R \rightarrow \infty}R^{\frac{p*}{n+p*}-p} = 0$$
and you are done.


Missing column while adding data into table using sequelize

Question: I am working with nodejs web application, just started, I created a Postgresql database and added some tables using sequelize.
In the process I created a table QuestionOptions which has columns Title:string and QueId:foreign key which were created and id, createdAt and updatedAt columns by default. Now if I try to add data into the table using this code:
app.post("/submitOptions", async (request, response) => {
  console.log("Options request body", request.body);
  try {
    for (const key in request.body) {
      if (key.startsWith("q-")) {
        const questionIDfromRequestBody = key.split("-")[1];
        const optionIndex = key.split("-")[3];
        const optionValueKey = `q-${questionIDfromRequestBody}-option-${optionIndex}`;
        const optionValue = request.body[optionValueKey];
        console.log(optionValue);
        const option = await QuestionOptions.addOption({
          Title: optionValue,
          QueId: questionIDfromRequestBody
        });
      }
    }
    // Store the added questions in a session variable
    return response.redirect(`/addElectors`);
  } catch (error) {
    console.log(error);
    error.errors.forEach((element) => {
      request.flash("error", element.message);
    });
    response.redirect("/addOptions");
  }
});

I have a request body like this:
Options request body [Object: null prototype] {
  _csrf: '550a1baf-04d2-46b1-9123-3977034d65c2',
  'q-11-option-1': '11',
  'q-11-option-2': '12',
  'q-12-option-1': '21',
  'q-12-option-2': '22'
}

but I get an

null values are inserted into the Title column

Executing (default): INSERT INTO "QuestionOptions" ("id","createdAt","updatedAt","QueId") VALUES (DEFAULT,$1,$2,$3) RETURNING "id","Title","createdAt","updatedAt","QueId";
Error
    at Query.run (/home/hemanth/Voting-app-master/node_modules/sequelize/lib/dialects/postgres/query.js:50:25)
    at /home/hemanth/Voting-app-master/node_modules/sequelize/lib/sequelize.js:315:28
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async PostgresQueryInterface.insert (/home/hemanth/Voting-app-master/node_modules/sequelize/lib/dialects/abstract/query-interface.js:308:21)
    at async QuestionOptions.save (/home/hemanth/Voting-app-master/node_modules/sequelize/lib/model.js:2432:35)
    at async QuestionOptions.create (/home/hemanth/Voting-app-master/node_modules/sequelize/lib/model.js:1344:12)
    at async /home/hemanth/Voting-app-master/app.js:269:24 {
  name: 'SequelizeDatabaseError',
  parent: error: null value in column "Title" of relation "QuestionOptions" violates not-null constraint
      at Parser.parseErrorMessage (/home/hemanth/Voting-app-master/node_modules/pg-protocol/dist/parser.js:287:98)
      at Parser.handlePacket (/home/hemanth/Voting-app-master/node_modules/pg-protocol/dist/parser.js:126:29)
      at Parser.parse (/home/hemanth/Voting-app-master/node_modules/pg-protocol/dist/parser.js:39:38)
      at Socket.<anonymous> (/home/hemanth/Voting-app-master/node_modules/pg-protocol/dist/index.js:11:42)
      at Socket.emit (node:events:513:28)
      at addChunk (node:internal/streams/readable:324:12)
      at readableAddChunk (node:internal/streams/readable:297:9)
      at Readable.push (node:internal/streams/readable:234:10)
      at TCP.onStreamRead (node:internal/stream_base_commons:190:23) {
    length: 275,
    severity: 'ERROR',
    code: '23502',
    detail: 'Failing row contains (6, null, 2023-03-19 04:39:56.652+00, 2023-03-19 04:39:56.652+00, 11).',
    hint: undefined,
    position: undefined,
    internalPosition: undefined,
    internalQuery: undefined,
    where: undefined,
    schema: 'public',
    table: 'QuestionOptions',
    column: 'Title',
    dataType: undefined,
    constraint: undefined,
    file: 'execMain.c',
    line: '1883',
    routine: 'ExecConstraints',
    sql: 'INSERT INTO "QuestionOptions" ("id","createdAt","updatedAt","QueId") VALUES (DEFAULT,$1,$2,$3) RETURNING "id","Title","createdAt","updatedAt","QueId";',
    parameters: [
      '2023-03-19 04:39:56.652 +00:00',
      '2023-03-19 04:39:56.652 +00:00',
      '11'
    ]
  },
  original: error: null value in column "Title" of relation "QuestionOptions" violates not-null constraint
      at Parser.parseErrorMessage (/home/hemanth/Voting-app-master/node_modules/pg-protocol/dist/parser.js:287:98)
      at Parser.handlePacket (/home/hemanth/Voting-app-master/node_modules/pg-protocol/dist/parser.js:126:29)
      at Parser.parse (/home/hemanth/Voting-app-master/node_modules/pg-protocol/dist/parser.js:39:38)
      at Socket.<anonymous> (/home/hemanth/Voting-app-master/node_modules/pg-protocol/dist/index.js:11:42)
      at Socket.emit (node:events:513:28)
      at addChunk (node:internal/streams/readable:324:12)
      at readableAddChunk (node:internal/streams/readable:297:9)
      at Readable.push (node:internal/streams/readable:234:10)
      at TCP.onStreamRead (node:internal/stream_base_commons:190:23) {
    length: 275,
    severity: 'ERROR',
    code: '23502',
    detail: 'Failing row contains (6, null, 2023-03-19 04:39:56.652+00, 2023-03-19 04:39:56.652+00, 11).',
    hint: undefined,
    position: undefined,
    internalPosition: undefined,
    internalQuery: undefined,
    where: undefined,
    schema: 'public',
    table: 'QuestionOptions',
    column: 'Title',
    dataType: undefined,
    constraint: undefined,
    file: 'execMain.c',
    line: '1883',
    routine: 'ExecConstraints',
    sql: 'INSERT INTO "QuestionOptions" ("id","createdAt","updatedAt","QueId") VALUES (DEFAULT,$1,$2,$3) RETURNING "id","Title","createdAt","updatedAt","QueId";',
    parameters: [
      '2023-03-19 04:39:56.652 +00:00',
      '2023-03-19 04:39:56.652 +00:00',
      '11'
    ]
  },
  sql: 'INSERT INTO "QuestionOptions" ("id","createdAt","updatedAt","QueId") VALUES (DEFAULT,$1,$2,$3) RETURNING "id","Title","createdAt","updatedAt","QueId";',
  parameters: [
    '2023-03-19 04:39:56.652 +00:00',
    '2023-03-19 04:39:56.652 +00:00',
    '11'
  ]
}
/home/hemanth/Voting-app-master/app.js:279
    error.errors.forEach((element) => {
                 ^

TypeError: Cannot read properties of undefined (reading 'forEach')
    at /home/hemanth/Voting-app-master/app.js:279:18
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

Node.js v18.13.0
[nodemon] app crashed - waiting for file changes before starting...

I noticed in the first line of the error it says "Executing (default): INSERT INTO "QuestionOptions" ("id","createdAt","updatedAt","QueId") VALUES (DEFAULT,$1,$2,$3) RETURNING "id","Title","createdAt","updatedAt","QueId";"
it it missing Title column in ("id","createdAt","updatedAt","QueId") but whereas when returning it says "RETURNING "id","Title","createdAt","updatedAt","QueId";" which contains Title column.
I cannot figure out what to do, I tried dropping and creating a new table from scratch but it behaves the same.
I am expecting some value in the Title column of my QuestionOptions table instead of null, I even added notNull constraint.
Comment: here is the git link for my project, https://github.com/20N31A0318/Voting-app
Answer: The error "null value in column 'Title' of relation 'QuestionOptions' violates not-null constraint" means that the 'Title' field in the 'QuestionOptions' table is set to not-null and a null value is being inserted into that field.
The error message is telling you that there is an issue with inserting null values into the 'Title' column of the 'QuestionOptions' table. You need to make sure that you are passing a non-null value for the 'Title' field when creating a new 'QuestionOption' object.
Check the value of 'optionValue' that you are passing to the 'Title' field. It seems that it is null, causing the error. You may need to add some validation to make sure that 'optionValue' is not null before attempting to create the 'QuestionOption' object.
Also, check that the 'Title' field in the 'QuestionOptions' table is set to allow null values if you want to be able to insert null values into that field. If the field is not set to allow null values, you will need to pass a non-null value for the 'Title' field when creating a new 'QuestionOption' object.
Comment: I tried printing the value of "optionValue", the out put is this :
`"Options request body [Object: null prototype] {
  _csrf: '150021c9-b377-4dc3-ba18-88ee4322e510',
  'q-13-option-1': '11',
  'q-13-option-2': '12',
  'q-14-option-1': '21',
  'q-14-option-2': '22'
}
11
12
21
22"`
`11
12
21
22` is the output i get for the optionValue. They are not null.


Lambdas execution inside Java 8 distribution

Question: Lambdas in Java 8 provides a great way to define the problem as a statement and keeps the code concise. But do they change the way in which statements are executed in the JVM?
Lets consider i am writing a lambda which streams a list of objects and filters them based on a condition and returns the filtered values as a list of the same data type. My lambda would basically have a filter and a collector.
When this piece of code is sent to the VM, does the compiler replace the lambda functions with traditional if loops and for loops?
I am asking this because the Virtual Machine is still the same and it was originally designed for imperative style of programming. What really changed in Java 8 was the way(FP) in which we define a problem statement. Is my understanding correct?
Comment: You seem to be confusing lambdas with stream pipelines.
Comment: http://stackoverflow.com/questions/16827262/how-will-java-lambda-functions-be-compiled
Comment: http://stackoverflow.com/a/15241404/2711488
Answer: The compiler doesn't "replace" the lambda functions.  The lambdas just become instances of normal interfaces that get passed to normal Java libraries that get run as normal Java code.
The JIT's certainly been optimized somewhat to be smarter about the ability to inline and simplify lambda calls, but there's no magic there.
Comment: I doubt that the JIT knows anything about lambdas. Since they are composed of methods and classes just like any other code, a JIT will attempt to recognize known patterns, regardless of whether the code in question stems from a lambda expression. Applying a potential optimization to the code of lambda expressions only, would be an unnecessary restriction.


File Copy Flutter Plugin in Android with Kotlin

Question: Trying to create a Flutter plugin that copies an asset file to the native Application Documents Folder.
For iOS, I achieved this by the following code (see below).
However, since I do not have much knowledge of the Android architecture, I would like to know how my Android MethodChannel code should look like.
My Android part of this Flutter plugin needs to be in KOTLIN !
I need a file copy from the Android assets folder to the Documents Folder of Android - all this done inside the Flutter plugin and in Kotlin!
Again, I have iOS in Swift ready made. What is missing is the Android in Kotlin counter part. Do you have any help on this ?
.
Here is the working code for the iOS FlutterMethodChannel in Swift:
(i.e. it copies a file from the main-bundle to the Documents-Directory of the iPhone...)
import UIKit

private func copyFile(fileName: String) -> String {

    let fileManager = FileManager.default
    let documentsUrl = fileManager.urls(for: .documentDirectory,
                                        in: .userDomainMask)
    guard documentsUrl.count != 0 else {
        return "Could not find documents URL"
    }

    let finalURL = documentsUrl.first!.appendingPathComponent(fileName)

    if !( (try? finalURL.checkResourceIsReachable()) ?? false) {
        let documentsURL = Bundle.main.resourceURL?.appendingPathComponent(fileName)
        do {
            try fileManager.copyItem(atPath: (documentsURL?.path)!, toPath: finalURL.path)
            return "\(finalURL.path)"
        } catch let error as NSError {
            return "Couldn't copy file to final location! Error:\(error.description)"
        }
    } else {
        return "\(finalURL.path)"
    }
}

In Kotlin, I tried this - but it does not work at all....:(
import java.io.File

private fun copyFileTrial1(fileName: String): String {

  File src = new File("../../assets/${fileName}");
  File dst = new File("../../DocumentsFolder/${fileName}", src.getName());
  FileInputStream inStream = new FileInputStream(src);
  FileOutputStream outStream = new FileOutputStream(dst);
  FileChannel inChannel = inStream.getChannel();
  FileChannel outChannel = outStream.getChannel();
  inChannel.transferTo(0, inChannel.size(), outChannel);
  inStream.close();
  outStream.close();
  return "hello1"
}

Or I tried this - but again - completely without success :(
private fun copyFileTrial2(fileName: String): String {

    InputStream in = null;
    OutputStream out = null;
    try {
      in = assetManager.open(fileName);
      String outDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/X/Y/Z/" ;
      File outFile = new File(outDir, filenfileNameame);
      out = new FileOutputStream(outFile);
      copyFile(in, out);
      in.close();
      in = null;
      out.flush();
      out.close();
      out = null;
    } catch(IOException e) {
      Log.e("tag", "Failed to copy asset file: " + fileName, e);
    }
    return "hello2"
}

private void copyFile(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[1024];
    int read;
    while((read = in.read(buffer)) != -1){
      out.write(buffer, 0, read);
    }
}

Answer: I have finally found a solution to file copy issue in Kotlin !
It was especially helpful in achieving my very first Flutter plugin.
Here is the solution of the file-copy in Kotlin
    import java.io.File
    import java.io.InputStream
    import io.flutter.util.PathUtils

    private fun copyFile(fileName: String): String {

      val assetStream: InputStream = mRegistrar.context().assets.open(fileName)
      val appliationDocumentsFolderPath: String = PathUtils.getDataDirectory(mRegistrar.context())
      val outputFilePath: String = appliationDocumentsFolderPath + "/" + fileName

      if (!File(outputFilePath).exists()) {
        File(outputFilePath).copyInputStreamToFile(assetStream)
      }
      return outputFilePath
    }

    private fun File.copyInputStreamToFile(inputStream: InputStream) {
      inputStream.use { input ->
        this.outputStream().use { fileOut ->
          input.copyTo(fileOut)
        }
      }
    }


Why Clojure's reverse function returns a non-lazy sequence?

Question: Why the designers of Clojure's reverse function decided that the returned sequence isn't a lazy one?
Clojure embraces lazy sequences usually.
Answer: Surely it's because by definition, in order to reverse a sequence, you have to know what's at the other end in order to return what will become the first item in the reversed collection.
Hence, the sequence must be finite, and you'd have to evaluate it in order to use what lies at it's end.
Addendum:
Reverse doesn't make sense as an infinite sequence, (although it's fair to say that infinite sequences are not always a prerequisite for laziness).
If you are about to reverse a collection, then you already have it loaded in memory; it doesn't need to be calculated.
Comment: @Chiron But have already read all of the end, there is no sense to delay.
Comment: From the Joy of Clojure: "The primary advantage of laziness in Clojure is that it prevents the full realization of interim results during a calculation" … "laziness guarantees that sequences won't be fully realized in memory at any given step". In the case of a reversal, we have no interim results. It's all done in one move with a reduce & conj.
Comment: What? You mean your computers only ever run forwards in time?! Ridiculous! (;-))
Comment: >>> e.g. `(reduce conj () '(1 2 3))` => `(3 2 1)`
Comment: I got your point but maybe I'm missing something. Yes the sequence should has an end in order to be reverse-able, but why reverse function returns a non-lazy result?
Comment: If you want on it, (lazy-seq *1)
Answer: rseq returns a seq that traverse a collection in reverse order. It only works on reversible collections such as vector, sorted-set and sorted-map.
reverse will reverse any finite seq but does so at the cost of going through all the items and perpending them to a list. It is implemented as (reduce conj () coll). This is obviously non-lazy.
Comment: This explains "why" in terms of how it's implemented. It doesn't answer why this implementation is chosen, which I think is the real question.
Comment: @ivant This implementation is chosen for its efficiency. You could build a lazy version of reverse which traverses the input seq numerous times up to the [(count-1)th, (count-2)th, (count-3)th, …] item as a lazy seq is consumed. But building a list in one go and returning it makes more sense. For collections that are reversible of course you should use rseq.
Answer: Further to Scott's answer:
The reverse function reduces its sequence argument, element by element. If we can make reverse truly lazy, we can do the same with other reductions. So let's write a lazy version of reduce:
(defn lazy-reduce [f init coll]
  (lazy-seq
   (if (seq coll)
     (lazy-reduce f (f init (first coll)) (rest coll))
     init)))

This only works on sequences, by the way.
But it works:
(lazy-reduce conj () (range 5))
; (4 3 2 1 0)

If we never touch the result, nothing is computed. We win. But as soon as we touch the first element, the whole sequence is realized, unravelling like knitting with a dropped stitch.
Comment: btw Jeff Terrell has an interesting blog post [Lazy reduce in Clojure](https://jeffterrell.tech/posts/2015-02-24-lazy-reduce-in-clojure/).


Fourier Series in different forms

Question: I am trying to write the Fourier series of $(1-x)$ in $[0,1]$ in two different ways:
$$f(x) = \frac{a_0}{2}+\sum_{n=1}^\infty (a_n\cos(\pi nx/L)+b_n\sin(\pi n x/L)),$$
$$f(x)=\frac{a_0}{2}+\sum_{n=1}^\infty (a_n\cos(2\pi nx/L)+b_n\sin(2\pi n x/L)),$$
If I use the first one to write the Fourier series of $(1-x)$ in the interval $[0,1]$, I get $$f(x)=1/2+\sum_{n=0}^\infty \left\{\frac{2(1-(-1)^n)}{n^2\pi^2}\cos(n\pi x)+\frac{2}{n\pi}\sin(n\pi x)\right\}.$$
If I use the second one, however, I get
$$f(x) = 1/2+\sum_{n=0}^\infty \frac{\sin(2\pi nx)}{\pi n}.$$
Shouldn't they result in the same series?
How I calculated the coefficients in the first case:
$$b_n=2\int_0^1(1-x)\sin(n\pi x)dx$$
$$a_n=2\int_0^1(1-x)\cos(n\pi x)dx$$
For the second case:
$$b_n=2\int_0^1(1-x)\sin(2\pi nx)dx$$
$$a_n=2\int_0^1(1-x)\cos(2\pi nx)dx$$
Comment: If you are calculating the series over the same period, yes. What values did you use for $L$ in the two series?
Comment: It would be helpful if you shared some details of how you computed the coefficients. For instance how did you compute the constant terms? Since these only involve integrating your function over the interval I am mystified that you got a different result in both cases.
Comment: See the edited version. I also discovered a mistake in the second series, but my question is still valid.
Comment: I guess my question is how I'm supposed to get cosines in the second series.
Answer: Your second calculation is correct and corresponds to the function $f$ with period $1$ such that $\forall x\in(0,1),f(x)=1-x$.
Your first calculation, where
$$g(x)=\frac{a_0}{2}+\sum_{n=1}^\infty \left(a_n\cos(\pi nx)+b_n\sin(\pi n x)\right)$$ and the real coefficients $a_n,b_n$ are given by
$$a_n+ib_n=2\int_0^1(1-x)e^{i\pi nx}dx,$$
corresponds to the function $g$ with period $2$ such that $\forall x\in(0,1),g(x)=1-x$ and $\forall x\in(1,2),g(x)=0$.

Fourier Series in different forms


Creating a centered table with Bootstrap

Question: I have 20 icons and I want to make a centered horizontal line of images from them. But I can't use HTML table because I want it to be responsive. It should be wrapped for mobile users. By using HTML table I guess I should use 1 row and 20 columns, but it won't wrap for small screens.
I created a group of divs like this. The view of this is OK.
http://jsfiddle.net/mayJ6/

But this answer tells not to use display inline block in this situation. Is there a better solution that looks similar, by using Twitter Bootstrap etc. ?
Answer: I think for this case display: inline-block is perfectly fine.
In the answer you reference they are talking about the main layout, like when you have 2 or 3 columns and want to display them side by side, in which case floating them is better.
You can achieve the same result with floats but you'll have to wrap the photos / icons with a container and set a fixed width or padding in order to center them like this. It will still wrap on smaller resolutions if you set the width in percentages like in my example here: http://jsfiddle.net/E9pS9/


duvida função javascript

Question: tenho uma pagina com uma tabela e dados vindo do banco, essa pagina possui refresh automático, os dados estão vindo de outra pagina (getdados.php), essa tabela possui uma coluna chamada status, que por default quando e inserido no BD ela vai como disponível, nesta mesma coluna adicionei um botão pra mudar o status para: pendente e recolhido, mas a minha função javascript não esta funcionando, o que ha de errado?
arquivo getdados.php

duvida função javascript


Why $_SERVER['HTTP_HOST'] sometimes return uppercase?

Question: I use $_SERVER['HTTP_HOST'] to check my script running on correct domain and send an email when it runs on illegal domain. The problem is that sometimes I receive incorrect alerts that script run on incorrect domain. It is a false alert with $_SERVER['HTTP_HOST'] in uppercase.
First, why this happen?
Second, is this safe to check $_SERVER['HTTP_HOST'] or is there a better why?
Note: I didn't convert value to lowercase in my code.
Comment: if you're including it from another file, then it can be faked...
Comment: @home it would be if it's using $_SERVER.
Comment: @pgl: Apologies, that's why I asked - I do not know PHP :-) Added PHP tag.
Comment: @home Oh, no worries - I didn't mean to sound rude, sorry!
Comment: @home yes that is PHP ;) thanks for tag
Comment: @CharmingPrince : I get same alert from my secured server. I am sure I am not hacked :D and there is not included file
Answer: $_SERVER['HTTP_HOST'] is the hostname that the script was accessed by. So, if someone goes to http://WWW.EXAMPLE.COM/ it'll be uppercase.
It's safe to check, just convert it to lowercase with strtolower() first.
Edit: I say it's safe to check, but there is one caveat: user agents using HTTP/1.0 won't supply a Host: header, so $_SERVER['HTTP_HOST'] will be unset. This is very unlikely to happen, but if you want to protect against it make sure you code for that possibility.
Comment: but all web browsers convert domains to lowercase automatically and I do not get alert when type it in uppercase.
Comment: Then it would be a good idea for you to post the code that generates the alert, along with some sample output.
Comment: here is it:

 $valid_domain="example.com";

 if(@strpos(@$_SERVER['HTTP_HOST'],$valid_domain)===FALSE)
  @mail('toemail', 'alert', $_SERVER['HTTP_HOST']);

 // I get EXAMPLE.COM sometimes in emailed alert.

Comment: I can't reproduce an upper case HOST with a standard browser but there may be some bookmark plugin etc that manages to create them. While most of the upper case HTTP_HOST instances seem to be definitely badly written robots I did find at least one valid looking user sending an upper case host with an agent of "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36".


Pointer is not being passed during a linked list swap

Question: This will most likely seem like I am missing something obvious but when I try to pass a Linked List pointer to my Selection sort I get a NULL pointer problem. In my C code I have this as my linked list:
typedef struct iorb
{
    int base_pri;
    struct iorb *link;
    char filler[100];
} IORB;

Then I pass my new linked list into this function after creating it:
void swapNodes(POINTER *head, POINTER CurrentHead, POINTER CurrentMinimum, POINTER TempSwap);

POINTER SortList(POINTER *head, char *SortMethod[])
{
    POINTER TempHead = *head;

    //Only one node, no need to sort.
    if (TempHead->link == NULL)
    {
        return head;
    }

    //Store node with the new minimum value.
    POINTER TempMin = *head;

    //Store curent node for swapping
    POINTER TempSwap = *head;

    //Transverse the list.
    POINTER TempCurrent;
    for (TempCurrent = *head; TempCurrent->link != NULL; TempCurrent = TempCurrent->link)
    {
        //Check if this node has a lower priority than the current minimum and if so, swap them.
        if (TempCurrent->link->base_pri < TempMin->base_pri)
        {
            TempMin = TempCurrent->link;
            TempSwap = TempCurrent;
        }
    }

    //Swap nodes if the head is not the same as the minimum.
    if (TempMin != TempHead)
    {
        swapNodes(&TempHead, TempHead, TempMin, TempSwap);
    }

    //Recursively sort the rest of the list.

    //FOR SOME REASON THE NODE POINTER IS NOT BEING PASSED HERE (EMPTY)
    TempHead->link = SortList(TempHead->link, *SortMethod);

    return head;

}

void swapNodes(POINTER *head, POINTER CurrentHead, POINTER CurrentMinimum, POINTER TempSwap)
{
    //Set new head as the minimum.
    *head = CurrentMinimum;

    //Link the current temp swap to the head.
    TempSwap->link = CurrentHead;

    //Swap pointers.
    POINTER temp = CurrentMinimum->link;
    CurrentMinimum->link = CurrentHead->link;
    CurrentHead->link = temp;
}

I am not sure why it is isn't being passed back into the same function, when I debug the linked list seems okay. I suspect that I am missing something in the swap node function, but I don't quite understand what this is. Can someone please offer some insight as to how this code should go for swapping the nodes around?
If you need additional information please let me know.
Comment: what is `POINTER`? I don't see it defined. Probably some `typedef` of a pointer, but then, don't do that. It's just confusing ...
Comment: Note: that you are trying to sort a list, by using a selection sort, this is highly ineffective and this is clearly not easy to do with a list, in my opinion this is where you should use a merge sort. It very easy with this kind of data representation.
Comment: `SortList(TempHead->link, *SortMethod);` shouldn't this produce a warning ? You must send the new head address.
Comment: Hi,  Stargateur is right, I was passing this the wrong way. I should have actually written that as &TempHead instead of TempHead->link
Comment: Sorry and just one more thing as well - this is an assignment I have so I am actually required to use the Selection Sort specifically. Perhaps because it is difficult to manage :)
Answer: SortList(TempHead->link, *SortMethod); needs to be listed as SortList(&TempHead, *SortMethod);
To correctly pass the pointer.


O que "android.R.id.content" significa?

Question: Estou seguindo um tutorial aqui e ele faz referência a isso nessa linha:
getSupportFragmentManager().findFragmentById(android.R.id.content);

Qual o significado deste identificador?
Answer: Explicação: O android.R.id.content É uma constante que tem o valor de um número Inteiro, que é o endereço referenciado a tal conteúdo, que está declarado em R.java que é um arquivo que é gerado toda vez que você der Build no projeto.
Explicação do contentem si:
android.R.id.content - É um numero inteiro usado para referenciar ou identificar o elemento usado como base de sua View.
A cada elemento que você criar, você terá um endereço para ele no R.java, este android.R.id.content é apenas uma maneira mais facil de referenciar ao seu elemento.
Também é utilizado android.R.layout.nomedolayout para referenciar Layouts em XML em sua aplicação.
Eles são Resources da sua aplicação, por isso ficam na pasta res do seu projeto Assim como há outros:
android.R.strings.nomedastring - para strings cadastradas em res/values/strings.xml
android.R.color.nomedacor - para cores cadastradas em res/values/colors.xml
android.R.attr.nomedoatributo - para atributos declarados em res/values/attrs.xml
android.R.style.nomedoestilo - para estilos que estão em res/values/styles.xml
Detalhes:
As strings são utilizadas para reutilizar a mesma string para vários locais, ou também para alterar apenas um lugar quando quiser alterar um padrão, como por exemplo um título que é usado em todas as Activity's do seu projeto, voce deseja altera-lo e para não ter que alterar em todos os Layout's você usa uma string no Layout e depois basta alterar ela no Strings.xml
Color's tem o mesmo objetivo como as strings mas seriam, no caso, cores.
Attr's, são atributos, porém consistem com o mesmo objetivo.
Styles são usados para criar temas e modificar estilos padrões do Android para componentes do Android.
Essas propriedades citadas, são utilizadas no Visual de sua Activity ou seja, no Layout.
Obs: Os layouts ficam em res/layout.
Comment: Entendi, e marquei como resposta. Valeu!
Comment: Obrigado! Acho que não fui específico o bastante. Minha dúvida é quanto ao android.R.id.content exatamente. Não sei o que é o "content".
Comment: Bom, achei que isto fosse meio óbvio, desculpe, vou editar a resposta.
Comment: Disponha, eu que agradeço.
Answer: É o valor da root view. "android." não é utilizado para referenciar resources do próprio app. Para seus próprios resources, utilize apenas R., não android.R.
Answer: O android.R.id.content e um identificador genérico para o elemento root da view.

O que "android.R.id.content" significa?


RewriteCond and RewriteRule to do a permanent redirect to https://www. and keep the query string

Question: I am using the mod_rewrite condition/rule as shown below to redirect a url to the www equivalent and ensure https.
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301,NC]

This, for example, converts example.com/foo/bar to https://www.example.com/foo/bar and works fine. However, if the link includes a query string (eg, http://example.com/foo/bar?x=baz&y=qux), the query string does not get appended. How can I modify my RewriteCond/RewriteRule above so that http://example.com/foo/bar?x=baz&y=qux is automatically converted to
https://www.example.com/foo/bar?x=baz&y=qux with the query string appended? I have tried adding the QSA (Query String Append) flag in the rewrite rule and that doesn't help.
Comment: The rule as posted would already preserve the query string, so it's likely that _something else_ is removing it.
Answer: You need the QSA flag (Query String Append)
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301,NC,QSA]

Second Option
RewriteRule ^(.*)$ https://www.example.com/$1?%{QUERY_STRING} [L,R=301,NC]

Comment: I would post more of your htaccess as there may be things conflicting with it
Comment: Here's a little more:

RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301,NC]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]


Depending on the argument passed in url go to specific content type

Question: I have a link "Add Details". suppose when I click on the Add Details, I will send arguments to the urls. such as in url "http://localhost/drupal/video" video will be my argument. When I click on "Add Details" link if argument is video then I want to go to "Video content type".
When I click on "Add Details", if argument passed is "image" in url("https://localhost/drupal/image), Then I want to go to "image content type".
When I click on "Add Details" link depending on the argument passed in URL I want to go to specific Content type.
How to achieve this.
Any help is appreciated.
Answer: Use hook_menu in custom module to achieve this using below code !
Change the links of Add Details to "goto/video" means full url will be localhost/drupal/goto/video
<code>function yourmodule_menu() {
    $menus['goto/%'] = array(
        'title' => 'Just Redirect',
        'page callback' => 'drupal_redirect_to_content_type',
        'page arguments' => array(1),
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
    );
    return $menus;
}

function drupal_redirect_to_content_type($type) {
  drupal_goto("admin/structure/types/manage/" . $type);
}
</code>
Otherwise,
Instead of above what you can do it directly give Add Details link to admin/structure/types/manage/ . $type instead of drupal/$type
Comment: See my updated answer ! Change the links of Add Details to "goto/video" means full url will be localhost/drupal/goto/video Clear menu cache after doing changes !
Comment: Is there anything wrong with the code:function drupal_redirect_to_content_type($type) {
  if($type == 'videolibrary'){
  drupal_goto("drupal/node/add/exhibit");
  }
 else{
  drupal_goto("drupal/node/add/section");
 }
 } When I click on the "Add Section Details" which is hyper linked to "http://localhost/drupal/videolibrary" Getting page not found error. sorry If anything is wrong with my coding.
Comment: remove drupal , make it "node/add/exhibit" if you are in localhost then localhost/drupal will become your base path !
Comment: Same page not found error is occuring  with the url showing "http://localhost/drupal/videolibrary"
Comment: Did all the things mentioned . But still getting the same page not found error. Am I missing anything?
Comment: Thanks Its working.Forgot to place [goto/%} in hook_menu.


Border-bottom I can't remove

Question: I'm stuck in IONIC 2 for removing something like a border-bottom on ion-item tag as presented in the picture attached.
Picture of the border I want to remove
My code is below:
<ion-header>
  <ion-navbar>
    <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-item class="header-item">
      <ion-avatar item-start>
        <ion-icon name="add-circle"></ion-icon>
      </ion-avatar>
      <ion-title>Gallerie</ion-title>
    </ion-item>
  </ion-navbar>
</ion-header>

And my CSS below:
.header-item {
        background: transparent;
        border: none;
    }

Have you any idea?
Thanks for your help!
Comment: that is not a border, that is `box-shadow`
Answer: Just like you can see in in the docs, you can use the no-lines attribute to remove that line:
<ion-item no-lines>
  Item with no border
</ion-item>

Comment: Thanks for your support, it's perfect! I didn't find the information, I've gone through the doc to quickly.

Border-bottom I can't remove