text:
Q: How do I solve this app startup error in heroku? Hey Guys please help me with this problem!
Thanks :D
OLD LOGS:
2018-10-02T06:47:43.191640+00:00 app[api]: Release v1 created by user kailauber@icloud.com
2018-10-02T06:47:43.308759+00:00 app[api]: Enable Logplex by user kailauber@icloud.com
2018-10-02T06:47:43.191640+00:00 app[api]: Initial release by user kailauber@icloud.com
2018-10-02T06:47:43.308759+00:00 app[api]: Release v2 created by user kailauber@icloud.com
2018-10-02T06:58:36.000000+00:00 app[api]: Build started by user kailauber@icloud.com
2018-10-02T06:58:37.000000+00:00 app[api]: Build failed -- check your build logs
2018-10-02T07:03:40.000000+00:00 app[api]: Build started by user kailauber@icloud.com
2018-10-02T07:03:42.000000+00:00 app[api]: Build failed -- check your build logs
2018-10-02T07:09:04.000000+00:00 app[api]: Build started by user kailauber@icloud.com
2018-10-02T07:09:54.741609+00:00 app[api]: Release v3 created by user kailauber@icloud.com
2018-10-02T07:09:54.741609+00:00 app[api]: Deploy 0c3d9616 by user kailauber@icloud.com
2018-10-02T07:09:59.000000+00:00 app[api]: Build succeeded
2018-10-02T07:16:48.138432+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=trapnationbot.herokuapp.com request_                                                                                id=6aced25b-f8c4-460e-8c1b-8f8794d40d2f fwd="89.217.251.114" dyno= connect= service= status=503 bytes= protocol=https
2018-10-02T07:16:48.457466+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=trapnationbot.herokuapp.com request_id=dd99c34d-0bbc-46b8-b9c9-ee2418cf8cc4 fwd="89.217.251.114" dyno= connect= service= status=503 bytes= protocol=https
2018-10-02T07:16:48.493293+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=trapnationbot.herokuapp.com request_id=47ec0871-d865-4ea4-93b1-d96e5782ccc2 fwd="89.217.251.114" dyno= connect= service= status=503 bytes= protocol=https
2018-10-02T07:18:52.707524+00:00 app[api]: Release v4 created by user kailauber@                                                                                icloud.com
2018-10-02T07:18:52.707524+00:00 app[api]: Set token config vars by user kailauber@icloud.com
2018-10-02T07:19:58.616740+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=trapnationbot.herokuapp.com request_id=f9116de7-d7f2-4354-b188-09624ed4c482 fwd="89.217.251.114" dyno= connect= service= status=503 bytes= protocol=https
2018-10-02T07:20:35.194420+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=trapnationbot.herokuapp.com request_id=1ae1bc26-39a2-482a-87cc-12149d45a89d fwd="89.217.251.114" dyno= connect= service= status=503 bytes= protocol=http
2018-10-02T07:20:35.382931+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=trapnationbot.herokuapp.com request_id=01d7c808-b8ca-4c82-a4b4-b0697541264f fwd="89.217.251.114" dyno= conect= service= status=503 bytes= protocol=http
2018-10-02T07:20:35.390361+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=trapnationbot.herokuapp.com request_id=3e2ed998-d89f-4961-b629-0dadcb00c89d fwd="89.217.251.114" dyno= connect= service= status=503 bytes= protocol=http

NEW LOGS AFTER DYNO:
2018-10-02T06:47:43.191640+00:00 app[api]: Release v1 created by user kailauber@icloud.com
2018-10-02T06:47:43.308759+00:00 app[api]: Enable Logplex by user kailauber@icloud.com
2018-10-02T06:47:43.191640+00:00 app[api]: Initial release by user kailauber@icloud.com
2018-10-02T06:47:43.308759+00:00 app[api]: Release v2 created by user kailauber@icloud.com
2018-10-02T06:58:36.000000+00:00 app[api]: Build started by user kailauber@icloud.com
2018-10-02T06:58:37.000000+00:00 app[api]: Build failed -- check your build logs
2018-10-02T07:03:40.000000+00:00 app[api]: Build started by user kailauber@icloud.com
2018-10-02T07:03:42.000000+00:00 app[api]: Build failed -- check your build logs
2018-10-02T07:09:04.000000+00:00 app[api]: Build started by user kailauber@icloud.com
2018-10-02T07:09:54.741609+00:00 app[api]: Release v3 created by user kailauber@icloud.com
2018-10-02T07:09:54.741609+00:00 app[api]: Deploy 0c3d9616 by user kailauber@iclud.com
2018-10-02T07:09:59.000000+00:00 app[api]: Build succeeded
2018-10-02T07:16:48.138432+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=trapnationbot.herokuapp.com request_id=6aced25b-f8c4-460e-8c1b-8f8794d40d2f fwd="89.217.251.114" dyno= connect= service= status=503 bytes= protocol=https
2018-10-02T07:16:48.457466+00:00 heroku[router]: at=error code=H14 desc="No web rocesses running" method=GET path="/favicon.ico" host=trapnationbot.herokuapp.com request_id=dd99c34d-0bbc-46b8-b9c9-ee2418cf8cc4 fwd="89.217.251.114" dyno= connect= service= status=503 bytes= protocol=https
2018-10-02T07:16:48.493293+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=trapnationbot.herokuapp.com request_id=47ec0871-d865-4ea4-93b1-d96e5782ccc2 fwd="89.217.251.114" dyno= connect= service= status=503 bytes= protocol=https
2018-10-02T07:18:52.707524+00:00 app[api]: Release v4 created by user kailauber@icloud.com
2018-10-02T07:18:52.707524+00:00 app[api]: Set token config vars by user kailauber@icloud.com
2018-10-02T07:19:58.616740+00:00 heroku[router]: at=error code=H14 desc="No web rocesses running" method=GET path="/" host=trapnationbot.herokuapp.com request_id=f9116de7-d7f2-4354-b188-09624ed4c482 fwd="89.217.251.114" dyno= connect= servce= status=503 bytes= protocol=https
2018-10-02T07:20:35.194420+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=trapnationbot.herokuapp.com request_id=1ae1bc26-39a2-482a-87cc-12149d45a89d fwd="89.217.251.114" dyno= connect= service= status=503 bytes= protocol=http
2018-10-02T07:20:35.382931+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=trapnationbot.herokuapp.com request_id=01d7c808-b8ca-4c82-a4b4-b0697541264f fwd="89.217.251.114" dyno= connect= service= status=503 bytes= protocol=http
2018-10-02T07:20:35.390361+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=trapnationbot.herokuapp.com request_id=3e2ed998-d89f-4961-b629-0dadcb00c89d fwd="89.217.251.114" dyno= connect= service= status=503 bytes= protocol=http
2018-10-02T08:01:08.132111+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=trapnationbot.herokuapp.com request_id=0cf0fb63-b02b-43d8-90a2-3a6526d8c96d fwd="89.217.251.114" dyno= connect= service= status=503 bytes= protocol=https
2018-10-02T09:50:43.236146+00:00 app[api]: Release v5 created by user kailauber@icloud.com
2018-10-02T09:50:43.236146+00:00 app[api]: Remove token config vars by user kailuber@icloud.com
2018-10-02T09:50:57.411848+00:00 app[api]: Set token config vars by user kailauber@icloud.com
2018-10-02T09:50:57.411848+00:00 app[api]: Release v6 created by user kailauber@icloud.com
2018-10-02T09:51:14.652913+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=trapnationbot.herokuapp.com request_id=048ef97b-f342-47b6-9266-d77926934cc2 fwd="176.127.140.95" dyno= connect= service= status=503 bytes= protocol=https
2018-10-02T09:51:14.671402+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=trapnationbot.herokuapp.com request_id=23759f86-fd20-442c-b8db-dfa3163140ab fwd="176.127.140.95" dyno= connect= service= status=503 bytes= protocol=https
2018-10-02T09:51:14.470107+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=trapnationbot.herokuapp.com request_id=02385247-7c6f-4e6f-a6b8-b1c89e4e8a02 fwd="176.127.140.95" dyno= connect= service= status=503 bytes= protocol=https
2018-10-02T09:58:22.000000+00:00 app[api]: Build started by user kailauber@icloud.com
2018-10-02T09:59:17.578544+00:00 app[api]: Deploy 7161d06f by user kailauber@icloud.com
2018-10-02T09:59:17.578544+00:00 app[api]: Release v7 created by user kailauber@icloud.com
2018-10-02T09:59:21.000000+00:00 app[api]: Build succeeded
2018-10-02T10:00:07.539714+00:00 app[api]: Scaled to worker@1:Free by user kailauber@icloud.com
2018-10-02T10:00:11.688081+00:00 heroku[worker.1]: Starting process with command `node bot.js`
2018-10-02T10:00:12.363320+00:00 heroku[worker.1]: State changed from starting to up
2018-10-02T10:00:13.702632+00:00 heroku[worker.1]: State changed from up to crashed
2018-10-02T10:00:13.704665+00:00 heroku[worker.1]: State changed from crashed totarting
2018-10-02T10:00:13.690858+00:00 heroku[worker.1]: Process exited with status 127
2018-10-02T10:00:13.631854+00:00 app[worker.1]: bash: node: command not found
2018-10-02T10:00:14.828142+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=trapnationbot.herokuapp.com request_id=7403214c-8e37-488c-b674-0b6255f8af52 fwd="176.127.140.95" dyno= connect= service= status=503 bytes= protocol=https
2018-10-02T10:00:18.760188+00:00 heroku[worker.1]: Starting process with command `node bot.js`
2018-10-02T10:00:19.575651+00:00 heroku[worker.1]: State changed from starting to up
2018-10-02T10:00:21.292435+00:00 heroku[worker.1]: Process exited with status 127
2018-10-02T10:00:21.307843+00:00 heroku[worker.1]: State changed from up to crashed
2018-10-02T10:00:21.213892+00:00 app[worker.1]: bash: node: command not found


text:
Q: Elegant implementation of n-dimensional matrix multiplication using lists? List functions allow us to implement arbitrarily-dimensional vector math quite elegantly. For example:
on   = (.) . (.)
add  = zipWith (+)
sub  = zipWith (-)
mul  = zipWith (*)
dist = len `on` sub
dot  = sum `on` mul
len  = sqrt . join dot

And so on.
main = print $ add [1,2,3] [1,1,1] -- [2,3,4]
main = print $ len [1,1,1]         -- 1.7320508075688772
main = print $ dot [2,0,0] [2,0,0] -- 4

