Is there an O(1) way to turn a std::map into a std::set

Question: I'd like to do some set intersection operations on the keys of a std::map<> instance without duplicating the keys into a std::set<> beforehand.
It's not documented in the API, but is there any way in O(1) time to extract the keys from a std::map<> and put them into a std::set<>?
Comment: What does O(1) mean? You mean an operation that has universally bounded time and space requirements for *any* imaginable input map?
Comment: @honk: Hm. I'm also not sure what "exract" means. If the OP wants a copy, then that's sort of obviously impossible. On the other hand, if you just want a "view" type iterator... a simple boost.transform-iterator could probably do the trick.
Comment: How do you plan to do the set intersection?
Comment: @KerrekSB, there *could* be an implementation of `map<>` that would allow that. The way it actually *is* implemented, yeah, it's impossible.
Comment: Even if there was an O(1) way, wouldn't that still be "duplicating the keys into a `std::set<>`" before doing the intersection?
Answer: Create an iterator adapter that returns first for the map and use it with set_intersection.
Answer: Firstly no, there is not an O(1) operation to get a set of keys from a map. Constructing the set would have to be Omega(n).
However, you can do the set_intersection you want directly on the map and the other range, whatever that is. Untested code:
template <typename InputIterator, typename Map, typename OutputIterator>
void map_set_intersection(InputIterator first, InputIterator last, const Map &m, OutputIterator o) {
    std::set_intersection(
        first, last,
        m.begin(), m.end(),
        o,
        KeyCompare<typename Map::value_type, typename std::iterator_traits<InputIterator>::value_type>()
    );
}

All the magic is in the KeyCompare type:
template <typename MapValue, typename SetValue>
struct KeyCompare {
    bool operator()(const MapValue &lhs, const SetValue &rhs) {
        return lhs.first < rhs;
    }
    bool operator()(const SetValue &lhs, const MapValue &rhs) {
        return lhs < rhs.first;
    }
};

std::set_difference is defined to copy values from the first range specified, which in this case is the range defined by the iterators. It can do that provided that it can compare values in the first range with values in the second range in either order (which it can, thanks to KeyCompare). The two ranges don't need to have the same type, so you don't need a set of keys from the map.
If you're already using the 6-parameter form of set_intersection, then you need to change KeyCompare so that after taking the key out of the map entry, it uses your comparator instead of <.
If you're using a custom comparator or overloaded operator< and the value type of the iterator range is the same as the value type of the map, then this doesn't work. KeyCompare can no longer use the types to work out which order the arguments have been provided and hence which one it should extract the first out of. I don't think this is a very common scenario, but I also don't see an escape from it using this approach. You'd need Crazy Eddie's solution, adapt the map iterator. Which amounts to this question: Iterate keys in a C++ map
Comment: I think you could make `KeyCompare` work when the types are the same iff the map is non-const, using `operator()(MapValue&, const SetValue&)` and `operator()(const SetValue&, MapValue&)` to exploit the fact that `std::set::iterator` is a constant iterator (guaranteed in C++11) but `std::map::iterator` is not. I haven't actually tested that theory, but I think it'd work.
Comment: Are you sure this is allowed?  Is it guaranteed that the output iterator assignment will be used with the type of the left side of the intersection?  If so then I this works...I'd considered giving it as an answer.  If not then the iterator adapter is needed if you want to be portable.  I don't think that the two can be the same since if you're comparing the key of the map to the value of the set then the key must equal the type of the set and this would preclude, I think, any and all possibility of them being the same type.  The type would have to somehow be recursive otherwise.
Comment: (1) [set.intersection] says, "the first min(m, n) elements shall be copied **from the first range** to the output range, in order".
Comment: @CrazyEddie: (2) I don't think you need a recursive type to break my code. Someone might have a `set>` that they want to intersect with the keys of a `map`. This will break my code. How did they ever expect to do the intersection, with non-matching types? Anticipating that they would extract the keys of the map into a set, that person has overloaded `operator<(int, std::pair)` and `operator<(std::pair,int)`, so that their set can be intersected with the set of keys of their map. They're a menace to society, but they're writing legal C++.
Comment: The general point being that `set_intersection` is scarily flexible. It can intersect anything that you can compare. The two iterator value types don't otherwise need to be related and they certainly don't need to be the same. "if you're comparing the key of the map to the value of the set then the key must equal the type of the set" -- not necessarily.
Comment: Well, yeah, your code breaks in that case just as if someone tried to compare a `std::set` to a `std::map`.  What I'm saying is that there's no way to create a type that matches the concept that your solution tries to solve that has the problem you're talking about.  Under your example it would be `set>` -> `map,??>` and this would behave fine.  Where my concern is wrt to your solution is that I don't know of any guarantee that says the value fed to the output iterator will match the left or right side of the comparison.  Without which...boom.
Comment: For example, if the code looks something like so: `if (!comp(lh,rh) && !comp(rh,lh)) *out++ = rh;` then if out wants the type of the set value_type and rh is of the map value_type...your solution will fail.  It makes sense that `lh` would be the assigned value but I know of no guarantee of that.  Without that guarantee I wouldn't recommend the approach and since I don't know of one...I didn't.
Comment: @CrazyEddie: The standard forbids that. If `rh` is of the map value_type then that means rh is from the **second** range provided to `set_intersection`, because my code passes the map second (after the input iterators `first` and `last`). As I already quoted, `[set.intersection]` says that the values copied to the output iterator are from the **first** range. This is leaving aside the problematic case where the map value type and the other value type are the same.
Answer: You can do an O(N) set intersection on your map.  Remember that when you iterate through a map, the keys are in order, so you can use an algorithm very much like a merge operation...
All you do is maintain an iterator into each map, and increment the one whose key is smallest.  If the keys are equal, you can add to a deque, list or vector (and in that case, you would increment both iterators).  As soon as one of the iterators reaches the end of its map, you are done.
Comment: Or just leverage `std::set_intersection`, maybe?
Comment: Ah cool, that's exactly what it's doing.  I didn't know about that function, but I see it can accept a compare function.  Cheers.
Comment: Just using the compare function won't work because the two args have to be the same type.  Though I wonder if a functor with overridden () might...


Input CSV via ruby into hash than selecting same vaule from hash

Question: i am learning Ruby recently, i wonder if i can input CSV via ruby into hash(each line is a hash) than selecting same value from each hash and if there is any value matches than print the key of all same value.
test.csv

person_name, birth_place
Mary,Indiana
John,Chicago
Sean,Indiana
Jason,New york
Monica,Chicago

ruby code (not finished yet)
require 'csv'
input_file = ARGV[0]
hash = {}
CSV.foreach(input_file, headers: true) do |row|
  row.each do |line|
    person_name, birth_place = line.chomp.split(",")
    hash[person_name] = birth_place
  end
end

The result should look like this:

[{Indiana => "Mary", "Sean"},
{Chicago => "John", "Monica"}]

Any advise or model?
Thanks for any assistance.
Answer: It looks like you don't need CSV in such a case:
hash = {}
input_file = ARGV[0]
File.new(input_file).readlines.each { |line|
  next if line =~ /birth_place/ # ignore headers
  name, bp = line.chomp.split(',')
  (hash[bp] ||= []) << name # create an array if it does not exist yet
}

puts hash

# ⇒ {"Indiana"=>["Mary", "Sean"], "Chicago"=>["John", "Monica"], "New york"=>["Jason"]}

Hope it helps.
Comment: Thanks for helping me out.
I tried your code and use txt file instead of csv file and i got the result as # {} (same us i use csv.file)
Any idea? Thanks
Comment: You should supply a CSV file as an input, because my code relies on comma as separator. To use a text file, you should change splitting to `name, bp = line.chomp.split(' ', 2)` (split to two parts, using space as delimiter.)
Comment: Would you put `puts "Line: #{line}"` line at the beginning of loop body (before `next if …`) and copy the result of execution here?
Comment: Here is the result: Monica,Chicagokme,birth_place
{}


Non-significant predictor variable becomes significant when two control variables are introduced into model

