Why are sound systems in karaoke bars so bad?

Question: Recently I have been singing in 15/20 karaoke bars in London and I only found one where the sound system was acceptable.
Some of the most commons problems are:

The speakers are only directed toward the public and you cannot hear the music or yourself very clearly.
The quality of the sound in not good and the sound not clear.
The voice volume is often too low and you are forced to shout.
Some of the frequencies are not very clear.

I have been singing in many rehearsal studios instead and I never found this kind of issues. The sound is always clean and clear and the experience ten times better.
I wonder why nobody can set up a karaoke system that works well? Why can't I find a karaoke bar with a good sound system? Why it's so difficult? Is there anything I can ask or check to know in advance if a karaoke bar is good or not?
Comment: They're set up by DJs, not sound engineers. The only qualification necessary to be a DJ is "can play records"
Comment: @Tetsujin What's a record? I think the real qualifications are, "can sing well enough to make people think they can sing also but not so well that people think they suck so they order more drinks to screw up their courage and thereby justify the bar paying for the KJ and equipment." Desired but not required qualifications include being attractive, knowing how to prevent feedback, and knowing how to not make it obvious that half the available songs are not correctly licensed.
Answer: Considering the mess  dedicated 'sound operators' routinely make of a gig, yes, it's not surprising a DJ knows little beyond pumping sound in the general direction of the audience.  But all but the most basic karaoke systems have a monitor speaker for the performer, through which he can hear both the track and his voice.   However, a drunken karaoke performer cannot be trusted not to point his mic into this speaker, causing annoying (and possibly destructive) feedback.  So a sensible karaoke operator will not put much vocals in the monitor.  Also, a karaoke microphone will be mistreated, so it starts off cheap-and-nasty and rapidly gets worse.
Comment: Depending on their own musical sensibilities, they may also duck the mic for poor performers & lift it for the good ones ;-)
Comment: But the poor ones are MUCH more entertaining!


Curve is a submanifold

Question: In our class today we said today that an 1-times continuously differentiable immersion $\phi:[0,1] \rightarrow \mathbb{R}^n$ is a submanifold of dimension 1 if it is closed such that $\phi(0)=\phi(1)$ (but this should be the only point where the curve is not injective) and $\phi'(0)=\phi'(1)$. I still do not get it why we want that the curve to be closed. what is wrong with a curve that is not closed?
Is this only because it may not be differentiable at the end points or is there more in it?
Comment: never mind, I did not use the assumption in the answer.
Answer: If the curve is not closed, i.e. if $\phi(0)\neq\phi(1)$, then there is no neighborhood $U_0$ ($U_1$) of $\phi(0)$ (or $\phi(1)$) in $\mathbb{R}^n$ and a neighborhood chart $\psi:U_0\to\mathbb{R}^n$ that carries the image of $\phi$ to the $x_1$-axis. Thus $\phi[0,1]$ cannot be a submanifold of $\mathbb{R}^n$.
Answer: My understanding of a k-submanifold $C$ of $\mathbb R^n $ is that there must be an open set $U$ in $\mathbb R^n $ , and some chart map $\gamma$ , so that $\gamma (C\cap U)=(x_1,x_2,..,x_k, 0,0,..,0)$, i.e., C is embedded in $\mathbb R^n$ in the same way as the "standard embedding" of $\mathbb R^k$ in $\mathbb R^n$. In the case of a curve $C$, you need an open set $V$ , and a chart map $\gamma$ with $\gamma (V \cap C)=(x,0,0,..,0)$. But: every intersection of an open set $V \subset \mathbb R^n$ with the non-closed curve $C$ will be of the form $(a,b]$, i.e., a half-open interval (when seen in $\mathbb R$. An a half-open interval subspace cannot be homeomorphic to a copy of $\mathbb R$ in $\mathbb R^n$, since $\mathbb R$ itself is homeomorphic to $(a,b); a\neq b$, but is not homeomorphic to $(a,b]$

Curve is a submanifold


Do competent violinists avoid open strings?

Question: I just picked up a violin for the first time in what must be 25 years. All that time ago, I had lessons and playing in school orchestras - but moved on to other instruments.
As a beginner I would use open strings to play the corresponding notes.
As a more experienced guitarist/bassist I often avoid open strings, because when fingering a note with the left hand, I can add vibrato, muting etc.
Violinists do a lot of vibrato. Would a reasonably advanced violinist play any open strings at all?
Answer: IANAV, but from what I've seen it depends on the kind of sound they want. An open string sounds so different that if you want a consistent sound for example for a melody line, you'd try to avoid it. In a fast scale it doesn't matter that much. Open strings can also be used to get certain effects, like a folk fiddle kind of sound or just a stronger sound. In short, open strings are used, but not mindlessly.
As for vibrato, they can do some kind of vibrato even on open strings. I believe the vibrato is done on another string an octave higher which then causes the note to vibrate due to sympathetic resonance or something. Or if you vibrate the whole instrument really vigorously, you can use the doppler effect... ;-)
Comment: @leftaroundabout I've actually tried this.  The differences are actually quite noticeable (even walking around when you're playing)!  Not really usable, but certainly something to consider.
Answer: Yes - they use open strings (I am a violinist.) They don't use them all the time however, and a competent violinist will make the decision as to whether to use an open string based on the type of sound required. An open string will often give a brighter, more open sound, which can sometimes stick out like a sore thumb and other times really enhance the melodic line.
As pointed out already, vibrato isn't always required, and IMO is used way too much these days (Bach with vibrato? Really? Really?!) You can do open string vibrato, though personally I avoid it whenever possible, it's a subtly different sound to normal vibrato and doesn't sit well with my ears. Generally for this reason, I'll often use open strings much more in Baroque and early classical than with later works, since I find the sound often fits better. This is of course by no means a hard and fast rule though.
Answer: Yes, violinists use open strings. I originally trained in Strathspey and Reel violin, and we would not only play fingered notes, but would also alternate open drone notes with high notes, or even play multiple strings at the same time.
Vibrato is also not mandatory, it it's used a lot but some pieces require none, and in fact a better violinist needs less vibrato to hit the right notes.
Answer: Now here's an example of a well-known open-string note:  the second theme of the first movement of Mendelssohn's Violin Concerto.  The soloist has to hold a low G for several measures.  There's only one way to play it, and that's on the open G string.  That G string had better be perfectly in tune!


iPhone: Using dispatch_after to mimick NSTimer

Question: Don't know a whole lot about blocks. How would you go about mimicking a repeating NSTimer with dispatch_after()? My problem is that I want to "pause" a timer when the app moves to the background, but subclassing NSTimer does not seem to work.
I tried something which seems to work. I cannot judge its performance implications or whether it could be greatly optimized. Any input is welcome.
#import "TimerWithPause.h"

@implementation TimerWithPause

@synthesize timeInterval;
@synthesize userInfo;
@synthesize invalid;
@synthesize invocation;

+ (TimerWithPause *)scheduledTimerWithTimeInterval:(NSTimeInterval)aTimeInterval target:(id)aTarget selector:(SEL)aSelector userInfo:(id)aUserInfo repeats:(BOOL)aTimerRepeats {

    TimerWithPause *timer = [[[TimerWithPause alloc] init] autorelease];

    timer.timeInterval  = aTimeInterval;

    NSMethodSignature *signature = [[aTarget class] instanceMethodSignatureForSelector:aSelector];
    NSInvocation *aInvocation = [NSInvocation invocationWithMethodSignature:signature];
    [aInvocation setSelector:aSelector];
    [aInvocation setTarget:aTarget];
    [aInvocation setArgument:&timer atIndex:2];
    timer.invocation = aInvocation;

    timer.userInfo      = aUserInfo;

    if (!aTimerRepeats) {
        timer.invalid = YES;
    }

    [timer fireAfterDelay];

    return timer;
}

- (void)fireAfterDelay {

    dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, self.timeInterval * NSEC_PER_SEC);
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    dispatch_after(delay, queue, ^{

        [invocation performSelectorOnMainThread:@selector(invoke) withObject:nil waitUntilDone:NO];

        if (!invalid) {
            [self fireAfterDelay];
        }
    });
}

- (void)invalidate {
    invalid = YES;

    [invocation release];
    invocation = nil;

    [userInfo release];
    userInfo = nil;
}

- (void)dealloc {

    [self invalidate];

    [super dealloc];
}

@end

Answer: So for timers that you want to fire a block, you would a dispatch source. There is a great example on the ADC website that I've used many times in lieu of NSTimer in my apps:
http://developer.apple.com/library/ios/#documentation/General/Conceptual/ConcurrencyProgrammingGuide/GCDWorkQueues/GCDWorkQueues.html%23//apple_ref/doc/uid/TP40008091-CH103-SW2
Comment: Dispatch sources are perfect for this. You can even suspend and resume a dispatch source, which is exactly what you are looking to do.
Answer: You could also simply "pause" a vanilla NSTimer by setting the fireDate to [NSDate distantFuture]. When your app comes back into the foreground, you could then simply resume the normal schedule.
Answer: I don't know much myself about blocks and background tasks but I would think of a different technique to "pause" your timer:
I would suggest to overwrite applicationDidEnterBackground and store the time remaining for the timer (based on NSTimer's fireDate), then when the app is back to foreground and applicationWillEnterForeground is fired, invalidate and re-calculate your timers based on the timestamp you saved before.
I haven't tested this solution, but seems it should be working
Hope this helps :)
Comment: I actually made a category that does just this: https://github.com/adamjernst/NSTimer-AbsoluteFireDate
Comment: I tried that by storing the information inside userInfo. But I don't think you can update that. Storing it outside the timer object does not make much sense. I could wrap the timer in a another object, but I do not think that is a very elegant solution. May do that still...
Comment: If you want to persist that information within the timer itself, why not use a mutable collection as the timer's `userInfo`? Wrap the remaining time until the next `fireDate` in an NSNumber and store it in the collection that is the timer's userInfo...


Get better fit on test data using Auto_Arima

Question: I am using the AirPassengers dataset to predict a timeseries. For the model I am using, I chosen to use auto_arima to forecast the predicted values. However, it seems that the chosen order by the auto_arima is unable to fit the model. The corresponding chart is produced.

What can I do to get a better fit?
My code for those that want to try:
import pandas as pd
import numpy as np
import matplotlib.pylab as plt
%matplotlib inline

from pmdarima import auto_arima

df = pd.read_csv("https://raw.githubusercontent.com/AileenNielsen/TimeSeriesAnalysisWithPython/master/data/AirPassengers.csv")
df = df.rename(columns={"#Passengers":"Passengers"})
df.Month = pd.to_datetime(df.Month)
df.set_index('Month',inplace=True)

train,test=df[:-24],df[-24:]

model = auto_arima(train,trace=True,error_action='ignore', suppress_warnings=True)
model.fit(train)

forecast = model.predict(n_periods=24)
forecast = pd.DataFrame(forecast,index = test.index,columns=['Prediction'])

plt.plot(train, label='Train')
plt.plot(test, label='Valid')
plt.plot(forecast, label='Prediction')
plt.show()

from sklearn.metrics import mean_squared_error
print(mean_squared_error(test['Passengers'],forecast['Prediction']))