Of course, this is not the most efficient solution, but is insightful to look at, as one can say map, zipWith and such generalize those vector operations. There is one function I couldn't implement elegantly, though - that is cross products. Since a possible n-dimensional generalization of cross products is the nd matrix determinant, how can I implement matrix multiplication elegantly?
Edit: yes, I asked a completely unrelated question to the problem I set up. Fml.

A: It just so happens I have some code lying around for doing n-dimensional matrix operations which I thought was quite cute when I wrote it at least:
{-# LANGUAGE NoMonomorphismRestriction #-}
module MultiArray where

import Control.Arrow
import Control.Monad
import Data.Ix
import Data.Maybe

import Data.Array (Array)
import qualified Data.Array as A

-- {{{ from Dmwit.hs
deleteAt n   xs = take n xs ++ drop (n + 1) xs
insertAt n x xs = take n xs ++ x : drop n xs

doublify f g xs ys = f (uncurry g) (zip xs ys)
any2 = doublify any
all2 = doublify all
-- }}}

-- makes the most sense when ls and hs have the same length
instance Ix a => Ix [a] where
    range     = sequence . map range . uncurry zip
    inRange   = all2 inRange . uncurry zip
    rangeSize = product . uncurry (zipWith (curry rangeSize))

    index (ls, hs) xs = fst . foldr step (0, 1) $ zip indices sizes where
        indices = zipWith index (zip ls hs) xs
        sizes   = map rangeSize $ zip ls hs
        step (i, b) (s, p) = (s + p * i, p * b)

fold :: (Enum i, Ix i) => ([a] -> b) -> Int -> Array [i] a -> Array [i] b
fold f n a = A.array newBound assocs where
    (oldLowBound, oldHighBound) = A.bounds a
    (newLowBoundBeg , dimLow : newLowBoundEnd ) = splitAt n oldLowBound
    (newHighBoundBeg, dimHigh: newHighBoundEnd) = splitAt n oldHighBound
    assocs   = [(beg ++ end, f [a A.! (beg ++ i : end) | i <- [dimLow..dimHigh]])
               | beg <- range (newLowBoundBeg, newHighBoundBeg)
               , end <- range (newLowBoundEnd, newHighBoundEnd)
               ]
    newBound = (newLowBoundBeg ++ newLowBoundEnd, newHighBoundBeg ++ newHighBoundEnd)

flatten a = check a >> return value where
    check = guard . (1==) . length . fst . A.bounds
    value = A.ixmap ((head *** head) . A.bounds $ a) return a

elementWise :: (MonadPlus m, Ix i) => (a -> b -> c) -> Array i a -> Array i b -> m (Array i c)
elementWise f a b = check >> return value where
    check = guard $ A.bounds a == A.bounds b
    value = A.listArray (A.bounds a) (zipWith f (A.elems a) (A.elems b))

unsafeFlatten       a   = fromJust $ flatten       a
unsafeElementWise f a b = fromJust $ elementWise f a b

matrixMult a b = fold sum 1 $ unsafeElementWise (*) a' b' where
    aBounds = (join (***) (!!0)) $ A.bounds a
    bBounds = (join (***) (!!1)) $ A.bounds b
    a' = copy 2 bBounds a
    b' = copy 0 aBounds b

bijection f g a = A.ixmap ((f *** f) . A.bounds $ a) g a
unFlatten       = bijection return head
matrixTranspose = bijection reverse reverse
copy n (low, high) a = A.ixmap (newBounds a) (deleteAt n) a where
    newBounds = (insertAt n low *** insertAt n high) . A.bounds

The cute bit here is matrixMult, which is one of the only operations that is specialized to two-dimensional arrays. It expands its first argument along one dimension (by putting a copy of the two-dimensional object into each slice of the three-dimensional object); expands its second along another; does pointwise multiplication (now in a three-dimensional array); then collapses the fabricated third dimension by summing. Quite nice.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Load log4j.properties with JAR I have a jar file with the following Manifest
Manifest-Version: 1.0
Created-By: 1.7.0_07 (Oracle Corporation)
Main-Class: test.Main
Class-Path: ./log4j.properties lib/log4j-1.2.17.jar

I run the class as follows
java -jar test.jar

And this is my folder
lib
log4j.properties
test.jar

Why I can't see the log4j properties file? This is what I see
log4j:WARN No appenders could be found for logger (test.Main).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

Thank you
SOLUTION:
changed my classhpath in the MANIFEST to this
Class-Path: . lib/log4j-1.2.17.jar

A: You can also start your JVM with argument:
-Dlog4j.configuration=file:"./your/properties/path/log4j.properties"

to specify arbitrary location of your external log properties. I used this a lot in one particular project.

A: Properties file doesn' go in classpath, you must provide it and call it from code as shown here.
EDIT:
With your directory structure you call it like this:
PropertyConfigurator.configure("log4j.properties");

EDIT2:
Also, you must provide appender for it:
log4j.rootLogger=DEBUG, Appender1
log4j.logger.[logger-name]=level, Appender1
log4j.appender.Appender1=org.apache.log4j.ConsoleAppender
log4j.appender.Appender1.layout=org.apache.log4j.PatternLayout
log4j.appender.Appender1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

If you want finer control over logging, remove the first line (root looger) and put the second one where instead of [logger-name] you put the topmost package so that all the classes inside that package can use logging.
You can define multiple appenders and assign them to different classes in that manner.

A: PropertyConfigurator.configure(ABC.class.getResourceAsStream("log4j.properties")) worked me correctly, but basically you need to place Log4j properties file in Source Code folder (next to Java Class).
OR you can try putting outside and give proper path in getResourceAsStream("resources/log4j.properties") method


text:
Q: Zener diode + transistor circuit
I need to turn off an LED when the voltage reaches 10V. My source is maximum 12.8V (three lithium batteries.) The (yellow) LED is rated 2.1V and 30mA forward current, but the resistor I chose is 3.3k because I need it dim and low consumption. When powered directly from the source, it marked 2.84mA @ 11.16v. Also 0.033mW.
The Zener diode is rated 10V 500mW.
I tried different values for the diode resistor and the one that came closest to producing the same overall 2.84mA current (and LED intensity) was 11k.
I don't know why and couldn't find a formula that explains my result. The transistor's measured Hfe is 140.
I would really appreciate if someone could explain me a bit of the theory behind, since I need to replicate the circuit under different conditions.

A: If you plan to use a zener, then the key idea to hold in your head is that the zener will start conducting when sufficiently reverse-biased. You also need to keep in your mind that you'll need a series, current-limiting resistor to protect the zener as well as to operate it at the correct (datasheet) current (which varies depending on the zener's nameplated voltage.)
So, you have two parts in mind now. Just use your imagination about how to keep a transistor off when there's no current and then on when there is current. That's the only problem to solve in your mind.
A BJT transistor is on when it's \$V_{\text{BE}}\$ is forward-biased, sufficiently. It's off, otherwise. (That's a gross simplification, but so long as you imagine "less than \$400\:\text{mV}\$ means off and more than \$550\:\text{mV}\$ it is starting to be on" then you won't be too far afield.)
Hmm. If the zener conducts then there must be a voltage drop across that current-limiting resistor. And if not, then there will be no voltage drop across it. Sounds like a fit -- maybe, anyway.
So what about:

simulate this circuit – Schematic created using CircuitLab
It almost looks okay. Using the overly-simplistic argument I just made, this circuit looks like it may work well. When the zener is 'on' then there will be a voltage drop across \$R_1\$ and that should turn on the BJT. And it does. So, technically, it will turn on the LED at "some determined voltage," now.
The problem with it (well, the bigger problem anyway) is that once on and as the supply voltage rises still further then the BJT base will start supplying insane levels of current into the zener. That will probably not comport with your:

I need it ... low consumption

So, another cheap idea is to just move the LED resistor to the other side of the BJT. That should limit the ability of the BJT base to jam current into the zener, because the emitter resistor will be in the way of it.

simulate this circuit
Now, if you try this arrangement, it will much better meet your requirement as well as turning the LED on at a particular threshold.
The problem with this arrangement is that now it is a voltage-dependent current source to the LED. Let's say \$R_1=R_2=1\:\text{k}\Omega\$. Then the max LED current will be about \$2\:\text{mA}\$. But that LED current will decline linearly with lower voltages. So the brightness will be less when the voltage is less. This may be acceptable. I cannot say.
But the point of the above is to use your imagination and just think, a little. Turn things over in your head in different ways.
Here's another simple approach that minimizes the voltage-dependent current source period and makes it more of an on/off circuit -- through it still has its "behaviors."

simulate this circuit
That might perform acceptably. Now, \$R_1\$ sets the LED current and because this is a voltage-independent current source (once sufficient voltage overhead is reached), it behaves more like on/off than the earlier circuit.
These aren't by any means the only ideas that come to mind. There are countless ways to do this. For example, the very first thing I may want to do for a low power unit is to avoid the zener. You already may only want about \$1\:\text{mA}\$ or maybe \$2\:\text{mA}\$ in the LED. That's bad enough. You don't want to have to waste about the same amount (or still more) when feeding a zener diode. So you may want to look for a lower-current "zener-like" circuit for the voltage comparison part of this circuit.
You cannot do anything much about the LED, except to buy as high-efficiency LED as possible. But once that's decided, you are stuck with its requirement. The only thing left is to worry about the voltage comparison part. And much can be done on that front.
For example, Diodes Inc has the AP431S, which is very low current (tens of microamps) and can be set to a desired voltage, as well.
In addition, BJTs require recombination currents. These can be quite modest -- absolutely no more than 10% but can be 1% or so. And that isn't usually a big deal. But a FET can use even less. So if you get to the point of really wanting to squeeze the last few current-pennies out of the circuit, then you might consider using more expensive FETs and modifying the design once again.


text:
Q: No parser defined for Content-Type: application/json I'm using google-http-java-client-1.10.3-beta for making RESTfull Json requests to a service provided by an external source.
I need to parse the Json that's coming in the response to build some POJOs to my app.
For that, I'm using HttpResonse method 'parse as':
response.parseAs(SomeModel.class)

But I'm getting this exception:
java.lang.IllegalArgumentException: No parser defined for Content-Type: application/json
    at com.google.api.client.http.HttpResponse.parseAs(HttpResponse.java:497)

The responded json has this format:
[{"key" : {"key" : "value", "key" : "value"}}]
I had experminted some issues with other Json libraries when handling responses with square brackets, could that be the problem here?
Any ideas?