Question: I want to investigate the correlation of $A$ and $B$ on $X$, so i do a multiple linear Regression. On their own $A$ and $B$ are significant predictors of $X$ in a simple linear regression.
When i test a multiple linear regression with with $A$ and $B$ as Predictors, only $B$ is a significant Predictor. I thought this is because they $A$ and $B$ are redundandt. However, when i do a multiple regression insert a control variable (i.e. Gender and Age), both $A$ and $B$ become significant. One of the CVs is not enough for this.
Could this be a problem related to overfitting?
Comment: You are asking FAQs.  A good way to address this set of related questions is to search our site for threads about [both significance and insignificance in regression](https://stats.stackexchange.com/search?q=regression+significant+not+score%3A25).
Answer: This might not be a "problem" at all.
First of all, it's hard to know what you want to do here without a clearly articulated  research question - WHY do you think A and B are associated with "X" (the dependent variable...which we usually refer to as "Y"...which is what I will do for the rest of this answer). There is no such thing as a "good" or "bad" model in the abstract, only models that are useful or not useful for answering a particular research question. One reason I worry you haven't done that is that you included both A and B at the same time means that you are looking for the "effect" of A on Y  holding B constant....and the effect of B holding A constant. If that's really what you want to know, that's fine, but you should make sure it really is.
Second, it's often the case that the significance of variable changes when you add controls to a model. That's how controls work. It's your job as a researcher to figure out what these changes means. What these models are telling you is that there is no significant association between your predictor A and Y when you don't control for age and gender, but there is a significant association when you do. That might just be how reality works.
For example, let's say you are testing whether enrolling in class (variable "A") leads to better scores on some sort of test. Let's say that the class itself is worthless, but that older females are both more likely to enroll in the class but less likely to do well on the test. If that were true then you might not see a significant effect effect for variable B (taking the class) in a model that doesn't control for gender and age, or only one of them, but you do see a significant effect when you control for both. Also, let's assume that variable A is associated with test score as well, but isn't associated with age or gender. That set of relationships would produce exactly the results you describe. It's not a problem, just a story about how things are related to each other. Does that help you answer your research question or not?
This is why it's good to clearly lay out the casual relationships you think might exist before running your model. Structural equation diagrams ("boxes and arrows") are especially helpful with this.
Comment: In addition, think about how little "statistical significance" actually means.


Error building Repository in a seprate project(library) within the same solution

Question: So, I was following this Link
to learn and implement Repository pattern in my solution which consisted of a single project.
But my senior told me this is not the way we usually use and the repository is referenced from a different way(not withing the project). Using a class library, adding it to the solution and then referencing it.
When I tried doing it that way I am getting error.
Error Image
I had shifted my repository interface, class and UnitOfwork class to the library class within the same solution(As a different project)
I have even tried adding references to assembly using nuget
as shown in this question
Link
Answer: And where is Your dbContext?
Check namespace of StudentsDemoEntities, and check if repository project referenced project with context.
Then add using statment for dbContext.
Edit
Your repository can't "see" dbContext.
Move Your context to repository project and this error will be resolved.
Remember about namespace!
Comment: dbContext is in my .Net Web application project (made using database first way)
Comment: if I try adding reference of project in my library, it gives error saying "it will cause circular dependency"
Comment: Then Your repository can't "see" context.
You need to move context to different project (it can be in repository project).


Can I plug a 15A UPS into a 30A receptacle?

Question: I know that typically electronics draw only as much current as they need. Is this the case with UPSs? I have a 120 volt, 30 amp circuit, and am replacing the UPS plugged into that circuit with a lower wattage UPS. This UPS has a 15 amp plug. Is it safe to use an adapter to do this?
Also, the current plug is NEMA L5-30, whereas the newer UPS is 5-15. If this is safe, are there adapters that are L5-30P to 5-15R?
Comment: Have a look at the adapter you propose to use, and see what current it is rated for.  If it's 15A or more, you should be OK.  *Disclaimer: we're not electricians here*.
Comment: It's safe.  Just beware of cheap adapters that don't provide good coverage of the pins when plugging in/out and have a very small area to grip.
Comment: I think you meant "L5-30R to 5-15P". L5-30R is the receptacle (wall) side, Locking 120V 30A Receptacle.
Comment: No, I didn't mean that. The adapter would have to have an L5-30P, because it's plugging into an L5-30R.
Answer: You should be safe.
It is always OK to put a lower load on a higher rated receptacle.
(At the proper voltage that is. Don't mix 230V and 115V).
Just think of it this way: If it wasn't OK nobody could plug a phone charger (about 2 Amp max) in a standard wall-outlet (10 Amps or more).
And for the record: I am a qualified electrician.
Even though it's been over 20 years since I worked in that field, the laws of electrical physics haven't changed.
I still recommend you have a electrician sort out the converter plug or cable. The cheap stuff you can buy online is often of shoddy quality. If you buy it yourself get it from a reputable source.
An UPS for, presumably, important equipment is not the place to skimp on quality.
Comment: `If the laws of physics no longer apply God help you` - **Cave Johnson**
Comment: @MichaelKjörling He's probably talking about 2A *out*, at 5 volts, which is 10 watts, which is more like 0.08A @ 120V.
Comment: @MichaelKjörling 2 A OUTPUT ON THE CHARGER. That's a standard iPad charger.
Comment: Wait... 2 A 120 V phone charger? Are you saying phones need 200+ W to charge in the States? No wonder people complain about the price of electricity. It's probably on the order of 1/10th to 1/20th of that here (10-20 W). Valid point, but check your numbers.
Comment: @Tonny It was not obvious at least to me that that was what you meant, when you mixed wall outlet 10 A and phone charger output 2 A in the same sentence. Even so, +1 for a good answer.
Comment: Just to clarify here, you are **NOT** saying its OK to try and draw a 30A load from a UPS that's only rated at 15A; if the current regulator wasn't doing its job that would be bad?
Answer: Why not just plug into a NEMA 5-15 or 5-20 receptacle? You don't need to use the L5-30 circuit.
But yes, you can do this. It's possible to just buy an L5-30P-NEMA 5-15R pigtail adapter online or manufacture your own. However, I'm assuming you have plentiful 5-15 receptacles available to you. Is there a reason you can't use one of those instead?
Comment: Sometimes you don't have a smaller circuit available.
Comment: Not in this case. It's pretty rare to see a lone L5-30 receptacle without any NEMA 5-15/5-20 outlets nearby.
Comment: I'm actually dealing with multiple UPSs with this configuration, so I don't have enough 5-15 receptacles to handle all of them, but I do have enough L5-30s. Point taken though, thank you.
Comment: Just use the adapter.
Answer: You are safe.
All you're taking about doing is plugging a 120V device into a 120V circuit, using a plug adapter you can purchase off the shelf.
For anything beyond this, consult a local licensed electrician.
If this wasn't safe, you couldn't just buy the adapters off the shelf. But you can buy these kinds of adapters:

http://lockingpowercords.com/Products/126-l5-30p-to-5-20r-power-cord-adapter.aspx
http://accessories.us.dell.com/sna/productdetail.aspx?c=us&l=en&s=bsd&cs=04&sku=A2894900
http://accessories.us.dell.com/sna/productdetail.aspx?c=us&l=en&s=bsd&cs=04&sku=A1652102
http://www.tripplite.com/metered-pdu-30a-120v-1u-nema-5-15-20r-outlets-nema-l5-30p-single-phase~PDUMH30

Your UPS isn't going to draw any more current through a 30A breaker than it does through a 15A or 20A breaker.
All of your circuit breakers are clamped directly onto the fat aluminum buses in your service panel and subpanel(s), which are in turn directly connected to the fat cables that connect directly to the windings on the step-down transformer coil on the pole outside your home or office.
All the devices you plug into the wall, from a tiny 5 watt light bulb to your phone charger to your dishwasher, are directly connected to that transformer outside (which is directly connected to the high voltage power distribution grid).
Essentially all your circuit breakers (or fuses) do is protect the wires downstream from them, by cutting the power when more current passes through them than the wires can carry without getting too hot. Have you ever noticed how thin the high voltage wires on power poles seem to be? They are air-cooled, not closed up inside walls in buildings. Circuit breakers are there to prevent fires. When current gets too high, electrical resistance in the wire increases, the wire gets hot, potentially extremely hot, and buildings burn down.
But again, the breaker doesn't affect how much current a device draws. It just cuts the circuit if the cumulative load passing through the breaker is more than the wire is rated to handle. You have a 30A breaker, in this case, protecting #10 wires, so barring some kind of equipment failure you're not going to have a fire.
And you won't damage your UPS, either, because, the voltage potential on that circuit is 120V, which is exactly what the UPS is designed for. It's only going to pull as much current (Amps) as it's designed for, and also has its own internal overload protection (it's UL listed, right?). You could attach it directly to the bus bars in your service panel and it would function without burning up (not advised for all kinds of other reasons, of course).
The breakers (or fuses) do not modify the power in any way, except possibly through a tiny bit of voltage loss to thermal inefficiency (like how an old incandescent light bulb uses more energy producing heat than it does producing light). The step-down transformer on the pole outside is where the power is modified. That's why you get 120 Volts in your outlets instead of the 17,000 Volts that is energizing the local distribution lines.
GFCI and arc-interrupt breakers don't modify the power that passes through them, either. They just detect and trip the circuit under additional conditions:

GFCI trips the circuit when a sudden voltage imbalance appears between the hot and neutral legs of the circuit, indicating that the juice found an alternative path to ground, which may well be straight through a human being. So GFCI protects against electrocution rather than protecting against fire.
Arc interruption breakers detect when an electrical arc occurs somewhere on the circuit and cut power. Electrical arcs start fires. Arc interrupt breakers are also a pain because they'll cut circuits when you do things like unplug your vacuum cleaner and a little arc occurs inside the wall receptacle as the prongs on the vacuum cleaner's plug break contact with the prongs inside the receptacle. But the electrical code requires them in many instances now.

Caveats:

DO NOT do something like jerry-rig a 120V receptable somewhere downstream on a 240V circuit (the 240V circuit will have 2 120V hot conductors, a ground and usually a neutral unless it is a very old circuit). That neutral wire (or the ground wire if it's an old hot/hot/ground circuit) carries the imbalance of the load between the hot conductors and you don't want to go around intentionally creating imbalanced circuits, and I'm pretty sure the N.E.C. says this is illegal.  (EDIT: Actually, a 230/240V circuit will be a little different depending on whether the incoming service is single phase ("Edison") or 3-phase, but this explanation is probably close enough.)
Also, if you have a noisy load like a big motor on that same 30A circuit, it could potentially impact your sensitive electronics (although your UPS might mitigate that, but you could also potentially shorten the life of your UPS).
Comment: +1 - Thank you for the comprehensive explanation. In this case, I feel the OP purchased poorly, as he has multiple UPS devices that require this. It's clearly a case of consolidation or buying the right equipment in the first place.
Comment: Just a follow-up note to reiterate and confirm the issues with plugging your UPS into the same circuit with something like an appliance (anything with a high-draw electric motor). Somebody plugged a UPS in our server room into the same outlet (same 20A/120V circuit) as the wall-mounted AC unit. The UPS, I discovered, kept cycling between about 15% and close to 100% charged, and the NAS unit with a USB connection to that UPS kept shutting itself off, while the other one kept running, but would have lasted only a minute or so in a power outage. I labeled that outlet "NO COMPUTERS."
Comment: 120V outlets on 240V circuits are allowed, they are called multi-wire branch circuits. And in America, the circuit breakers are integral to the safety of the whole system. The main limiter is the circuit size, for example, a 10 AWG wire will in 99% of cases be protected by a breaker equal or smaller than 30A. When a circuit is dedicated to a device (single outlet, hard-wired or not), the breaker is supposed to be matched to the equipment manufacturer's rating. A 30A cooking top on a 40A (8 AWG) is supposed to be protected by a 30A breaker, unless the manufacturer allows a 30A.
Comment: For hard wired equipment, sure. But your LED alarm clock, for example, draws about 100 milliamps, while you typically plug it into a 15A or 20A circuit. A load draws what it draws. It isn't going to draw more through a bigger breaker than it does through a smaller breaker. It just doesn't work that way. Will you clarify that your saying it's okay to slap 120V receptacles on a 240V circuit that is serving 240V loads? Yes, I know this is done within equipment, like driving oven lights, LED displays, timers, etc. But just hanging a 120V receptacle off of, say, one side of a range circuit?
Answer:
Is it safe to use an adapter to do this?

If the voltage is the same (120v in your case) and the Amp rating is less (15 < 30 in your case), then Yes.

Are there adapters that are L5-30P to 5-15R?

Yep. An eletrical supply house would have this. You should be able to find one on the Googles too.
Answer: Like MadHatter mentioined, we are not electricians here.
But my take on that is that the Amps are a like a maximum load you can bruden the circuit with. What's more important in this case (with my non-electrician knowledge) is that your new UPS can deal with 120 volts. It's most likely the case quite honestly.
I don't think you will find adapters for this, I believe the point of twist type plugs is to secure the connection physically. Having an adapter would pretty much defeat the purpose.
I would get an electrician over just to change the receptacle.
Comment: Please reread. **IF** the electrician changes the receptacle, he'll be required to change the fuse/breaker. It's against code in many countries to have a fuse/breaker with higher amperage than the outlets on that circuit.
Comment: If the electrician changes the receptacle, he'll be required to change the fuse/breaker. It's easier (and future-compatible) to just buy an adapter.
Comment: He does not need to change the breaker. The UPS will never send anything above 15 amps. If it was the other way around (getting a 30 amp UPS and plug it in 15 amp circuit) then I would agree with you.
Answer:
This UPS has a 15 amp plug. Is it safe to use an adapter to do this?

It LIKELY is safe, but the UPS fuse LIKELY is OUTPUT - and the UPS can suck a lot more power because it msut deliver it's maximum load AND LOAD AT THE SAME TIME. The documentation (of the UPS) will have requirements for the input circuit.
Comment: "UPS fuse LIKELY is OUTPUT"? Sense you no make.
Comment: We don't rely on circuit breakers to enforce the maximum load on hardware; they're to prevent fires due to overloaded wiring.  To fill an entire 15A circuit at 110V, the UPS (and attached equipment) would need to draw 1650W, which is quite a lot for the kind of UPS I suspect this is.
Comment: Umm... really?  The UPS isn't going to draw more current through a 30A breaker than it does through a 15A or 20A breaker.
Answer: If you're going for an adapter, change the breaker for a 15A breaker. All risks are then avoided. That's a $5 part. If you can't fit the 10 AWG wire in the breaker, splice it with a 14 AWG wire using a suitable wire nut.
Dedicated circuits (circuits with a single outlet) are supposed to have a circuit breaker that protects not only the wire, but also the appliance connected to it. Since your "appliance" is your UPS rated at 15A, it should have a 15A breaker protecting it (or at the very least, a fuse built into the adapter).
The same applies to built-in appliances. For example, a 30A cooking top on a 40A or 50A circuit will usually require a 30A breaker. This happens commonly when a stove receptacle has been repurposed for a cooking top, after a remodel or renovation. Sometimes, the manufacturer will state that connection to a 40A or 50A circuit is allowed, but in the case of 15A devices, it will almost always say that the device should be connected to a 15A circuit with a 15A over-current protection.


Refatoração de função para remover pontuação, espaços e caracteres especiais

Question: Tenho esta função já muito antiga para "limpar" o conteúdo de uma variável:
Função
function sanitizeString($string) {

    // matriz de entrada
    $what = array( 'ä','ã','à','á','â','ê','ë','è','é','ï','ì','í','ö','õ','ò','ó','ô','ü','ù','ú','û','À','Á','É','Í','Ó','Ú','ñ','Ñ','ç','Ç',' ','-','(',')',',',';',':','|','!','"','#','$','%','&','/','=','?','~','^','>','<','ª','º' );

    // matriz de saída
    $by   = array( 'a','a','a','a','a','e','e','e','e','i','i','i','o','o','o','o','o','u','u','u','u','A','A','E','I','O','U','n','n','c','C','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_' );

    // devolver a string
    return str_replace($what, $by, $string);
}

Utilização
<?php
$pessoa = 'João dos Santos Videira';

$pastaPessoal = sanitizeString($pessoa);

// resultado
echo $pastaPessoal; // Joao_dos_Santos_Videira
?>

Sendo uma função antiga, na altura da sua criação fazer uma substituição de um caráter A por B era a melhor opção, mas fazer manutenção a uma matriz de entrada e uma matriz de saída não é fácil e de volta e meia lá aparece um cenário não previsto.
Com a evolução do PHP, como refatorar esta função fazendo uso de soluções da própria linguagem ou mais fáceis de manter?
Comment: Nota referente à tag **sanitize**: Não consegui traduzir ou encontrar uma tag já existente para esta palavra.
Comment: Marque uma resposta como aceita, se uma delas serve para você.
Comment: **sanitize** significa sanitizar ou higienizar. Mas é meio feio traduzir pra isso, rs! Deixa sanitize mesmo.
Answer: Basta usar expressões regulares!
<?php
function sanitizeString($str) {
    $str = preg_replace('/[áàãâä]/ui', 'a', $str);
    $str = preg_replace('/[éèêë]/ui', 'e', $str);
    $str = preg_replace('/[íìîï]/ui', 'i', $str);
    $str = preg_replace('/[óòõôö]/ui', 'o', $str);
    $str = preg_replace('/[úùûü]/ui', 'u', $str);
    $str = preg_replace('/[ç]/ui', 'c', $str);
    // $str = preg_replace('/[,(),;:|!"#$%&/=?~^><ªº-]/', '_', $str);
    $str = preg_replace('/[^a-z0-9]/i', '_', $str);
    $str = preg_replace('/_+/', '_', $str); // ideia do Bacco :)
    return $str;
}
?>

A linha de código abaixo do comentário serve para substituir todos os caracteres  por "_", exceto se for letras ou números.
Comment: Se eu tivesse que implementar, faria algo parecido com essa resposta. Todavia, para um projeto em produção acho que usar a URLify (ver minha resposta) é mais vantagem no longo prazo, já que é bem testada, fácil de estender e modificar.
Answer: Acho que essa seria a melhor e mais simples solução para seu problema:
$valor = "João dos Santos Videira"
$valor = str_replace(" ","_",preg_replace("/&([a-z])[a-z]+;/i", "$1", htmlentities(trim($valor))));
// Joao_dos_Santos_Videira

Caso queira manter os espaços em vez de trocá-los por "_", basta apenas retirar o str_replace:
$valor = "João dos Santos Videira"
$valor = preg_replace("/&([a-z])[a-z]+;/i", "$1", htmlentities(trim($valor)));
// Joao dos Santos Videira

Comment: Esta foi a melhor resposta e solução. Acrescentei duas coisas em meu sistema de login: `$FormataLogin = str_replace(" ","",strtolower(preg_replace("/&([a-z])[a-z]+;/i", "$1", htmlentities(trim($_POST['login'])))));` Obrigado.
Comment: Ótima resposta.
Answer: Você pode querer usar a biblioteca URLify.php (código fonte aqui), que possui testes extensivos para suportar diversos caracteres e idiomas, e também suporta adicionar mapeamentos mais complexos que 1 caractere -> 1 caractere.
Ela também ignora símbolos que não consegue transliterar, o que a deixa bastante robusta para usar numa URL ou nome de arquivo.
Seguem alguns exemplos da página do projeto:
Limpando para usar em URL ou nome de arquivo
echo URLify::filter (' J\'étudie le français ');
// "jetudie-le-francais"
echo URLify::filter ('Lo siento, no hablo español.');
// "lo-siento-no-hablo-espanol"

Apenas removendo os caracteres especiais por ASCII
echo URLify::downcode ('J\'étudie le français');
// "J'etudie le francais"
echo URLify::downcode ('Lo siento, no hablo español.');
// "Lo siento, no hablo espanol."

Mapeando caracteres complexos para expressões
URLify::add_chars (array (
    '¿' => '?', '®' => '(r)', '¼' => '1/4',
    '¼' => '1/2', '¾' => '3/4', '¶' => 'P'
));
echo URLify::downcode ('¿ ® ¼ ¼ ¾ ¶');
// "? (r) 1/2 1/2 3/4 P"

Answer: Pode usar o PHP para remover acentos de forma simples usando iconv, respeitando maiúsculas e minusculas sem conflito. IGNORE vai ignorar os caracteres que porventura não tenham tradução. Depois preg_replace vai remover o que não for A-Z e 0-9, deixando uma string limpa sem espaços, símbolos ou caracteres especiais.
$string = "ÁÉÍÓÚáéíóú! äëïöü";
$string = iconv( "UTF-8" , "ASCII//TRANSLIT//IGNORE" , $string );
$string = preg_replace( array( '/[ ]/' , '/[^A-Za-z0-9\-]/' ) , array( '' , '' ) , $string );

-----------------------------------------------------------------
Input:  ÁÉÍÓÚáéíóú! äëïöü
Output: AEIOUaeiouaeiou

Veja um exemplo no ideone
Comment: Uma pequena alteração para quem precisa manter o espaço

```php
$string = "ÁÉÍÓÚáéíóú! äëïöü";
$string = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $string);
$string = preg_replace('/[^a-zA-Z0-9\s]/', '', $string);
-------------------
Input:  ÁÉÍÓÚáéíóú! äëïöü
Output: AEIOUaeiou aeiou
```
Answer: Tu procura pela função strtr(). As expressões regulares ajudam a tratar dos casos excepcionais:
function sanitizeString($str)
{
    return preg_replace('{\W}', '', preg_replace('{ +}', '_', strtr(
        utf8_decode(html_entity_decode($str)),
        utf8_decode('ÀÁÃÂÉÊÍÓÕÔÚÜÇÑàáãâéêíóõôúüçñ'),
        'AAAAEEIOOOUUCNaaaaeeiooouucn')));
}

PS: Usei a função utf8_decode() porque salvo os arquivos como UTF-8 em meu sistema (OSX). É provável que não precise usá-la caso o arquivo seja salvo em outras codificações como ISO-8859-1, CP1252 e afins.
Comment: Obrigado pela resposta, mas estou um pouco confuso após ler a mesma. Falas em `utf8_encode()` mas utilizas `utf8_decode()` na função. Por outra lado dizes que usas `utf8*` por causa da forma como guardas o ficheiro? Assumo que estejas a dizer isso porque os `headers` da aplicação não estão em `UFT-8`? Não tive oportunidade de testar a tua solução, mas se entretanto for possível clarificar estas minhas duvidas, agradeço!
Comment: Oops! Eu me referia à `utf8_decode()` mesmo, já corrigi  minha observação... No meu caso é necessário usar a `utf8_decode()` porque salvo os arquivos com a codificação UTF-8 em meu sistema... Isso se faz necessário justamente por causa dos caracteres acentuados que estão sendo usados na função.
Answer: Eu desenvolvi uma forma diferente para remover todos os caracteres especiais e acentos.
<?php

$VString = "Matan-zá@Ç/_454ç8";

echo "Com caracteres especiais e acentos: " . $VString . "
";

$VString = preg_replace("/[ÁÀÂÃÄ]/", "A", $VString);
$VString = preg_replace("/[áàâãä]/", "a", $VString);
$VString = preg_replace("/[ÉÈÊ]/", "E", $VString);
$VString = preg_replace("/[éèê]/", "e", $VString);
$VString = preg_replace("/[ÍÌ]/", "I", $VString);
$VString = preg_replace("/[íì]/", "i", $VString);
$VString = preg_replace("/[ÓÒÔÕÖ]/", "O", $VString);
$VString = preg_replace("/[óòôõö]/", "o", $VString);
$VString = preg_replace("/[ÚÙÜ]/", "u", $VString);
$VString = preg_replace("/[úùü]/", "u", $VString);
$VString = preg_replace("/[Ç]/", "C", $VString);
$VString = preg_replace("/[ç]/", "c", $VString);
$VString = preg_replace("/[Ñ]/", "N", $VString);
$VString = preg_replace("/[ñ]/", "n", $VString);

echo "Com caracteres especiais: " . $VString . "
";

$VNovo = "";
for ($i = 0; $i < mb_strlen($VString); $i++)
  if (preg_match ("/[a-zA-Z0-9]/", substr($VString, $i, 1)) == 1)
    $VNovo .= substr($VString, $i, 1);

echo "Sem caracteres especiais e acentos: " . $VNovo . "
";

Answer: public static function removerCaracteresEspeciaiss($str){
    $str_saida = "";
    for($i=0; $i<strlen($str); $i++){
        $num_asc = ord($str[$i]);
        if( ($num_asc>=65 && $num_asc<=90) || ($num_asc>=97 && $num_asc<=122) || ($num_asc>=48 && $num_asc<=57)){
            $str_saida .= $str[$i];
        }
    }
    return $str_saida;
}


Get varnish statistics for each backend

Question: I'm running an instance of Varnish with load-balancing to several backends.
I want to get the statistics of the cache hits, cache misses, hit for pass for each backend and not the total if the server but varnishstat doesn't seem to have this information.
Do you guys know a way of getting this statistics?
Answer: Honestly, I'm not sure this makes sense.  The backends don't store the cache data, Varnish does.  Further, Varnish doesn't "select" a backend unless the cache misses.  Taken together, this means that in a typical case, the number of cache misses for each of two backends, for example, is exactly half of the total.  Now, I know you can get quite a bit fancier than this—for example, you might have different backends for administrative access modalities.  However, that then simply makes this question a specific case of the general question, "Can I break down varnishstat output by (arbitrary distinction)?", the answer to which is, "No."
However, you can probably insert more data into varnishstat's output by using inline C in your VCL to directly modify the buffer from which varnishstat reads; never tried it, mind you, but seems like it should work.  Failing that, you can always use the inline C to update your very own buffer (even an external one, e.g. memcache) and then write your own query program for it.

Get varnish statistics for each backend


Format Code As a Code Block in R Markdown

Question: Is there anyway to format code in the "code" format offered by many websites like Stackoverflow in R Markdown.
I want to be able to do something like the following:

Any model that takes the form income ~ education + parental_income
  ...

I want to emulate that greyed out text in R markdown for ease of readability when I eventually knit the document.
Comment: RMarkdown is a superset of Markdown (i.e. includes all Markdown features + extra unique ones), so using backticks like `\`income ~ education + parental_income\`` in your document should work the same way.
Comment: Wow.  Huge if true.
Answer: One can use backticks or indenting by 4 spaces to generate the equivalent of the HTML   tag block. Here is an Rmd document illustrating this behavior.
---
title: "Sample Document"
author: "bigNumber"
date: "12/5/2017"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## R Markdown

here is some example code written in R Markdown. If we want to enter a code block we use the backtick, such as `inc ~ ed + occ`.

If we want a code block with multiple lines, indenting by 4 spaces also works

    # first line of code
    for(i in 1:100) {
       # do something here
    }

More text after the code block ends.

...and the output. Unfortunately I have to include an image to show that it renders correctly.
Answer: ```</code>
<code>
If you'd rather not
</code>
<code>indent your code block by four spaces, you can use</code>
<code>
triple back-ticks on separate lines.
</code>
<code>```
https://bookdown.org/yihui/rmarkdown/markdown-syntax.html#block-level-elements
Answer: html could work if you want to have a string with gray color as a background
Changing chunk background color in RMarkdown


Trace of a third order tensor

Question: So, I have learned that the trace of a second order tensor $\textbf{Q}^{(2)}$ is given by:
$Tr(\textbf{Q}^{(2)})=Q_{11}+Q_{22}+Q_{33}$
Now, I want to calculate the trace of a third order tensor $\textbf{Q}^{(3)}$, is it true that:
$Tr(\textbf{Q}^{(3)})=Q_{111}+Q_{222}+Q_{333}$ ?
Or maybe this just doesn't make sense... In particular I want to calculate the trace of:
$Q_{ijk}=\int\bigg[r_{i}r_{j}r_{k}-\frac{1}{5}r^{2}(r_{i}\delta_{jk}+r_{j}\delta_{ik}+r_{k}\delta_{ij})\bigg]\rho(\textbf{r})d^{3}r^{\prime}$
where $\rho(\textbf{r})$ is a function of $r_{i}$, also $i,j,k=1,2,3$ (It is supposed to be a traceless tensor).
Any help with this?
Answer: Trace generalizes to tensor contraction which is defined for pairs of indices.
I suspect that by calling $Q$ a "traceless" tensor, the author/ your professor means that contracting $Q$ over any pair of indices yields $0$.  Which certainly is the case here (try summing the part in brackets over any two of the indices and then notice that this is a totally symmetric tensor).
Comment: Okay, nice, but what does it mean for rank-4 tensor? What is a trace for a rank-4 tensor?

Trace of a third order tensor


Why does there not exist a 3 regular graph of order 5?

Question: Because the lines of a graph don't necessarily have to be straight, I don't understand how no such graphs exist. Can anyone shed some light on why this is?
Answer: The degree $\mathrm{deg}(v)$ of a vertex $v$ is the number of its incident edges. By the handshaking lemma, $$\sum_{v\in V} \mathrm{deg}(v) = 2\left|E\right|,$$ i.e., the sum of degrees over all vertices is twice the number of edges. This number must be even since $\left|E\right|$ is integer. In a 3-regular graph, we have $$\sum_{v\in V}\mathrm{deg}(v) = \sum_{v \in V} 3 = 3\left|V\right|.$$ However, $3\left|V\right|$ is even only if $\left|V\right|$ is even. Therefore, 3-regular graphs must have an even number of vertices.
Comment: I'm sorry, I miss typed a 8 instead of a 5!


On rings with a unique maximal ideal

Question: I would be grateful if you guide me through the following question:
Suppose a commutative ring with identity, $R$, has a unique maximal ideal, say $M$. If $M$ is principal, can we show that every ideal is finitely generated?
Well, I am considering the following facts:
$1)$ Every ideal $I$ of $R$ lies in a maximal ideal, and since we have a unique maximal ideal, then $I$ lies in $M=(m)$.
$2)$ We can also consider Nakayama's lemma: $IM$ is an ideal of $M$, and if IM=M then $M=0$. In particular we can set I=M.
$3)$ Another fact I can think of, is that it follows easily that all nonunits form an ideal in such a ring, which is $M$ itself.
Comment: In (2), $M = 0$ is not a contradiction, but it would mean that $R$ is a field, and thus answer your question in the affirmative. Out of curiosity, is this a homework problem?
Comment: I'm not sure but I don't think the claim's true without requiring the ring is Noetherian, and I'm almost sure I've a coutner example somewhere in books/papers/stuff. Anyway, check the Noetherian thing.
Comment: In fact, I would like to know: are you being asked to prove this exact statement? Or did you come up with the statement yourself?
Comment: I see, this is completely equivalent to the statement you posted. I appreciate your honesty - this homework problem is not so easy! As a start, it is enough to prove that every (nonmaximal) prime ideal is finitely generated
Comment: @Sean, I'm not sure I understood: the question was "is it true that...", and what I wrote above is that it is not true (if I remember correctly). So if the question asked to prove a local ring with principal maximal ideal is a PIR  then, I think, that can't be done.
Comment: @Sean: In fact, I have also run into a snag with the proof I was considering. It does in fact boil down to whether the intersection of all powers of the maximal ideal is zero or not. I can post an answer that shows you why, if it is zero, that the ring is Noetherian
Comment: You're right; thx; yeah, it is pertaining to a hw assignment
Comment: In fact the problem itself asks to prove such rings are Noetherian;
Comment: Thanks; here's the hint which was included: To prove every ideal I of R, is in fact a power of M. That's why I was thinking of Nakayama's lemma to kind of produce such products.
Comment: Thanks DonAntonio,,,but the point is it was a problem asking to prove the above described ring is Noetherian.
Comment: Actually it asks to prove every quasi-local ring with principal maximal ideal is Noetherian.
Comment: @user115654: It would be great,,,I think it would pave the way for a final proof.
Answer: This question came up on Math Overflow several years ago.  I answered it -- negatively -- here.
I am pretty sure that the question has been asked several times on this site as well.  I will try to search for it.  (But I am not good at searching on this site.  Help would be appreciated...)
Comment: Thanks for the reference - I'll keep that example in mind. I'd like to note though, that the reasoning I gave shows that it is true if the ring is complete (or just $M$-adically separated)
Comment: "The reasoning I gave..." I agree.
Comment: I just *knew* a choice of valuation group would do the trick, but I did not know what would work. Glad to see the method applied. My advisor showed me how to pull something similar for an example in my dissertation...
Answer: As in the problem statement, write the maximal ideal as $M = (m)$. Notice that since $M$ is finitely generated, by Nakayama's Lemma, $M \neq M^2$, and in general $M^i \neq M^j$ for any $i \neq j$. Assume that the following holds:
Lemma: $\cap_{n=1}^\infty M^n = 0$.
Assuming the lemma, let $I \neq 0$ be an proper ideal of $R$. Since $I \subseteq M$ but $I \not \subseteq \cap_{n=1}^\infty M^n$, there exists an $n$ such that $I \subseteq M^n$, but $I \not \subseteq M^{n+1}$. Pick $x \in I \setminus M^{n+1}$. As $x \in M^n$, write $x = m^ny$ for some $y \in R$. If $y \in M$, then $x \in M^{n+1}$, a contradiction, so $y$ is a unit, i.e. $(x) = (m^n) = M^n$. But then $(x) \subseteq I \subseteq M^n = (x)$, so $I = (x)$ is in fact principal.
EDIT: (placed later so as to not disrupt continuity) Together with the Krull Intersection Theorem, the reasoning above in fact proves that a local ring $R$ with principal maximal ideal is Noetherian iff it is $M$-adically separated.
Comment: Your Lemma holds if $R$ is Noetherian by the Krull Intersection Theorem (see e.g. $\S$ 8.12.2 of http://math.uga.edu/~pete/integral.pdf).  It does not hold in general: see my answer.
Comment: Of course, the lemma is exactly (a weak version of) Krull Intersection. Your example explains why it was so impossible to prove without Noetherian hypotheses

On rings with a unique maximal ideal


Are the real product rule and quotient rule for integration already known?

Question: In "A Quotient Rule Integration by Parts Formula", the authoress integrates the product rule of differentiation and gets the known formula for integration by parts:
\begin{equation}\int f(x)g'(x)dx=f(x)g(x)-\int f'(x)g(x)dx\ \ \ \ \ \ \ \ \ \ \ \ \ \ (1)\end{equation}
This formula is for integrating a product of two functions. It can be named therefore product rule integration by parts formula.
Furthermore, the authoress integrates the quotient rule of differentiation and gets a formula which is for integrating a quotient of two functions:
\begin{equation}\int\frac{f'(x)}{g(x)}dx=\frac{f(x)}{g(x)}+\int \frac{f(x)g'(x)}{g(x)^{2}}dx\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ (2)\end{equation}
She names it therefore quotient rule integration by parts formula.
"Quotient-Rule-Integration-by-Parts" goes also not beyond this.
To get a real product rule for integration and a real quotient rule for integration, I substitute in equation $(1)$: $g'(x)\rightarrow g(x)$, and in equation $(2)$: $f'(x)\rightarrow f(x)$. For abbreviation, I set $F(x)=\int f(x)dx+c_{1}$ and $G(x)=\int g(x)dx+c_{2}$, where $c_{1}$ and $c_{2}$ are constants. So I get the following product rule of integration:
\begin{equation}\int f(x)g(x)dx=f(x)G(x)-\int f'(x)G(x)dx\ \ \ \ \ \ \ \ \ \ \ \ \ \ (3)\end{equation}
and the following quotient rule of integration:
\begin{equation}\int\frac{f(x)}{g(x)}dx=\frac{F(x)}{g(x)}+\int\frac{F(x)g'(x)}{g(x)^{2}}dx\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ (4)\end{equation}
Formulas $(3)$ and $(4)$ bring nothing new. They seem to be more complex than the formula of integration by parts, and it is harder to remember this formulas than the formula of integration by parts. But this formulas are more clear for the inexperienced because he sees what he wants: a product or a quotient of two functions at the left side of the equations.
My questions to formulas $(3)$ and $(4)$ are:
Are this formulas already known?
What are the reasons why this formulas are not used?
Comment: Isn't formula (1) identical completely with formula (3), but with other writing? And the same for (2), (4) .
Answer: Recently, this integration rules were published in
Will, J.: Produktregel, Quotientenregel, Reziprokenregel, Kettenregel und Umkehrregel für die Integration. May 2017.
Will, J.: Product rule, quotient rule, reciprocal rule, chain rule and inverse rule for integration. May 2017.
Answer: It is the case that they are mathematically the same as (1) and (2). You're welcome to write it that way if you prefer, but you haven't changed the meaning of the expression by doing so.
Comment: Also worth mentioning that these formulas *are* used. At least (3) is; see *Brief Calculus and its Applications* by Goldstein et al. I'm not aware of any textbooks that use (4), but I'm not aware of any textbooks that use (2) either, so...
Comment: @IV_ does this not answer your question...


Determining Population Size from Error

Question: Assume you have a set of unique values $V$ with a known distribution (e.g. Normal, Uniform) but unknown size $|V|$.
Assume you have function $O(t)$ that tells you the value $v \in V$ that is closest to the target value $t$
If you generate another (smallish) set values $T$ under the same distribution, I feel that you can determine an approximation of $|V|$, given $|T|$, and the RMS or something of $T-O(T)$
Is there a formula?
Example:
<code>V = [0.090, 0.135, 0.288, 0.413, 0.434, 0.715, 0.717, 0.797, 0.841, 0.904] (actual set)
T =     [0.096, 0.767, 0.900] (generated values)
O(T) =  [0.090, 0.797, 0.904] (closest values to T in V)
error = [0.006, 0.030, 0.004]
</code>
The assumption is that as $V$ grows, the error will shrink.
Comment: My values come from a Bernoulli$(1/2)$ distribution.  $V$ is large enough that there is at least one $0$ and one $1$ in $V$.  Thus, $O(t)$ is $0$ when $t\lt 1/2$, $1$ when $t\gt 1/2$, and indeterminate when $t=1/2$. Since this will be the case no matter how large $V$ is, how do you suppose $|V|$ could possibly be estimated?
Comment: What is $t$, the target value? Are you estimating something from a distribution? Perhaps you can include one concrete example and show how it works, and then ask for a generalisation.
Comment: @Gijs $t$ can be any value. $O(t)$ just magically polls $V$ for the nearest value. $T$ is a generated set with the same distribution as $V$ to test $V$ against.
Answer: If you know the distribution of $V$, find the distribution of the error of $O(t)$, which is indeed a formula of $N$, then given the observed errors you may try and derive the maximum likelihood estimator for $N$.
The distribution of the error of $O(t)$ is not easy I would think but you can start with this question and it's answers: Spacings between discrete uniform random variables.
Comment: could you post the formula please, at least for uniform or normal distributions?
Answer: In the absense of a better answer I will use the following
Given Uniform distribution: $|V| \approx$ (1/error) - 1
this conclusion was reached by looking at ideally distributed sets, and their element's distance from an extremity:
<code>[0.5] 1/2 => 1
[0.33, 0.66] 1/3 => 2
[0.25, 0.50, 0.75] 1/4 => 3
[0.2, 0.4, 0.6, 0.8] 1/5 => 4
</code>
Comment: What is "error" in this answer?  How is it computed from the $|T|$ ordered pairs $(t_i, O(t_i)),\ t_i\in T$ generated by your procedure?
Comment: MAE or RMSE should both be fine. I'm not sure which is better though

Determining Population Size from Error


Is the set described in the main text a polytope?

Question: Definition: the convex hull of a finite subset of a vector space is called a polytope.
Consider the set of continuous, non-decreasing, and (weakly) concave functions whose domain and codomain are both $[0,1]$. Is this set a polytope?
I guess the answer is "No". So I tried to prove this by taking any $n \in \mathbb{N}$ functions in this set, and then construct a function that cannot be written as a convex combination of these functions. But I do not really know how to construct...
In addition, I feel that even if I replace "continuous, non-decreasing, and (weakly) concave" with other features, the answer should still be "No". I was wondering whether there is a generic method of proving this.
Answer: The functions $f_n(x) = 1 - (1-x)^n$ for positive integers $n$ are continuous, non-decreasing, concave, and map $[0,1]$ to $[0,1]$.  Since they are linearly independent, they can't all be convex combinations of some finite set of functions.
Comment: Thank you for your answer. Could you please elaborate on why 1. $\left\{f_n\right\}_{n \in \mathbb{N}}$ ae linear independent; 2. They being linear independent implies they can't all be convex combinations of some finite set of functions?
Comment: 1) They are linearly independent because they are polynomials of different degrees.  A linear combination of polynomials of different degrees has the same degree as the polynomial (with nonzero coefficient) whose degree is highest.
2) A convex combination is a linear combination.  The span (i.e. space of linear combinations) of $n$ polynomials has dimension at most $n$.
Answer: Robert's answer is great, here's a similar example, with details. For each $n \in \mathbb{N}$ define:
$$f_n(x) = \begin{cases} nx & \textrm{ if } x \in [0, n^{-1}]\\ 1 & \textrm{ else.}\end{cases}$$ Let $N \subseteq \mathbb{N}$ be an arbitrary finite subset with at least two elements, and suppose, for sake of contradction, there exist not-all-zero scalars $\alpha_i$, $i \in N$ such that:
$$
\sum_{i \in N} \alpha_i f_i(x) = 0
$$
for all $x \in [0,1]$.  Since $f_i(1) = 1$ for all $i$, this means that:
$$\tag{$\ast$}
\sum_{i \in N} \alpha_i = 0.
$$
Let $n',n''\in N$ denote, respectively, the smallest and second smallest numbers in $N$ whose $\alpha$'s are non-zero. By ($\ast$),
$$
-\alpha_{n'} = \sum_{i \in N \setminus \{n'\}} \alpha_i,
$$
and both sides of this equality must be non-zero.
But at $x = n''^{-1}$, every $f_i(n''^{-1}) = 1$ except for $i = n'$. Thus:
$$
0 = \sum_{i \in N} \alpha_i f_i\big(n''^{-1}\big) = \alpha_{n'}f_{n'}\big(n''^{-1}\big) + \sum_{i \in N \setminus\{n'\}} \alpha_i = \alpha_{n'}f_{n'}\big(n''^{-1}\big)  -\alpha_{n'} \neq 0,
$$
a contradiction. Thus for any $N$, the family $\{f_i(\cdot)\}_{i \in N}$ is linearly independent, and since $N$ can be chosen to be any (finite) size, the set $\{f_n(\cdot)\}_{n \in \mathbb{N}}$ cannot be contained in any finite dimensional subspace of $C([0,1])$.


Can I use Pathauto with additional url values?

Question: Is it possible to use pathauto url aliases and still use additional url parameters?
For example, I use pathauto for polls to map "node/123" to "poll/title-of-my-poll".
The poll results are at "node/123/results" but using "poll/title-of-my-poll/results" doesn't work.
Answer: The Sub-pathauto module is for exactly that purpose.

The Drupal Path module matches only full URLs when creating SEO-friendly aliases. This module extends that behavior by also matching known sub-paths and replacing them with their respective alias.
For example, if user/1 is aliased to users/admin, this module rewrites the link to the user contact page user/1/contact to use the aliased URL users/admin/contact instead. This also includes Views URLs taking a node as argument (e.g. node/%/yourview), in short, every URL that is based on, or extends, an existing alias. In combination with the Pathauto module it is possible to get rid of all remaining exposed internal non-administrative URLs.


Is there a way to populate a column with scalar value in power pivot?

Question: I'm new to Power Pivot, sorry if the question is simple but i've been searching for hours already and i can't find an answer to this. The table below is from Power Pivot's Manage. The total Sum of (CoveredAndGapTotal) is 147. The table below is filtered therefore my CoveredAndGapTotal's sum (SumCandG) is 22. Is there a way to convert SumCandG to column? Because when i put the same formula (SUM([CoveredAndGapTotal]) in the column (Calculated Column 1), the return value is 147 and not 22. It sums up all the data regardless of the filter.
Answer: This is not possible, a calculated column is not related to filtering. That's why it's needs to be a calculated measure.
When you are using this in an Excel pivot table, you will see that you can use these to calculate.
What result are you expecting in the pivot table in Excel?
Comment: I'm expecting 22, like the value from (SumCandG). I need it to be in column form and also this column should be available in my (Power Pivot - Manage) because i need the data for my power view. Should i just give up on this? Thank you for the reply.
Comment: Do you need have dynamic filtering?
anyhow you can use a calculated measure in powerview, so that's not the issue.
http://www.wimv.be/pbi/se20160503.png
Comment: I will use your attached image as reference. Is there a way where i can make a column that contains just the Total of NrOfCalls? That's what i need.
John 20
Karen 20
Kerry 20
Comment: yes. If it's depended of filter context:
NrOfCalls   :=countrows(MyTable)

If it's not depended of filter context:
NrOfCalls_noFilter   :=calculate(countrows(MyTable),all(MyTable))
Comment: The filter that i'm talking about is the dropdown in the image above. Maybe that is a different filter from what you are expecting? Because when i do countrows(MyTable), it just returns all the rows from the table. I'm assuming the filter i'm talking about is actually not a filter rather a grouping. But from the image above, is there a way for the 22 to be inserted as a column above? Thanks


pass multi dimensional range as parameter python

Question: I am using python and munpy. I have 2 dimesional object mask. It is graphic mak with integer coordinates and value.I want to use part of matrix like:
mask[:100,300:]

Is it possible to create variable like range = (:100,300:)
and to use like:
mask[range]

or similar approach
Comment: `range = ":100,300:"` and then `mask[eval(range)]` could do it.
Answer: You can use the built-in slice
ranges = slice(0, 100), slice(300, None)
mask[ranges]


How to apply layoutConstraints for CustomTableView Cell

Question: I need design custom cell like below with nslayoutconstraints by programtaically with visual format lanuguage as well as constraintswithitem.Any help will be appreciate one.

`    /* Intialize and assign Product Name */
        productName=[[UILabel alloc]init];
        productName.font=[UIFont fontWithName:@"HelveticaNeue" size:17.0f];
        self.productName.lineBreakMode = NSLineBreakByWordWrapping;
        self.productName.numberOfLines = 0;
        productName.translatesAutoresizingMaskIntoConstraints=NO;
        [self.contentView addSubview:productName];
<code>    /* Intialize and assign Product Option */
    productOption=[[UILabel alloc]init];
    productOption.translatesAutoresizingMaskIntoConstraints=NO;
    productOption.font=[UIFont fontWithName:@"HelveticaNeue" size:13.0f];
    productOption.textColor=[UIColor colorWithRed:128/255.0f green:128/255.0f blue:128/255.0f alpha:1.0f]; /* 808080 */
    [self.contentView addSubview:productOption];

    /* Intialize and assign Product Image */
    productImageView=[[UIImageView alloc]init];
    productImageView.translatesAutoresizingMaskIntoConstraints=NO;
    productImageView.clipsToBounds=YES;
    productImageView.contentMode=UIViewContentModeScaleAspectFill;
    productImageView.layer.cornerRadius = 22.5;
    productImageView.layer.masksToBounds = YES;
    productImageView.layer.borderColor =[UIColor whiteColor].CGColor;
    productImageView.layer.borderWidth = 1;
    [self.contentView addSubview:productImageView];

    /* Intialize and assign List icon Image */
    listIconImage=[[UIImageView alloc]init];
    listIconImage.translatesAutoresizingMaskIntoConstraints=NO;
    listIconImage.image=[UIImage imageNamed:@"right-arrow.png"];
    [self.contentView addSubview:listIconImage];

   [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.productImageView
                                                                 attribute:NSLayoutAttributeTop
                                                                 relatedBy:NSLayoutRelationEqual
                                                                    toItem:self.contentView
                                                                 attribute:NSLayoutAttributeTop
                                                                multiplier:1.0
                                                                  constant:7]];

    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:productImageView
                                                                 attribute:NSLayoutAttributeLeft
                                                                 relatedBy:NSLayoutRelationEqual
                                                                    toItem:self.contentView
                                                                 attribute:NSLayoutAttributeLeft
                                                                multiplier:1
                                                                  constant:11.5]];

    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.productImageView
                                                                 attribute:NSLayoutAttributeWidth
                                                                 relatedBy:NSLayoutRelationEqual
                                                                    toItem:nil
                                                                 attribute:NSLayoutAttributeWidth
                                                                multiplier:1.0
                                                                  constant:45]];

    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.productImageView
                                                                 attribute:NSLayoutAttributeHeight
                                                                 relatedBy:NSLayoutRelationEqual
                                                                    toItem:nil
                                                                 attribute:NSLayoutAttributeHeight
                                                                multiplier:1.0
                                                                  constant:45]];

    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.productName
                                                                 attribute:NSLayoutAttributeLeading
                                                                 relatedBy:NSLayoutRelationEqual
                                                                    toItem:self.productImageView
                                                                 attribute:NSLayoutAttributeTrailing
                                                                multiplier:1.0
                                                                  constant:10]];

    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.productName
                                                                 attribute:NSLayoutAttributeTop
                                                                 relatedBy:NSLayoutRelationEqual
                                                                    toItem:self.contentView
                                                                 attribute:NSLayoutAttributeTop
                                                                multiplier:1.0
                                                                  constant:5]];

    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.productOption
                                                                 attribute:NSLayoutAttributeLeading
                                                                 relatedBy:NSLayoutRelationEqual
                                                                    toItem:self.productImageView
                                                                 attribute:NSLayoutAttributeTrailing
                                                                multiplier:1.0
                                                                  constant:10]];

    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.productOption
                                                                 attribute:NSLayoutAttributeTop
                                                                 relatedBy:NSLayoutRelationEqual
                                                                    toItem:self.productName
                                                                 attribute:NSLayoutAttributeBottom
                                                                multiplier:1.0
                                                                  constant:5]];

    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.listIconImage
                                                                 attribute:NSLayoutAttributeRight
                                                                 relatedBy:NSLayoutRelationEqual
                                                                    toItem:self.contentView
                                                                 attribute:NSLayoutAttributeRight
                                                                multiplier:1.0
                                                                  constant:-15.0f]];

    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.listIconImage
                                                                 attribute:NSLayoutAttributeHeight
                                                                 relatedBy:NSLayoutRelationEqual
                                                                    toItem:nil
                                                                 attribute:NSLayoutAttributeHeight
                                                                multiplier:1.0
                                                                  constant:20.0f]];

    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.listIconImage
                                                                 attribute:NSLayoutAttributeWidth
                                                                 relatedBy:NSLayoutRelationEqual
                                                                    toItem:nil
                                                                 attribute:NSLayoutAttributeWidth
                                                                multiplier:1.0
                                                                  constant:11.0f]];

    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.listIconImage
                                                                 attribute:NSLayoutAttributeCenterY
                                                                 relatedBy:NSLayoutRelationEqual
                                                                    toItem:self.contentView
                                                                 attribute:NSLayoutAttributeCenterY
                                                                multiplier:1.0
                                                                  constant:0]];  `
</code>
The above is the code i have used to create this Design.Now i am struggling for how to get dynamic height in tableviewcontroller.It is always returning 0 when i am getting in heightForRowAtIndexPath.
Thanks & Regards
Sam.P
Answer: You should set tableView.rowHeight = UITableViewAutomaticDimension and also provide  tableView.estimatedRowHeight = 68.0f (estimated height, doesn't have to be exact);
More info in following link:
SO Link


Is it an example of bilinear pairing?

Question: Consider a bilinear pairing $e: G_1 \times G_2 \rightarrow G_T$. Let's assume, $G_1 = G_2 = G_T = (\mathbb{Z}_n,+)$, i.e. additive group of integer modulo $n$ and $e(x,y) = xy$ mod $n$. Isn't it an example of bilinear map?
$G_1 = G_2 = G_T = (\mathbb{Z}_n,\ast)$, i.e. multiplicative group of integer modulo $n$ and $e(x,y) = y^x$ mod $n$, is it still a bilinear map?
Can there be other bilinear map defined over $\mathbb{Z}_n$?
EDIT:

Actually all my question were to understand Groth-Sahai proof system. Here, they have recast the general equation to fit the form of a quadratic equation. (See teh highlighted part below). But, how can they remark that all maps with $f(x,y) = xy$ mod $n$ will satisfy properties of bilinear pairing?
Answer: In your secondxample  assume you mean $\mathbb Z_n^\times$, i.e., the $\phi(n)$ element gorup of invertible elements mod $n$. Note that $y^x\pmod n$ makes little sense as in general we do not have $y^{x+n}\equiv y^n\pmod n$. Also, while w have $(y_1y_2)^x\equiv y_1^x\cdot y_2^x$, we do not have $y^{x_1x_2}\equiv y^{x_1}y^{x_2}$. You may want to look at $(\mathbb Z_n^\times,\cdot)\times (\mathbb Z_{\phi(n)},+)\to (\mathbb Z_n^\times,\cdot)$ instead.
For your second question, $(\mathbb Z_n,+)\times (\mathbb Z_n,+)\to (\mathbb Z_n,+)$, $(x,y)\mapsto cxy$ is bilinear for eny  fixed $c\in\mathbb Z_n$
Comment: Did I correctly identify first one to be a bilinear map?
Comment: Also, is $\phi(n)$ Euler's totient function?
Comment: @Holmes.Sherlock Yes (cf. my last statement with $c=1$) and Yes
Comment: I have edited the original question, can you please have a look?

Is it an example of bilinear pairing?


How to make a dropdown overlaps a div that has width and overflow-x hidden?

Question: Here is my issue:
I have a div with some specific width, inside that div i have a dropdown and some other elements that shows as popups or dropdowns, if i just set the overflow properties to default it works fine.
But i need it to scroll and when i set the overflow: scroll my dropdown just is cutted like the snipped down below, there is some way that i can show the dropdown outside the square (in my snipped) keeping the scroll?

.wrapper {
  width: 150px;
  height: 150px;
  border: 1px solid black;
  overflow-y: auto;
  overflow-x: hidden;
}

<link href="https://email@example.com/dist/css/bootstrap.min.css" rel="stylesheet"/>

    <button class="btn btn-primary dropdown-toggle"
      data-toggle="dropdown">Click me</button>

      Action
      Another action
      Something else here

Answer: The issue is a result of the overflow alongside position: relative on the dropdown parent.
Just setting the
 to position: static; solves the issue:

.wrapper {
  width: 150px;
  height: 150px;
  border: 1px solid black;
  overflow-y: auto;
  overflow-x: hidden;
}

.dropdown.dropright {
  position: static;
}

<link href="https://firstname.lastname@example.com/dist/css/bootstrap.min.css" rel="stylesheet"/>

    <button class="btn btn-primary dropdown-toggle"
      data-toggle="dropdown">Click me</button>

      Action
      Another action
      Something else here

Please note that this has the downside that you can no longer use top, right, bottom and left on absolute positioned children when these positions are meant to relate to the parent.
Instead (as Bootstrap does) you use transform: translate(...) for the positioning of absolute children.


Autowired Repository is Null

Question: I am trying to use repository in a class which named CacheManager. This repository should get all rows from the table. Despite using @Autowired annotation, it gets null. Where am I missing? Thanks.
REPOSITORY
@Repository
public interface FraudCacheListRepository extends CrudRepository<FraudCacheListEntity,Integer> {
    List<FraudCacheListEntity> findAll();
}

Cache Manager
@Component
public class CacheManager {

    private long second = 1000L;
    private long minute = second * 60;
    private long hour = minute * 60;

    private long TTL = hour;

    @Autowired
    private FraudCacheListRepository fraudCacheListRepository;

    public CacheManager() {
        getAllTables();
    }

    private void getAllTables(){
        List<FraudCacheListEntity> fraudCacheListEntities = fraudCacheListRepository.findAll();
        for (FraudCacheListEntity entity:fraudCacheListEntities) {
            System.out.println(entity.toString());
        }
    }
}

Core Controller
@Component
@Configurable
public class CoreController {
    public ComController com;
    @Autowired
    private CacheManager cacheManager;

    public CoreController() {
        com = new ComController();
    }
}

MAIN - Rest Controller
@RestController
public class FraudRestController {
    @Autowired
    private CoreController core;
}

Comment: Keep in mind, that field injection happens after the constructor is completely executed. So `CacheManager.getAllTables()` will produce a NullPointerException, since the field `fraudCacheListRepository` is not initialized. Suggestion: change from field injection to constructor injection.
Comment: I changed my code but problem still exist
Comment: In constructor: public CacheManager() { getAllTables(); } this will injected as dependency before repository dependency. for fix that you need to create @PostConstructor private void init() { getAllTables(); } and remove it in constructor  if this works please vote as useful else let me know it. kind regards
Answer: Since you used private CoreController core = new CoreController();, CoreController and CacheManager are not Spring managed beans, therefore no dependency injection occurs.
UPDATE
I suggest you this approach:
@Component
public class CacheManager {

    private long second = 1000L;
    private long minute = second * 60;
    private long hour = minute * 60;

    private long TTL = hour;

    @Autowired
    private FraudCacheListRepository fraudCacheListRepository;

    @PostConstruct
    public void getAllTables(){
        List<FraudCacheListEntity> fraudCacheListEntities = fraudCacheListRepository.findAll();
        for (FraudCacheListEntity entity:fraudCacheListEntities) {
            System.out.println(entity.toString());
        }
    }
}

The reason it's not working for you is that the constructor is called before the injection take place. The @PostConstruct annotation instructs Spring to call getAllTables method after the bean is fully initialized.

Autowired Repository is Null


Parse Server Cloud Code Error 141: Unauthorized

Question: I have just created a parse-server deployment for learning on Cloud9 and everything works fine when I am accessing it using the REST API using PostMan. I am now trying out Cloud Functions.
I have the following code in my cloud.js file,
Parse.Cloud.define('hello', function(request, response) {
    var query = new Parse.Query("Test");
      query.find({
          success: function(data){
              response.success(query);
          },
          error: function(err){
              response.error(err);
          }
      })
});

And in the response I get the following error,
{
  "code": 141,
  "error": {
    "message": "unauthorized"
  }
}

My request on PostMan looks something like this,

The response is fine as long as I do not try a query and send a simple response like response.success("OK").
Is this an issue with Parse or am I missing something related to authorization?
Answer: All I had to do was add useMasterKey: true in the find method.
query.find({ useMasterKey: true, success: function(data){ response.success(query); }, error: function(err){ response.error(err); } })


HttpServletResponse.sendRedirect is not working when the tomcat is upgraded

Question: I am working on a java web application and which is deployed on Tomcat. I am using servlets to handle some functionality, In the Servlet I am redirecting from one servlt to other servlet by using
SendRedirect method and it was succesfully redirecting to other servlet.
Problem: Earlier we wereusing Tomcat version - 7.0.65 but recently it has been upgraded to 7.0.67.
After upgrading tomcat to newer version(7.0.67), send redirect calls are not working.
Example:
<code>Public class MainServlet  extends HttpServlet {

  protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

  // do some operations..
  String emptyStr = " ";
  String urlPath = "http:localhost:8085/DemoProject/demoServlet? username=dummy&eid=emptyStr";
  response.sendRedirect(urlPath);
  return;
    }

 }
</code>
I have seen the Tomcat specification also and they are talkiing about redirections which is below whic i can not understand.
Apache Tomcat 7.0.67
Release Date: 2015-12-10
Full release notes can be found here.
56917: As per RFC7231 (HTTP/1.1), allow HTTP/1.1 and later redirects to use relative URIs. This is controlled by a new attribute useRelativeRedirects on the Context and defaults to true. (markt)
58660: Correct a regression in 7.0.66 caused by the change that moved the redirection for context roots from the Mapper to the Default Servlet. (markt)
Fixed potential NPE in HostConfig while deploying an application. Issue reported by coverity scan. (violetagg)
58655: Fix an IllegalStateException when calling HttpServletResponse.sendRedirect() with the RemoteIpFilter. This was caused by trying to correctly generate the absolute URI for the redirect With the fix for 56917, redirects may now be relative making the sendRedirect() implementation for the RemoteIpFilter much simpler. This also addresses issues where the redirect may not have behaved as expected when redirecting from http to https to from https to http. (markt)
Please look into the problem and let me know if you have any suggestion.
Any suggestions would be appreciated.
Comment: You've two compilation errors in the code snippet and the URL syntax is wrong. Please don't be careless with posting problematic code and eliminate those red herrings from your question.
Comment: Hello @BalusC, Please look into the edited question. My intention is to specify some example not to provide running code which i am working.
Answer: I was actually running into the same thing with an app I inherited that was running swell in Tomcat 7.0.62. The upgrade path I had to perform was to use Tomcat 8.x and Java 8. Upon testing the app, it also broke.
Narrowed it down to the fact that there were spaces in the URL generated for the redirect (that were not encoded and were not using +. This worked no problem through all versions up to 7.0.65. Once 7.0.67 was hit, Tomcat was no longer handling the spaces in the redirect URL (which btw, was an absolute https://.... path, not relative)
The behavior for sendRedirect seems to have been directly affected with the changes in 7.0.67+. The solution is to properly URL Encode your redirect URL so that spaces, specials chars, etc are encoded before calling the sendRedirect function with the location to go to
Just my 2 cents on the topic since I have recently hit this as well.


Are Parse IDs deterministic?

Question: I know that in Mongo, when you create IDs, the IDs are created in part by a time element which can be nice for sorting without using any other keys like createdAt or updatedAt. Is the same true for IDs created in Parse?
Answer: Parse-server doesn't use deterministic IDs for the object but 10 characters random strings (which can be configured on your side also if you wish to have longer objectIds)
https://github.com/parse-community/parse-server/blob/master/src/cryptoUtils.js#L39

Are Parse IDs deterministic?


Windows Virtual PC or VMware Workstation

Question: I would like get some feedback on virtualization software. I am looking at using either VMWare Workstation or Windows Virtual PC.  Any suggestions, feedback, experiences, pros/cons would be greatly appreciated.
Thanks,
Brennan
Answer: I don't think MS Virtual PC is really being actively developed, and in its' current form, has limited support for non-MS OSes.
VMWare Workstation is a very well developed and flexible product, whose main competitor is Oracle's VirtualBox- also a very well developed and flexible product. The biggest difference between the two is price - VirtualBox is available for free as in no $$$ needed, as well as free as in an OSS version is available. VMWare Workstation costs $$$, although the no cost VMWare Player is available, and still very feature rich.
My personal preference is VirtualBox, and have been using it for a few years. It does everything I've asked of it, although my needs aren't very complex. If you're just getting started with virtualization, or want to try some stuff out, I suggest getting VirtualBox or VMWare Player. If you need something specific that only VMWare Workstation provides, go with that.
Answer: It depends a little bit on your usage. I would say Virtual PC is only viable if host and guest are both going to be Windows. I find Virtual PC is a lilttle simpler to use than VMWare. I would suggest also recommend trying out VirtualBox because as well as being free, it is also well featured.
Answer: I would suggest trying VirtualBox and VMware Player. I use Player on my laptop and my desktop, to keep a Linux system available even though I use Windows.
It used to be more challenging to create new VMs in Player, but the current version lets you create them pretty easily.
If you need a bit more power and can devote a supported machine to the effort, the vSphere Hypervisor a.k.a. ESXi is free. I'm running it on a run of the mill Dell Precision Workstation at work... check the HCL if you build your own machine.


Is there an official list of abbreviations for ballroom dances?

Question: When looking around for notes on ballroom dancing you will stumble across many abbreviations, many of them are very clear. But the dances itself (referring to the usual ten ballroom dances in a competition) seem to lack clear abbreviations.
While searching I have found

S/SA/SB for Samba, C/CC/CCC for Cha Cha Cha, R/RU/RB for Rumba, J/JI/JV for Jive, P/PA/PD for Paso Doble
W/SW for Slow Waltz, VW/WW for Viennese Waltz, T/TA/TG for Tango, F/SF for Slow Foxtrot, Q/QS for Quickstep

Unfortunately, I have found no official reference (maybe from WDSF) which lists the abbreviations. Is there such a list or if not why not?
Please note that I have not found a tag for dancing here on Sports.SE, so if it is off-topic I would be glad if you could point me to some other place.
Answer: Seems I have found at least a regional answer. The German "Turnier- und Sportordnung des Deutschen Tanzsportverbandes e.V. (TSO)" (the reference for the DTV) lists the following abbreviations (according to the German names of the dances) on page 19 (version dated January 2019):

Langsamer Walzer: LW
Tango: TG
Wiener Walzer: WW
Slowfox: SF
Quickstep: QU
Samba: SB
Cha-Cha-Cha: CC
Rumba: RB
Paso Doble: PD
Jive: JV
Comment: I'm still waiting for a more international answer…
Comment: I don't think you're really going to find one (an internationally accept set), as each federation or organization uses it's own rules and abbreviations. For the US, for example, in the NDCA Rules and Application forms, they do not abbreviate. Yet, the USDC Application uses 17 different abbreviations, none of which are listed above.


Cannot create yearly auto renewal subscription in iTunes Store

Question: I can create monthly autorenewal subscription , submit it and test it.
But I don't find any options to create yearly auto renewal subscription.
Screenshot of the pop up dialogue is as follows:

Can't we really make yearly auto renewal product id ?

As a solution I tried to create yearly non renewal product but I couldn't add end date.? Should that be handled from our code ?
Any suggestions would help for me.
Thank you.
Answer: In your screenshot, Monthly Subscription is just the name of a group that you can add multiple IAPs to. It doesn't refer to a time period.
If you select select one of these options and proceed you should be taken to a screen where you can customise your IAP like this screenshot.
You can then update your subscription duration.


In iOS, is it possible to open notifications directly in customized mode?

Question: iOS provides for custom push notifications in mobile devices, however they are implemented by first opening a default notification, if the user taps it, then an event is sent to open the custom notification.
In the example below, the left one is the default notification, the right one is the custom one displayed after tapping the default.

I'm wondering if there is a way to open the custom notification directly with no user interaction?
Comment: Even if this *was* possible, wouldn't automatically having an application open without the user's direct consent be horrible user experience? Or am I mis-understanding your question?
Comment: @esqew – could argue it would be a better user experience since it would remove the need to open a second notification
Answer: I dont think there is a way to open the custom notification by default or render the custom notification as a default notification.
As per apple documentation, when the device receives a push, it displays the alert in 2 stages

First, an abbreviated banner with the title, subtitle, and two to four lines of body text from the notification
If the user presses the abbreviated banner, it displays the full notification interface, including any notification-related actions.

And it clearly states

The system provides the interface for the abbreviated banner, but you
  can customize the full interface using a notification content app
  extension.

So I dont think there is a way to display a custom notification UI without the user action.
But if you absolutely want to display an media in the notification, you can use UNNotificationAttachment to display the media elements like image, audio, and video in the system alert itself.
Answer: @RameshVel answer is correct. Here is sample and tutorial for doing this.

https://www.appcoda.com/user-notifications-ios12/


Trouble getting command line arguments in x86 assembly

Question: I'm trying to write an x86 version of the 'cat' program as a training of syscall calls in assembly.
I'm struggling a lot with command line arguments.
I use the main symbol as an entry point, so I thought I would find the argc parameter in %rdi and the argv parameter in %rsi.
Actually argc is in %rdi as expected, but I keep segfaulting when trying to pass argv[1] to the open syscall.
Not sure of what I'm doing wrong, here is my assembly code:
main:
    cmp $2, %rdi            // If argc != 2 return 1
    jne .err1

    lea 8(%rsi), %rdi       // Move argv[1] -> %rdi
    xor %rsi, %rsi          // 0 to %rsi -> O_RDONLY
    xor %rdx, %rdx
    mov $2, %rax            // Open = syscall 2
    syscall

    cmp 0, %rax             // If open returns <0 -> exit status 2
    jl .err2

    mov %rax, %rdi          // Move fd to %rdi
    call cat
    ret

.err1:
    mov $1, %rax
    ret
.err2:
    mov $2, %rax
    ret

Comment: Okay, then your code should work.  Note that `lea 8(%rsi), %rdi` retrieves a pointer to the pointer to the second argument.  If you want to obtain a pointer to the string itself (which it looks like it is what you are trying to do), use `mov 8(%rsi), %rdi`.
Comment: How do you assemble and link your code?  If you don't link with the libc, there's nothing that places an argument count into `esi` or a pointer to the arguments into `rdi`.  Instead, you'll have to retrieve the arguments from where the program loader puts them on the stack.  The name of the entry point doesn't matter then.
Comment: I assemble using gcc: gcc -o cat cat.S -no-pie
Comment: Does this answer your question? [Linux 64 command line parameters in Assembly](https://stackoverflow.com/questions/3683144/linux-64-command-line-parameters-in-assembly)
Answer: There are two issues with your code.
First, you use lea 8(%rsi), %rdi to retrieve the second argument.  Note that rsi points to an array of pointers to command line arguments, so to retrieve the pointer to the second argument, you have to dereference 8(%rsi) using something like mov 8(%rsi), %rdi.
Second, you forgot the dollar sign in front of 0 in cmp $0, %rax.  This causes an absolute address mode for address 0 to be selected, effectively dereferencing a null pointer.  To fix this, add the missing dollar sign to select an immediate addressing mode.
When I fix both issues, your code as far as you posted it seems to work just fine.


block visibility snippet restrict path

Question: I use the following snippet to restrict who can see a block inside admin pages. Can you help me add the restriction of a path /cart* for non admin users into this snippet?
if (user_access('access administration pages')) {
  return FALSE;
} else {
  return TRUE;
}

Answer: I am assuming the logic is:
Display this block only on pages with a path beginning with cart/*,
And only when the user has `access administration pages` permission

If so....
if (arg(0)=='cart' && arg(1) && user_access('access administration pages')) {
  return TRUE;
} else {
  return FALSE;
}

If you want it displayed on path cart all by itself as well, just remove the && arg(1) from the above and then it will work on cart in addtion to cart/foo and cart/foo/bar etc.
If, however, you want it only on cart/oneargumentonly, you can add in && !arg(2).
ADDITION/CORRECTION:
if (user_access('access administration pages') || (arg(0)=='cart' && arg(1))) {
  return FALSE;
} else {
  return TRUE;
}

while return FALSE if the user can access administration pages regardless of the path OR the path is cart/* regardless of any permissions.
So, if my logic is right now, if the user can access administration pages the if is "short circuited" and returns FALSE.  Otherwise, if the user doesn't have this permission, it continues on and if the path is cart/* it returns FALSE.  Otherwise, since we already know the user doesn't have the access administration pages permission it returns TRUE for any other path.
FINAL?
if (user_access('access administration pages') || arg(0)=='cart') {
  return FALSE;
} else {
  return TRUE;
}

Comment: No, it should be visible for anybody anywhere except for all paths starting with cart and not visible for admin users at all anywhere.
Comment: ah....ok....brb :)
Comment: Hi, thank you for this code. It works ok but I need to hide the block on cart page as well. Now it is hidden for all pages with cart in path. can you tell why this code doesn;t work? `if (user_access('access administration pages')) || (stristr(current_path(),"/cart")
{
  return FALSE;
}
else {
  return TRUE;
}`
Comment: your code in your comment doesn't work on path `cart` because it (the path) doesn't begin with a `/`, it's just plain old `cart`.  If you take the `&& arg(1)` out of my code it will work on `cart`, `cart/foo`, `cart/foo/bar` etc
Comment: Final solution doe's the trick. Thank you. I need to learn some basics of PHP.
Answer: This is to hide the block in cart/* for non administrator roles.
if(stristr(current_path(),"cart/") && user_access('access administration pages')) {
  return TRUE;
}
else {
  return FALSE;
}

Comment: Hi,I was thinking about something like this
if (user_access('access administration pages')) {
  return FALSE;
}
elseif (stristr(current_path(),"/cart")
{return false;}
else {
  return TRUE;
}
But it is not working
Comment: Hi,I was thinking about something like this
Comment: almost, this just checks if `cart/` is in the path and thus would match something like `teacart/` anywhere :)

block visibility snippet restrict path


Is there a 64 bit version of CharLowerBuff?

Question: I am currently transitioning some C++ code to be compiled for 64 bit instead of 32 bit. The code calls the function CharLowerBuff(lpsz, strlen(lpsz)) which raises a warning since strlen returns the type size_t (aka long long unsigned int) but CharLowerBuff expects DWORD (aka long unsigned int).
Is there a 64 bit version of CharLowerBuff that takes DWORDLONG (or something equivalent) instead?
Comment: Just cast it, unless you really plan on having a 4GB string.
Comment: Are you really going to call strlen on a 4GB string? And then walk over it a second time. Perhaps you'd be better using C++ libraries for your text process rather than winapi. Surely you aren't using C strings.
Answer: I don't see one, however CharLowerBuff(x, strlen(x)) is just the same as CharLower(x), but the latter does not have this DWORD problem.
Another approach would be to write your own function to do this operation and take a size_t length, which shouldn't be difficult.


gaps within menu tabs?

Question: Why do I have gaps between my tabs?

my css for each tab is:
    .tab1
{
    color: white;
    display: inline-block;
    height: 110px;
    width: 234px;
    background-image: url("../images/first-tab.png");
    background-repeat:no-repeat;
}

.tab2
{
    color: white;
    display: inline-block;
    height: 110px;
    width: 234px;
    background-image: url("../images/second-tab.png");
    background-repeat:no-repeat;
}

.tab3
{
    color: white;
    display: inline-block;
    height: 110px;
    width: 234px;
    background-image: url("../images/last-tab.png");
    background-repeat:no-repeat;
}

Answer: your tabs are inline-block and thuis treated almost the same as inline wich means theres whitespace between them id theres' whitespace (spaces, tabs or linebreaks) between them in the html-source.
this will give you "gaps":

Content here

Content here

Content here

this won't:

Content here

Content here

Content here

and this also won't:

    Content here

    Content here

    Content here

to change this, update your html-source and remove the whitespace or (better) change your css to use block-elements and float:left (wich may lead to other problems, but thats hard to say since you havn't give your html-sourcecode)
Answer: Since they are inline block they display a single text space between them if there is actual whitespace between them in the html, so either remove the whitespace in the html(ugly html) or think of another solution to display your elements this way(floating for example).
Answer: What html are you using? Most elements have default paddings/margins. You will have to override these in most cases. Try "margin:0;padding:0;" to remove them or add your html-example.

gaps within menu tabs?


Strip caption from image using css

Question: I am adding a caption to images by using the following module: https://www.drupal.org/project/image_field_caption
For the front page I am using views. There, I also show the images but I do NOT want to show the captions. I guess the captions can be stripped away by using CSS...
How is that done? I do not know CSS and the "interaction" of Drupal and CSS very well.
My questions:
1. Where do I have to add the CSS code?
2. What do I have to write there?
3. How is this CSS snipped included in views to get the effect of stripping caption away?
Thanks!
Answer: if this is strictly a css question, I believe it's off-topic here, but...
I've never worked with that module, so this may or may not be an option:
If you output your View as a table, you can modify how fields are represented. Unless the module overwrites the default image formatter, you should be able to choose the Image formatter instead for that field and bypass the module.

Strip caption from image using css


Are countable intersections of convex sets convex?

Question: Let $X$ be a Banach space $\{C_n\colon n\in\mathbb N\}$ a collection ofconvex sets in $X$. Is the set $$C=\bigcap_{n\in\mathbb N}C_n$$ convex?
Comment: Taking intersections is very well behaved. Most properties are preserved. Just appeal to the definition. If $x,y\in C$ then $x,y\in C_n$ for each $n\in\mathbb N$ and use the convexity of the $C_n$s
Comment: Yes: pick two points in the intersection $x$ and $y$. For each $n$ and $0\leq a\leq 1, $ax+(1-a)y\in C_n$. (actually it works for arbitrary intersections.
Comment: They don't even have to be countable.  I'm tempted to say even a proper class, as opposed to a set, of convex sets would have a convex intersection.  But I don't know where you'd find any such class that's not a set.
Answer: Suppose $x,y\in C$ then $x,y\in C_n$ for all $n\in\mathbb{N}$. Now as $C_n$ is convex hence for all $0\leq\lambda\leq 1$ we have $\lambda x+(1-\lambda)y\in C_n$ for each $n$. So $\lambda x+(1-\lambda)y\in C$. So $C$ is convex
Answer: In fact, any intersection of convex sets in this setting is convex. Suppose that $\mathcal{E}$ is a Banach space and that $\mathcal{K}$ is any family of convex sets. If $\bigcap\mathcal{K}$ is void, it is vacuously convex. Otherwise, take $x,y\in\bigcap\mathcal{K}$, $\lambda\in[0,1]$ and $K\in \mathcal{K}$. Since $K$ is convex, we have
$$(1-\lambda)x + \lambda y\in K.$$
But this holds for any $K\in \mathcal{K}$, so
$$(1-\lambda)x + \lambda y\in \bigcap \mathcal{K}.$$
There is no induction or sequential property here.  In fact, the argument generalizes to any real vector space.


xml validation for nullable element

Question: I have a xml element with following schema:
<xs:element name="Date" type="xs:date" nillable="true" />

But it failed the validation with following node.
<Date />

Why the nillable attribute doesn't work for this? Thanks!
I use .net XmlReader for validation
Thanks in advance!
Answer: Try:
<Date xsi:nil="true"></Date>

xml validation for nullable element


plotar gráfico série temporal onde no eixo x mostre todos os anos

Question: Quando ploto a série temporal normal plot(serie), alguns anos ficam subentendidos que existem, mas não aparecem. Teria uma forma de mostrar todos os anos da serie temporal horizontalmente no eixo x ?
Comment: Faz parte da ferramenta ocultar sozinho não?
Answer: Para fazer o que pede, tem de começar por não incluir os eixos com o argumento axes = "n". Depois usa-se a função axis para por a anotação dos eixos onde e como se quiser.
Primeiro vou criar uma série temporal, uma vez que não temos dados na pergunta.
set.seed(4745)    # torna os resultados reprodutíveis

x <- ts(rnorm(14), start = 2005, end = 2018)

Agora, o gráfico. Note que mesmo assim os anos podem não caber no gráfico. Então rodei 90 graus para ficarem perpendiculares ao eixo dos x. Isso é feito com las = 2.
plot(x, xaxt = "n")
axis(1, at = 2005:2018, labels = 2005:2018, las = 2)

Gráfico:
Comment: Muito obrigado, exatamente o que eu queria !!