Thank you for reading. Any advice is appreciated.
Comment: Have you tried explicitly setting the seasonality parameter `D` (presumably 12 here)?
Comment: @IgorRivin I did after you mentioned so. There still no change in the fit it seems. However, I explicitly statede the m to be 12 and there is a massive improvement.
Comment: @IgorRivin I have answered my own question but are there still ways to fit it better?
Answer: The problem was that I did not specify the m, in this case, I assigned the value of m to be 12, denoting that it is a monthly cycle, that each data row is a month. That's how I understand it. source
Feel free to comment, I'm not entirely sure as I am new to using ARIMA.
Code:
model = auto_arima(train,m=12,trace=True,error_action='ignore', suppress_warnings=True)

Just add m=12,to denote that the data is monthly.
Result:
Answer: This series is not stationary, and no amount of differencing (notice that the amplitude of the variations keeps increasing) will make it so. However, transforming the data first by taking logs should do better (experiment shows that it does do better, but not what I would call well). Setting the seasonality (as I suggest in the comment by m=12, and taking logs produces this: which is essentially perfect.
Comment: Doesn't auto_arima take into account non-stationarity and automatically finds the best values for it? source: https://www.analyticsvidhya.com/blog/2018/08/auto-arima-time-series-modeling-python-r/
Comment: No, it can only fit a SARIMA model to the data you give it. It will not transform the data first.If some differenced data is stationary it will succeed, but for this data no amount of differencing (or seasonality) will make it stationary.
Comment: Yes, I tried it. Thank you for your time @Igor Rivin
Comment: @cswannabe You are welcome. I have to say that this auto_arima is a bit disappointing (the fact that you have to set the seasonality parameter by hand AND it takes a LONG time are both not great).


Permutation with optimal payoff

Question: You play a game as follows. You have $N$ coins in front of you. For each coin you know:

the probability to get "heads" $p_i$
the prize $r_i$ you get when you get "heads" (as money)

The rules are:

choose a coin
if you get heads, you're done, you get the prize and the game stops.
otherwise you can choose and flip another coin (you can't flip twice the same coin).
and so on until you get heads or you reach a limit of $K$ flips ($K\leq N)$.

You want to find the best strategy: the one with highest expected payoff. Some simple cases:

For $K=N$ the solution is just ordering by decreasing $r_i$ ($p_i$ does not matter).
For $K=1$ the solution is just choosing the coin with highest expected payoff $p_ir_i$.

For $1<K<N$, it doesn't seem to be that simple. One solution is brute force: compute expected payoff for all partial permutations.
Do you see an (algorithmically) better solution?
Comment: I may be wrong but why not compute the products $p_ir_i$ and order the elements that way, and then choose elements in descending order?
Comment: Oh never mind I realize my mistake. The expectation values of second-and-onward flips depend on the first probability (because if the first coin is heads, we dont reach the latter coins and their values)
Comment: Yep :-). The case $K=N$ is an extreme counter-example against ordering by expected payoff.
Comment: Even for $K=2$ I don't see how to do it without computing.  That is, looking at examples, I don't see a simple way to "read off" the answer by inspection.
Comment: I did some brute-force calculations just to see what expressions look like. Start off with $p_ir_i$ and go for another coin, so your total expectation is $p_ir_i + (1-p_i)p_jr_j = (p_ir_i + p_jr_j) - (p_ip_j)r_j$. In general, each set of flips will have the "naïve sum" of all expectations, minus "coupling terms" that look like the $(\prod_{n=1}^{k}p_n)r_k$ for each $k \in (1...# of flips)$. This convinces me that brute-force computation is the best solution, but since the coupling terms do kind of depend on the easily-calculable terms, perhaps I am wrong...
Answer: This still takes exponential time and probably qualifies as "brute force", but it's better than your suggestion (computing expected payoff for all partial permutations): Compute the expected payoff for all subgames with more than $N-K$ coins left (choosing coins by comparing the subgames with one fewer coin left). For instance, for $K=N$, this takes $O\left(2^N\right)$ time, instead of $O(N!)$ for the permutations.

Permutation with optimal payoff


Como compilar fontes em diferentes pastas usando Makefile?

Question: Preciso compilar arquivos .cpp, gerando os respectivos .o, mas cada arquivo está em um diretório diferente.
Por exemplo, tenho duas pastas:

build: onde deveria ficar os arquivos compilados .o
src: onde estão os arquivos fontes .cpp

Meu objetivo é fazer com que o Make compile (ou recompile) os arquivos fonte que foram modificados e bote os arquivos compilados .o no diretório build. O problema é que os arquivos .cpp estão em diferentes sub-diretórios.
Estou utilizando o Windows como sistema operacional.
Meu Makefile:
APP_NAME = uni.exe
BUILD_PATH = build

CC = g++
CPP_VERSION = -std=c++20
SOURCE = \
    main.cpp \
    src/color/parser/colorParser.cpp \
    src/commands/definition/filesystemHelpDef.cpp \
    src/commands/definition/listHelpDef.cpp \
    src/commands/definition/literalHelpDef.cpp \
    src/commands/definition/numberTypeDef.cpp \
    src/commands/definition/objectHelpDef.cpp \
    src/commands/definition/regexHelpDef.cpp \
    src/commands/definition/systemHelpDef.cpp \
    src/commands/definition/typeHelpDef.cpp \
    src/filesystem/formating/fileFormating.cpp \
    src/filesystem/handle/file.cpp \
    src/instream/input/instream.cpp \
    src/instream/scanner/instreamScanner.cpp \
    src/parser/processing/token/tokenProcessing.cpp \
    src/path/handler/pathHandler.cpp \
    src/path/scanner/pathScanner.cpp \
    src/system/exception/exceptionRef.cpp \
    src/system/global/global.cpp \
    src/system/system.cpp \
    src/utilities/cmdUtil.cpp \
    src/utilities/typeUtil.cpp

OBJECTS := $(addprefix $(BUILD_PATH)/, $(notdir $(SOURCE:.cpp=.o)))

.PHONY: build

# procura pelos arquivos objeto em "build/"
# se o arquivo não existir, então compile-o a partir de
# seu arquivo fonte correspondente.

# exemplo: build/colorParser.o = src/color/parser/colorParser.cpp

build: $(OBJECTS)

# regra que deveria criar um arquivo objeto em "build/" a partir
# de um arquivo fonte correspondente de "%.o"
.SILENT:
%.o:
    echo $@

Answer: Primeiro, adicione a variável VPATH:
VPATH:=$(shell find src -type d)

O comando find src -type d retorna todos os diretórios dentro da pasta src. E o VPATH, segundo a documentação, indica a lista de diretórios que o make usa para procurar os arquivos. Sendo assim, a linha acima está indicando para procurar em qualquer sub-diretório dentro de src.
Se for no Windows, pode trocar o comando para cmd dir src\* /AD /S, ou ainda usar $(sort $(dir $(wildcard src/*/ src/*/*/))) para uma solução mais portável - o problema é que esta precisa de cada subnível explicitamente (por exemplo, se quisesse também o terceiro subnível, teria que adicionar src/*/*/*/).

Depois, basta incluir os comandos para gerar os arquivos .o, e também o comando que junta-os no executável final:
$(BUILD_PATH)/%.o : %.cpp
    $(CC) $(CPP_VERSION) -c -o $@ $<

build: $(OBJECTS)
    $(CC) $(CPP_VERSION) $(OBJECTS) -o $(APP_NAME)

Agora é só rodar make build e pronto.

Opcionalmente, pode incluir a opção para limpar tudo:
clean:
    rm -f $(BUILD_PATH)/*.o $(APP_NAME)

Para mais informações, consulte a documentação.
Comment: @MarvinMarjan Se não me engano, seria `cmd dir src\* /AD /S`. Ou, usando funções do `make`, seria `$(sort $(dir $(wildcard src/*/ src/*/*/)))` (mas é mais chato porque precisa incluir um `src/*/` para cada subnível - por exemplo, se tiver 3 subníveis, tem que adicionar `src/*/*/*/`, bem mais chato)
Comment: Seu exemplo de código parece funcionar, mas esqueci de mencionar que estou utilizando o sistema operacional Windows >﹏< (desculpa aí), então acho que o "shell find" não vai funcionar. Existe algum comando de CMD do Windows ou do Make que tem uma funcionalidade semelhante?
Comment: Funcionou mano!! valeu mesmo.


Convert Flow> to List<> From Room database

Question: I am trying to get list of player from my room database. Get it in Flow<List> and i convert it to List
I want to loop over the list to check which player should get win/lose/draw.
I think is something's wrong with my playerList, becouse i cant even show it in Log.d
val playerList = playerStatsRepository.getAllPlayerStats(tournament.id)
            .flatMapConcat { it.asFlow() }.toList()

my tournamentViewModel
https://github.com/DawidSiudeja/Tournament/blob/master/app/src/main/java/com/example/tournamentapp/TournamentViewModel.kt
It's good way to convert Flow to List?
Answer: To simply convert a Flow to its containing type, you can use .first(). Note, if this value then later changes after it is first read, .first() won't pick up on this, as it simply reads the first value, then stops observing the flow.
As you are using Jetpack compose, if this is a value you are using in a composable, you can convert the flow to a state via tournamentViewModel.playerList.collectAsState(initialValue = emptyList())
Note: That when collecting a Flow as a state you must provide an initial value. To avoid this you could convert your flow to a StateFlow in your viewmodel via the .stateIn(..) method (see docs)
To directly answer your question, this should resolve your issue:
val playerList = playerStatsRepository.getAllPlayerStats(tournament.id).first()


When is $y=t^2$ not a solution of homogeneous second order differential equation?

Question: How do I show that $y(t)=t^2$ can never be a solution of $y''+p(t)y'+q(t)y=0$ if $p(t)$ and $q(t)$ are continuous in $t=0$?
I haven't tried anything yet, because I simply do not know how to solve this problem.
Answer: Or seen in another way, one has $y(0)=0=y'(0)$. Any initial value problem for a homogeneous ODE of order 2 with these initial conditions can only give the zero function as solution.
Answer: Suppose $y=t^2$ were a solution. Then
$$2 + 2tp(t)+t^2q(t) = 0$$
for all $t$. What happens as $t\to 0$?
Comment: Then you would have $tp,t^2q\rightarrow 0$?
Answer: Well, if
$y(t) = t^2, \tag{1}$
then
$y'(t) = 2t \tag{2}$
and
$y''(t) = 2. \tag{3}$
Inserting (1), (2), and (3) into
$y'' + p(t)y' + q(t)y = 0 \tag{4}$
yields
$2 + t(2p + qt) = 0, \tag{5}$
and now letting $t \rightarrow 0$ we see that (5) forces
$2 = 0, \tag{6}$
an obvious contradiction.  QED.
Note we have used the continuity of $p(t)$ and $q(t)$ at $t = 0$ to establish that $t(2p(t) + tq(t)) \rightarrow 0$ as $t \rightarrow 0$.


javascript extension error: Cannot perform modifications

Question: I'm building a custom dynamicValue extension for paw. However i'm not able to set header in the evaluate method. See the sample code below:
evaluate(context) {
  const request = context.getCurrentRequest();
  request.setHeader('Content-Type', this.contentType); // <-- this gives warning
  return this.createSignable(request); // This returns a base64 string.
}

I get the warning saying Javascript extension error: Cannot perform modifications and the header is not set. ( when i comment out request.setHeader call, i get no warnings)

Can anyone please help me resolve this issue?
Answer: This is correct, you cannot use setters (set any value) in a dynamic value. In fact, the way Paw evaluates dynamic values is asynchronous and as multiple evaluations can take place simultaneously it would be impossible to record the modifications. For this reason, Paw is simply denying changes and no change is persisted during evaluation.
In the documentation, it's specified that these methods (like setHeaders) is only available for importer extensions. Sorry for the inconvenience!
I think to achieve what you're trying to do, you would need two dynamic values one set in the Authorization header and one set in the Content-Type header.
Alternatively, in the future we're going to add request post-processors, so you'll be able to mutate the computed request ready to be sent to the server for additional modifications.
Comment: Thanks Micha! That's exactly what i did. created two dynamic value headers. Anyways thanks for this awesome tool. Looking forward to `request post-processor` feature.


Advantages of using a Dynamic Client with JAX-WS

Question: What are the advantages of using a dynamic client with JAX-WS services as opposed to just using generated client classes? What are the disadvantages?
**For my particular case I am using Apache CXF, I'm not sure what other libraries allow "dynamic" clients.
-I thought I didn't need to add this, but... I'm looking for non-obvious(I know...subjective) advantages.  I don't need someone else to tell me that an advantage of not using generated classes is that I don't need to generate classes.
Answer: Well, the CXF documentation is pretty clear about the advantages of Dynamic Clients:

CXF supports several alternatives to allow an application to communicate with a service without the SEI and data classes. JAX-WS specified the JAX-WS Dispatch API, as well as the Provider interface for reading and writing XML. This page, however, describes the dynamic client facility of CXF. With dynamic clients, CXF generates SEI and bean classes at runtime, and allows you to invoke operations via APIs that take Objects, or by using reflection to call into full proxies.

In other words, you don't need the definitions of classes as shown in the documentation sample below:
<code>JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
Client client = dcf.createClient("echo.wsdl");

Object[] res = client.invoke("echo", "test echo");
System.out.println("Echo response: " + res[0]);
</code>
Regarding the disadvantages, they are pretty obvious (and this is the price to pay): you are manipulating strings, you lost strong typing.
Comment: @Pascal - I appreciate the answer... Maybe I should have better phrased the question as what conditions would cause you to use a dynamic client over generated...
Answer: The advantage is avoiding generating and including code. In some environments, that's a problem. If there's no barrier in your environment to including generated code, then the dynamic client is a bad idea, being slower and more cumbersome.
The dynamic client is slower because the code (of which I wrote some) must:

parse the wsdl and schema
generate code
compile the code

It is more cumbersome because you don't have bean classes for any complex objects in your data model. You need to use reflection.
Keep in mind that the dynamic client is different from the invocation interface.
Comment: The only real "slow" part of the dynamic client is the startup costs.  We basically need to parse the wsdl, call xjc to generate some code, compile it, load the compiled classes into memory, etc.. and THEN, after that is all done, do much of the same setup as the normal generated clients.

Once all generated and running, the dynamic clients aren't any slower.
Comment: @bmargulies - Any reference for dynamic clients being slower? Care to elaborate on what more "cumbersome" means?  I'm not saying its not correct, just looking for a reference.
Answer: The advantage to using a dynamic client is that you don't need to have generated the stubs before run time.  This allows you to generically invoke services that you may not know about at run time.
Comment: @Kevin - This is the reason why I was asked to move to a "dynamic" client.. in order to create compile time dependencies... but it also introduces coupling between the client and server side code... I guess I'm still weighing the positives and negatives.
Answer: The generated client classes are great if you know precisely what web-service your client code is going to call and that it isn't going to change over the lifetime of your client.
If either of these isn't the case then you will need to think about how your client will handle these situations. The Dispatch API gives you the flexibility to generate the web-service call on the fly without having an apriori knowledge of the service being accessed.
This obviously comes at the cost of your code needing to support the configuration options required to build that call.
With all this said, a certain amount of responsibility does lie with the developer/maintainer of the server side interface to not introduce changes that will break client code.
Answer: I had a similar conversation with a co-worker the other day. He was using the Spring client, that requires the use of an Interface to compile the client against, but then Spring injects the actual code to make the interface work. It basically boiled down to the oldest of saws between us, things like dynamic proxies usually introduce some sort of performance tax, he's ok with that, I started out life writing device drivers, and so am thoroughly prejudiced in favor of speed. Faster/smaller wins as far as I'm concerned, and since I'm not constrained to such limited environments...heck my Droid phone makes all the systems I worked on, including mainframes, in my first 10 years professionally look puny, I'll come down on the side of speed. The common rejoinder for this is that there are many other bottlenecks that are the "real" problem, and that this issue is insignificant against them....and it may be true...but every little bit helps. If you read the stuff from Steve Souders and his compatriots...users can notice a change of as little as 400 milliseconds...they don't necessarily register that things are slower, but their reaction is different. So since I can't do anything about network speed, database index overhead, etc, then I can at least do the best job I can with the things that I can influence.
Whew! Sorry 'bout that!! Stepping off the soapbox now! ;)
Answer: DII(Dynamic Invocation Interface) Client: With the DII, a client can call a remote procedure even if the signature of the remote procedure or the name of the service are unknown until runtime.
Because of its flexibility, a DII client can be used in a service broker that dynamically discovers services, configures the remote calls, and executes the calls.

Advantages

Here we have to create simple java interface describing the operations supported by the web service to access. So no need auto generated stubs to access the service.
Using endpoint it generates WSDL and Stubs on the fly i.e. at run-time.

Disadvantages

Even in this style we have to know the web service before the creating client.
Comparing to Generated Stub(GS) it works slowly because of WSDL and stubs generates at run-time.


What happens when setting object property without setter in javascript

Question: var vehicle = function(){
var type;
var tyre;

this.tellTyres = function(){
  console.log(type + " has " + tyre + " tyres");
};

this.__defineGetter__("type", function(){
  return type;
});
this.__defineSetter__("type", function(val){
  type = val;
});
this.__defineGetter__("tyre", function(){
  return tyre;
});
//   this.__defineSetter__("tyre", function(val){
//     tyre = val;
//   });

};

var car = new vehicle();
car.type = "Car";
car.tyre = 4;

console.log(car.tyre);

car.tellTyres();

I was learning about the getter and setter. Then I realized Javascript is not throwing any error while setting the value of car.tyre without having its setter method.
What happens to the car.tyre property outside the constructor. Where does the value 4 store? Does it override?
Comment: If you are learning then please note that this feature `__defineGetter__` is deprecated, Instead use `Object.defineProperty()`
Comment: Oh and console.log prints out "undefined". Umm... why so?
Comment: The book says introduced in ECMAScript 3.1. Thanks for telling... will explore about `defineProperty()`. Do you have any clue what's up with the `defineSetter` method?
Answer: JavaScript objects are more like dictionaries than like Java objects. This means that you can set and get an object's properties just by using the property accessor operators . and []:
var obj = { foo: 'bar' };
obj.baz = 17;
console.log(obj.foo, obj.baz); // logs '"bar" 17'

And that is absolutely fine.
But sometimes, you want to do something whenever someone modifies a property of your object. In these cases, you define a getter or setter function for that property (use Object.defineProperty instead of defineGetter and defineSetter):

var obj = { foo: 'bar' };
Object.defineProperty(obj, 'baz', {
  get: function () {
    console.log('Someone wants to read the property "baz"!');
    return 34;
  },
  set: function (value) {
    console.log('You are not allowed to modify the property "baz"!');
  }
});

obj.baz = 17; // doesn't work
console.log(obj.foo, obj.baz); // logs '"bar" 34'

When you create a new vehicle(), you create a new object, on which you can set or read properties. You don't need the getters and setters.
Comment: Thanks. :) At the last line you have written // logs bar 17. It should be 34. Almost confused me until I ran the code. Anyway, thanks a lot.
Comment: How does this answer the question? The question asks "what happens without setter" and you provide code with setter. Kidding?


Use file creation date as archive name in batch archiving (7zip)

Question: So what I basically want to achieve is to make archive of each file in a specified directory and so the name of resulted archive consisted of compressed file creation date.
Say we have some directory in which file A is located. The creation date of the A file is 2008-18-10-20:12:54 (we can ask ls to show us exactly that). So the resulted archive should be named 2008-18-10-20:12:54.7z and be located in another directory.
The best I came with is the following:
for file in $HOME/tmp; do
    7z a -mhe=on -mx=0 -p123456 $HOME/tmp-done/`ls -l "$HOME"/tmp/ --time-style=+%Y-%m-%d_%H:%M:%S "$file" | awk '{ print $6 }'`.7z $file;
done

As I understand it, the command above should instruct bash to read all files in a ~/tmp/ directory and then for each file execute 7z with arguments. One of the argument should be archive name computed form the creation date of archived file. And the archive file should be created in ~/tmp-done directory.
It suppose to produce a batch of 7z files in ~/tmp-done/ directory, but instead it completely ignores ls part and creates a ~/home/done/.7z file with all files compressed inside it.
I do think I am missing the way to deal with this sub command in argument part of 7z, but can't figure it out.
Any guide would be appreciated.
Answer: try below bash script
set -ex

DIR_WITH_FILES="/tmp/myfiles"

DIR_WITH_ARCHIVES="/tmp/myarchives"

for file in $(ls -1 "${DIR_WITH_FILES}"); do
    filename=$(ls -l --time-style=+%Y-%m-%d_%H:%M:%S "${DIR_WITH_FILES}/${file}" | awk '{ print $6 }')
    7z a -mhe=on -mx=0 -p123456 -- "${DIR_WITH_ARCHIVES}/${filename}.7z"  "${DIR_WITH_FILES}/${file}"
done


Pass scroll gestures through container in Flutter

Question: I have a smaller element on a screen that I'm using a PageView to build, since I need that snap-to effect for each item in the list. But this means the edges will be flush, with no visual indication that the PageView element is scrollable. I tried putting the PageView in a stack with a container on top (like an overlay) that had a linear gradient to "shadow" the sides to make the element look rounded, but this blocks the scrolling gesture from reaching the PageView.
My question is this: is there a widget that I'm not finding that allows scroll gestures to pass through it, while visually appearing on top of other elements? I know I can draw smaller-than-the-PageView elements on top of it, but I'm just wondering if someone else has done something like this successfully.
EDIT: here is a simplified version of the working code. I can't swipe to the next page view.
    return Scaffold(
      body: Center(
        child: Container(
          padding: const EdgeInsets.all(35.0),
          child: Stack(
            children: [
              PageView(
                children: [
                  Container(color: Colors.blue[200]),
                  Container(color: Colors.red[200]),
                  Container(color: Colors.deepPurple[200])
                ]
              ),
              Container(
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.centerLeft,
                    end: Alignment.centerRight,
                    colors: [ Color.fromARGB(50, 0, 0, 0), Color.fromARGB(0, 0, 0, 0), Color.fromARGB(0, 0, 0, 0), Color.fromARGB(50, 0, 0, 0) ],
                    stops: [ 0.05, 0.25, 0.75, 0.95 ]
                  )
                )
              )
            ]
          )
        ),
      ),
    );

Comment: this shouldn't be happening as long as there is no input expecting widget over the pageview you should be good to go if there is then you should check its `hittestbehavior` property, please post the working code
Comment: @Yadu there aren't any other gesture detectors in the tree for this element.
Answer: It seems Containers block scroll input, so I decided to go another route with something like Pedro R.'s suggestion. I created a page indicator at the bottom of the PageView that indicates which page the user is currently on and how many pages total there are. Here is the CodePen I made to showcase the effect.
EDIT AND BEST ANSWER: So I found exactly what I was looking for a little while later. It's a class called IgnorePointer, and it works like the below code example. This will allow you to swipe on the PageView. Try removing the IgnorePointer and your swiping becomes blocked.
Stack(
  children: <Widget>[
    PageView(
      children: <Widget>[
        Container(color: Colors.deepPurple[300]),
        Container(color: Colors.blue[300]
      ]
    ),
    IgnorePointer(
      child: Container(
        color: Color.fromARGB(100, 100, 100, 100)
      )
    )
  ]
)

And the code to go with the code pen
import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      home: MyWidget(),
    ),
  );
}

class MyWidget extends StatelessWidget {
  MyWidget({Key key}): super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          padding: const EdgeInsets.all(35.0),
          child: PageIndicator()
        ),
      ),
    );
  }
}

class PageIndicator extends StatefulWidget {
  PageIndicator({Key key}): super(key: key);

  @override
  _PageIndicatorState createState() => _PageIndicatorState();
}

class _PageIndicatorState extends State<PageIndicator> {
  int _pageNum;
  PageController _controller;

  @override
  void initState() {
    super.initState();
    _pageNum = 0;
    _controller = PageController(initialPage: 0);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        PageView(
          controller: _controller,
          onPageChanged: (page) {
            setState(() {
              _pageNum = page;
            });
          },
          children: [
            Container(color: Colors.blue[200]),
            Container(color: Colors.red[200]),
            Container(color: Colors.deepPurple[200])
          ]
        ),
        Align(
          alignment: Alignment.bottomCenter,
          child: Container(
            width: 200,
            height: 80,
            child: Center(
              child: Text("${_pageNum + 1} / 3", style: TextStyle(fontSize: 25.0))
            )
          )
        )
      ]
    );
  }// end build
}

Answer: You could use a PageIndicatorWidget. Something like this:
var pageController = PageController();
          Stack(
            children: [
              PageView(
                controller: pageController,
                children: [
                  Container(color: Colors.blue[200]),
                  Container(color: Colors.red[200]),
                  Container(color: Colors.deepPurple[200])
                ]
              ),
          PageIndicator(
              layout: PageIndicatorLayout.WARM,
              size: 10.0,
              controller: pageController,
              space: 5.0,
              count: 3,
              color: Colors.green,
              activeColor: Colors.gray,
            ),

            ]
          )


Can't resolve sites with Windows 2008 R2 DNS

Question: I have recently added a Windows 2008 R2 AD controller and DNS to my home network. However, I have a problem resolving some of the sites.
If I don't use my home DNS, everything's fine.
Can anyone help please?
Comment: Google DNS servers works very well. I never had any problem with those.
Comment: Thanks guys, I googled up on how to setup "forward requests to another DNS". That fixed it. I am forwarding them to google public DNS. Is that a good dns? Edit, I am in sydney area.
Answer: Please provide more information about DNS configuration. Did You check does server listen on right network adapter?? Check forwarders and ROOT hints... Use nslookup utility from servers command line to check does server resolves external namespace... Like I said, You must provide more information.
Answer: Your home DNS should be set to forward requests to another DNS (usually your ISP or your router).  We could do a better job of assisting if you could give us more detail on what works and what doesnt as well as how you have it configured.


Using Fivestar to list items that are 'trending' (highly rated in the last week)

Question: I would like to create a list of items that are 'trending'. By 'trending' I mean nodes (in my case, Watches) that have been highly rated within the last several days. Right now I have a block that displays the 4 highest rated Watches, and would like to create a similar block that displays the 4 highest rated Watches, but only using votes that have been cast within the last 3 days.
For the trending block, I have the following filter criteria (the content type for a watch is Watch Detail):

Content: Published (Yes)
Content: Type (= Watch Detail)
(Vote results) Vote results: Timestamp (>= -3 days)

The watches are sorted by highest rated using the following sort critera:

(Vote results) Vote results: Value (desc)

It's a fairly standard view, and I used the Relationship Content: Vote results to access the voting results for sorting and filtering.
The problem with what I've done is that while it is filtering by watches that have received votes within the last 3 days, it is not calculating the average value of the rating on votes that have been cast in the last 3 days. It is using the rating of the watch since the watch node was created. Hence, the Trending block and the Top Rated block essentially are identical, since the rating isn't limited to the last 3 days.
If anyone has done something like this I would very much appreciate some tips for how to limit the calculation the the average vote value to only votes cast within the last 3 days.
See http://ratemytimepiece.com/ for the exact website I'm working on if that helps you visualize this a little better.
Answer: Fivestar uses voting API. Voting API stores the individual votes and the total aggregates. You'll either have to create your own aggregates or calculate it "on the fly".
If you have lots of ratings in a week you'll be better off calculating your own aggregates. I would take a look how voting API does the calculation and copy that to your own module. Then modify it to only aggregate votes in the last week.
If you don't have a lot of ratings you can do it in views. Create a view of your type "watch detail". Add relationship "content: votes", require relationship, value type "percent", vote tag (whatever vote tag you are using for those fivestar ratings).
Then add filter "votes: value" >= 80 (gives you all 4 + 5 star ratings), "votes: timestamp" > "-1 week". Check to make sure you'll see the correct ratings show up.
Now turn on aggregation, add "nid" and use "count distinct" to show the number of ratings for each node. Then sort by that value.
Turn on query caching to make sure the view renders quickly for future requests.


if blog_id > 50000 use 2nd server

Question: I am trying to understand possibilities if i need in future. I am preparing to open a network on WordPress MultiSite with HyperDB. I want to let users open subdomain sites with registration and i need a solution for using a 2nd server when need.
There is 1 main site and subdomains are not connecting each other. I need somehow forward requests to other server if blog_id > 50000 There is some "old" duscussions about it: http://codex.wordpress.org/How_to_Scale_WPMU

The idea is to receive all incoming requests on a single HTTP server.
  This server, using mod_proxy and mod_rewrite, will route requests to X
  backend servers, acting as a reverse proxy.

Well, I am barely managing a server and really newbie on this area. How can i do this?
Answer: The 'How to Scale WPMU' page you link to proposes a solution which seems like a nice solution but I question how well it will scale. What they do is fairly straight forward. They use the host name header to let the reverse proxy decide to which server to route the request. Basically they look at the first letter of the blog name and then route the request to 1 of 26 servers, one for each letter of the alphabet.
This potentially doesn't scale very well. First of all because some letters in the alphabet will be more popular than others. There will be far less blogs starting with the letter q or x than for example with the letter e or m. The second problem is that if one or a few blogs starting with the same letter are very popular that one server will get a much higher load than the 25 other servers. The other servers might be at a very low utilization while that one server can not cope with the traffic. Not very good use of the available resources.
Load balancing at such a scale is not a very easy task and requires a lot more intelligent logic at the reverse proxy. This also is true for the solution you are trying to build. If you need to forward requests based on the blog_id you need some custom logic at the reverse proxy that can look up the host name to find the blog_id and then decide to which server to forward it to. I don't know if this kind of logic would be possible at all using Apache. I'm more of an IIS specialist and to build such a solution with IIS it would be necessary to write a custom rewrite provider. Not that hard to do but also doesn't tackle the scaling problem.
To solve the scaling problem you need additional logic that can dynamically add servers to blogs or groups of blogs that at that time receive a lot of traffic. This requires synchronization between the reverse proxy and a provisioning/deployment system that can dynamically add/move servers to a pool of blogs. Blog platform Squarespace has made this one of their unique selling points.
Answer: You should scale this the simple way:

Start of on a single server with local MySQL service.
Later move your database service to a dedicated instance.

Cloud computing can be nice for this kind of thing – start off slow and have computing resources always available. You could also look into a provider who manages servers for you and try to build a relationship with them so they can help you along the way.
Either way there are plenty of things to do (and learn):

How to scale PHP (e.g. you probably use Apache first, then later something like nginx and php-fpm).
How to scale MySQL – the defaults usually don't utilize the available resources very well, etc.. Down the road you could set up master-master MySQL setups and read-only slaves to scale this further.
Implementing a cache – e.g. WP Supercache or something more aggressive like Varnish which could cache and serve requests for blogs without any PHP or database interaction required. This can work really well when updates are not as frequent. Of course measures have to be implemented to invalidate the cache when an update (new blog post, edited blog post) happened.

All of this will work for a while, but there is no ultimate fix. Or no "one fits all solution".
I'm not sure how much logic is required here and doing it automatically doesn't work really well.
The problem you will most likely have is, that some blogs get more busy then others. Something to think about is how you can easily move a blog from one server to another, e.g. to a new server (dedicated to it or one that is more idle).
Same applies for your database service, you can scale it out with replication only so far. One of the things you might need is to setup a dedicated instance for more busy clients, etc.. I'm not sure how WP MU works on the backend to answer how much of this can be automated or what exactly is required to get this done.
Bottom line: I wouldn't overdo it and I'd play it by the ear. I'm not sure if you can predict your success, but I wouldn't invest money in infrastructure unless it is really required.
Last but not least, you sound like a beginner from what I gather. So don't take me wrong, but I suggest you either take a lot of time and take some courses for system administration and become a PHP developer (and database administrator) along the way, or you figure out a way to hire people who can solve these problems for you.
HTH

if blog_id > 50000 use 2nd server


Counters on a Chessboard (BMO 2010/11)

Question:
Isaac has a large supply of counters, and places one in each of the $1 \times 1$ squares of an $8 \times 8$ chessboard. Each counter is either red, white, or blue. A particular pattern of colored counters is called an arrangement. Determine whether there are more arrangements which contain an even number of red counters, or more arrangements which contain an odd number of red counters. (Note that 0 is an even number.)

I solved this problem using a recurrence relation: laying out the chessboard squares in a straight line, counting the number of ways to do it for any number of squares, and coming up with closed-form formulae:
$$e_n = \frac{3^n + 1}{2} \\
o_n = \frac{3^n - 1}{2}$$
where $n$ is the number of squares, $e_n$ counts even reds, $o_n$ counts odd reds.
However, the two quantities differ only by 1. This seems significant to me, because I cannot intuitively see why: I tried to come up with a 'bijection' sort of approach to the problem, which perhaps would say "for all arrangements with an even number of red counters, there is a unique one with an odd number of red counters, but hey, we have precisely one we can't account for". I tried doing this by various means, like flipping colors, counting sub-boards, etc. but didn't get anything. Can you find a bijection/mapping which makes intuitive sense?
Answer: Consider a fixed placement of white counters on the chessboard; the remaining squares must be occupied by red or blue counters.
Claim: For a given placement of white counters, there are just as many arrangements with an even number of red counters as with an odd number of red counters.
Proof: Pick a square that is not occupied by a white counter. Flipping the counter on that square between red and blue gives the desired  bijection.
OOPS!! There is one exception! If ALL the squares are occupied by white counters, then there is only one possible arrangement, and it has an EVEN number of red counters!!
Comment: Ok, so I flipped a red counter to make it a blue counter giving me another arrangement. However, there are plenty of initial arrangements, on which I can flip a counter to get the same new arrangement! How can I be sure that it is a bijection?
Comment: Maybe you overlooked that the bijection is defined for a ***fixed*** placement of white counters, and a ***fixed square*** (depending on the placement of white counters) is flipped to make the bijection.
Comment: Right, you're flipping a fixed counter (in a defined position), unique for every arrangement of white counters. Thanks!
Comment: It's basically the **same** as the way you prove that, for $n\gt0$, exactly half of the bit strings of length $n$ have an even number of ones.
Comment: So for bit strings, you flip, say, the last bit; in this question, you can flip the topmost nonwhite counter in the leftmost row or something like that; and the general approach will work whenever you can have some order on the individual pieces you're counting?
Comment: It's really the same thing. The square array has nothing to do with it, you might as well arrange the counters in a straight line. For a fixed arrangement of white counters, the arrangement of red and blue counters **is** just a bitstring.

Counters on a Chessboard (BMO 2010/11)


Fair system to score players between friend games

Question: We play football/soccer between our group of friends, but often some of them can't play, so the teams vary every week. My teammate this week can be my opponent next week.
We're starting a sort of championship, trying to rank players individuadilly, and we want a system that makes it so that the actual best players are expected to end at the top. Something simple would be to just award 3 points to a player for a win, 1 point for a draw and 0 points to a loss. While this would work if teams were choosen randomly, we also would like to keep the games balanced, and random teams aren't good to fulfill that requirement.
To choose each week's team in a balanced manner, two opposite players take turns picking the best next player that is not yet picked. But this makes a system like the above a bit weird, in the sense that the best players aren't more likely to make more points than the worst. Probabilly this system now favors the most underrated player, which is interesting but not quite what we're looking for.
Is there any combination of scoring system/picking strategy that would allow us to keep games balanced, yet making it so that the score table will represent absolute individual skill in the end (disregarding luck, for simplicity)?
Answer: You could start with random teams (or any team composition you would consider fair) and start keeping track of points by simply awarding 3 points for a victory and 1 for a draw.
Then, from next match on, you create teams whose combined total score are equal. That way, you slowly create a ranking by which the better players have better scores.
Example
Match 1: ABCD* - EFGH
Match 2: ABEF* - CDGH
Match 3: ACEG* - BDFH

Asterix (*) indicates winning team
Standings:
A        - 9 points
B, C, E  - 6 points
D, F, G  - 3 points
H        - 0 points

Next match could be: ADFG - BCEH.
Refinements
Of course, this is very simple and requires every player to be present every time. However, some adjustments can be made to create a more flexible statistic.

Divide a player's score over the number of participations (or maximum points or so).
Use goaldifference (or percentage of goals) instead of the 3-1-0 point system. That way, a very big victory shifts the ranking more than a narrow one. This way, you will get the ranking to adapt faster to the "real world values".
Comment: You can still use goal average AND the point system, which is useful to tell which player is decisive in complicated games too and has the thing to make his team win. For example and as we say in France, better are seven 1-0 wins than one 7-0 win ;) (and better is one 0-7 loss than seven 1-0 losses !)
Answer: Well, it completely depends on what the purpose of your ranking system is. Building evenly competitive teams, or simply providing a list of the best players for personal satisfaction.
Case 1: Optimally Balancing Teams
It is worth noting that a good team isn't necessarily the team of the most skilled players but rather the most balanced team offensively and defensively. Your question reads like you play more of a small-sided game or park football, which is more suited to unstructured play with utility-style (no fixed position) players but even so a well structured team would comfortably beat a park team.
I have coached low-grade football for many years, and an important skill is dividing the playing squad into fair teams at training to maximise the benefit of drills and scratch matches. There is no way to do this mathematically; you have to observe your players and note their individual strengths and weaknesses, try them in different roles and mess with the formula until you get it right. Players aren't robots, they will perform differently on different days- the right squad on a Tuesday may be completely off on a Thursday.
For the purposes of your situation, my recommendation would be to assign two people (possibly including yourself, or whoever the group feel is the most knowledgeable, reliable and balanced) to have the responsibility of picking the teams. These people should then confer after matches about who was good and where, who was out of their depth and where, and use this to create a "fuzzy" ranking system (ideally, impart some structure and rate players defensively, offensively, or even in finer detail such as passing, tackling, dribbling etc). This can then be used to pick the next two teams, ensuring an even balance of playing style and ability. The two who pick the teams then are separated into a team each (for further impartiality, one is nominated to flip a coin - heads they are team one, tails team two).
Case 2: Individual Ranking For Personal Glory
OK, cautionary warning here, nobody likes being told they are the worst (or amongst the worst) at something. Especially when they are with friends. Letting team-mates down is bad enough, letting friends down is even worse. Having a public leader-board of player rankings may encourage middle and upper level players to push higher, but you do so at the risk that you will lose your players propping up the table. You've already said you have trouble with consistent attendance week-to-week, implicitly shaming players could very well make that worse.
If you are ranking players purely to find the best, as some sort of reward mechanism, many clubs run a voting system amongst players to determine this for end of year awards. Have your players submit 3-2-1 votes (3pts = best, 2pts = second best, 1pt = third best) for their team-mates for the match, average them over the number of players (this prevents a player from having a blinder that puts them way in front, but being mediocre afterwards and still winning it) then tally them up in a private leader-board. Publicly make available the top subset of this list if your players want it (say top 5) so Fred can say "I'm fourth, I'm going to try even harder and get ahead of Bob in third", whilst sparing the less skilled players from the public humiliation of being last. Having the players do it for their own team means that good players in a losing team are still acknowledged.
Important Side Note
It is for a similar reason to the above private leader-board that I would stop using the "captains pick" team selection method. You are telling the last people picked that they aren't wanted, which is awful for morale, enjoying the game, and will only lead to worse performance. Good examples of fair team selection include:

Line up players by height, or
Line up players by age/date of birth, or
Line up players alphabetically by first/last name, and then go along the line labelling them alternately "team 1" or "team 2"

Pick characteristics that are completely not skill related. If one method unbalances the sides, choose another the next week. At no point is anyone being given the impression that they are the last choice, or only being picked because the team needs another player.
If you get a good combination going, try to stick with it. It is always better to have a group that plays together every week with minimal changes to the team. If a team is missing a player, ask for a volunteer to go across from the other team rather than dictating. Should no-one volunteer, draw straws or equivalent. Keep it as random as possible.
Comment: When we ranked players, we formed a committee of former players, coaches, and refs, people everyone trusted to do it fairly.  They explained what would be important in the ranking, but the end result was secret.  Each player was put into one of four buckets: Awesome to Working-on-it.  Teams were created by randomly selecting players from the buckets.  Nobody had to be told you are the most rubbish player or even you are in the "Working-on-it" bucket.
Answer: Okay, if you are asking this question, then you probably haven't heard of Jogabo. It lets you track number of goals and many more for pickup matches, it also allows you to see pickup games around you. This tracks performance and statistics. The best app out there, my friends and I use it and it is world wide, anywhere you find yourself, you might find people around you.
Once you are tracking your goals and performance with Jogabo, you are halfway done with the job. You can use the statistics to separate your team to balance things out.
Answer: It seems that rankade, our ranking system for sports, games, and more, fits your needs.
It's free to use and it's designed to manage rankings (and stats, including matchup stats, and more) for small or large groups of players.
It can manage any kind of match: one-on-one, faction vs. faction (two teams, which may be asymmetrical), and more.
Here are some examples for soccer and foosball (and table tennis, and more) public group. We have many groups that use ranking to build teams (and/or brackets) for next match/tournament.
Answer: The best thing would be planning the teams in a way that everyone plays with every other player in the end, or you can draw lots for the teams, while keeping your scoring system, and this would bring equity (and not equality, which is an important distinction) to the rankings.
Answer: Record an individual score for each player as $(f,a)$ where $f$ is the number of goals scored by that player's team when that player was actively playing, and $a$ similarly the goals against their team.
This means a sub, or someone who left early or arrived late or left the field or switched teams partway through, doesn't get credit for a goal scored by their team if they couldn't possibly have contributed to the goalscoring situation, and similarly don't get marked against if they couldn't have done anything to prevent the goal.
You could add a third component $p$, which is how many goals a player personally scores, if there are individuals who often get the decisive strike or final touch.
Having established this system, future teams are picked such that the 2-norm of differences of sums is minimised. For example, a team has $(F,A)=(17,10)$ and their opponents have $(14,8)$. The differences are 3 and 2; the squares are 9 and 4; the sum is 13; the 2-norm is therefore $√13=3.6$. If there is no way to trade exactly one player from each team and lower that value, then this is the "fairest" way to pick two teams from that group of players. If you have a $p$-score as well, the difference between $P$-scores must be as small as possible (this balances the amazing strikers separately from picking teams).
This is a simple system to score for: either they were on the field or they weren't, and either their team scored or was scored against, each time a goal happens. It gives some measure of attacking and defending ability, especially after several games or when several players are added together. It can be modified for creating three fair teams from a group of players (this requires more math than needed here). It can even be applied after every single goal, especially if a computer spreadsheets is being used to record scores and calculate teams. If you don't like the 2-norm team calculation, the $(p,f,a)$ system gives you something to start with, anyway.
Comment: Further, if you also track attendance by $g$ (games played), you can adjust these scores by a factor of the maximum g divided by their own g. Say Joe plays 5 games with 6 goals and Owen plays 2 with 3, then Owen adjusts to $3×5/2=3×2.5=7.5$ for the next calculation.


Why won't my .gif files show up when I call them using PhotoImage?

Question: from tkinter import *
from random import *
from functools import partial

class Game:
    def __init__(self):
        self.root = Tk()

        self.frame = Frame(width = 574, height = 574)
        self.frame.grid(columnspan = 30, rowspan = 30)

        self.minex = []
        self.miney = []

        self.clickx = 0
        self.clicky = 0

        blank = PhotoImage(file = 'C:\\Users\\PC\\Desktop\\Python Programs\\Minesweeper\\blank.gif')

        for i in range(0,30):
            for j in range(0,30):
                button = Button(width = 15, height = 15, padx = 2, pady = 2, image = blank, command = partial(self.click, j, i))
                button.grid(row = i, column = j)

        self.mine_place()

        self.root.mainloop()

    def mine_place(self):
        for i in range(0,15):
            self.minex.append(randint(1,30))
            self.miney.append(randint(1,30))

    def click(self, j, i):
        miss = PhotoImage(file = 'C:\\Users\\PC\\Desktop\\Python Programs\\Minesweeper\\miss.gif')
        hit = PhotoImage(file = 'C:\\Users\\PC\\Desktop\\Python Programs\\Minesweeper\\hit.gif')
        for k in range(0, len(self.minex)):
            if j + 1 == self.minex[k] and i + 1 == self.miney[k]:
                button = Button(image = hit)
                button.grid(row = i, column = j)
            else:
                button = Button(image = miss)
                button.grid(row = i, column = j)

app = Game()

In self.click, when I wish to create a button with this image I am given a blank image. If I create a button in init, the image comes out just fine. What is wrong?..............................................................
Answer: It looks like you're images are getting garbage collected you need to save a reference to the images after using PhotoImage.
ie - you create the image blank so save a reference as self.blank= blank and use image = self.hit


Casting device orientation to LANDSCAPE, PORTRAIT, LANDSCAPE_REVERTED and PORTRAIT_REVERTED

Question: I have a task where I have to cast device (not activity) orientation to 4 values (LANDSCAPE, PORTRAIT, LANDSCAPE_REVERTED and PORTRAIT_REVERTED). I came up with a solution but it uses fixed values, and does not represent the android functionality of how and when it changes the activities orientations.
I was unable to find an api that could easily notify a listener of when the device has changed it's orientation to the specified 4 values.
It would be grate if someone could share the function of how the android computes the orientation and informs WindowManager to change the orientation of the activities.
[SOLVED]
To does who might end up in the same situation as me.
frameworks/base/core/java/android/view/WindowOrientationListener.java
this listener contains all the magic that informs the activity to change it's orientation.
Answer: In onConfigChanges()you 'll always be notified whenever ur screen orientation changes and you can always get orientation of ur screen like this :
Display getOrient = getWindowManager().getDefaultDisplay();
switch(orientation){
case Configuration.ORIENTATION_LANDSCAPE:
Log.e();
break;
case Configuration.ORIENTATION_PORTRAIT:
Log.e();
break;
}

Comment: This will read the top most activity orientation. Not the device activity. (And cast it only to two orientations).
Answer: Use the screenOrientation in your project manifest and set the orientation.
<activity
            android:name=".SplashScreen"
            android:screenOrientation="portrait"
</activity>

Comment: It's not for the device orientation.
Comment: Hi Hoan Nguyen . can you pls share you code base or pls advice me for this post http://stackoverflow.com/questions/25133241/need-help-on-rotating-image-view-with-animation-on-orientation-change-4-side-ro
Answer: If u want the activity to show and align in landscape mode then add a folder in drawable namely layout-landscape and if u want the app to run only in portrait mode then declare in the manifest as the following
android:screenOrientation="portrait"

or u want in the landscape mode:
 android:screenOrientation="landscape"

Comment: It's not for the device orientation.
Answer: I am pretty sure the OS calculate the rotation of the device and change orientation when the rotation angle change by 60 degrees. Thus if the device is in Portrait orientation with rotation angle equal to 0, then when the device is rotated say counterclockwise, the rotation angle will increase and when the rotation angle is about 60 degree, the OS will change to Landscape. Now suppose the device is in Landscape orientation when you rotate the device clockwise, the angle will decrease and at about 30 degree the OS will change to Portrait orientation.
Orientation change state
Left side is the current orientation.
Right side is the new orientation when the device is rotated.
Portrait ---> Landscape  rotation counterclockwise rotation angle > 60
Portrait ---> Landscape_Reverse  rotation clockwise rotation angle < -60
Landscape ---> Portrait rotation clockwise rotation angle < 30
Landscape ---> Portrait_Reverse rotation counterclockwise rotation angle > 150
Landscape_Reverse ---> Portrait rotation counterclockwise rotation angle > -30
Landscape_Reverse ---> Portrait_Reverse rotation clockwise rotation angle < -150
The rotation angle can not be calculated when the device is laying flat. This is why if you start an app when the device is laying flat and rotate the device no orientation change occurs.
You can see how the rotation angle is calculated at my answer at How to measure the tilt of the phone in XY plane using accelerometer in Android
Comment: Please tell, where did you found this information about 60 and 30 degrees. I have been browsing android source code and couldn't find it. Also, your solution seems promising.
Comment: I wrote an app to calculate the rotation angle and show the rotation angle in the UI. When I rotate the device, the OS changes the orientation as describe in the answer.
Comment: There seems to be a problem when tilting the device using two axes at the same time (it does not resemble the actual activity orientation change). Also, your orientation change state lacks the Portrait_Revers ---> Landscape && Portrait_Revers ---> Landscape_Reverse.
Comment: What do you means by 2 axes at the same time? I can send you my app for you to test.
Comment: Using roll and pitch. Left top corner of your device turn down from you. Anyway, your solution seems to work but it's not perfect. Sometimes the Portrait --> Landscape has different 'turn' angle. Sometimes is 80 sometimes is 40. Depending on the other axes.
Comment: I just play with my app again. When rotate from Landscape counterclockwise, the orientation does not change until the rotation angle is > -150 then the OS change from Landscape to Landscape_Reverse.
Comment: I do not understand your comment about using roll and pitch. If the device is near flat, there is no rotation angle. So whatever "your device turn down from you" may be too much down.
Comment: I see what you mean, probably change orientation depends also on the inclination angle.
Comment: Seem like if inclination is larger than 100, no orientation change. So you can check the inclination in combine with rotation.
Comment: Your solution is acceptable but it still needs a little more of improvement. I'll accept it as solution to my problem, but Ill have to spend more time understanding the 3d math. Thanks.
Answer: Use getRotation()
Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int rotation = display.getRotation();

from the docs

Returns the rotation of the screen from its "natural" orientation. The
  returned value may be Surface.ROTATION_0 (no rotation),
  Surface.ROTATION_90, Surface.ROTATION_180, or Surface.ROTATION_270.
  For example, if a device has a naturally tall screen, and the user has
  turned it on its side to go into a landscape orientation, the value
  returned here may be either Surface.ROTATION_90 or
  Surface.ROTATION_270 depending on the direction it was turned. The
  angle is the rotation of the drawn graphics on the screen, which is
  the opposite direction of the physical rotation of the device. For
  example, if the device is rotated 90 degrees counter-clockwise, to
  compensate rendering will be rotated by 90 degrees clockwise and thus
  the returned value here will be Surface.ROTATION_90.
Comment: Again, this is how to the the most top activity rotation not the device orientation.
Comment: No, its the orientation of the Display / Device. You see there is Surface.ROTATION_0, Surface.ROTATION_90, Surface.ROTATION_180 and Surface.ROTATION_270
Comment: Have you checked this on actual device? Please do not bother answering if you can't distinguish what's a surface orientation and what's a device orientation.


Position of holes on a floorball ball?

Question: I'm not a floorball player, I'm a mathematician. I got recently curious about the floorball ball: it's got 26 holes, which is an unusual number, and I wondered how they are placed on the ball.
It seems there is no regulation for this, certainly it's not in IFF Material Regulations (2016) document. There is some drawing in the appendix, but still, the placement seems to only have some general rules (like minimal distance between holes).
Is it really true that the balls do not have a predefined shape? And if so, what is the most common placement of the holes?
Comment: Not sure as to the "why" but on a sphere we have 1 hole at each end, then a row of 4 holes and then a 2 rows of 8 holes, followed by another row of 4 holes. Totalling 26. Seems logical to have 1,4,8,8,4,1 configuration but that does not mean why other slight variations are not considered
Answer: It is not true that ball have no predetermined shape. And the distribution of the holes of the ball is usually made following the design represented in SP document MATERIAL REGULATIONS, which divides the ball in two equal halves, later joined to position a hole between two holes above the joint,

For a more even distribution of holes, during design process the ball was divided into eight sections for symmetry. As each section should have the same number of holes, it leads to 3.25 holes that can be differently distributed. For the possibility of creating a seamless ball, the holes can be distributed along every direction as shown in figure.

From Development of the Floorball by Sara Mateos Fernández.
Comment: Reading the TOU under the "legal" link on any page is probably a useful thing, and asking about how copyrighted material on Stack Exchange work would be a good question on Law SE.
Comment: Thanks for this. However, you write "usually" at the very beginning. So you confirm that there is no hard rule on this?
Comment: @yo' Usually balls are made from the first figure but now other method shown in second fig is also used for more even distribution. Thanks sir for reading all and letting me know.
Comment: @Nij sir thanks for editing, still don't know how to reference copyrighted material. Sometime referencing too much while sometime not enough to prevent downvote.

Position of holes on a floorball ball?


Is there a way to block internet access using iptables for particular access points

Question: In our company we have several access points. For some of them in the production area it should be disallowed to use them for accessing the internet.
The router we have has (at least) two interfaces: one for the local traffic (intif) and one for internet access (extif).
Is there a way to handle this just with iptables rules?
I already tried to block forwarding for the AP MAC Address, but that obviously only prohibits the AP itself to access the internet.
Comment: If the production area has its own subnet it should be possible to implement with minimum effort. is this the case?
Comment: @BANJOSA unfortunately at the moment the whole company is in the same subnet and for the moment it wouldn't be easy to change that.
Comment: if there is no distinct factor between a user that is connected to production from a user that's not this will be difficult to achieve. From my point of view you need to implement something that can distinguish what is production and what is not. A different subnet would be the easiest. With the addiction that having prod and non prod networks mixed up is a big no for security reasons.
Answer: If you don't have  a dhcp server and you use the router and APs to serve dhcp, you can give different ranges of ips for the given APs you don't want to access the internet from, and then with iptables block traffic from those ips. So you don't have to create a new subnet and they will be able to communicate between them too.


Alter slide layout with Python pptx

Question: I am attempting to alter some text which is on a layout that I will be using for a handful of slides. I will be creating the same pptx document for a number of different parties, and I would like to alter the text on the layout, depending on who the pptx is for.
I know it is possible to get the slide layouts as below. Is it possible to edit the shapes on the layout?
import pptx

prs = pptx.Presentation(importPath)

layouts = prs.slide_layouts
layout1 = layouts[0]

## Edit layout1's shapes here...

Answer: A slide layout is a special variant of a slide, so it also has a .shapes property you can use to access the shapes on the layout. Many of these will be placeholders, but background shapes (such as text-boxes or pictures/logos) will be there too. Once accessed, those shapes are manipulated the same way as shapes on any other slide.
Answer: Here is a script that will modify the text of the title shape in one of the layout slides.  It also includes code that lists all of the placeholders and shapes on that layout.  This is useful in figuring out how to access the shape you want to modify.
from pptx import Presentation

prs = Presentation()                    # create a new blank presentation
idx_layout = 1
slide = prs.slide_layouts[idx_layout]   # reference a specific layout

print('Placeholder indices for template %d' % (idx_layout))
for shape in slide.placeholders:
        print('idx:{:>3d}   name: {}'.format(shape.placeholder_format.idx, shape.name))

print('\nList of shapes for template %d' % (idx_layout))
for shape in slide.shapes:
    print(shape.name)

slide.shapes[0].text = "New Title"      # set the text in the first shape
prs.save("test.pptx")

Alter slide layout with Python pptx


Proof of ring isomorphism

Question: Proof that $Z[X]/(X^2-22) ≈ Z[\sqrt{22}]$.
I have tried all sorts of things to resolve this but I don't know how to wrap my head around it.
Can you please explain how to solve these kind of equations? Thank you.
Comment: well, you have to prove there's an isomorphism.. Why don't you try to write down the first function you can think and prove that it's an isomorphism?
Answer: You need to define a ring homomorphism
$$
\phi:\Bbb Z[X]\longrightarrow\Bbb Z[\sqrt{22}]
$$
with the property that $\phi(1)=1$ and $\phi(X)=\sqrt{22}$.
Now (HINTS):

show that there is a (in fact unique) ring homomorphism as such;
show that $\phi$ is surjective;
show that $\ker\phi=(X^2-22)$
conclude.
Comment: The first hint doesn't make much sense. $\phi$ is constructed as a ring homomorphism, using the universal property of the polynomial ring; so you don't have to calculate anything. If you don't want to use the universal property for some reason, then "Define a ring homomorphism by $\phi(X)=\sqrt{22}$" is not a definition.
Comment: @MartinBrandenburg: yeah, right, I somehow rushed in my answer: I edited it slightly changing the wording. Should be fine now
Comment: For "show that there is a (in fact unique) ring homomorphism as such",
do I need to pick a random equation from $ϕ$ to check ?
Comment: @CioroianuDenis: well, $\Bbb Z[X]$ is generated *as a ring* by $1$ and $X$. So, for any other ring $R$, you can define a ring homomorphism $\phi:\Bbb Z[X]\rightarrow R$ just by declaring who $\phi(1)$ and $\phi(X)$ are. Indeed you then have $\phi\left(\sum_{k=0}^dz_kX^k\right)=\sum_{k=0}^dz_k\phi(1)\phi(X)^k$. Moreover, there's no problem setting $\phi(1)$ and $\phi(X)$ at will, since $1$ and $X$ are algebraically independent in $\Bbb Z[X]$ (i.e. satisfy no algebraic relation among them). The uniqueness of $\phi$ follows immediately from the construction but it is not needed for your problem.
Comment: @AdLibitum: $\mathbb{Z}[X]$ is generated by $X$. The unit is contained in any subring (by definition of ring; since we don't talk about rngs here). $1,X$ are algebraically dependent.
Comment: So we apply the isomorphism theorem which says(in our case) that $Z[X]/ker ϕ ≈ Z[\sqrt{22}]$ ? And then what?
Comment: @MartinBrandenburg: also the ring $(2\Bbb Z)[X]$ is generated just by $X$?
Comment: @CioroianuDenis: Then, that is exactly what you wanted in the first place, once you realize that $\ker\phi$ is as in my answer.
Comment: @AdLibitum: This is not a ring. It is a rng.
Comment: @MartinBrandenburg: rng doesn't ring a bell :) Or you mean to say a ring without 1? But that would be a r1ng without 1, methinks. :)
Answer: Hints:
The evaluation homomorphism: define
$$\phi:\Bbb Z[x]\to\Bbb Z[\sqrt{22}]\;,\;\;\phi(f(x)):=f\left(\sqrt{22}\right)$$
Show this indeed is a ring homomorphism, which is trivially surjective. Now, what about its kernel?
$$f\in\ker\phi\implies f(\sqrt{22})=0$$
Yet $\;x^2-22\;$ is the minimal polynomial of the complex number (or if you prefer: the algebraic) $\;\sqrt{22}\;$ over $\;\Bbb Z\;$ (or over $\;\Bbb Q\;$ , if you prefer), so...
Comment: I don't understand this $ϕ(f(x)):=f(\sqrt{22})$, who is $f(x)$ ?
Comment: @CioroianuDenis Where am I defining $\;\phi\;$ on? Integer polynomials!
Answer: Define $\Phi : \mathbb{Z}[X] \to \mathbb{Z} [\sqrt{22} ] .$  $\Phi (W) =W(\sqrt{22} )$ then from the first isomorphism theorem we have that $$\mathbb{Z}[X] /_{\mbox{Ker} \Phi } \approx  \mathbb{Z} [\sqrt{22} ]$$ but $$\mbox{Ker} \Phi =\mathbb{Z}[X]/_{(X^2 -22 )}$$

Proof of ring isomorphism


slow scrolling in twitter widget

Question: Im using the Twitter widget in a web app and it scrolls really bad-slow and I have tried to set webkit-overflow-scrolling on a surrounding div and on every tag that the widget loads in the iframe, but nothing helps. I dont know what Im missing, but setting webkit-overflow-scrolling:touch; on the right tag should make it scroll good.
Any input appreciated, thanks.
Answer: Use overflow:"auto" or overflow-y:"scroll" in the surrounding div for vertical scrolling after re-size twitter widget
Answer: please use these customize twitter widget or use customize twitter feed .
look into these answers .
1) Is there any way to customize embedded Twitter feed?
2 ) Dynamic timeline selection for embedded timelines - Hashtag Timeline
May be this help you

slow scrolling in twitter widget


Command to count the characters present in the variable

Question: I am trying to count the number of characters present in the variable. I used the below shell command. But I am getting error - command not found in line 4
#!/bin/bash

for i in one; do
n = $i | wc -c
echo $n
done

Can someone help me in this?
Answer: In bash you can just write ${#string}, which will return the length of the variable string, i.e. the number of characters in it.
Answer: Something like this:
#!/bin/bash

for i in one; do
n=$(echo $i | wc -c)
echo $n
done

Answer: Assignments in bash cannot have a space before the equals sign. In addition, you want to capture the output of the command you run and assign that to $n, rather than that statement which would probably just assign $i to $n.
Use the following instead:
#!/bin/bash

for i in one; do
n=`$i | wc -c`
echo $n
done

Answer: It can be as simple as that:
str="abcdef"; wc -c <<< "$str"
7

But mind you that end of line counts as a character:
str="abcdef";  cat -A <<< "$str"
abcdef$

If you need to remove it:
str="abcdef"; tr -d '\n' <<< "$str" |  wc -c
6


Continuous linear operator, $T: (C[0,1],\|\cdot\|_p)\to (C[0,1],\|\cdot\|_p)$ continuous for some $p$

Question:
Observe $C[0,1]$ and for $1\leq p<\infty$ the norm $\|f\|_p=\left(\int_0^1 |f(t)|^p\, dt\right)^{1/p}$. Let $T: C[0,1]\to C[0,1]$ be an arbitrary linear operator. Show, that when it exists a $1\leq p<\infty$ such that $T: (C[0,1],\|\cdot\|_p)\to (C[0,1],\|\cdot\|_p)$ is continuous, then is $T: (C[0,1],\|\cdot\|_\infty)\to (C[0,1],\|\cdot\|_\infty)$ continuous.

I do not really know how to start here.
Thanks in advance for any help.
Comment: Do you mind giving a full answer, or a guide, on how to do this? I do not know how I can show that $(C[0,1], C[0,1])$ is closed. A full answer will be rewarded with 200 reputations as a bounty.
Comment: The closed graph theorem should do the trick.
Comment: So I have to show, that $G(T)$ is closed in $(C[0,1], C[0,1])$ both with the $\|\cdot\|_\infty$ norm?
Comment: Yes, this is what you have to show.
Answer: For convenience, we set $C_\infty := (C([0,1]), \|\cdot\|_\infty)$ and $C_p := (C([0,1]), \|\cdot\|_p)$. Since $C_\infty$ is a Banach space, we can apply the closed graph theorem to show the boundedness of $T : C_\infty \to C_\infty$.
Therefore, given a sequence $\{f_n\} \subset C([0,1])$ with $f_n \to f$ in $C_\infty$ and $T f_n \to g$ in $C_\infty$, we have to show that $g = Tf$. Since the measure of $[0,1]$ is finite, $f_n \to f$ in $C_\infty$ implies $f_n \to f$ in $C_p$. The continuity of $T$ in $C_p$ gives $T f_n \to T f$ in $C_p$. Similarly, $T f_n \to g$ in $C_\infty$ implies $T f_n \to g$ in $C_p$. Since the limit in $C_p$ is unique, this gives $T f = g$.
Hence, the graph of $T$ is closed in $C_\infty \times C_\infty$ and $T$ is continuous by the closed graph theorem.


rails css: website not responsive on mobile devices

Question: My website looks great on desktop but I'm having trouble making it responsive on mobile devices (it's just a zoomed out version of the desktop website, except for the jumbotron that is actually completely zoomed in and blurry...).
The website is just one homepage with a jumbotron that takes up the entire screen size and then multiple sections one after the other that 'wrap' over the jumbotron when scrolling down. This effect looks great on desktop so I'd like to keep it, but I believe this may be why it's completely unresponsive on smaller devices.
My jumbotron:

TITLE

 06 00 00 00 00

My homepage (the content class allows me to do the section wrap over jumbotron effect):
<%= render 'jumbotron' %>

  <%= render 'therapy' %>
  <%= render 'consult' %>
  <%= render 'modalities' %>
  <%= render 'method' %>
  <%= render 'background' %>
  <%= render 'contact' %>
  <%= render 'map' %>
  <%= render 'layouts/footer'%>

My main.css (I believe this might be where the problem is, with all of the z-index, and fixed jumbotron?):
/* HOMEPAGE */