A: Responding to myself, the api needs you to set manually a JsonObjectParser object to the request involved.
A JsonObjectParser might be a GsonParser or JacksonParser or any other implented parser.
So, in order to set a GsonParser to your request you could use this code:
HttpRequest setJsonParser(HttpRequest request) {
    JsonObjectParser parser = new JsonObjectParser(new GsonFactory());
    return request.setParser(parser);
}

Then you will be able to do:
HttpRequest request = setJsonParser(request).execute().parseAs(SomeModel.class);

And all your POJOs will be automatically generated.
Note: I've upgraded my google-http-java-client version to 1.11.0-beta, an earlier version won't return a HttpRequest object when calling setParser so be carefull when using the presented code, you may need a void instead of a function.


text:
Q: How to call exception after timeout socket connect Python? I have socket connection:
# Create a TCP/IP socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # Bind the socket to the address given on the command line
    sock.connect((host, port))

So, how to set timeout parameter and call exception when timeout comes?
login = login.encode()
        sock.sendall(login)
        sock.recv(buf).decode("utf-8")

A: You could refer to the socket documentation:
socket.settimeout(value)

"Set a timeout on blocking socket operations. The value argument can be a nonnegative floating point number expressing seconds, or None. If a non-zero value is given, subsequent socket operations will raise a timeout exception if the timeout period value has elapsed before the operation has completed. If zero is given, the socket is put in non-blocking mode. If None is given, the socket is put in blocking mode.
So you could specify it with:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(3) # 3 Seconds timeout.

That way a socket.timeout is thrown when the connection takes more than 3 seconds and you could handle the exception catching a socket.timeout in a try-catch block.


text:
Q: How do I insert an int into a sorted array quickly? I'd like to insert an int into a sorted array. This operation is going to be performed very often, so it needs to be as fast as possible.

*

*It is possible and even preferred to use a List or any other class instead of an array

*All values are in the 1 to 34 range

*The array typically contains exactly 14 values

I was thinking of many different approaches, including binary search and simple insert-on-copy, but found it hard to decide. Also, I felt like I missed an idea. Do you have experiences on this topic or any new ideas to consider?

A: I will use an int array whose length is 35(because you said range 1-34) to record the status of the numbers.
int[] status = Enumerable.Repeat(0, 35).ToArray();
//an array contains 35 zeros
//which means currently there is no elements in the array
status[10] = 1;  // now the array have only one number: 10
status[11] ++;   // a new number 11 is added to the list

So if you want to add a number i to the list:
status[i]++;  // O(1) to add a number

To remove an i from the list:
status[i]--;   // O(1) to remove a number

Want to know all the numebrs in the list?
    for (int i = 0; i < status.Length; i++)
    {
        if (status[i] > 0)
        {
            for (int j = 0; j < status[i]; j++)
                Console.WriteLine(i);
        }
    }
    //or more easier using LINQ
    var result = status.SelectMany((i, index) => Enumerable.Repeat(index, i));

The following example may help you understand my code better:
the real number array: 1 12 12 15 9 34 // i don't care if it's sorted
the status array: status[1]=1,status[12]=2,status[15]=1,status[9]=1,status[34]=1
                  all others are 0

A: At 14 values this is a pretty small array, I don't think switching to a smarter data structure such as a list will win you much, especially if you fast good random access. Even binary search may actually be slower than linear search at this scale. Are you sure that, say, insert-on-copy does not satisfy your performance requirements?

A:
This operation is going to be performed very often, so it needs to be as fast as possible.

The things that you notice happen "very often" are frequently not the bottlenecks in the program - it's often surprising what the actual bottlenecks are. You should code something simple and measure the actual performance of your program before performing any optimizations.

I was thinking of many different approaches, including binary search and simple insert-on-copy, but found it hard to decide.

Assuming that this is the bottleneck, the big-O performance of the different methods is not going to be relevant here because of the small size of your array. It is easier to just try a few different approaches, measure the results, see which performs best and choose that method. If you have followed the advice from the first paragraph you already have a profiler setup that you can use for this step too.

A: For inserting into the middle, a LinkedList<int> would be the fastest option - anything else involves copying data. At 14 elements, don't stress over binary search etc - just walk forwards to the item you want:
using System;
using System.Collections.Generic;
static class Program
{
    static void Main()
    {

        LinkedList<int> data = new LinkedList<int>();
        Random rand = new Random(12345);
        for (int i = 0; i < 20; i++)
        {
            data.InsertSortedValue(rand.Next(300));
        }
        foreach (int i in data) Console.WriteLine(i);
    }
}
static class LinkedListExtensions {
    public static void InsertSortedValue(this LinkedList<int> list, int value)
    {
        LinkedListNode<int> node = list.First, next;
        if (node == null || node.Value > value)
        {
            list.AddFirst(value);
        }
        else
        {
            while ((next = node.Next) != null && next.Value < value)
                node = next;
            list.AddAfter(node, value);
        }
    }
}

A: Doing the brute-force approach is the best decision here because 14 isn't a number :). However, this is not a scalable decision, since should 14 become 14000 one day that will cause problems

A: What is the most common operation with your array?
Insert? Read?

*

*Heap data structure will give you O(log(14)) for both of them. SortedDictionary may hit your performance.

*Using a simple array will give you O(1) for reading and O(14) for insert.

By the way, have you tried System.Collections.Generic.SortedDictionary ot System.Collections.Generic.SortedList?

A: If you're on .Net 4 you should take a look at the SortedSet<T>. Otherwise take a look at SortedDictionary<TKey, TValue> where you make TValue as object and just put null into it, cause you're just interested into the keys.

A: If there is no repeated value on the array and the possible values won´t change maybe a fixed size array where the value is equal to the index is a good choice
Both insert and read are O(1)

A: You have a range of possible values from 1-34 which is rather narrow. So the fastest way would likely be using an array with 34 slots. To insert a number n just do array[n-1]++ and to remove it do array[n.1]-- (if n>0).
To check if a value exists in your collection you do array[n-1]>0.
edit: Damn...Danny was faster. :)

A: Write a method takes an array of integers and sorts them in place using Bubble Sort. The method is not allowed to create any additional arrays. Bubble Sort is a simple sorting algorithm that works by looping through the array to be sorted, comparing each pair of adjacent elements and swapping them if they are in the wrong order.


text:
Q: unable to connect to localhost:80 after installing nginx I just installed nginx by doing sudo yum install nginx and I'm unable to connect to it on port 80.
I tried stopping iptables by doing sudo service iptables start and was still unable to connect.
I'm testing this out by doing telnet localhost 80. Here's the output I'm getting back:
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused

When I try telnet localhost 22 it works as I'd expect it to:
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
SSH-2.0-OpenSSH_5.3

Any ideas?

A: Are you actually running it?
I'd do:
netstat -lnt | grep 80

and see if something is actually running. If you're root, you could do:
netstat -lntp | grep 80

And it would show you the PID as well.
If you just brought it down, I wouldn't guarantee it's configured to run on port 80 anyway. It may be configured for another port, for testing.

A: Try:
http{
  server {
    listen 80;
    listen localhost;  # <-probably will fix your problem.
    location / {
      root /data/www;
    }
    location /images/ {
      root /data;
    }
  }

A: Do not forget to add in host file:
127.0.0.1 localhost


text:
Q: Size of icon in SwitchPreference I want to change the size of the icon in SwitchPreference
        <SwitchPreference
        android:defaultValue="false"
        android:key="Key"
        anroid:icon ="@drawable/icon"
        android:layout="@layout/preference_item_normal"
        android:title="Title" />

It should have size 48*48. How can I achieve this?

A: You could change the size of your icon file to 48x48. With any image manipulation tool.


text:
Q: Method to return extending type instance from extended control In my solution, I have a custom component which implements IExtenderProvider in order to provide properties to other controls. I would like to implement a method for that component which, taking a control as argument, would return the instance of the extender component it is associated with, something like this:
    Public Function GetErrorProvider(c As Control) As MyErrorProvider
        Dim errorProvider as MyErrorProvider
        'Some code here
        Return errorProvider
    End Function

I thought of simply looking at the form and looping for a control of the MyErrorProvider type and use that, as I am not going to have more than one of this component per form, but I would like a more direct approach. I want this for some logic that depends on runtime defined values for that instance, outside the scope of forms.
Any ideas/suggestions?
Thanks

A: For completeness purposes, I am adding the solution that worked converted from the C# code linked above and adjusted slightly. It appears this can only be accomplished with reflection (correct me if I am wrong!):
Public Shared Function GetErrorProvider(control As Control) As MyErrorProvider
    'get the containing form of the control
    Dim form = control.GetContainerControl()

    'use reflection to get to "components" field
    Dim componentField = form.[GetType]().GetField("components", BindingFlags.NonPublic Or BindingFlags.Instance)

    If componentField IsNot Nothing Then
        'get the component collection from field
        Dim components = componentField.GetValue(form)

        'locate the ErrorProvider within the collection
        Return TryCast(components, IContainer).Components.OfType(Of MyErrorProvider)().FirstOrDefault()
    Else
        Return Nothing
    End If
End Function


text:
Q: NHibernate & Castle ActiveRecord - learn by doing or RTFM? I'm a complete noob to NHibernate & ActiveRecord.
What would you say is the best way to start using them productively - following the manuals step by step, or progress in small steps by actually using it and cross the problems as I encounter them?

A: Getting a book might help you get a solid foundation of concepts faster. Resorting to trial and error programming with NHibernate without understanding the basic stuff can lead to WTF moments, bad performance and subtle errors.
Also remember that ActiveRecord is really a thin layer over NHibernate, 99% of the information on the web about NHibernate applies to ActiveRecord as well.


text:
Q: What does "these" refer to in this context? Does it refer to "See's Candies and Coca-Cola's stocks"?

It's not the not selling that makes these so good, it's that discipline to buy things only when he really, really likes them," Lowenstein says.

Source: Warren Buffett's winning investing strategy can be applied to any purchase you make

A: I can't be sure, but after reading the article it seems like it's a mistake in the quote. The quote is seemingly talking about Buffett's ability to pick good investments, but it doesn't make sense with the word these. What I believe the quote was supposed to be:

"It's not the not selling that makes him so good, it's that discipline to buy things only when he really, really likes them," Lowenstein says.

Corrected, it's saying that what makes Buffett good is not sticking with his investments, but his self-control when it comes to choosing what to invest in.


text:
Q: web.config overrides app.config...why? I have two DLLs: one with a web.config, another one with app.config
I moved the connection strings from web.config to app.config so that it can be used by other DLLs.
Now, when I call ConfigurationManager.GetSection("SomeSection") , the application looks for a web.config, when it should be looking for the app.config.  It doesn't make sense why it does it because web.config is in a separate DLL.
Can anybody explain this please?

A: app.config for DLLs will never be used.
app.config for EXEs is renamed to <Application>.exe.config, and used by the EXE
web.config is used by websites/applications.
Essentially, if Visual Studio helpfully adds an app.config file to a DLL project for you, all it's giving you is something to copy and paste into the appropriate final config file - either the app.config of the EXE, or the web.config of the web site/application.
@vikps comment: Ignoring, for a second, the issues of website subdirectories and configSource, you can not have more than one configuration file involved in the configuration of an application. And neither subdirectories or configSource will help you, in this instance.
With configSource, the application can specify that an entire configuration section should be read from an alternative configuration file. But you can only do this if the entire configuration section exists in this other file (you cannot, for instance, have a connectionStrings section in the web.config, and also load some more connection strings from another source)


text:
Q: How to do connection pooling in jboss 5 in xml file I need to add connection pooling in jboss 5 but I don't know to make the changes. I find all configuration related to jboss6. Can any one help me step by step.

A: Step 1. Put your MS SQL JDBC Driver in your /lib directory, for sqlserver it is called sqljdbc.jar
Step 2. Put a datasource definition file in deploy directory. Call it ms-sql-ds.xml or something ending in -ds.xml.
<?xml version="1.0" encoding="UTF-8"?>
  <datasources>
    <local-tx-datasource>
      <jndi-name>DefaultDS</jndi-name>
      <connection-url>jdbc:sqlserver://localhost:1433;DatabaseName=pubs</connection-url>
      <driver-class>com.microsoft.sqlserver.jdbc.SQLServerDriver</driver-class>
      <user-name>sa</user-name>
      <password>jboss</password>
      <pool>
           <min-pool-size>5</min-pool-size>
           <max-pool-size>50</max-pool-size>
           <prefill>false</prefill>
           <use-strict-min>false</use-strict-min>
           <flush-strategy>FailingConnectionOnly</flush-strategy>
      </pool>
      <check-valid-connection-sql>SELECT 1 FROM sysobjects</check-valid-connection-sql>
      <metadata>
         <type-mapping>MS SQLSERVER2008</type-mapping>
      </metadata>
    </local-tx-datasource>
</datasources>

Note: I don't have a SQL Server instance to test this with but if it is correct you will see some configuration messages in the log file and you can also verify the datasource connectivity through the JBoss conole. My answer is based on information here -> https://developer.jboss.org/wiki/HowToSetADatasourceConnectionToMSSQLServer


text:
Q: install firefox in ubuntu-server edition I have ubuntu server edition installed and I want to install firefox inside it , I don't want full ubuntu-desktop package just a minimal setup which would let me run firefox inside ubuntu-server 10.04 LTS

A: If you just want to install Firefox and run it remotely, install the firefox package. If you also want to run Firefox locally, you'll need a GUI environment: install the x-window-system package. If you also want to run Firefox locally comfortably, you'll need a window manager (any of the packages that provide the x-window-manager virtual package) or desktop environment (the Ubuntu default is Gnome, install at least gnome-core).
I assume you only have a command line at your disposal; use the apt-get command to manipulate packages, or aptitude for a command line or text mode interactive program.
apt-get install firefox x-window-system gnome-core

Strictly speaking, this won't be a minimal system, as it'll pull up a few packages that are recommended but not strictly necessary. Install all recommended packages unless you understand why you don't need them (in other words, if you need to ask, install them all).


text:
Q: Pattern for schema split across sources I was not sure how to title this question, but bear with me.
My company is building a new product and for it we will use a third-party service (let's call it ENB for short) to be responsible for many operations on our data that are not our core business. It's in .NET Core if it matters.
To illustrate I will use the entity ApplicationUser, which is the user that logs in to our application. ApplicationUser will consist of account data as well as a Person, representing the real life person that created this account. To function, ENB needs the Person object and most of its data to function, so we have to create the Person object in ENB. This puts us in a situation where if we store the Person in both our database and in ENB, we will have duplicated the data which rings all kinds of alarm bells in my head.
public class ApplicationUser
{
    public int Id { get; set; }
    < ... other fields ... >
    public int EnbPersonId { get; set; }  // This is stored in ENB
}

The above is the case for many of our entities: ENB needs their data to function so we have to store it there. For others, part of the fields of a domain object are specific to our application and parts are needed by ENB. This is why I say that the schema is split across sources.
One solution to this is to prefer storing in ENB whenever it's needed, and store the rest (as said, sometimes parts of an entity) in our database. Then, whenever a type is needed, we assemble it by querying both our own database as well as calling ENB through API (we don't have direct access to ENB's database).
Another solution is to simply duplicate the data. This instinctively feels bad because we have to update two sources whenever anything is changed, and we have to make sure they stay in sync (what happens if one update fails and the other doesn't?).
What I'm looking for is if any solution is better than the other, and if there is a name for this pattern of splitting a schema across multiple sources i.e. our own and ENB.

A: When it comes to business logic we agree that DRY principle is a cornerstone of structuring it well. However, this is not always true for the database world.
The main reason is that assembling needed information from different sources requires additional costs. If we talk about the same database-scenario this is what denormalization is for: sometimes you let your data to be duplicated in order to improve your select-intensive application. We can extrapolate this pattern for your case with multiple sources: in case querying data for your system is prevalent you may want to duplicate your data. Otherwise, you shouldn't do it.

what happens if one update fails and the other doesn't?

This is a tricky question. In the scenario with a single database transactions would be a natural answer. However, for your case, you may try to emulate transactions programmatically. I enjoy the idea of compensating actions in case when part of your "transaction" fails. The link I've provided mentions microservices but still, I think it's sufficient for you to capture the essence.


text:
Q: Java wildcards - generics creating Arrays.asList or ImmutableList.of I have just came accross a question which I don't quite understand.
I have following variable (class field):
List<Validator<?, Data>> validators;

Now I want to assign some validators' instances to this list, then:
validators = Arrays.asList(validatorsFactory.create(Obj1.class));

Where the create method returns Validator<?, Data>
And there is a problem: I need to specify generic type of that list, due to wildcards. Okay, right version is:
validators = Arrays.<Validator<?, Data>>asList(validatorsFactory.create(Obj1.class));

But, when I add two elements instead of one I dont have to specify any generic type. How does Java know that the wildcards are the same?
validators = Arrays.asList(
    validatorsFactory.create(Obj1.class), validatorsFactory.create(Obj2.class)
);

My understanding of that was that all wildcards are different placeholders when they are an arguments to a method.
Same applies to Guava's: ImmutableList.of
Thanks in advance

A: When you have an argument with a wildcard at the top level, e.g. Validator<?, Data>, you are allowed to pass it to a generic method with a type variable in the place where the wildcard is, e.g. public <T> void foo(Validator<T, Data>). This is called wildcard capture.
This case is a little different, because the Arrays.asList() takes parameters of type T. For some reason in your first case, it is keeping the capture when inferring the type of T, so it infers T to be Validator<capture #XXX, Data>, which is not the T that you want.
In your second case, I am guessing that the fact you have two arguments, both of type Validator<?, Data>, somehow makes it impossible for T to be inferred to contain a capture, since the two wildcards would have two different captures, so it just infers T to be Validator<?, Data>, which is what you wanted in the first place.


text:
Q: Null pointer exception while writing to SourceDataLine I have a byte array with audio samples. I want to play it, so I try to write it into SourceDataLine:
SourceDataLine sample;
private byte[] samplebytes;

...

sample.start();
sample.write(samplebytes, 0, samplebytes.length);
sample.drain();
sample.stop();
sample.close();
sample = null;

And I get this:
java.lang.NullPointerException
at virtualcut.Sample.<init>(Sample.java:45)
at virtualcut.model.SelectionModel.setPosition(SelectionModel.scala:79)
at draggable.DraggableComponent$2.mouseReleased(DraggableComponent.java:128)
at java.awt.Component.processMouseEvent(Component.java:6504)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6269)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4860)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4686)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2713)
at java.awt.Component.dispatchEvent(Component.java:4686)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:707)
at java.awt.EventQueue.access$000(EventQueue.java:101)
at java.awt.EventQueue$3.run(EventQueue.java:666)
at java.awt.EventQueue$3.run(EventQueue.java:664)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:680)
at java.awt.EventQueue$4.run(EventQueue.java:678)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:677)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

I'm new In Java and sometimes I don't get what is cousing NullPointerException - this is one of those times :(.

A: You haven't instantiated sample. You need to call new SourceDataLine().


text:
Q: Return json into ajax from Action Class Am currently working on fullCalendar (jQuery plugin) and now stuck with silly issue but I couldn't overcome it .
Trying populate event details from database on Calendar page load . Here is my code ,
$('#calendar').fullCalendar({
            defaultDate: '2016-03-12',
            editable: true,
            eventLimit: true, // allow "more" link when too many events
            eventSources: [
                     getEvents()
                     ]
        });

        function getEvents(){
            alert("Inside get Events");

            $.ajax({
                url : "/FullCal/eventDetails.do",
                dataType : 'json',
                success : function(data){
                    alert(data)
                }
            });
        }

Am using Struts framework and here is my action mappings,
<action path="/eventDetails" type="com.struts.action.CalendarInviteAction" >
            <forward name="success" path="/Calendar.jsp" />
        </action>

And my action class has the event details data in JSON format. My question is how to write the json data into ajax response(In simpler words , how to return the json data to ajax call) . Here is my action class UPDATED
public ActionForward execute(ActionMapping mapping , ActionForm form , HttpServletRequest request , HttpServletResponse response) throws  Exception{

        System.out.println("TEsting inside getEventDetails");

        ArrayList<EventForm> arr = new ArrayList<EventForm>();

        arr.add(new EventForm("HandOff Meeting" , new Date(), new Date(),"Meeting at HandOffBridge"));

        Gson gson = new Gson();
        String jsonString = gson.toJson(arr);

        response.getWriter().write(jsonString);

        return null;
    }

jsonString contains eventDetails in JSON format , how to return this to ajax.
Please help me to achieve this.

A: A dataType : 'json' is used by [jQuery Ajax][1] to specify a data type that is expected to return by the success callback function when the action and result is executed, and a response returned from the server.

dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).