.content {
  position: relative;
  z-index: 2;
  margin-top: 100vh;
  width: 100%;
}

.custom-section {
  padding-top: 7rem;
  padding-bottom: 7rem;
}

/* JUMBOTRON */

.jumbo {
  background-image: url("L1000286.jpg");
  background-size: cover;
  background-attachment: fixed;
  text-align: center;
  padding: 40px 10px;
  color: blue;
  position: fixed;
  z-index: 1;
  width: 100%;
  height: 100vh;
  top: 0;
}

.jumbo-text {
  position: absolute;
  left: 50%!important;
  z-index: 10;
  color: rgb(236, 234, 234);
  text-align: center;
  top: 50%!important;
  transform: translate(-50%, -50%);
  width: fit-content;
  padding: 50px
}

Example of a section (they're essentially always the same layout):

Title

Some random text

My main.js:
function dynamicNavbar() {

  $(document).ready(function() {
    $(window).scroll(function() {
        var scroll = $(window).scrollTop();
        var height = $(window).height() - $(".navbar").height();

        if (scroll >= height) {
            $(".navbar").addClass("bg-pink");
        } else {
          $(".navbar").removeClass("bg-pink");
        }
    });
  });
};

function softScroll() {

  $(document).ready(function(){
    $( "a.scrollLink" ).click(function( event ) {
        event.preventDefault();
        $("html, body").animate({ scrollTop: $($(this).attr("href")).offset().top }, 500);
    });
  });

}

softScroll();
dynamicNavbar();

My application.html.erb:
<!DOCTYPE html>

    <title>Title</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.1/css/all.css" integrity="sha384-vp86vTRFVJgpjF9jiIGPEEqYqlDwgyBgEF109VFjmqGmIY/Y4HV4d3Gp2irVfcrp" crossorigin="anonymous">

    <%= render "layouts/navbar" %>
    <%= render 'layouts/flash' %>
    <%= yield %>

Any idea what I could do to make my website friendly?
Comment: What do you expect to happen?  I didn't see any mobile breakpoint style updates in your stylesheet, it looks like you are using bootstrap, but you are not setting any breakpoints in the HTML entities either, what is suppose to change? Can you elaborate a little bit on what you expect it to look like exactly?
Comment: Right now the mobile version works fine, but it is just a zoomed out version of the desktop website, so the text/buttons/navbar and everything else is very small which isn't practical. I'm still very new at this obviously, but in previous websites I made, I've never had to use any CSS breakpoints to make it responsive. Using bootstrap was enough. The only thing I did different this time is the wrap over jumbotron effect, which makes me think it prevents my sections from being responsive. I just can't figure out why and how to fix it without messing up the wrap over jumbotron effect.
Answer: I believe you are missing a viewport tag in your layout. This is from Bootstrap if that's what you're using.
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    ...

Comment: Amazing! Thank you so much


Vector - push_back uses default constructor not copy constructor

Question: I'm facing the problem of adding new elements to my vector.
Let's start with the herarchy
Index conatins Companies. Companies contain Stocks
Index
{
...
vector <Company> composition;
...
}

Company
{
...
vector <Stock> stocks;
...
}

Stock
{
....
}

The problem is when I start adding a company with stocks (till this moment everything is ok) to an index
Comapny c1(bla bla, some arguments);
mindex->composition.push_back(c1);

Where "mindex" is defined as
 Index* mindex=new Index();

I got some memory errors and I decided to put some cout<<"here\n"; in some parts of the program to see what was going on.
While
mindex->composition.push_back(c1);

is being executed, (at first I sized it mindex->composition.resize(0); ) it's size is being enlarged so that everything in it is moved to the temporary vector and in composition everything is deleted. But then vector uses not copy constructor, but default constructor to create the Stocks.
Stock::Stock()
{
  cout<<"The default constructor\n";
}

I got this on the screen about 6 times.
The question is: Why vector doesn't use copy contructor when it is being enlarged?
(I have my copy constructor declared and defined)
COMPLETE CODE WHERE THE THING HAPPENS:
Sorry for my language - it's Polish :)
Akcja=Stock
Spolka=Company
Indeks=Index

void Portfel<T,T2,T3>::dodaj_spolke()
{
  std::string nazwa;
  double cena_emisji;
  double aktualna_cena;
  usi ilosc_akcji;
  std::string indeks;
  cout<<"Podaj nazwe spolki: \n";                      //UNIMPORTANT
  cin>>nazwa;
  cout<<"Podaj cene emisji akcji przy IPO. \n";
  cin>>cena_emisji;
  cout<<"Ile akcji jest w obiegu ?\n";
  cin>>ilosc_akcji;
  cout<<"Jaka jest aktualna cena? \n";
  cin>>aktualna_cena;
  if (mindex->GetNast()==NULL)
  {
      cout<<"Spolka zostanie przypisana domyslnie do WIG. \n";
      indeks="WIG";
  }
  else
  {
    cout<<"Do jakiego indeksu nalezy spolka? \n";
    cin>>indeks;
  }                                                         //TILL THIS MOMENT
Spolka s1(nazwa,cena_emisji,aktualna_cena,ilosc_akcji,indeks);
cout<<"-------------------------------------------\n";
for (int i=0;i<(int)s1.akcje.size();i++)
{
 cout<<"Spolka: "<<s1.akcje[i].spolka<<endl;
  cout<<"Cena aktualna: "<<s1.akcje[i].cena_aktualna<<endl;
  cout<<"Twoja cena zakupu: "<<s1.akcje[i].cena_zakupu<<endl;
}
cout<<"-------------------------------------------\n";
cout<<"tutaj po dodaniu spolki \n";
cout<<"Przed zmiana \n";
Spolka s2=s1;
mindex->sklad.push_back(Spolka s1); // tutaj błąd
cout<<"Zmiana rozmiaru wektora - tutaj pomiedzy \n";
mindex->ilosc_spolek++;
for (int i=0;i<ilosc_akcji;i++)
{
mindex->sklad[mindex->ilosc_spolek-1].akcje[i].spolka=nazwa;
mindex->sklad[mindex->ilosc_spolek-1].akcje[i].cena_aktualna=aktualna_cena;
Akcja::Akcja()
{
  //std::cout<<sizeof(this)<<std::endl;
  cout<<"Domyslny konstruktor \n";
}
Akcja::Akcja(std::string nazwa,double akt)
{
  spolka=nazwa;
  cena_zakupu=0;
  cena_aktualna=akt;
  zysk=cena_zakupu-cena_aktualna;
}
Akcja::Akcja(const Akcja& a1)
{
  this->spolka=a1.spolka;
  this->cena_zakupu=a1.cena_zakupu;
  this->cena_aktualna=a1.cena_aktualna;
  this->zysk=a1.zysk;
}    mindex->sklad[mindex->ilosc_spolek-1].akcje[i].cena_zakupu=0;
mindex->sklad[mindex->ilosc_spolek-1].akcje[i].zysk=0;

}
cout<<"tutaj koniec\n";
cout<<"Ilosc spolek w mindex: "<<mindex->sklad.size()<<"\n";
cout<<mindex->ilosc_spolek<<endl;
cout<<"-------------------------------------------\n";
for (int i=0;i<mindex->ilosc_spolek;i++)
{
    cout<<mindex->sklad[i].GetNazwa()<<endl;
    cout<<mindex->sklad[i].akcje[0].GetSpolka()<<endl;
    cout<<mindex->sklad[i].akcje[0].cena_zakupu<<endl;
    cout<<mindex->sklad[i].akcje[0].cena_aktualna<<endl;
}
cout<<"-------------------------------------------\n";
getchar();
}

spolka.cpp (the concerning part only - there's no need to paste the rest of the code, but I obviously may if you wish)
Spolka::Spolka(string naz,double cena_e,double cena_a,usi ilosc,string ind)
{
  nazwa=naz;
  cena_emisji=cena_e;
  aktualna_cena=cena_a;
  ilosc_akcji=ilosc;
  akcje.resize(0);
   for(int i=0;i<ilosc;i++)
   {
    akcje.push_back(Akcja (naz,cena_e));
   }
  indeks=ind;
  std::cout<<"Dodano spolke: "<<this->nazwa<<endl;
}

akcja.cpp
Akcja::Akcja()
{
  //std::cout<<sizeof(this)<<std::endl;
  cout<<"Domyslny konstruktor \n";
}
Akcja::Akcja(std::string nazwa,double akt)
{
  spolka=nazwa;
  cena_zakupu=0;
  cena_aktualna=akt;
  zysk=cena_zakupu-cena_aktualna;
}
Akcja::Akcja(const Akcja& a1)
{
  this->spolka=a1.spolka;
  this->cena_zakupu=a1.cena_zakupu;
  this->cena_aktualna=a1.cena_aktualna;
  this->zysk=a1.zysk;
}

and the effects:
after adding first company
    tutaj po dodaniu spolki
    Przed zmiana
    Domyslny konstruktor
    Domyslny konstruktor
    Domyslny konstruktor
    Domyslny konstruktor
    Domyslny konstruktor
    Domyslny konstruktor
    Zmiana rozmiaru wektora - tutaj pomiedzy
    tutaj koniec
    Ilosc spolek w mindex: 1
    1
    -------------------------------------------
    KGHM
    KGHM
    0
    160
    -------------------------------------------
    Usunieto: KGHM
    Usunieto: KGHM

and after adding second company

tutaj po dodaniu spolki
Przed zmiana
Domyslny konstruktor
Domyslny konstruktor
Domyslny konstruktor
Domyslny konstruktor
Domyslny konstruktor
Domyslny konstruktor
Domyslny konstruktor
Domyslny konstruktor
Domyslny konstruktor
Usunieto: KGHM
Zmiana rozmiaru wektora - tutaj pomiedzy
tutaj koniec
Ilosc spolek w mindex: 2
2
-------------------------------------------
KGHM

==2375== Conditional jump or move depends on uninitialised value(s)
==2375==    at 0x539A683: __printf_fp (printf_fp.c:406)
==2375==    by 0x53975B7: vfprintf (vfprintf.c:1629)
==2375==    by 0x53BF441: vsnprintf (vsnprintf.c:120)
==2375==    by 0x4EB62DF: ??? (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.18)
==2375==    by 0x4EBC715: std::ostreambuf_iterator<char, std::char_traits<char> >

I know it's much but I would be really grateful for help.
Comment: I think you can find the answer to your question here http://stackoverflow.com/questions/6310638/c-vectorpush-back-using-default-copy-constructor
Answer: mindmindex->composition.resize(0);

Was that really supposed to be 0? Assuming you resized the vector, resize is what calls the default constructor, so that is the reason why you see The default constructor 6 times. What you probably wanted is reserve and not resize which does not call the default constructor.
Comment: @user1960582: You said `there's no need to paste the rest of the code`, but obviously that was incorrect. Would you like to delete this question?
Comment: At the begining, yes.
Because when program is launched mindex->composition consists of 0 company.
But you know.. I resized the vector at the begining.
Now the problem is with Stocks, not Index
Comment: I can't tell from the code, but whenever you resize a vector, the default constructor is called to initialize the elements. To avoid that, do not resize the vector and call `reserve` instead before pushing back elements onto the vector.
Comment: I FOUND IT
IT WAS IN THE COPY CONSTRUCTOR OF THE SPOLKA.
I made there a line which made default construcotrs :)


Ler e escrever multipas variaves com só um ponteiro

Question: obtive sucesso em fazer tarefa parecida com o determinado código:
int *ptr[5], i;

for(i = 0; i < 5; i++){
    ptr[i] = (int *)malloc(1 * sizeof(int));
}

for(i = 0; i < 5; i++){
    scanf("%d", ptr[i]);
}

for(i = 0; i < 5; i++){
    printf("%d\n", ptr[i]);
}

No entanto, gostaria de fazer o mesmo com algo similar a isto:
int *ptr = (int *)malloc(5 * sizeof(int));

Também seria bem vindo a informação do mesmo porem para uma string de caracteres.
Desde já obrigado.
Answer: Um vetor alocado dinamicamente se comportará da mesma maneira que um vetor comum.
A referência de um vetor é o seu primeiro elemento, no caso ptr[0], e ptr aponta para o primeiro elemento do vetor, e os elementos restantes estarão a uma dada distância do primeiro elemento, por exemplo nesse código o último elemento está a uma distância de "4 ints" do primeiro elemento (ptr[4]), por isso a utilização da função sizeof(), pois usaremos um "bloco" na memória do tamanho que precisamos nesse caso "5 ints" ou 20 bytes(uma variável do tipo int ocupa 4 bytes).O mesmo caso se aplica aos outros tipos com exceção de uma string, por que uma string é um vetor do tipo char só que nesse caso uma string sempre deve ter como ultimo elemento o caractere\0, logo numa alocação dinâmica de n caracteres terá que ser sizeof(n+1).
#include <stdio.h>
#include <stdlib.h>

int main(void) {
   int *ptr = (int*)malloc(5 * sizeof(int));

   for(int i = 0; i < 5; i++){
      scanf("%d", &ptr[i]);
   }

   for(int i = 0; i < 5; i++){
      printf("%d\n", ptr[i]);
   }
   free(ptr);

   return 0;
}