The URL should correctly point to the action mapping. Assume it will be in the default namespace, otherwise you should modify URL and mapping to add the namespace attribute.
<script type="text/javascript">
  $(function() {
    $("#dialog-form").dialog ({
      autoOpen: true,
      height: 500,
      width: 750,
      modal: true,
      buttons : {
        "Search" : function() {
          $.ajax({
            url : '<s:url action="part" />',
            success : function(data) {
              //var obj = $.parseJSON(data);
              var obj = data;
              alert(JSON.stringify(obj));
            }
          });
        }
      }
    });
  });
</script>

A: Your ajax call seems fine. Just need to display ajax response in proper way.
events: function(start, end, timezone, callback) {
  $.ajax({
    url : "/FullCal/eventDetails.do",
    dataType : 'json',
    success : function(data){
      callback(data);
    }
  });
}

A: My first guess is why return null?
return null;

Just return the json string:
return jsonString;


text:
Q: SQL no DB MySQL Eu tenho a seguinte situação, um cadastro com 5 campos sendo eles:
Tipo1, Tipo2, Tipo3, Tipo4 e valor
Os 4 campos de tipo são campos combos, onde pode ser selecionado a opção todos, ou outra opção qualquer.
Pra exemplificar:
<select class="form-control" id="tipo1" name="tipo1">
    <option value="" selected>TODOS</option>
    <option value="1">Opção 1</option>
    <option value="3">Opção 2</option>
    ...
</select>
<select class="form-control" id="tipo2" name="tipo2">
...

Até ai tudo bem, está funcionando ok.
No MySQL eu tenho a seguinte situação
Id  Tipo1  Tipo2  Tipo3  Tipo4  Valor
1   1      Null   2      3      100.00

Obs.:

*

*Os 4 tipos não podem ser nulos ao mesmo tempo.

*Pode acontecer de o tipo1, ou tipo2 ou tipo3 estar preenchido e todos os demais tipos serem nulos.

Pra contextualizar, isso é um cadastro de metas, que dependendo da situação e do valor se foi ultrapassado, deve deixar passar, ou bloquear.
Estou usando PHP e MySQL, meu problema é fazer uma consulta se a situação existe no banco, não estou conseguindo enxergar como fazer isso.
Não sei se consegui ser claro, e pode ser que a resposta esteja na minha frente, mais já quebrei bastante a cabeça e não saiu nada, então resolvi pedir ajuda. hehe.

A:
meu problema é fazer uma consulta se a situação existe no banco

Cara pelo que entendi a única situação que não pode ocorrer é se os quatro campos são nulos ao mesmo tempo, qualquer outra é aceita. Parece que você não validou isso antes pois aí não teria sentido fazer a consulta no banco.
O sql para verificar os casos nessa situação 'errada' seria:
select id from tabela
where tipo1 is null
and tipo2 is null
and tipo3 is null
and tipo4 is null

Lembrando que
tipo1 is null (campo nulo)

é uma expressão diferente de
tipo1 = "" (string vazia)


text:
Q: Detrimental impact of magnetic field on PCB and battery? We are developing a small consumer electronics product consisting of a small 4-layer PCB along with a few PDM microphones and BLE chip/ an antenna, as well as a LiPo battery. We are locating a small but pretty strong magnet next to these components in the enclosure. It is an N52 (Surface Field: 3032 Gauss, \$B_{r_{max}}\$: 14,800 Gauss, \$B_{H_{max}}\$: 52 MGOe). Are there any long term effects of the magnet which may be detrimental to the battery or PCB electronics?

A: *

*LiPo Battery - The battery will be fine.  A good way to verify this is to see if your magnet is attracted to the battery at all.  There can be some weird variations on LiPo chemistry, but as far as I know, there aren't any ferromagnetic materials in most, if not all, LiPo cells.  High strength (even N52 grade) magnets are frequently used to attach LiPo batteries in hobbyist RC products, and many other consumer products.

*Magnetic Cores - I know you didn't mention this, but this is really the only thing you need to worry about.  Static magnetic fields generally won't impact how the circuit itself behaves (ignoring magnetic cores, of course), but static magnetic fields will impact any bulk magnetic material used in the circuit.  This includes any inductors that don't use an air core and ferrite beads.
All magnetic core materials can saturate.  With inductors, this is usually specified as saturation current, which is the current through the inductor that, if you exceed, will cause a rapid drop in inductance.  Measuring it as current is just for our convenience, and what is really occurring during saturation is that the magnetic field in the core has reached saturation.
Any nearby static magnetic fields will cause some degree of magnetization in the core material, and any current or ripple current through the inductor will be another field superimposed on the core material.  Depending on the exact properties and geometry of the core, this can potentially lower the saturation of the core well below spec, or increase losses in the core.
So this is very much worth considering, especially if you are using any power inductors (like in a buck or boost converter) that you're running near saturation.
That said, the saturation field for power ferrites is usually in the range of 300mT (conservatively).  So that is already equal to the surface field of your magnet. Considering that magnetic fields fall off at distance cubed (as opposed to squared), so you can be extremely close to a magnet and experience almost negligable field strength from it.
Case in point: assuming your magnet is an N52 square 10mm x 10mm x 2.5mm (which would yield a surface field of about 3000 gauss, give or take.  Unless the dimensions are different by a huge amount, numbers will be similar), the static magnetic field just 2mm away from the center, in the direction of the poles, will be ~2140 gauss or 214mT.  5mm, and it is down to 993 gauss.  This is low enough that I would not be concerned.
So the short answer to if it will affect your circuit is: maybe.  But probably not, especially if you put even the tiniest amount of distance between the magnet and inductors that might present on board or inside the bluetooth module.


text:
Q: UIButton only partially tappable So, this seems like a weird occurrence. I have a UIButton with a custom background image and and animation that is called randomly (it's an image of a buoy rocking back and forth). The strange thing is, only the bottom portion of the button is tappable. I have another button that is identical in the way that is set up, and you can tap anywhere on the image.
The background image is just a png (it has transparency) but the other buttons I've created are work as long as you tap within the bounding box.  Any ideas?
-(void)displayPauseButton
{
    NSArray *pauseInfo = [self.sharedGameModel.theAssets objectForKey:@"buoy-ani"];

    //
    // add mascot button
    // aButtonArray has the info for a individual button in an array
    // the buttons are read from the array in this order
    // 0 array of images for the button animation triggered when clicked
    // 1 x position
    // 2 y position

    // this array only has the names of the image animation
    // so we init
    NSArray *pauseImages = [pauseInfo objectAtIndex:0];
    UIImage *pauseImage = [UIImage imageNamed:[pauseImages objectAtIndex:0]];
    CGFloat theX=[[pauseInfo objectAtIndex:1] floatValue];
    CGFloat theY=[[pauseInfo objectAtIndex:2] floatValue];

    // create a new mutable array to fill with the actual object
    // in the following loop
    NSMutableArray *buttonAniImages = [[NSMutableArray alloc] init];
    for (id object in pauseImages)
    {
        [buttonAniImages addObject:[UIImage imageNamed:object]];
    }

    // sets the custom image for the button
    [self.pauseButton setImage:pauseImage forState:UIControlStateNormal];

    self.pauseButton.frame = CGRectMake(theX, theY, pauseImage.size.width, pauseImage.size.height);
    self.pauseButton.imageView.animationImages = buttonAniImages;

    self.pauseButton.imageView.animationDuration=3.0;
    self.pauseButton.imageView.animationRepeatCount=1;

    [self.gameScreen addSubview:self.pauseButton];

    // add the action associated with the button
    [self.pauseButton addTarget:self action:@selector(someoneHitThePauseButton:) forControlEvents:UIControlEventTouchUpInside];
}

A: Escrafford is right. There was something on top, only it was never visibly on top. I'll add my experience just in case anyone else runs into the same issue.
In my game, there are multiple UIViews that have path animations. Their initial frames were initially set to 0,0 and then the path starting points were adjusted randomly. But their initial frames were covering the top portion of the buttons.
Thanks to everyone who provided feedback.


text:
Q: ReactJS, ES6: Using Arrow( => ) to modify state arrays' individual elements' member, a better way? I have itemList as my state array of objects.
    this.state = {
        .....
      itemList: [],
       .....
    }

itemList has title, desc, expState. The code present below works perfect. I want to know is there a better way to do it, like using arrow of ES6. I am new to ReactJS as well as ES6, so can't figure out.
    var index = this.state.itemList.indexOf(item);
    item.expState = !(item.expState);
    var newItemList = itemList;
    newItemList[index] = item;
    this.setState({itemList: newItemList});

A: item.expState = !item.expState;
this.setState({ itemList: this.state.itemList });

The code above is the simplified version of what you have (it's pretty much ES5.1 still, since there is no place to use anything from the new standards).
The part
var newItemList = itemList;
newItemList[index] = item;

was entirely removed since in JS arrays are not cloned on assignment, but only references to them are assigned to a variable. Hence you are working with the same array anyway.


text:
Q: Unable to run Cypress 9.7.0 tests in Firefox My Cypress tests run as expected in Chrome, Electron, & Edge.
However, when I try to run these tests against Firefox, I get the below error:

Cypress failed to make a connection to Firefox.
This usually indicates there was a problem opening the Firefox
browser.
Error: could not find CRI target
at lazyAssLogic

I am using Cypress version9.7.0, & using the below command:
"scripts": {
  "firefoxTest": "cypress run --browser firefox"
}

One thing that may be important is that I'm using failOnStatusCode in some of the tests.
I've seen there have been similar issues before with earlier versions of Cypress such as this issue, but I believe that has been fixed in a later release.
Can someone please tell me what the issue may be?

A: By installing a older version from firefox (v 99) i could solve it. The idea i got from this forum https://issuehint.com/issue/cypress-io/cypress/22086 and the link for downloading an older version is from here https://ftp.mozilla.org/pub/firefox/releases/99.0/win64/en-US/. Hope this helps


text:
Q: Find a and b such that the line $10ex + 10y = 0$ will be a tangent of the curve $ y = ae^{1/(x-1)} - b$ at $x = 2$? How do I solve this, it seems very simple, yet when I try it turns impossible because I have no idea how to continue:
$$
10ex+10y=0 \\
ex+y=0\\
y=-ex\\
f(x) = -ex\\
f(2)=-2e
$$
And now? I am not sure if this is the right path to solving this so far, and as for the next steps I think I need to find the derivative of the 2nd line. I end up with $$y =- ae^{\frac{1}{x-1}}\frac{1}{(x-1)^2} $$ and I have no idea how to continue from here, I think I am supposed to use $-2e$ somewhere, but I don't understand how that will help me find $a$ or $b$, considering $b$ is gone now?

A: Let $$f(x)=ae^{\frac{1}{x-1}}-b$$
then for $x>1$
$$f'(x)=-\frac{1}{(x-1)^2}(f(x)+b)$$
the equation of the tangent at $x=2$ is
$$y=f'(2)(x-2)+f(2)$$
$$=-(f(2)+b)(x-2)+f(2)$$
$$=-(f(2)+b)x+3(b+f(2))-b$$
$$=-ex$$
thus
$$f(2)+b=ae=e$$
and
$$3ae-b=0$$
therefore
$$a=1\;;\;b=3e$$


text:
Q: Displaying gifs in jupyter notebook using widgets How do you use python widgets to display gifs in a jupyeter notebook.
I have tried:
gif_box = widgets.Image("sample.gif")

or
gif_box = widgets.Video("sample.gif")

but receiver error:
TypeError: __init__() takes 1 positional argument but 2 were given

Regardless of what I try it won't work

A: You need to read your image into a file handler and read it into a byte string before you can pass it into the widget like so:
# read file as bytes and get file handler. use `with` to ensure
# your file is closed after you're done reading it
with open("sample.gif", "rb") as file:
    # read file as string into `image`
    image = file.read()

widgets.Image(
    value=image,
    format='gif'
)

See the docs for the Image widget.


text:
Q: Calendar extender I am using calendarextender control in asp.net.It displays only date ,not time.But while inserting to database ,time is inserted automatically.But while retrieving the data from database using date in where condition ,no correponding records displays.What modification in storedprocedure i can do to resolve this problem.
I used following code in storedprocedure. Name Of table is FileM
Select * from FileM Where OldDate = '@OldDate%'

OldDate field in databese is stored as datetime i.e date is date I inserted but time is  in either 08:00:00:000 or 00:00:00:000.So the above query gives records for date that coming with time as 00:00:00:000,but not with 08:00:00:000

A: -- assumes that the @OldDate parameter is a DATETIME
SELECT *
FROM FileM
WHERE DATEDIFF(day, OldDate, @OldDate) = 0

If you're able to modify the stored procedure then you can have more flexibility and performance by passing two DATETIME parameters, specifying the start and end times of the range that you need:
CREATE PROCEDURE dbo.GetRangeOfRecords
@StartDateTime DATETIME,
@EndDateTime DATETIME
AS
SELECT *
FROM FileM
WHERE OldDate BETWEEN @StartDateTime AND @EndDateTime

And then call your stored procedure like this, for example:
EXEC dbo.GetRangeOfRecords
    @StartDateTime = '2009-02-25 00:00:00.000',
    @EndDateTime = '2009-02-25 23:59:59.999'

A: The following code will strip out the time component of your datetime value (by strip out I mean make it 00:00:00 i.e. midnight): -
dateadd(d,datediff(d,0,MyDateTimeColumn),0)
so you can use: -
Select * from FileM Where dateadd(d,datediff(d,0,OldDate),0) = @OldDate
Alternatively, if you are using SQL Server 2008, there is a new date data type (with no time component).

A: As long as none of your dates are explicitly given a time component, they should all be defaulting to 00:00:00.000. In that case a simple equality comparison will do just fine. In your code though, you're putting quotes around your parameter, which means that you're now comparing your date to a literal string of "@OldDate%". Remove the quotes and see if that helps.
I like Luke's answer for flexibility, but if you don't have that option and can only correct the existing stored procedure, maybe this will help.


text:
Q: How do I develop a JDBC application to take data from a keyboard and store it in a database? How do I develop a JDBC application to take data from a keyboard and store it in a database? Do we need to separate business logic and presentation logic?

A: If you want to do a standalone java application then you do not need presentation layer. The input could be obtained from "keyboard" using Scanner library. But if you are talking about a web application then you need use any framework preferably spring to create a Model, View, Controller (MVC) application.


text:
Q: Suppose that $X$ is a discrete random variable taking values in $\{0,1,2,...\}$. Show that $E[X]=\sum^{\infty}_{k=0}{P(X>k)}$ Suppose that $X$ is a discrete random variable taking values in $\{0,1,2,...\}$. Show that $E[X]=\sum^{\infty}_{k=0}{P(X>k)}$

Absolutely lost. From my notes, we define $E[X]$ as follows
$E[X]=\sum^{\infty}_{k=1}{xP(X=k)}$
I am also unsure how to explictly write $\sum^{\infty}_{k=0}{P(X>k)}$. My intuitive understanding of $P(X>k)=\{$ probability of the event not occuring consequetively until $X=k\}$, i.e.
$P(X>k)=(1-P(0))(1-P(1))(1-P(2)) \dots (1-P(k-1))$
Or is it
$P(X>k)=1-[P(X=0)P(X=1) \dots P(X=k-1)$

A: Write
$$\begin{align}
\mathbb{E} X &= \sum_{k=0}^\infty k \mathbb{P}\{ X = k\}
= \sum_{k=1}^\infty k \mathbb{P}\{ X = k\}
= \sum_{k=1}^\infty \sum_{j=1}^k \mathbb{P}\{ X = k\} \\
&= \sum_{j=1}^\infty \sum_{k=j}^\infty  \mathbb{P}\{ X = k\}
= \sum_{j=1}^\infty \sum_{k=j}^\infty  \mathbb{P}\{ X = k\}
= \sum_{j=1}^\infty  \mathbb{P}\big\{ \bigcup_{k=j}^\infty X = k\big\} \\
&= \sum_{j=1}^\infty \mathbb{P}\{ X > j- 1\}
= \sum_{i=0}^\infty \mathbb{P}\{ X > i\}.
\end{align}$$
For the record, the third equality may look like a magic "trick", and hard to figure out; the whole thing is more intuitive and easier to figure out starting from $\sum_{i=0}^\infty \mathbb{P}\{ X > i\}$ and trying to get back to $\sum_{k=0}^\infty k \mathbb{P}\{ X = k\}$.

A: To generalize, we have for an arbitrary random variable $X$ with $\mathbb P(X\geqslant 0)=1$,
$$ \mathbb E[X] = \int_0^\infty \mathbb P(X>t)\mathsf dt.$$
This follows from Fubini's theorem:
$$
\begin{align*}
\int_0^\infty \mathbb P(X>t)\mathsf dt &=
\int_0^\infty \mathbb P(\omega\in\Omega: X(\omega)>t)\mathsf dt\\
&= \int_0^\infty \mathbb E[\mathbb I_{\{\omega\in\Omega :X(\omega)>t\}}]\mathsf dt\\
&= \int_0^\infty \int_\Omega \mathbb I_{\{\omega\in\Omega: X(\omega)>t\}}]\mathsf d\mathbb P\;\mathsf dt\\
&= \int_\Omega \int_0^{X(\omega)}\mathsf dt \mathsf\; d\mathbb P\\
&= \int_\Omega X\mathsf d\mathbb P\\
&= \mathbb E[X].
\end{align*}
$$

A: $$\begin{array}{cccccccccc}
P\{X>0\} & = & P\{X=1\} & + &P\{X=2\} & + & P\{X=3\} & +& \cdots\\
P\{X > 1\} &= &&&P\{X=2\} & + & P\{X=3\} & +\ &\cdots\\
P\{X > 2\}&= &&&&& P\{X = 3\} & + & \cdots\\
\vdots & \vdots &&&&&&& \ddots
\end{array}$$
Now sum by columns to get
\begin{align}
\sum_{k = 0}^\infty P\{X > k\} &= P\{X=1\}+2P\{X=2\}+3P\{X=3\}+\cdots\\
&= \sum_{n=1}^\infty n P\{X = n\}\\
&= \sum_{n=0}^\infty n P\{X = n\}&\scriptstyle{\text{added term}~ 0P\{X=0\}~\text{equals}~ 0}\\
&= E[X] & \scriptstyle{\text{by definition}}
\end{align}

A: This is essentially a change of order of summation.
Let $p_k = P(X=k)$.
$\sum_{k=0}^\infty P(X >k) =\sum_{k=0}^\infty \sum_{i=k+1}^\infty p_i  = \sum_{i=1}^\infty \sum_{k=0}^{i-1} p_i = \sum_{i=1}^\infty i p_i = E[X]$.


text:
Q: How to setup a hook with a view in Drupal 7? So I have a view called "export-spreadsheets". When an admin goes to this page, I want a function to be called so that it basically runs a long SQL query and exports its results to a CSV.
I was wondering where I would add this function to be called?
Thanks.

A: Make a custom module, add on to the *_menu() hook, make it call the function when you go to a certain url. Have it output the .csv file and die()


text:
Q: Flutter: "Unhandled Exception: NoSuchMethodError: The getter 'httpClientAdapter' was called on null." I'm trying to use dio on Flutter, but i have to ignore the certificate validation so I made some changes on code and i got the error:
E/flutter (21674): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: NoSuchMethodError: The getter 'httpClientAdapter' was called on null.
E/flutter (21674): Receiver: null
E/flutter (21674): Tried calling: httpClientAdapter

Can someone help me fixing it?
The function that i'm using:
  Future<void> _login3() async {

    Dio dio;
    if (Platform.isAndroid) {
      (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
          (client) {
        client.badCertificateCallback =
            (X509Certificate cert, String host, int port) => true;
        return client;
      };
    }

    Response response =
        await Dio().get("https://sistema.hutransportes.com.br/api/login.php");
    // Response response;

    response =
        await dio.post("/test", data: {"user": "renato", "password": "123456"});
    print(response.data.toString());

  }

A: This should be pretty easily solvable by stepping through your code. I suggest putting a breakpoint on the first line of this method and debugging before looking at the answer, it should be pretty obvious what's going on. The message of the exception also states specifically what went wrong.

 You haven't newed up an an instance of Dio before trying to access properties on
 that variable. Dio dio creates the variable but the value is null. In the next
 line you try to access the httpClientAdapter property of the null value and it
 rightfully throws an exception.

 Fix this by changing your first line to Dio dio = Dio();


text:
Q: HTML Live Text Update I have the following Website: https://neat.000webhostapp.com/
I have set some example values under Exhaust 4 Temp., Battery Level etc. However, what I'm looking to do is to update these values real-time (using Python). If I could be given the HTML code, I'm sure I could figure out how to make this Python compatible.
If it's changing a file's content, which the page will be reading from, then I can make Python modify the file accordingly.
Of course, I could just refresh the page. However, I would like to only change these values, without refreshing the entire page every time...
I took a look at http://www.labbookpages.co.uk/web/realtime.html (Dynamic Text), but I didn't exactly understand what it stated about the liveData file. Should I create a new liveData file (no extension)? If so, what should be the content of the file etc.?


text:
Q: how to select entity with relationship to other entity in EF core How can I get the list of products for specific project without including project? Something similar to
select p.Id, p.Name
from product p
inner join ProjectProduct j on p.Id = j.ProductId and j.ProjectId = @Id

The closest solution that I have is
var products = await (from proj in context.Project select proj)
                    .Where(proj => proj.Id == 1)
                    .Select(proj => proj.Product)
                    .ToListAsync();

but this returns a List<List<Product>>
in addition I need to be able to add the order by and pagination to that
I know that I can do it by raw sql like this
var param1 = new SqlParameter("@Id", id);
var query = @"select * from product p
inner join ProjectProduct j
on p.Id = j.ProductId and j.ProjectId = @Id ";

var queryable = context.product.FromSqlRaw(query, param1).AsQueryable();
await HttpContext.AddPaginationToHeader(queryable);

var products = await queryable.OrderBy(x => x.Name).Paginate(paginationDTO).ToListAsync();

But I was hoping to do it by linq to entity
public class Project
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Product> Product { get; set; }
}

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Project> Project { get; set; }
}

public class ProjectProduct
{
    public int ProjectId { get; set; }
    public int ProductId { get; set; }
}

A: Thanks to Harald Coppoolse's response on another post
and for those that have the same problem
here are the steps
1- we define our query as queryable
var queryable = context.Project
                .Where(proj => proj.Id == id)
                .SelectMany(p => p.Product).AsQueryable();

2- Now we can pass the query to SQL server like this
var products = await queryable.OrderBy(x =>
x.Name).Skip(...).Take(...).ToListAsync();

for Skip and Take we can create a generic Extension for IQueryable
and add a method to that with return of
return queryable
                .Skip((paginationDTO.Page - 1) * paginationDTO.PageSize)
                .Take(paginationDTO.PageSize);

and of course our paginationDTO is nothing more than a POCO class with 2 properties of page and pageSize

A: try this:
var products = await  context.Project
                      .Where(proj => proj.Id == 1)
                      .Select( proj=>proj.Products)
                      .FirstOrDefaultAsync();

if you want to order product after this you can do this common way
products= products.OrderBy(p=>p.Name).ToList();

it can be put in one line but EF sometimes generates a very ridiculous  Sql script, so better to do this separately.


text:
Q: Python - как подключить модуль? День добрый! В консоли получил такой Exception:
ImportError: No module named PIL

Вопрос: как его подключить.
P.S. Просьба не ругать за глупые вопросы, язык только начал изучать. (Сам я PHP-шник)
UPD:
Сорри, забыл код приложить :))
from PIL import Image, ImageDraw

A: pip install PIL

Для установки этого пакета.


text:
Q: Getting no output while running Python Script to Scrape News Stories from CNN import requests
from lxml import html

page = requests.get('http://www.cnn.com')
html_content = html.fromstring(page.content)

for i in html_content.iterchildren():
    print i

news_stories = html_content.xpath('//h2[@data-analytics]/a/span/text()')
news_links = html_content.xpath('//h2[@data-analytics]/a/@href')

I am trying to run this code to understand how web scraping in python works.
I want to scrap top news stories and their links from CNN.
When i run this in Python Shell, the output for news_stories and news_links i get is:
[]

My question is where am i going wrong with this and is there a better way to achieve what i am trying to than this one?

A: In your code html_content is returning only page address and not the actual content of the page.
html_content = html.fromstring(page.content)

You can try printing following to see complete HTML code for  that page:
import requests
from lxml import html

page = requests.get('http://www.cnn.com')
print page.text

Even though if you'll get the content also somehow, you will get it a gzipped response from the server. (Get html using Python requests?)
I would highly recommend you to use httplib2 library and BeautifulSoup to scrape news stories from CNN. That is really handy in use and get you what you want. You can see another stackoverflow post here (retrieve links from web page using python and BeautifulSoup)
I hope that help you.


text:
Q: Android PreferenceFragment No view found for id for fragment So I'm making an android application and I started dealing with preferences, when I simply use a PreferenceActivity, everything works perfectly, however, if I use it with a PreferenceFragment, it crashes right after I click the button that calls intents to SettingsActivity with an error:
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{*app package*/*app package*.SettingsActivity}: java.lang.IllegalArgumentException: No view found for id 0x7f08003d for fragment SettingsFragment{41cc1a98 #0 id=0x7f08003d}

this is SettingsActivity:
public class SettingsActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //addPreferencesFromResource(R.xml.preference);
        // Display the fragment as the main content.
        getFragmentManager().beginTransaction()
                .replace(R.id.pager, new SettingsFragment())
                .commit();
    }

    public static class SettingsFragment extends PreferenceFragment {

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            addPreferencesFromResource(R.xml.preference);

        }
    }
}

R.id.pager is only a simple viewPager layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager
android:id="@+id/pager"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

my preference xml:
<?xml version="1.0" encoding="utf-8"?>

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <CheckBoxPreference
        android:key="pref_sync"
        android:title="Sync?"
        android:summary="Do u wanna sync?"
        android:defaultValue="true" />

</PreferenceScreen>

I'm still quite new to android so any help would be awesome!! Thanks!!
EDIT:
Problem solved in comments of correct answer

A: You have to call setContentView(R.layout.view_pager_layout) before
getFragmentManager().beginTransaction().replace(R.id.pager, new SettingsFragment()).commit();


text:
Q: Color and efficient vector graphics I want to use complex monocolor vector graphics but I would like to be able to specify the color inside my latex source. Solutions :

*

*Use a pdf, but I can't specify the color afterwards. Perhaps a solution with svg ?

*Use tikz, but it makes my compilation so slow as it needs to parse the complex paths again each time I use one of those graphics !

*Use tikz+\savebox, as my graphics have a lots of complexity, but there are only a few different of them that I use a lots of time.

Here is my question : can I use \savebox to save some tikz operations with a custom color that will be specified only when I use \usebox ?
My wish would be to have a command \mygraphics that takes one argument the color such that \mygraphics{blue} and \mygraphics{red} typeset my graphic in blue or in red without parsing my graphic each time.

A: It seems to me there is a fourth solution using both an external pdf and tikz. You could compile the tikz using the "standalone" class, an example of such code is given here, then include the obtained pdf in your main document. The compilation would then be fast while keeping full control over the graph.

A: Ok, I finally found what I need in programming-in-tikz. Soft paths allow to compute a path and save it for later, using it with different fill, stroke, ...


text:
Q: extending permutation algorithm (including duplicates) I m looking for an algorithm that give all possible combinations of letters
Let me explain better. If i have
base-letters = ["a","b","c"];
depth = 2; //max chars allowed

then the expected result would be these 12 elements (3^1 + 3^2 = 12):
["a", "b", "c", "aa","ab","ac","ba","bb","bc","ca", "cb", "cc"]

If i had a depth value = 3, i would expect (3^1) + (3^2) + (3^3) = 39 elements
["a", "b", ... , "aa", "ab", ... , "aaa", "aab", ..., "aba", ...]

Now, if i understood correctly permutation algorithm is similar, but doesn't consider duplicated letters (like "aa","bb","aab", "aba"), and the variable depth value (it could be different then base-letters length).

A: You can define a recursive function F(s) which takes a string s of length less than or equal to your maximum length, and start by calling F(s) with s equal to the empty string. The function F computes the length of the string and if it is equal to the maximum length, it prints the string s and returns. If the length of the string is less than the maximum, then F(s) prints out the string s and then iterates over all possible letters in the alphabet and for each letter, it adds the letter to the end of string s to produce a string s' of length one more, and then calls F(s'). This has very low memory usage and is essentially the fastest method possible, at least in asymptotic terms.

A: In Python, use itertools's permutations function (a code recipe is included if you need to translate the code to your native language)
>>> import itertools
>>> base_elements = ['a', 'b', 'cow']
>>> max_depth = 2
>>> result = [''.join(element) for element in itertools.chain.from_iterable([itertools.permutations(base_elements, depth) for depth in range(1, max_depth+1)])]
>>> print(result)
['a', 'b', 'cow', 'ab', 'acow', 'ba', 'bcow', 'cowa', 'cowb']

If you want only unique values, then rather than concatenating the each output element into a string, create a set. This removes duplicates. Then remove duplicates from the final set.
>>> result = frozenset([frozenset(element)
                        for element in itertools.chain.from_iterable(
                          [itertools.permutations(base_elements, depth)
                           for depth in range(1, max_depth+1)]
                        )])

Or more cleanly,
def permutations(base_elements, max_depth):
    result = set()
    for depth in range(1, max_depth+1):
        for element in itertools.permutations(base_elements, depth):
            result.add(frozenset(element))
    return result

A: It seems this code will give you what you need:
def all_strs(iterable, depth):
    results = []
    if depth==1:
        for item in iterable:
            results.append(str(item))
        return results
    for item in iterable:
        for s in all_strs(iterable, depth-1):
            results.append(str(item) + s)
    return results

if __name__ == "__main__":
    print all_strs('abc', 2)
    print all_strs([1, 2, 3], 3)

    s = 'abc'
    results = []
    for i in range(len(s)):
        results += print all_strs(s, i+1)
    print results

the output is:
['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc']
['111', '112', '113', '121', '122', '123', '131', '132', '133', '211', '212', '213', '221', '222', '223', '231', '232', '233', '311', '312', '313', '321', '322', '323', '331', '332', '333']
['a', 'b', 'c', 'aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc', 'aaa', 'aab', 'aac', 'aba', 'abb', 'abc', 'aca', 'acb', 'acc', 'baa', 'bab', 'bac', 'bba', 'bbb', 'bbc', 'bca', 'bcb', 'bcc', 'caa', 'cab', 'cac', 'cba', 'cbb', 'cbc', 'cca', 'ccb', 'ccc']


text:
Q: How to extract contacts and emails from an OST file? Recently my Outlook 2016 client failed on me and a number of my saved outlook data files became corrupt. I was able to add the active online accounts back into outlook with no problem, but, all the offline accounts I could not which are mainly backups files.
I managed to track all of my backup files which have been saved in .ost format, couldn't find any .pst. I have managed to open the .ost files using "SysTools OST Viewer v.4.2" which has allowed me to just VIEW all my emails, can't seem to do anything else with it.
What will be the best way to add these .ost files back into outlook?


text:
Q: How to ignore everything except a folder and all it's subfolders / contents in git In my .gitignore I have:
*
!file.txt
!folder1
!folder1/
!folder1/*

This almost does what I want except whenever I add something beyond one folder past folder/ it does not get committed. For instance folder1/test/folder2/test.txt will not be committed.  Is there any way to fix this without adding endless * to my .gitignore?

A: EDIT:
I kept playing with this, and here is a shorter version
/*          # ignore everything in root
!/folder1   # except folder1

ORIGINAL:
Give this a shot
*
!folder1
!folder1/**

From gitignore documentation:

Two consecutive asterisks ("**") in patterns matched against full
  pathname may have special meaning:
...

*

*A trailing "/**" matches everything inside. For example, "abc/**" matches all files inside directory "abc", relative to the
  location of the .gitignore file,
         with infinite depth.

  ...


text:
Q: Read a list of dictionaries with a list of dictionaries contained within, Python I have a file that contains a list of dictionaries that each contain another list of dictionaries. As an example say the list is customers and the list within the customer dictionary is a shopping cart like this:
[{"id":11,"name":"Jane Doe","cart":[{"name":"milk","cost":3},{"name":"apple","cost":2}]},{"id":04,"name":"John Smith","cart":[{"name":"cake","cost":4},{"name":"chips","cost":1}]}]

What is the best way to read this in and parse out the data?

A: That's a JSON file. Use the json module


text:
Q: Tools to manage Windows Azure Active Directory users Other than the Azure Portal, are there any tools to manage users in a Windows Azure Active Directory?

A: There are several options, each has its pros and cons depending on your requirements:

*

*The 'Azure Active Directory' section of the Azure portal

*The 'Users' section of the Office 365 portal

*The Azure AD PowerShell modules: MSOnline (v1) or AzureAD (v2) (scripting)

*The Microsoft Graph API (programmatic access)

*The Azure AD Graph API (programmatic access)

Note: If you have Active Directory on-premises and are synchronizing to your Azure Active Directory tenant, I guess that could also be viewed as a management tool.

A: As things stand there are no useful tools from Microsoft to manage WaaD outside code/scripting.
There is a WaaD portal but its about to be retired (if it hadn't been already) and I haven't seen any announcement about a replacement.
One can also use the O365 admin portal to manage O365 related tenant, but, like the Azure management portal, this provides access to more that just managing the WaaD tenant.


text:
Q: Best way to restrict actions (edit/delete) with Ruby on Rails and Devise I am fairly new to Ruby On Rails and right now I am doing a simple app. In this app a user can create many items and I use devise for authentication. Ofcourse I want to make sure that you are the owner in order to delete items (Teams, Players etc) and the way I do it now is:
def destroy
    @team = Team.find(params[:id])
    if current_user.id == @team.user_id
      @team.destroy
      redirect_to(teams_url, :notice => 'The team was deleted.')
    else
      redirect_to root_path
    end
end

Is this the best way? I was thinking about putting a method in the model but I am not sure I can access current_user from there. I was also thinking about a before_filer, something like:
before_filter :check_ownership, :only => [:destroy, :update]

I that case and if I want to code only one method for all objects (all objects this relates to have a "user_id"-field)

A: In my application controller I put:
before_filter :authorize

def authorize
  false # Or use code here to check if user is admin or not
end

Then I override the authorize method in my actual controller to allow access to various actions.

A: You're looking for an authorization solution on top of your authentication (devise)
You can't access current user in the model no.  I've had a fair amount of success using Makandra's Aegis for authorization.  It allows you to create roles specify permissions attributed to each role.  The docs are pretty good and I know it works fine with Devise, it's pretty agnostic that way, I've also used it with Clearance.  It also passes an implicit "current_user" to your permissions so you can specify and check that your current user can take appropriate actions.


text:
Q: Is a graph database better for shortest paths algorithms? My objective is to write a shortest path algorithm for a road network.
Currently my architecture is something like that: I store all the data in the PostGIS enabled PostgreSQL database. I do one SELECT * FROM ways, which takes less than 3 seconds on a table with 100,000 edges (ways) and after that I will apply a (Java, Ruby or anything-based) shortest path algorithm to the graph that already resides in memory. The second operation can take about 1.5 seconds on a graph with 100,000 edges.
So, it takes:

*

*2-3 seconds to load all the ways from the database into memory and create a graph (nodes are stored in one table with ways(edges));

*1-1.5 seconds to calculate a shortest path on a graph which is already in memory.

This is very similar to what pgRouting does (to my knowledge it uses C Boost to store the graph in memory), except pgRouting takes about 2 seconds in total to compute a shortest path on the same data set (yes, it is fast, but it is a black box for me, so I need my own).
But recently I found about Graph databases and about Neo4j. On their site they claim that "Still being able to do these calculations in sub-second speeds on graphs of millions of roads and waypoints makes it possible in many cases to abandon the normal approach of precomputing indexes with K/V stores and be able to put routing into the critical path with the possibility to adapt to the live conditions and build highly personalized and dynamic spatial services.".
So the question is: Will a graph database be faster with my particular problem?
The problem has the following properties:

*

*the database consists of one table (ways);

*the only query to the database is to get all the ways into the memory (to build a graph);

*I do not need scalability, i.e. it is likely that the graph will not grow.

A: You certainly dont have to reinvent the wheel if you are using any graph database, like Neo4j. Many shortest path algorithms are built into this and it's designed to handle complexity in case you have to consider speed limitation in any specific road, one-way road, score of a road etc. How do you keep up with performance when your data grows 10 times, or, 100 times. Considering your total computation time 3sec for 100,000 ways, it can be in minutes for 1M ways and in Neo4j, the response will be in milli sec.

A: The breakthrough with graph databases is not only performances, it more about concept: your routing algorithms deal with single relational graphs (that is graph were links are all of the same type) whereas with graphdatabases you have a multi-relational graph.
This enables you to compute the shortest path between nodes taking only a specific kind of edge or avoid another type.
For more information you should read about the algebra behind graph db and the concept of pipes.
I strongly recommend thinkerpop project to start with graph database.

A: I don't have experience with "graph" databases but judging by your question i have a few things in mind.
First of all, the straightforward answer will be "Create such a graph database and do a performance comparison with your solution". You could measure memory usage, execution time (speed), cpu utilization and/or possibly other metrics. That would provide you with enough data to make your decision.
My other advice is to revise your method. The three problem properties that you described (one table, loading all paths & no need for scalability) apply in your current domain but not in the graph databases' one. It's a whole different programming paradigm and you might have to adjust and adapt your method to suit the domain of those special kind of databases. It is unreasonable to do performance or any other kind of comparisons if you're applying your standard approach in a non-standard environment (like that graph database).
Recap: Translate your problem to the terms of the graph database and model it accordingly. After doing that, do a performance comparison between the two solutions.
My bet is, assuming that you translated & modeled your problem suitably for the graph database, it will grant you better performance. Your classical approach of "store-read-sort" is simple but not that effective unless optimized aggressively.

A: A graph database probably won't load all of your data into memory initially, but over time, as good ones are designed to deal with extremely large datasets. However, once the data is there, the graph database has to do less work that the relational database to traverse the links. This is because it can directly access related objects using their identities, rather than having to use B-tree indices and (possibly) a join table, so it should be faster once the nodes and edges are cached.


text:
Q: Git Automatically push to Dev and Production from Central Repository depending on branch pushed I am somewhat new to Git only and I have only used it for basic projects with simple setups. Now I am struggling to wrap my head around a more complex setup. I have been up all night Googling but I can't find anything related to how I want to set this up.
I have three servers on my network: one for development (dev.example.com), one for production (www.example.com), and another that acts a central stage between the two (central.example.com).
I want to create a main (probably bare) Git repository on Central that I can push to from my local machine (which is separate from the three main servers but on the same network). Ideally, this repo would have two branches: master and Development. My local machine will only deal with this repo on Central.
When I push to the dev branch on Central, Central should then push those changes to the DEV server. Likewise, changes to the master branch should be pushed to WWW. I think using a commit/update hook would be the best way to accomplish this.
Here is a crudely drawn diagram:
 Local
   |
 Central
  /   \
DEV   WWW

Could someone kindly point me in the right direction? Thanks!

A: You have to use post-update or post-receive hook; they are the ones that run after push to the repository completes. The only difference between them is how they get the arguments.
Than I'd suggest using an ssh trigger to the production/staging server tu run a pull from there, because:

*

*You need to run some code there anyway, because push in git does not support checking the pushed version out on the remote end. So you'd need another hook there.

*Running a push there means allowing push access there and that means one more thing to secure. On the other hand the ssh trigger will have hardcoded branch to pull, so nobody can do any harm with it unless the central repository is also compromised and more importantly, even if it is, potential harm is only limited to tricking it to pull bad version, but no data can be deleted an no access to the rest of the computer may be gained.

An ssh trigger is a script, that is associated with particular public key in ssh (prefix the public key in .ssh/authorized_keys with command=trigger). When you log in with ssh using that key, ssh will ignore command provided by client and run the trigger. This limits possible damage when somebody steals the key, because the trigger can use it's own logic to know what to do and not accept any input from the client.
Alternatively you can simply push and install appropriate hook to check out. See this question.

A: You can setup hooks in Git to easily get what you want here. Make use of post-receive hook, which receives the following from stdin:
<oldrev> <newrev> <refname>
Example:
aa453216d1b3e49e7f6f98441fa56946ddcd6a20 68f7abf4e6f922807889f52bc043ecd31b79f814 refs/heads/master
Using the refname you can see in your script what branch is being pushed to and inturn push to the appropriate repo - www or dev.
Or, you can use the post-update hook which receives only refname and also as an argument  to do the same thing.
For sake of completeness, the hook must be placed in the hooks of the Central repo.


text:
Q: How to set Dynamically UITableView height in Swift? How to set Tableview height dynamically like in android. i tried with following code, but its not working.
 tblHeightConstraint.constant = downSelectionTbl.contentSize.height

see this below link i tired upvote answers even though its not resolved my issue.

iOS: Dynamically set UITableView height in Swift

A: Do like this,
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    tblHeightConstraint.constant = downSelectionTbl.contentSize.height
}