Q:

Vertical alignment in table: m-column, row size - problem in last column

Unfortunatly, I have a problem with m-columns (array package) in tables with adjusted row height. Somehow in the last column (only there) the text is not centered vertically.
Check it out:

\documentclass{article}
\usepackage{array}

\begin{document}

\begin{tabular}{|m{0.18cm}|m{0.18cm}|m{0.18cm}|}
\hline
a & b & c  \\[2ex]
\hline
0 & 0 & 0  \\
\hline
\end{tabular}

\end{document}

A:

In my opinion, it is a bug and should be reported. Tweak for the impatient: add one extra column with zero width and no padding. Remember to pre-pend \\ with & on the problematic lines!
\documentclass{article}
\usepackage{array}

\begin{document}

\begin{tabular}{|m{0.18cm}|m{0.18cm}|m{0.18cm}|@{}m{0pt}@{}}
\hline
a & b & c &\\[2ex]
\hline
0 & 0 & 0 \\
\hline
\end{tabular}

\end{document}

A:

The question as well as the answer by @tohecz indicate that there is at least one fundamental misconception about what the preamble tokens "m", "b", etc. do and how this relates to \\ and its optional argument.
The "m" token is not centering its material vertically in the available space!
The tokens "c", "l" and "r" produce horizontal cells (one line high) and their alignment point vertically is just the baseline of each cell.
Now "p", "m" and "b" generate cells of a certain width and possibly several lines. Their vertical alignment  is the first line, the middle of the box and the bottom line, respectively. So if we modify the example a bit and run:
\begin{tabular}{|p{0.18cm}|m{0.18cm}|b{0.18cm}|l|}
\hline
a\newline a & b\newline b & c\newline c\newline c& d \\
\hline
\end{tabular}

and what we get is

So this is all positioned relative to the baseline of the cell containing "d".
Now the optional argument of \\ only extends the space from the alignment point downwards it is not extending the size of the actual cells. Furthermore it is not actually adding this space but only making sure that there is at least that amount of space to the next row. So for example, in the above case \\[2ex] would have no effect because the cell in the first column goes further down than this.
So coming back to the original question and its input: because each cell has only a single line they should all line up but the "m" would not have the effect of centering the content in the available space. Instead the extra space requested by \\[2ex] would go after it (or should ... that's the bug).
So let's add an "l" column to avoid the bug and see what happens:
\begin{tabular}{|m{0.18cm}|m{0.18cm}|m{0.18cm}|l|}
\hline
a & b & c & d \\[2ex]
\hline
a\newline a & b & c & d \\[2ex]
\hline
\end{tabular}

Result is

The first row shows that "m" and "l" sit side by side if the "m" has only a single line inside and that the 2ex is between the baseline and the next row.
The second line has an "m" with 2 lines inside and there you see again that the 2ex goes from the row baseline to the next row and "m" is not vertically centered either.
So the suggestion to use an extra (kind of hidden row) like
\begin{tabular}{|m{0.18cm}|m{0.18cm}|m{0.18cm}|@{}m{0pt}@{}}
\hline
a & b & c &             x\\[4ex]   % x normally being a space
\hline
a\newline a & b & c &   x\\[4ex]
\hline
\end{tabular}

is actually making use of the current bug, i.e., the "space" in that hidden question is actually pushed upwards so that the visible rows now appear more or less centered (which I made visible by putting in an "x" above):

So the moment this would get fixed the above trick no longer works.
So what is the bug?
The issue is very subtle. To make a table with rules work it is not possible to vertically skip downwards on \\[2ex], instead what happens is that in one of the row an invisible rule/box is placed that has a depth extending the normal depth by 2ex. If you don't do this then any vertical rule gets a disruption in places where you add additional vertical space.
The downside of this is, that if a row has an unusual depth, any such exstra space may come out short because it is measured in relation to the "normal" depth.
In addition and that is the "bug" in array putting this invisual strut at the end of the material in the last row, simply goes wrong for m-columns as they are vertically centered. Thus here you see the "c" moving upwards as the strut ends up in some sort of $\vcenter{... c \strut}$ instead of $\vcenter{... c}$\strut.
The reason for this is the strange behavior of the underlying \halign mechanism of TeX that is used to build tables: when we reach \\[2ex] LaTeX has processed $\vcenter{... c but not yet seen the remaining material that forms the column, i.e., }$.
So \\[ex] calculates and adds the strut and then tells TeX that the column is finished (using \crinternally) and that results in TeX copying the remaining part of the column template (}$...plus space and rule) into the input stream and bingo you end up with the strut inside vcenter.
A possible fix would be to delay the strut placement to ensure that this happens only in the right part of the column template. That in turn is a bit tricky as by that time scoping will have changed values back etc. So this needs to be a global operation.
\documentclass{article}
\usepackage{array}

\makeatletter
\def\@classz{\@classx
   \@tempcnta \count@
   \prepnext@tok
   \@addtopreamble{\ifcase \@chnum
      \hfil
      \d@llarbegin
      \insert@column
      \d@llarend\fmi@fix \hfil \or
      \hskip1sp\d@llarbegin \insert@column \d@llarend\fmi@fix \hfil \or
      \hfil\hskip1sp\d@llarbegin \insert@column \d@llarend\fmi@fix \or
   $\vcenter
   \@startpbox{\@nextchar}\insert@column \@endpbox $\fmi@fix
    \or
   \vtop \@startpbox{\@nextchar}\insert@column \@endpbox\fmi@fix \or
   \vbox \@startpbox{\@nextchar}\insert@column \@endpbox\fmi@fix
  \fi}\prepnext@tok}

\def\@mkpream#1{\gdef\@preamble{}\@lastchclass 4 \@firstamptrue
   \let\@sharp\relax \let\@startpbox\relax \let\@endpbox\relax
   \let\fmi@fix\relax
   \@temptokena{#1}\@tempswatrue
   \@whilesw\if@tempswa\fi{\@tempswafalse\the\NC@list}%
   \count@\m@ne
   \let\the@toks\relax
   \prepnext@tok
   \expandafter \@tfor \expandafter \@nextchar
    \expandafter :\expandafter =\the\@temptokena \do
   {\@testpach
   \ifcase \@chclass \@classz \or \@classi \or \@classii
     \or \save@decl \or \or \@classv \or \@classvi
     \or \@classvii \or \@classviii
     \or \@classx
     \or \@classx \fi
   \@lastchclass\@chclass}%
   \ifcase\@lastchclass
   \@acol \or
   \or
   \@acol \or
   \@preamerr \thr@@ \or
   \@preamerr \tw@ \@addtopreamble\@sharp \or
   \or
   \else  \@preamerr \@ne \fi
   \def\the@toks{\the\toks}}

\def\@xargarraycr#1{\gdef\fmi@fix
 {\@tempdima #1\advance\@tempdima \dp\@arstrutbox
  \vrule \@depth\@tempdima \@width\z@\global\let\fmi@fix\relax}\cr}
\let\fmi@fix\relax

\makeatother

\begin{document}

\begin{tabular}{|m{0.18cm}|m{0.18cm}|}
\hline
a&c \\[2ex]
\hline
0& 0  \\
\hline
\end{tabular}

\end{document}

As I said this is rather delicate so I'm not sure it is safe to make that type of change without breaking a lot of other stuff (after all array is a really old package (25+ years) which is used quite a lot and that issue is in there from the beginning.
Anyway with the above change we now get:

which is what we should but perhaps not what people hoped when they thought they specify an "m" column.
Update
As of 2018-04 release of LaTeX (or even one release earlier) the actual bug has now been corrected as outline above. That means (unfortunately) that the trick suggested above and marked as the correct answer is not longer working, but as I explained it was based on a wrong assumption of what the specification of "m" is.


Q:

UDP TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'

I'm completely newbie to python and computer networking. While working on Uni project I have faced a problem. What am I doing wrong? Any help will me much appreciated.
Here is server side:
import socket

def Main():
    host = "127.0.0.1"
    port = 5000

    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind((host, port))

    print ("Server Started.")
    while True:
        data, addr = s.recvfrom(1024)
        print ("message from: ") + str(addr)
        print ("from connected user: ") + str(data.decode('utf-8'))
        data = str(data).upper()
        print ("sending: ") + str(data)
        s.sendto(data, addr)

    s.close()

if __name__ == '__main__':
    Main()

Here is my client side:
import socket

def Main():
    host = "127.0.0.1"
    port = 5000

    server = ('127.0.0.1', 5000)

    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind((host, port))

    message = input('->')
    while message != 'q':
        s.sendto(message.encode('utf-8'), server)
        data, addr = s.recvfrom(1024)
        print ('Received from server: ') + str(data)
        message = input('->')
    s.close()

if __name__ == '__main__' :
    Main()

A:

There were a couple of issues; mostly with the printing.
You had a few instances of print('some text') + str(data); this won't work, because while print() outputs to the screen (STDOUT) it returns None, so what you were actually doing was trying to concatenate None + str(data)
What you need is print('some text' + str(data)).
Additionally, there was as issue on the server-side where you echo the data received from the client back to the client- it needed to be re-encoded as a bytearray (it comes in as a bytearray, gets converted to a utf-8 string for display, it needs to go back to bytearray before replying).
In summary, server:
import socket

def Main():
    host = "127.0.0.1"
    port = 5000

    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind((host, port))

    print("Server Started.")
    while True:
        try:
            data, addr = s.recvfrom(1024)
            print("message from: " + str(addr))  # moved string concatenation inside print method
            print("from connected user: " + str(data.decode('utf-8')))  # moved string concatenation inside print method
            data = str(data).upper()
            print("sending: " + str(data))  # moved string concatenation inside print method
            s.sendto(data.encode('utf-8'), addr)  # needed to re-encode data into bytearray before sending
        except KeyboardInterrupt:  # added for clean CTRL + C exiting
            print('Quitting')
            break

    s.close()

if __name__ == '__main__':
    Main()

And the client:
import socket

def Main():
    host = "127.0.0.1"
    port = 5001

    server = ('127.0.0.1', 5000)

    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind((host, port))

    message = input('->')
    while message != 'q':
        try:
            s.sendto(message.encode('utf-8'), server)
            data, addr = s.recvfrom(1024)
            print('Received from server: ' + str(data))  # moved string concatenation inside print method
            message = input('->')
        except KeyboardInterrupt:  # added for clean CTRL + C exiting
            print('Quitting')
            break

    s.close()

if __name__ == '__main__':
    Main()


Q:

Decomposition of a signal to slow and fast components

I am currently recording biological responses which are triggered by different events. The figure below shows the original signal (black) and the occurrence of input events (colored dots). There is typically few seconds of a delay in  response to different events, and only some of the events generate a response. These phasic responses occur simultaneously with slowly changing fluctuations (tonic component), which are also biologically important (rather than measurement noise). So it is important to come up with a model that can decompose these signals with few constraints that are biologically plausible: signal = tonic + phasic.
In this system, phasic responses can be well modeled with typical linear system characterization methods based on impulse response function. Also note that, these phasic responses are always positive, that is biologically speaking there is no inhibition. For this reason, if there were no slow fluctuations in the recordings, the recorded signal would never go below zero, except for measurement noise.
What is more problematic is to account for baseline shifts (the tonic component). I would like to come up with a method that can be used to model the tonic component and phasic responses simultaneously based on the following assumptions:
1/ tonic component changes slowly.
2/ phasic component changes fast.
3/ phasic component is always positive, that is: signal - tonic should contain as negative values as possible.
The problem boils down to extracting slow and fast components of a signal. I have already 4 methods in mind, and I would like to see what you think is best suited or come up with an alternative.
The first thing that comes to mind is to low-pass filter the signal to obtain an estimation of the tonic component (see blue line). The main problem here is that the estimated tonic component violates the above-mentionned constraint #3. According to this assumption, no points in the recorded signal should be below the tonic component. Instead the tonic component should pass through all the data points where the phasic response is close to zero (schematically shown with the red curve in the figure below).
Another approach would be to make an assumption about the duration of phasic response. In doing so, one could use recorded samples that are at least as far as the duration of phasic response as keypoints and interpolate using cubic splines for the remaining data points. This is actually how I have drawn the red curve, but I feel like the interpolation of data points between the key points is problematic, because there are not many key points.
A third approach would be to work on first or second derivative space and characterize the system in this domain, as it is supposed to be less sensitive to low-variations.
A fourth approach consists of extracting slow components. One could use rely more on the history, when the signal is changing fast, and update the history with new data when the signal changes slowly. I am not sure though how to mathematically tackle this one.

A:

Your problem is pervasive in signal and image processing: being able to separate a trend (with some assumptions) from a signal (with some other assumptions) and potentially additional noise. This is an instance of (semi-)informed source separation: a sine from a drift,  a texture from a cartoon image, a biological information from instrumental artifacts, etc, that requires a more involved modeling and optimization framework.
Your choices are related to fundamental questions related to the model you can build based on physical and mathematical assumptions, aside from the algorithmic tools you can program.
1) Low-pass filtering:
Standard low-pass filtering is linear and time-invariant. Linearity is very consistent with "signal = tonic + phasic". But phasic could be (on theory) negative, as "$2+(-1) = 1$". As your graphic does not include x/y scales, "above" is clear, but i am not sure of what you can model with "no points in the recorded signal should be below the tonic component", since additional noise can be fluctuating too. But positivity is a property which can be taken into account, with some non-linearity caveats.
2) Duration:
"that are at least as far as the duration of phasic response" : your assumption seems to me to related to a time-delay, yet i cannot interpret it precisely so far.
3) High-order derivatives:
"A third approach would be to work on first or second derivative space and characterize the system in this domain, as it is supposed to be less sensitive to low-variations" Indeed, slow variations are expected to be with limited derivatives. This could result in a "sparsity" prior assumption.
4) Causality: "rely more on the history" there is some causality assumption behind that. This too is a tough stuff.
All your four approaches seem consistent to me, and may help you ponder and state your assumptions. They are otherwise termed as “morphological component analysis (MCA)”, “geometric separation” or “clustered sparsity”, adding positivity. Such topics are addressed for instance in "Blind source separation of positive and partially correlated data" http://dx.doi.org/10.1016/j.sigpro.2005.03.006.
You may find additional history for instance in the introduction of (mong other papers "Chromatogram baseline estimation and denoising using sparsity (BEADS)"
http://dx.doi.org/10.1016/j.chemolab.2014.09.014
which also deals with positivity, low-pass-filtering and derivative sparisty, yet the causal approach is not considered. So you can specify your model in more precise terms (you did do talk about the noise yet), you may find some tracks to solve your questions


Q:

Prevent Git from changing permissions on pull

When I pull change from my repositories, Git change the file permissions (actually, he change the group write permission).
If I'm correct, Git should only track executable bit and this anyway can be removed using setting core.filemode to false.
But, although the filemode is set to false (in local, global and user), when I pull, write permission constantly change.
I could use a git-hooks in order to reset correct chmod, but this is some overhead and I'd prefer if there's a way to just ask git to completly ignore file mode change.
Anyone know how to achieve this ?

A:

One config setting that might help here is core.sharedRepository, presented in the blog post "Preserving Group Write on Git Objects in a Collaborative Repository":

The solution turned out to be fairly straightforward.
  In the file .git/config, I added a line that read: "sharedRepository = group", like so:
[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    sharedRepository = group

Thereafter, new files in .git/objects were created with the proper permissions for group write.
  (However, note that new files are group-owned by the primary group of the user account via which the push was received. If the users collaborating on the project have different primary groups, and if those users do not share membership in that set of groups, you may still run into problems.)

Make sure of the value of your umask:

Example: 0660 will make the repo read/write-able for the owner and group, but inaccessible to others (equivalent to group unless umask is e.g. 0022).

A:

The solution I use is to run the command as the user that has the permissions you want to keep:
sudo -u user command

In this case, it could be:
sudo -u www-data git pull

www-data being the apache default user on Ubuntu at least.
This keeps the permissions from changing. I use it when updating git repositories on my VPS, while keeping the file permissions set to the webserver user.


Q:

How can I make SKSpriteNode positions the same for any simulator/device?

In my game, the position of my SKNodes slightly change when I run the App on a virtual simulator vs on a real device(my iPad).
Here are pictures of what I am talking about.
This is the virtual simulator
This is my Ipad
It is hard to see, but the two red boxes are slightly higher on my iPad than in the simulator
Here is how i declare the size and position of the red boxes and green net:
The following code is located in my GameScene.swift file
func loadAppearance_Rim1() {
Rim1 = SKSpriteNode(color: UIColor.redColor(), size: CGSizeMake((frame.size.width) / 40, (frame.size.width) / 40))
Rim1.position = CGPointMake(((frame.size.width) / 2.23), ((frame.size.height) / 1.33))
Rim1.zPosition = 1
addChild(Rim1)
}

func loadAppearance_Rim2(){
    Rim2 = SKSpriteNode(color: UIColor.redColor(), size: CGSizeMake((frame.size.width) / 40, (frame.size.width) / 40))
    Rim2.position = CGPoint(x:  ((frame.size.width) / 1.8), y: ((frame.size.height) / 1.33))
    Rim2.zPosition = 1
    addChild(Rim2)
}
func loadAppearance_RimNet(){
    RimNet = SKSpriteNode(color: UIColor.greenColor(), size: CGSizeMake((frame.size.width) / 7.5, (frame.size.width) / 150))
    RimNet.position = CGPointMake(frame.size.width / 1.99, frame.size.height / 1.33)
    RimNet.zPosition = 1
    addChild(RimNet)
}
func addBackground(){
    //background
    background = SKSpriteNode(imageNamed: "Background")
    background.zPosition = 0
    background.size = self.frame.size
    background.position = CGPoint(x: self.size.width / 2, y: self.size.height / 2)
    self.addChild(background)
}

Additionally my GameViewController.swift looks like this
import UIKit
import SpriteKit

class GameViewController: UIViewController {

var scene: GameScene!

override func viewDidLoad() {
    super.viewDidLoad()

    //Configure the view
    let skView = view as! SKView
    //If finger is on iphone, you cant tap again
    skView.multipleTouchEnabled = false

    //Create and configure the scene
    //create scene within size of skview
    scene = GameScene(size: skView.bounds.size)
    scene.scaleMode = .AspectFill
    scene.size = skView.bounds.size
    //scene.anchorPoint = CGPointZero

    //present the scene
    skView.presentScene(scene)

}

override func shouldAutorotate() -> Bool {
    return true
}

override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
    if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
        return .Landscape
    } else {
        return .All
    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Release any cached data, images, etc that aren't in use.
}

override func prefersStatusBarHidden() -> Bool {
    return true
}
}

How can I make the positions of my nodes be the same for each simulator/physical device?

A:

If you are making a Universal application you need to declare the size of the scene using integer values. Here is an example:
scene = GameScene(size:CGSize(width: 2048, height: 1536))

Then when you initialize the positions and sizes of your nodes using CGPoint and CGSize, make them dependant on SKScene size. Here is an example:
node.position = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2)

If you declare the size of the scene for a Universal App like this:
scene.size = skView.bounds.size

then your SKSpriteNode positions will be all messed up. You may also need to change the scaleMode to .ResizeFill. This worked for me.


Q:

TD contenteditable with autocomplete bootstrap 3

I spend my whole day for searching any autocomplete lib that support contenteditable. The closest that I found is jQuery UI which I tried but it conflicts with Bootstrap 3( this is only my guess i'm not really sure ).
Is there any lib that will allow me to do this?
Note: if it is related I'm also using dataTables
I will really appreciate it if someone give me a working example with this fiddle ready

A:

On mouse click of any td why don't you dynamically add an input tag inside td. Which can make your cell editable.
If you are trying to implement something similar to excel data grid, try this:
suppose each cell (td) of your grid has a class - "cell" then,
$('.cell').click(function(){
   var text = $(this).text();
   $(this).html("
"+text+"
");
});

I added class "editable" so that you can add any styling to it if required.
To move to next cell on tab you either need to bind 'keydown' and do the required action for tab or use tabindex property if your grid is made of divs


Q:

Remove Binary while Waiting for Review

I have just uploaded a binary file for review.
The status for my app now is Waiting for Review. But i discovered a bug which i should fix it before submitting but i can't find where the remove binary is located.
The last submit, it was under the Version section, But now it is just disappeared!!
I have tried lot of research and all refers to the old iTunes design, and just found 1 solution which was under the version tab which is not found in my case now.
Does anyone know where is it now with all these changes made by iTunes every day? or it is delayed more than 1 hour to appear ?
Thank you

A:

I met the same problem and could not found where to Reject the binary.
Finally I downloaded an iTunes Connect app from App Store and rejected the binary by it.


Q:

MySQL won't start after reboot. Exiting with signal 11

last night I was doing a server maintenance that required DB reboot.
No changes in a config were made.
Current setup is as follows:
master (server1) - master (server2) and slave (server0)
MySQL version: mysql-5.5.32
server0 and server1 started fine after a reboot but when i try to start server0 it crashes with signal 11 error:
Here's the log output:
140604 03:10:08 mysqld_safe Starting mysqld daemon with databases from /opt/mysql/mysql_data
140604  3:10:08 [Note] Plugin 'FEDERATED' is disabled.
140604  3:10:08 InnoDB: The InnoDB memory heap is disabled
140604  3:10:08 InnoDB: Mutexes and rw_locks use GCC atomic builtins
140604  3:10:08 InnoDB: Compressed tables use zlib 1.2.3
140604  3:10:08 InnoDB: Using Linux native AIO
140604  3:10:08 InnoDB: Initializing buffer pool, size = 32.0G
140604  3:10:10 InnoDB: Completed initialization of buffer pool
02:10:10 UTC - mysqld got signal 11 ;
This could be because you hit a bug. It is also possible that this binary
or one of the libraries it was linked against is corrupt, improperly built,
or misconfigured. This error can also be caused by malfunctioning hardware.
We will try our best to scrape up some info that will hopefully help
diagnose the problem, but since we have already crashed,
something is definitely wrong and this may fail.

key_buffer_size=67108864
read_buffer_size=8388608
max_used_connections=0
max_threads=2000
thread_count=0
connection_count=0
It is possible that mysqld could use up to
key_buffer_size + (read_buffer_size + sort_buffer_size)*max_threads = 49240442 K  bytes of memory
Hope that's ok; if not, decrease some variables in the equation.

Thread pointer: 0x0
Attempting backtrace. You can use the following information to find out
where mysqld died. If you see no messages after this, something went
terribly wrong...
stack_bottom = 0 thread_stack 0x40000
/usr/local/mysql/bin/mysqld(my_print_stacktrace+0x35)[0x7a2825]
/usr/local/mysql/bin/mysqld(handle_fatal_signal+0x403)[0x670b43]
/lib/x86_64-linux-gnu/libpthread.so.0(+0xf030)[0x7f1c2db0e030]
/usr/local/mysql/bin/mysqld[0x93ec38]
/usr/local/mysql/bin/mysqld[0x8328d2]
/usr/local/mysql/bin/mysqld[0x861511]
/usr/local/mysql/bin/mysqld[0x7f302f]
/usr/local/mysql/bin/mysqld[0x7c40dd]
/usr/local/mysql/bin/mysqld(_Z24ha_initialize_handlertonP13st_plugin_int+0x48)[0x673948]
/usr/local/mysql/bin/mysqld[0x58307a]
/usr/local/mysql/bin/mysqld(_Z11plugin_initPiPPci+0xb5d)[0x586c9d]
/usr/local/mysql/bin/mysqld[0x507bab]
/usr/local/mysql/bin/mysqld(_Z11mysqld_mainiPPc+0x3e2)[0x508772]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xfd)[0x7f1c2ccccead]
/usr/local/mysql/bin/mysqld[0x4fe17a]
The manual page at http://dev.mysql.com/doc/mysql/en/crashing.html contains
information that should help you find out what is causing the crash.
140604 03:10:10 mysqld_safe mysqld from pid file /opt/mysql/mysql_data/odb2.pid ended

After that I started mysql with innodb_force_recovery = 1 and server started ok.
Looking at the documentation:

*1 (SRV_FORCE_IGNORE_CORRUPT) Let the server run even if it detects a corrupt page. Try to make SELECT * FROM tbl_name jump over corrupt
  index records and pages, which helps in dumping tables.*

So my next step was to run mysqlcheck on all databases but no errors were found.
Any ideas how to bring that server to life? I have a backup of all databases (~300GB) but restoring it would take a considerable amount of time and if possible I'd like to avoid that

A:

Turns out it was a bug introduced in 5.5.32  http://bugs.mysql.com/bug.php?id=69623 where MySQL fails to open a second tablespace if stored in more than 1 file.
Update to 5.5.39 solved the issue


Q:

Iterate thru ec2 describe instance boto3

I am trying to get specific values for a describe instance call. So for example, if I want to get the 'Hypervisor' value or the Ebs has 'DeleteOnTermintation' value from the output. Below is the current code I am currently using to make the call and iterate thru the dictionary output.
import boto3
import pprint
from datetime import datetime
import json

client = boto3.client('ec2')

filters = [{
'Name': 'tag:Name',
'Values': ['*']
}]

class DatetimeEncoder(json.JSONEncoder):
  def default(self, obj):
    if isinstance(obj, datetime):
        return obj.strftime('%Y-%m-%dT%H:%M:%SZ')
    elif isinstance(obj, date):
        return obj.strftime('%Y-%m-%d')
    # Let the base class default method raise the TypeError
    return json.JSONEncoder.default(self, obj)

output = json.dumps((client.describe_instances(Filters=filters)), cls=DatetimeEncoder)

pprint.pprint(output)

for v in output:
  print v['Hypervisor']

Getting this error:
TypeError: string indices must be integers, not str

Using the pprint to see all the values available from the output.

A:

Here's how you could display the information via the AWS Command-Line Interface (CLI):
aws ec2 describe-instances --query 'Reservations[*].Instances[*].[InstanceId, Hypervisor, NetworkInterfaces[0].Attachment.DeleteOnTermination]'

Here's some Python:
import boto3

client = boto3.client('ec2')

response = client.describe_instances()

for r in response['Reservations']:
  for i in r['Instances']:
    print i['InstanceId'], i['Hypervisor']
    for b in i['BlockDeviceMappings']:
      print b['Ebs']['DeleteOnTermination']

A:

Here's John's answer but updated for Python3
import boto3

client = boto3.client('ec2')

response = client.describe_instances()

for r in response['Reservations']:
    for i in r['Instances']:
        print(i['InstanceId'], i['Hypervisor'])
        for b in i['BlockDeviceMappings']:
            print(b['Ebs']['DeleteOnTermination'])


Q:

Foreach loop array with same array name

What I am trying to do is this:
I want to echo information based on year/month/day.
My code is:
  $data = array(
    "2018" => array(
        "September" => array(
            "02" => array(
                "Line 1"
            ),
            "02" => array(
                "Line 11"
            ),
            "12" => array(
                "Line 2"
            ),
            "31" => array(
                "Line 3"
            )
        ),
        "December" => array(
            "02" => array(
                "Line 11"
            ),
            "12" => array(
                "Line 22"
            ),
            "31" => array(
                "Line 33"
            ),
            "32" => array(
                "Line 66"
            )
        )
    ),
    "2019" => array(
        "May" => array(
            "05" => array(
                "Line z"
            ),
            "15" => array(
                "Line y"
            ),
            "55" => array(
                "Line x"
            )
        )
    )
);

echo '
';
print_r($data);
echo '
';

foreach ($data as $years => $year) {

    echo $years . "
";

    foreach ($year as $months => $month) {

        echo $months . "
";

        foreach ($month as $days => $day) {

            foreach ($day as $key => $value) {
                echo $days . " - " . $value . "
";
            }
        }
    }
}

As you see for 2018 september there are two arrays for the date of 2nd.
I was hoping to see this when print_r
2018
September
02 - Line 1
02 - Line 11
12 - Line 2
31 - Line 3

but instead I get this
2018
September
02 - Line 11
12 - Line 2
31 - Line 3

How can I echo both values of september 2, 2018?

A:

You cannot have duplicate keys. You are defining "02" twice.
Solution: Define "September" as:
    "September" => array(
        "02" => array(
            "Line 1",
            "Line 11"
        ),
        "12" => array(
            "Line 2"
        ),
        "31" => array(
            "Line 3"
        )
    ),


Q:

NetBeans: how to split window and place output panel to the right?

By default NetBeans has projects on the left, open files on the top part of right panel and output/variables/... on the bottom part of the left panel. As a result file panel is wide and tall. Is it possible to reorganize panels, so that "projects" panel is on the left, "open files" panel is on the center and "output/variables/..." panel is on the right?

A:

This can be done much the same way you split the string horizontally. Grub the page tab and move it until you see that the red rectangle indicating alignment appears vertically along the right side of screen. This works in NetBans 8.1 and above.


Q:

If .NET uses mark&sweep GC, why does it cut the memory addresses space in half?

According to MSDN, the .NET framework uses the mark&sweep garbage collection method. The same page also says that on 32bit systems, the address space is 2GB - which means that the address space is cut in half from the 4GB of 32bit systems.
Cutting the available memory in half is a trait of the stop&copy garbage collection method, but .NET uses mark&sweep which can operate on the whole address space - so why does .NET cut the address space in half?

A:

This is Windows, not .NET.  32bit Windows reserved the top 2GB of the address space for the operating system, and restricted applications to 2GB (provided the /3GB flag wasn't used).
Note that, in practice, it's actually worse.  A 32bit .NET application will typically start raising OutOfMemoryException between 1.2 and 1.6GB of RAM usage, even on a 64bit system with plenty of phsyical memory.


Q:

extend a right floating div to the left

I am trying to extend a right floating div to the left.
I have an image and would like to put some text on the right of the image.
EDIT
the goal is that the site stays dynamic. So I can not use a fixed width.
One way would be to use Javascript, I guess but I would prefer to do this in HTML CSS only if possible.
Here is a picture of what I have

And here is a picture of what I would like to have

How can I extend the right div to left ?
Or should I use a div in the middle ?
Here is the HTML

    test
address 1
address2

and the CSS
#logo_container

{
padding: 0px;
overflow: hidden;
zoom: 1;

}

#logo_image

{
float: left;
background-color: transparent;
border: 1px solid red;

}

#logo_address

{
background-color: #0E4194;
color: #FFFFFF;
margin-left: auto;
padding: 0px;
float: right;
border: 1px solid red;
height: 150px;

}

A:

#logo_address
{
background-color: #0E4194;
color: #FFFFFF;
padding: 0px;
textalign: right;
float: left;
border: 1px solid red;
height: 150px;
width: ENTER VALUE HERE;
}

This would be a solution. If you float the #logo_address to the left, align the text to the right and enter a width value it would look as you want.


Q:

Either Remote or Local Sandbox, why not both ?

WRT : http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7e3f.html
Why a flash application can either use Remote  or Local Sandbox . What is the problem if it's using both of them ?
Say a flash application at one time communicating with a local file... and also communicating with some file on the server. Isn't that allowed ?

A:

It is not allowed because of security reasons, if it was allowed to communicate with both you can potentially take files from the users machine and send them to a server on the web.


Q:

Map of mutex c++11

I need to make a thread-safe map, where I mean that each value must be independently mutexed. For example, I need to be able to get map["abc"] and map["vf"] at the same time from 2 different threads.
My idea is to make two maps: one for data and one for mutex for every key:
class cache
{
private:
....

    std::map<std::string, std::string> mainCache;
    std::map<std::string, std::unique_ptr<std::mutex> > mutexCache;
    std::mutex gMutex;
.....
public:
    std::string get(std::string key);

};
std::string cache::get(std::string key){
    std::mutex *m;
    gMutex.lock();
    if (mutexCache.count(key) == 0){
        mutexCache.insert(new std::unique_ptr<std::mutex>);
    }
    m = mutexCache[key];
    gMutex.unlock();
}

I find that I can't create map from string to mutex, because there is no copy constructor in std::mutex and I must use std::unique_ptr; but when I compile this I get:
/home/user/test/cache.cpp:7: error: no matching function for call to 'std::map<std::basic_string<char>, std::unique_ptr<std::mutex> >::insert(std::unique_ptr<std::mutex>*)'
         mutexCache.insert(new std::unique_ptr<std::mutex>);
                                                          ^

How do I solve this problem?

A:

Why do you need to use an std::unique_ptr in the first place?
I had the same problem when I had to create an std::map of std::mutex objects. The issue is that std::mutex is neither copyable nor movable, so I needed to construct it "in place".
I couldn't just use emplace because it doesn't work directly for default-constructed values. There is an option to use std::piecewise_construct like that:
map.emplace(std::piecewise_construct, std::make_tuple(key), std::make_tuple());

but it's IMO complicated and less readable.
My solution is much simpler - just use the operator[] - it will create the value using its default constructor and return a reference to it. Or it will just find and return a reference to the already existing item without creating a new one.
std::map<std::string, std::mutex> map;

std::mutex& GetMutexForFile(const std::string& filename)
{
    return map[filename]; // constructs it inside the map if doesn't exist
}

A:

Replace mutexCache.insert(new std::unique_ptr<std::mutex>) with:
mutexCache.emplace(key, new std::mutex);

In C++14, you should say:
mutexCache.emplace(key, std::make_unique<std::mutex>());

The overall code is very noisy and inelegant, though. It should probably look like this:
std::string cache::get(std::string key)
{
    std::mutex * inner_mutex;

    {
        std::lock_guard<std::mutex> g_lk(gMutex);

        auto it = mutexCache.find(key);
        if (it == mutexCache.end())
        {
            it = mutexCache.emplace(key, std::make_unique<std::mutex>()).first;
        }
        inner_mutex = it->second.get();
    }

    {
        std::lock_guard<std::mutex> c_lk(*inner_mutex);
        return mainCache[key];
    }
}


Q:

How a group represents the passage of time?

I am reading a book on algebraic geometry and I google some keywords, eventually come up with this post in terry tao blog:
http://terrytao.wordpress.com/2009/10/19/grothendiecks-definition-of-a-group/
I think I got good intuition on the different thoughts on a group, but not this one:

(6) Dynamic: A group represents the passage of time (or of some other
  variable(s) of motion or action) on a (reversible) dynamical system.

Can anyone explain to me how a group represents the passage of time?
I can only think of Noether's theorem on conservation law when combining the concept of time and algebra.

A:

It's hard to say what Terry meant exactly unless you ask him. Nevertheless, it seems quite probable that he is talking about flows on manifolds (or more general kind of spaces but let's stick with this).
A reversible flow on a manifold $M$ is a family of diffeomorphisms $\phi_t:M \to M, t \in {\bf R}$ that obey the rule of composition $\phi_t \circ \phi_s = \phi_{s+t}$. In other words, flow is an action of the group $({\bf R}, +)$ on the manifold. That this describes dynamics is immediate: for any $x \in M$, $\phi_t(x)$ is a curve that shows how $x$ moves under the flow.


Q:

OutOfMemoryError Whilst Writing a String to a ByteArrayOutputStream

I have a method which I have an array of String objects which I need to write to a ByteArrayOutputStream which later on I will write into a ZipOutputStream.
Here is my code.
// SAVE THE STRING AS A BYTE ARRAY IN MEMORY INSTEAD OF CREATING AND SAVING TO A NEW FILE
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            DataOutputStream byteOut = new DataOutputStream(baos);
            byte[] data;
            if (i == 1) {
                if (nodeStringArray != null) {
                    for (String s : nodeStringArray) {
                        byteOut.write(s.getBytes("UTF-8"));
                    }
                }
            } else {
                data = stringArray.get(i).getBytes("UTF-8");
                byteOut.write(data);
            }

            byteOut.close();
            byte[] input = baos.toByteArray();

            ZipEntry entry = new ZipEntry(fileName);
            entry.setSize(input.length);
            zos.putNextEntry(entry);
            zos.write(input);
            zos.closeEntry();

The issue is, and I have only received on crash report for it, I am getting an OutOfMemoryError on the line that reads byteOut.write(s.getBytes("UTF-8"));
Anyone know of a better way of doing this or can see if I am doing something wrong?
IDEA
Could I put a try catch statement around the problem and when it happens call byteOut.flush()?
Thanks in advance

A:

You are making to many copies of the data, and this is causing you to run out of memory.
You should be directly writing into your ZipOutputStream in your first loop.
ZipEntry entry = new ZipEntry(fileName);
zos.putNextEntry(entry);
for (String s : nodeStringArray) {
    zos.write(s.getBytes("UTF-8"));
}
zos.closeEntry();


Q:

java program to return the sum of all integers found in the parameter String

i want write a java program to return the sum of all integers found in the parameter String.
for example take a string like:" 12 hi when 8 and 9"
now the answer is 12+8+9=29.
but i really dont know even how to start can any one help in this!

A:

You may start with replacing all non-numbers from the string with space, and spilt it based on the space
String str = "12 hi when 8 and 9";
str=str.replaceAll("[\\D]+"," ");
String[] numbers=str.split(" ");
int sum = 0;
for(int i=0;i<numbers.length;i++){
    try{
        sum+=Integer.parseInt(numbers[i]);
    }
    catch( Exception e ) {
      //Just in case, the element in the array is not parse-able into Integer, Ignore it
    }
}
System.out.println("The sum is:"+sum);


Q:

Comparing rated, stall, and inrush current in DC motor

I see the definitions of them are:

Rated current: maximum current the motor draws (or some says the maximum current the motor can endure?)
Stall current: the current the motor draws when hold physically
Inrush current: the current the motor draws when it just starts to rotate

I have a motor and it only says a rated current. Would it be safely larger than the other two? In other words, if I make sure the circuit can stand the rated current, would it be safe enough in words of current?
Also, is there some general rule like, the stall current is larger than or equal to the inrush, or vice versa?

A:

I have a motor and it only says a rated current. Would it be safely larger than the other two?

For nearly all motors, the rated current is much less than stall/inrush current. Most motors are rated for continuous operation at rated current. A typical motor can withstand stall current for no more than a few seconds. DC motors that are rated in the kilowatt range typically can not withstand stall current at all. They must always be started using some external means of limiting the current. When such motors were widely used for industrial applications, the de facto standard for the controller short-term current rating was 150% of rated current for 1 minute.
There are motors called torque motors that are designed to operate an extended period of time at stall current.

A:

[disclaimer: I'm not an expert on electric motors.]

Is there some general rule like, the stall current is larger than or equal to the inrush, or vice versa?

No, there is no general rule like that.  Once in my previous life, I've had to deal with a motor1 which could overheat and burn if it remained stalled for an hour.  The maximum allowed stall depended on the ambient temperature and air flow.  For this reason, some motors are equipped with thermal cutoffs.
1 Unable to recall the model or datasheet at this time.

Stall current: the current the motor draws when hold physically
Inrush current: the current the motor draws when it just starts to rotate

The current which the motor draws when it just starts to rotate is equal to the stall current.
 (source)
The spike around 300 is spin-up (inrush) current.


Q:

Shell script - Couldn't find 'fi' for this 'if'

I have found this error alongside couple more. I believe that the nesting is not quite all right or the for is not correctly indented or without some semicolon. Either way I have tried for quite some time to figure it out, but to no avail. Here is the code:
if [ "${runcmd}" != "echo" ]; then
statusmsg "Kernels built from ${kernelconf}:"
kernlist=$(awk '$1 == "config" { print $2 }' ${kernelconfpath}) for kern in ${kernlist:-netbsd}; do
[ -f "${kernelbuildpath}/${kern}" ] && \
echo " ${kernelbuildpath}/${kern}"
done | tee -a "${results}"
fi

It is part of a build.sh file.

A:

The
var=value cmd ar1
syntax doesn't quite seem to work if cmd is a for loop (in neither bash nor sh).
Both sh and bash give syntax errors for:
foo=bar for f in ${foo:-BAR}; do echo $f; done

which is what you're esentially doing.
(

sh: 1: for: not found
bash: syntax error near unexpected token `do'

)
And that error seems to result in a couldn't find fi error in your case;
Setting the variable on a separate line fixes the syntax error:
kernlist=$(awk '$1 == "config" { print $2 }' ${kernelconfpath})
for kern in ${kernlist:-netbsd}; do #...

Note:
I would just write "$kernelbuildpath/$kern" instead of "${kernelbuildpath}/${kern}" if I were you.  There's no technical reason for the curlies.


Q:

Why did keyboard input stop working in Android Emulator

Recently upgraded my Android SDK install to r20 and now keyboard input seem to have stopped working with both existing and new AVDs.
Everything was working fine prior to the upgrade.
Does anyone know what would have caused this? (I'm using ubuntu 12.04 x64).

A:

I solved this problem by adding "Keyboard Support" to the AVD within the AVD-Manager and changing the value to "true".

A:

Turns out its a change in the default settings for the emulator in r20 of the Android SDK.

A:

If you want to enable the keyboard for your android virtual device via command line, edit ~/.android/avd/[YOUR_AVD].avd/config.ini and add this to the file:
hw.keyboard=yes

Restart your AVD and you should be in business.


Q:

Organizing and displaying list-like result

This is most likely a piece of cake for you guys, but it is difficult for me.
Related to a math problem, I examine if Fibonacci[n]*Fibonacci[n] + <some number K between 1 and 99> is a prime, and all this for first 1000 Fibonacci numbers only.
For example, this code: (K=1)
Select[Table[Fibonacci[n], {n, 1, 1000}], PrimeQ[#*# + 1] &]

returns

{1, 1, 2}

This code: (K=2)
Select[Table[Fibonacci[n], {n, 1, 1000}], PrimeQ[#*# + 2] &]

returns

{1, 1, 3, 21, 6765, 32951280099, \
  971183874599339129547649988289594072811608739584170445, \
  1082459262056433063877940200966638133809015267665311237542082678938909\
  }

This code: (K=3)
Select[Table[Fibonacci[n], {n, 1, 1000}], PrimeQ[#*# + 3] &]

returns

{2, 8, 3524578, 27777890035288, \
  2011595611835338993891308327102733537615455242513357158345612749706882\
  9146295425939723629305572732574726246290673965789878845363842331040064\
  16432124798818261534841714338, \
  2949592466076064248964701302014885591673737506156850406413751530665307\
  5810241060939483954895520932111023343610904846943097162533007651451709\
  723277579925520157875345780869307228929160}

And this code: (K=99)
Select[Table[Fibonacci[n], {n, 1, 1000}], PrimeQ[#*# + 99] &]

returns

{2, 8, 3524578, 6557470319842, \
  4286863412788815942499567477797350205106309231244244822408841055026686\
  7672}

I need to get all results from 1 to 99, then count elements of each answer, and display these in the following (or similar) form:
   K    number of primes
   1            3
   2            8
   3            6
   .            .
   .            .
  99            5

I appreciate your help.

A:

fibs2 = Fibonacci@Range@1000^2;
tab = Table[{k, Count[fibs2 + k, _?PrimeQ]}, {k, 1, 99}];

TableForm[tab, TableHeadings -> {None, {"K", "number of primes"}}]

(welcome back)


Q:

Question regarding algebraicity of two elements whose sum and product are algebraic.

Let $\alpha , \beta \in \Bbb C$ and suppose $\alpha + \beta$ and $\alpha \beta$ are algebraic over $\Bbb Q$. Prove  $\alpha , \beta$ are algebraic over $\Bbb Q$.

A:

Observe that $\alpha^2-(\alpha+\beta)\alpha + \alpha \beta = 0$. Hence, $\alpha$ is algebraic over $\mathbb{Q}(\alpha+\beta,\alpha\beta)$. But $\mathbb{Q}(\alpha+\beta,\alpha\beta)$ is algebraic over $\mathbb{Q}$. Hence, $\alpha$ is algebraic over $\mathbb{Q}$.


Q:

Redirect Working on Module Not Menu Item

Joomla 3.9.19
I have a login module and in the Login Redirection Page I have selected a menu item > single article. This redirect works fine.
I also have a menu item type > login form. In the Menu Item Login Redirect I have selected a menu item > single article (same as above). This redirect doesn't work, I am always redirected to the user profile page.
I have tried an absolute URL in the menu item type > login form, makes no difference.
I don't have any other login componetns or plugins installed.
I've seen a similar question here and a few other places.
Any ideas why this could be or how I can redirect to an article on both the login module and the login menu item? I don't want to edit core files, and I dont think I should need an override for such a basic task?

A:

The solution was the change the Login Redirect Type to an Internal URL, and ensure it was non-sef.
This is in the documentation https://docs.joomla.org/How_do_you_redirect_users_after_a_successful_login%3F

Due to a security fix on Joomla 3.4.6, the redirect url must be an
internal url, it must start with index.php? and be a non-sef url.
Before Joomla 3.4.6, it worked but that was due to a bug in the way
Joomla validated the urls. Now that security has been applied and the
urls tested correctly the above examples will fail.

Once I change my URL to a non-sef version of my menu item it worked;

index.php?option=com_content&view=article&id=32&Itemid=469

Thanks to @Grant G for the tips.


Q:

Can the Dispel Magic spell be used to dispel a familiar summoned by the Find Familiar spell?

Since you cast the find familiar spell to get a familiar, is the familiar a magical effect? And if that is true, would you be able to target the familiar with the dispel magic spell and get the familiar destroyed/killed/dispelled?
Would this then be a good reason to cast find familiar at a higher level?

A:

No.
The familiar from find familiar isn't an ongoing magical effect to be dispelled. When you cast the spell (with a duration of instantaneous), the following occurs (from the spell's text):

You gain the service of a familiar, a spirit that takes an animal form you choose... it is a celestial, fey, or fiend (your choice) instead of a beast.

The spell doesn't create the familiar, per se. Rather, the familiar is a spirit whose service you instantaneously gain when you cast the spell. So the familiar isn't a spell effect.
In addition, the spell's duration of instantaneous indicates that there is no ongoing effect to be dispelled (from the rules on spell duration):

Many spells are instantaneous. The spell harms, heals, creates, or alters a creature or an object in a way that can't be dispelled, because its magic exists only for an instant.

So the familiar can't be dispelled using dispel magic.
For more details on dispelling magical effects, see this related question.


Q:

JS - Removing Keys from object

I got a question, and would be really grateful if someone could explain to me in pseudo code how do I solve it
So here we go, I have an object like this
const obj = {
     'key1': [],
     'key2': [val1, val2],
     'key3': [],
     'key4': [val3]
     }

I need to remove the keys which contain an empty array, in this case key1 and key3, and then return a new object without the keys that contained the empty array.
Im trying to figure this out on my own, but I'm still a JS newbie.

A:

It could be done by using the following actions:

use Object.entries() method to return an array of a given object's own enumerable string-keyed property
then use reduce() method to iterate through result of Object.entries. At each iteration, you are making a decision whether key_x contains array with length > 0

So the code looks like this:
const result = Object.entries(obj).reduce((a, [k,v])=> {
    if (v.length > 0) {
      a[k] = v;
    }
    return a;
},{})

An example:

const obj = {
     'key1': [],
     'key2': ['val1', 'val2'],
     'key3': [],
     'key4': ['val3']
     };

  const result = Object.entries(obj).reduce((a, [k,v])=> {
    if (v.length > 0) {
      a[k] = v;
    }
    return a;
  },{})

  console.log(result);


Q:

TCP kernel implementation

I have developed a new TCP congestion avoidance algorithm which I want to implement in the linux kernel and test its performance. But for this I need to understand the existing TCP kernel (2.6) implementation. How do you suggest I should proceed with this? Please suggest some articles/books etc which can give me a head start. I know I will have to eventually dive into the source code but it would be helpful if I at least know broad implementation aspects and how to navigate through the code.

A:

I would just dive directly into the source code of the simpler congestion avoidance algorithms already in the kernel. They're in the net/ipv4 directory, and tcp_vegas.c is pretty thoroughly commented. You may also wish to look at tcp_highspeed.c and tcp_bic.c because they're fairly simple (fewer than 250 lines of code).


Q:

Create Apache mod rewrite rule to process all request to subdirectory

I want to redirect all incoming requests to a subdirectory, but can't figure out how. I looked here but that did not work for me.
So, if someone visits www.example.com/test, I want it to redirect to: www.example.com/test/subdirectory, but the URL still needs to be www.example.com/test
I also need the parameters to work, for example www.example.com/test/index.php?action=home must redirect to www.example.com/test/subdirectory/index.php?action=home.
I hope someone can help me!

A:

So in fact what you ask for is not a redirect.
A redirect means the web server will send a new url containing the subdirectory, the browser will then request this new url, and show it in the url bar of the browser.
What you want is to tranparently map an directory structure to a real directory structure which differs. This is what Apache can do easily with the Alias instruction. Mod-rewrite could also do that, with RewriteRules not containing the [R] tag, this would imply an internal rewrite, not a redirect HTTP response. A [QSA] tag would also tell mod-rewrite to keep the current query string parameters on the rewritten url. But Mod-rewrite is not always simple to understand, and your problem is simple enough for a basic Alias, which is almost always included in Apache (more often than mod-rewrite).
this should be ok:
Alias /test /test/subdirectory


Q:

Python shlex.split(), ignore single quotes

How, in Python, can I use shlex.split() or similar to split strings, preserving only double quotes? For example, if the input is "hello, world" is what 'i say' then the output would be ["hello, world", "is", "what", "'i", "say'"].

A:

import shlex

def newSplit(value):
    lex = shlex.shlex(value)
    lex.quotes = '"'
    lex.whitespace_split = True
    lex.commenters = ''
    return list(lex)

print newSplit('''This string has "some double quotes" and 'some single quotes'.''')

A:

You can use shlex.quotes to control which characters will be considered string quotes. You'll need to modify shlex.wordchars as well, to keep the ' with the i and the say.
import shlex

input = '"hello, world" is what \'i say\''
lexer = shlex.shlex(input)
lexer.quotes = '"'
lexer.wordchars += '\''

output = list(lexer)
# ['"hello, world"', 'is', 'what', "'i", "say'"]


Q:

textFieldDidBeginEditing: is not called although delegate is connected

Here is my code:
In .h file
@interface VTViewController : UIViewController <UITextFieldDelegate>

In .m file
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
        self.postText.delegate = self;

}

#pragma mark - textField delegate

- (void)textViewDidBeginEditing:(UITextView *)textView {
    NSLog(@"textViewDidBeginEditing:");
}

- (void)textViewDidEndEditing:(UITextView *)textView{
    NSLog(@"textViewDidEndEditing:");
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return NO;
}

The last one works, the first two do not since I do not see the NSLog being printed. I also tried connected the textfield in the IB.

A:

You are mixing your methods up - some are text view methods and some are text field methods. Check the names from the appropriate delegate protocols and replace as required.


Q:

Updating data with jQuery Mobile

I have a simple form that contains the jquery UI date picker and basically when the date changes I want to refresh my data (go and get all records based on date).
However i have no idea how to do refresh the data?
So looking for advice and simple example if you could help please.
@model ViewModels.ScheduleMobileDisplay
@{
    ViewBag.Title = "Test";
    Layout = "~/Views/Shared/_AppHomeLayout.Iphone.cshtml";

}

@using (Html.BeginForm())
{
{

        <link href="~/Content/CSS/jquery-ui-1.10.1.Redmond/jquery-ui-1.10.1.custom.min.css" rel="stylesheet" />

            <input type="text" id="datepicker"  placeholder="Select Date" />

                    @Model.AppointmentDate

                @foreach (var item in Model.Appointments)
                {

                            @item.StartTime @item.Name

                }

}

A:

You'd want to make an ajax call to a webservice to get the data, then update your page in the ajax call's success callback.
$.ajax('www.mywebsite.com/myserviceurl', {
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    data: messageData,
    type: 'POST',
    timeout: 20000,
    success: function(data) {
        /* update page here */
    },
    error: function(jqXHR, textStatus, errorThrown) {
        console.log(errorThrown);
    }
});


Q:

When I reopen the program is everything fades in txt file

I have a code like that,
database = open(r"C:\Users\PC\Desktop\database.txt", "w")

print("Please type 1 if add a film")

enter = input("Enter: ")

if enter == "1":
    film=input("Please write a film name: ")
    database.write(film)
    database.close()

When I reopen the program is everything fades in txt file.How I do before writing what I write is saved under :)

A:

Use the a mode.
database = open(r"C:\Users\PC\Desktop\database.txt", "a")

The w mode will truncate the file when you open it (rewriting the file), while this will append to the end of the file.
To append into a new line, simply:
if enter == "1":
    film=input("Please write a film name: ")
    database.write(film + "\n") #\n is the newline character
    database.close()


Q:

Html and css Trying to put image

I am trying to put image to above of my video but it won't show up, only little mark top of the left side ? I know this is maybe simple but I don't get it.Maybe add something to css and change that images code place ?
<!DOCTYPE html>

<TITLE>    </TITLE>

<LINK href="to.css" rel="stylesheet" type="text/css">

HOME

 dropdown #1

dropdown #1 item #1

dropdown #1 item #2

dropdown #1 item #3

 dropdown #2

dropdown #2 item #1

dropdown #2 item #2

dropdown #2 item #3

Hello and Welcome --------------

<video width="900" height="550" controls >
<source src="fifa.mp4" type="video/mp4">
<source src="fifa.ogg" type="video/ogg">
<source src="fifa.webm" type="video/webm">
<object data="fifa.mp4" width="320" height="240">
<embed src="fifa.swf" width="320" height="240">
</object>
</video>

CSS:

body {
margin:0;
padding:0;
min-width:525px;
font-family: Arial;
font-size: 17px;
background-image:url('fifa2.jpg');
}

#header {
float: left;
width: 100%;
height: 100px;
position: absolute;
}

#footer {
float: left;
width: 100%;
background-color: #000000;
font-size: 14pt;
font-weight: bold;
text-align: center;
position: absolute;
height: 40px;
left: 0px;
bottom: 0px;
}

#wrapper {
padding-left: 200px;
padding-right: 125px;
overflow: hidden;
}

#left_side {
position: relative;
float: left;
width: 200px;
right: 200px;
margin-left: -100%;
padding-bottom: 2000px;
margin-bottom: -2000px;
}

#right_side {
position: relative;
float: left;
width: 125px;
background-color: #66CCCC;
margin-right: -125px;
padding-bottom: 2000px;
margin-bottom: -2000px;
}

#content_area {
position: relative;
float: left;
width: 100%;
padding-bottom: 2000px;
margin-bottom: -2000px;
}

#nav {
background-color: #222;
}
#nav_wrapper {
width: 335px;
margin: 0 auto;
text-align: left;
}
#nav ul {
list-style-type: none;
padding: 0;
margin: 0;
position: relative;
min-width: 200px;
}
#nav ul li {
display: inline-block;
}
#nav ul li:hover {
background-color: #333;
}
#nav ul li a, visited {
color: #CCC;
display: block;
padding: 15px;
text-decoration: none;
}
#nav ul li:hover ul {
display: block;
}
#nav ul ul {
display: none;
position: absolute;
background-color: #333;
border: 5px solid #222;
border-top: 0;
margin-left: -5px;
}
#nav ul ul li {
display: block;
}
#nav ul ul li a:hover {
color: #699;
}

video {
margin-top: 250px;
}

![My page][1]

Link to image: [1]: http://i.stack.imgur.com/AARLw.jpg

A:

Set css position form image and video elements as:
img{
   position:absolute;
}

video{
   position:relative;
}


Q:

Cannot start Docker in Azure Shell

When in Azure Shell I type the following
PS Azure:\> systemctl start docker.service

I get the following error message

Error getting authority: Error initializing authority: Could not
  connect: No such file or directory (g-io-error-quark, 1) Failed to
  connect to bus: No such file or directory

How can I resolve it?
Thank you in advance

A:

Azure Cloud Shell offers a browser-accessible, pre-configured shell experience for managing Azure resources without the overhead of installing, versioning, and maintaining a machine yourself. You could read the supported features and tools here.
Moreover, you could not run the docker daemon in the Azure cloud shell since Cloud Shell utilizes a container to host your shell environment, as a result running the daemon is disallowed. You could Utilize docker-machine to manage Docker containers from a remote Docker host.


Q:

Red Circle Around Custom Android Button Image

I have created a floating action button, and made my own image (at each of dpi sizes), but there is a red circle around it (image below).  Here is my xml defining the button
<android.support.design.widget.FloatingActionButton
android:id="@+id/addplant"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="@dimen/fab_margin"
android:src="@mipmap/add_plant"/>

Here is my source image (@192x192), and a screenshot of what i'm seeing in android studio.

A:

You can try the below -
   <android.support.design.widget.FloatingActionButton
    ...
    ...
    android:src="@drawable/icon" // change backgroung icon
    app:backgroundTint="@android:color/transparent" // change background color
    />

setting tint to transparent will override that primary color pink you have given in styles.

A:

EDIT 2
No need to use app:backgroundTint juse USE android:scaleType="center" in your FloatingActionButton it will work
<android.support.design.widget.FloatingActionButton
    android:id="@+id/addplant"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end|bottom"
    android:layout_margin="@dimen/fab_margin"
    android:scaleType="center"
    android:src="@mipmap/add_plant" />

OUTPUT

Try this
<android.support.design.widget.FloatingActionButton
    android:id="@+id/addplant"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end|bottom"
    android:layout_margin="@dimen/fab_margin"
    android:src="@drawable/add_plant"/>

android:src="@drawable/add_plant"

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:fillColor="#FFFFFF"
        android:pathData="M19,13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
</vector>

OUTPUT

EDIT
To support vector drawablea add this in  your build.gradle file
defaultConfig {
        vectorDrawables.useSupportLibrary = true
 }


Q:

Is it possible to import XML or JSON data from a table within a Word online document into Apps Script website as an HTML table?

I am building a web app using Apps Script.
In this web app I have a table that needs to be populated from a table in a Word doc in OneDrive.
This document is updated regularly, so I would prefer to programmatically update the content of the html table in Apps Script.
Is this possible?
If so, can anyone give me guidance as to how to accomplish this?
I've started looking into importing xml from a url, but I'm not sure that I'm on the right track.

A:

You need to incorporate the following steps

Read your data into a Google Apps function, e.g. with OneDriveApp as recommended by Cooper
Use google.script.run to call the Apps Script function from you html file
Incorporate a Web Polling function that updates your html table with fresh contents in desired intervals

Sample:

code.gs

function doGet(){
  return HtmlService.createHtmlOutputFromFile('index');
}
function getFreshData(){
  //read here your Word Doc data, e.g. with One DriveApp and store it e.g. in an array
  ...
  return myDataArray;
}

index.html

...
<body onload="polling()">
...
  <script>
    function polling(){
      setInterval(myFunction,2000);  //chose how often you want your table
     }
    function myFunction(){
      google.script.run.withSuccessHandler(onSuccess).getFreshData();
    }
    function onSuccess(myDataArray){
      // Create a html table with the freshly obtained myDataArray from the Word Doc
     ...
    }
  </script>
...


Q:

MSTest: How to assert positive if one of 3 asserts are valid?

I have an IntegrationTest where I want to test the result of a linq query.
The linq query goes something like this
where myObject.fieldA.StartsWith(aString)
   || myObject.fieldB.StartsWith(aString)
   || myObject.fieldC.StartsWith(aString)

Now I want write the test like so:
foreach(var result in results)
{
   StringAssert.StartsWith(result.fieldA, aString);
   StringAssert.StartsWith(result.fieldB, aString);
   StringAssert.StartsWith(result.fieldC, aString);
}

but of course that is not correct, because it should assert valid when one of the 3 above is valid.
Any idea how to do that using MSTest ?

A:

You can work around it by using
Assert.IsTrue(
    result.fieldA.StartsWith(astring) ||
    result.fieldB.StartsWith(astring) ||
    result.fieldC.StartsWith(astring)
);


Q:

Is passing data between directives, controllers, and services using $emit and $broadcast bad practice?

Hi I'm a beginning Angular developer and I was wondering if the way I've passed data between controllers is bad practice or not.
I'm creating a seatmap widget whereby you click on a seat and it will display data in another part of the App using a different controller.
1) I have a directive that incorporates dynamic templating. Based on the model being passed (from an ng-repeat), it will create an event listener like so:
if(scope.seat.isAvailable) {
  element.bind('click', function() {
    scope.$emit('clickedSeat', scope.seat);
  }
  element.append(seatAvailableTemplate);
}

2) In my controller, I have the following listening for the click:
$scope.$on('clickedSeat', function(event, seat) {
  seatSelectionService.broadcastSeatData(seat);
}

3) I have a service where I've passed in $rootScope which allows me to broadcast the data to a different controller:
var seatSelectionService = {};
seatSelectionService.broadcastSeatData = function(clickedSeat) {
  seatSelectionService.seatData = clickedSeat;
  $rootScope.$broadcast('seatSelected');
}
return seatSelectionService;

4) In the other controller, I have a listener which sets the $scope attribute, which renders {{selectedSeat}} in the view:
$scope.$on('seatSelected', function() {
  $scope.selectedSeat = seatSelectionService.seatData;
  $scope.apply();
}

Of course I have had to pass in seatSelectionService into both controllers for it to work.
Is there a better way to do this? Or is this way of passing data valid practice?

A:

$broadcast and $emit themselves aren't bad practice, but it does look like you've over complicated your app.
You can add services directly to directives - they can have controllers built into them that depend on the services.
So in your directive, add a controller that uses the seatSelectionService, something like:
seatSelectionService.setSeat( scope.seat )

Which cuts out one of the steps at least - your setSeat method would still want to do a $broadcast when it's done down to anything listening.
Directives can be really simple or really complex - they can simply be a quick way of outputting a repeated template, or a dynamic template with a controller and access to multiple services.
Something else you might want to look at is promises - I used to use $broadcast and $emit a lot more than I needed to, until I learnt how to use promises and defer properly


Q:

Firefox/Chrome Web Extension - Security Error When Trying To Inject IFrame Through Content Script

I have the following really simple code in a content script that runs whenever a button in my "popup.html" file is pressed:
Section of code inside "inject.js"
browser.runtime.onMessage.addListener((message) => {
    console.log("Trying to inject iFrame");
    var iframe = document.createElement("iframe");
    iframe.src = browser.extension.getURL("inject.html");
    document.body.appendChild(iframe);
});

The content of "inject.html" is:
<!DOCTYPE html>
<html>

<head>
</head>

<body>
    <p>
        Hello. This is a Test.
    </p>
</body>

</html>

However, when this code runs I get the following output in the console (Using "example.com: as an example URL):

Trying to inject iFrame
  Security Error: Content at http://example.com/ may not load or link to moz-extension://218287b3-46eb-4cf6-a27f-45b9369c0cd9/inject.html.

Here is my "manifest.json"
{
"manifest_version": 2,
"name": "Summarizer",
"version": "1.0",

"description": "Summarizes webpages",

"permissions": [
    "activeTab",
    "tabs",
    "storage",
    "downloads",
    "*://*.smmry.com/*"
],

"icons":
{
    "48": "icons/border-48.png"
},

"browser_action":
{
    "browser_style": true,
    "default_popup": "popup/choose_length_page.html",
    "default_icon":
    {
        "16": "icons/summarizer-icon-16.png",
        "32": "icons/summarizer-icon-32.png"
    }
}

"web_accessible_resources": [
    "inject.html"
]
}

And, lastly, here is the top level file structure of my extension:

How can I fix this security error?
This is not a duplicate of this: Security error in Firefox WebExtension when trying getUrl image because I provided the full path in my manifest.json

A:

I was missing a comma. Here is the relevant portion of the manifest.json with the comma in place:
"browser_action":
{
    "browser_style": true,
    "default_popup": "popup/choose_length_page.html",
    "default_icon":
    {
        "16": "icons/summarizer-icon-16.png",
        "32": "icons/summarizer-icon-32.png"
    }
},

"web_accessible_resources": [
    "inject.html"
]


Q:

How can I toggle the margin of an element using JavaScript?

I am trying to move a div to the side, and back, with a transition, by changing the margin. I have one button that I want to toggle it's margin. The div moves to the right,but when I click again, it doesn't move back to it's original position. This is what I have:
HTML

Click Me!

CSS
#movingdiv {
overflow: hidden;
left: 0;
top: 0;
right: 0;
bottom: 0;
background-color: gray;
-webkit-transition-duration: 0.3s;
-moz-transition-duration: 0.3s;
-o-transition-duration: 0.3s;
transition-duration: 0.3s;
}

JavaScript
function toggle () {

var el = document.getElementById("movingdiv");
if ( el.style.marginLeft="250px" ) {

    el.style.marginLeft="250px";

}

else {

    el.style.marginLeft="0px";

}

}

Here it is in action:
http://codepen.io/dakoder/pen/nfimJ

A:

You're making an assignment, instead of checking equality. In addition, you have your else condition and if condition mixed. Change it to the following:
if ( el.style.marginLeft==="250px" ) {
    el.style.marginLeft="0px";
} else {
    el.style.marginLeft="250px";
}


Q:

How to hide products in Shopify search results based on a vendor name

I'm in a situation where hiding a certain vendors products in the control panel isn't an options due to an outside POS.  For a test in search.liquid, I used search.terms like below.  This code works but not everyone will type thevendor exactly the same way and will see the products if they don't type thevendor.
{% for item in search.results %}
{% if search.terms == 'thevendor' %}
{% else %}
{% include 'search-result' %}
{% endif %}
{% endfor %}

I tried to figure out how to write the code to hide these products in a better way.  I tried product.vendor like below but when I search for those products individually they are not hidden.  The code:
{% for item in search.results %}
{% if product.vendor == 'thevendor' %}
{% else %}
{% include 'search-result' %}
{% endif %}
{% endfor %}

Can someone tell me what I'm missing here?  It seems it doesn't know what product.vendor is but when I print out who the vendor is, it displays the vendor.  I don't understand why it's not hiding the products that are associated with this vendor.

A:

{% for item in search.results %}
{% if item.product.vendor == 'thevendor' %}
{% else %}
{% include 'search-result' %}
{% endif %}
{% endfor %}

This should work.


Q:

Animate layout on different activities on android 4.4(kitkat) and higher

Now this specific page does describe a way to animate between layouts of different activities, but the problem is that the API is only supported for android 5.0 and higher, so I'd like to know what are the ways in which animation(like transition or any other type of fade/slide in etc.) could be done for layouts in two different activities.

A:

You can't set transitions on your theme prior to Lollipop version but you can still use animations programmatically.
Here’s an example with animations that slide the new activity in when first created, and the opposite movement when you press the back button.
left_in.xml
<set>

    <translate xmlns:android="http://schemas.android.com/apk/res/android"
               android:fromXDelta="-100%"
               android:toXDelta="0"
               android:interpolator="@android:anim/decelerate_interpolator"
               android:duration="500"/> //in milliseconds
</set>

right_in.xml
<set>

    <translate xmlns:android="http://schemas.android.com/apk/res/android"
               android:fromXDelta="100%"
               android:toXDelta="0"
               android:interpolator="@android:anim/decelerate_interpolator"
               android:duration="500"/>
</set>

left_out.xml
<set>

    <translate xmlns:android="http://schemas.android.com/apk/res/android"
               android:fromXDelta="0"
               android:toXDelta="-100%"
               android:interpolator="@android:anim/decelerate_interpolator"
               android:duration="500"/>
</set>

right_out.xml
<set>

    <translate xmlns:android="http://schemas.android.com/apk/res/android"
               android:fromXDelta="0"
               android:toXDelta="100%"
               android:interpolator="@android:anim/decelerate_interpolator"
               android:duration="500"/>
</set>

On your activities you can call the animations as follows:
On start: overridePendingTransition(R.anim.right_in, R.anim.left_out);
On Back Pressed: overridePendingTransition(R.anim.left_in, R.anim.right_out);
Or any combination of the above.
Note that the first animation on overridePendingTransition is for the incoming activity and the second for the outgoing activity.


Q:

iOS Mapkit - Cache maps?

I need maps of certain areas available when no internet connection is available.
It would be like this:

User loads app internet connection is available
App downloads list of coordinates and places pins on the map
User leaves their house and has no internet connection
Pins and map remain readily available for user to interact with, even without internet connection

How do I do this?

A:

You probably won't use MKMapView and MapKit for that, but the Google Maps Static API that allows you to download static images (even with pins on it) directly.
Here is the example given by the Google Maps API doc itself
Then you can store this image and display it in an UIImageView in a UIScrollView for example.


Q:

Units in Polynomial Rings

Give an example of a natural number $n > 1$ and a polynomial $f(x) ∈ \Bbb Z_n[x]$ of degree $> 0$ that is a unit in $\Bbb Z_n[x]$.
I am trying to understand how units work in polynomial rings. My book doesn't really define it and I need a bit of help with this.

A:

Hint: Note that $(2x+1)(2x+1)=1$ in $\mathbb{Z}_4$.
For another example, use $\mathbb{Z}_9$. Note that $(3x+1)(6x+1)=1$, so $3x+1$ has a multiplicative inverse.


Q:

Unable to assign data to specific index of array in javascript

let new_json = {
  sessions: []
};

new_json.sessions[0]["timing"] = []

Error:
VM73:1 Uncaught TypeError: Cannot set property 'timing' of undefined
    at <anonymous>:1:32
(anonymous) @ VM73:1

Here I am trying to add data to one index of the array
But, getting above error while doing this.
Is there any way to do this?
Please have a  look

A:

First initialize the object at 0th position and the add the value like this
new_json.sessions[0] = {};
new_json.sessions[0]["timing"] = []


Q:

What to do when I have energy loss due to distance

I have to connect a total of 15 12 V, 2 A motors in parallel.
They are all going to be connected to a battery and I’m trying to bring a line to connect all 15 of them. The distance between them is 25 meters. What can I do to reduce the energy loss due to the distance?

A:

Everyone seems to be suggesting the thicker wire route here.. but you do have a different option.
Your other alternative is to either use a boost convertor to convert your 12V into a high DC voltage or use an invertor to make high voltage AC and transmit that down cheaper cabling instead. Then add DC-DC or AC-DC power regulators at each motor.
That may seem extreme, but you need to do a cost comparison of which is cheaper. Big beefy hard to manage cables, or cheap wiring and low cost convertors.
The other benefit of this route is you separate the power transfer efficiency issue from the target voltage-drop issue. That is, the system ought to be 100% functional despite the transmission costs.


Q:

Make an image clickable to expand

I have a background image that I would like to expand when clicked. I have setup animations that will dim the background and prop the image to the center, but for some reason the image is not clickable.
I have tried to implement a simple print(tapped) and when I tap I dont see anything as well. I am wondering if I have to declare my image view as something else?
import Foundation
import UIKit

class JobViewController: UIViewController {

let imageView: UIImageView = {
    let iv = UIImageView(image: #imageLiteral(resourceName: "yo"))
    iv.contentMode = .scaleAspectFill
    iv.isUserInteractionEnabled = true
    iv.translatesAutoresizingMaskIntoConstraints = false
    iv.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleZoomTap)))
    return iv
}()

@objc func handleZoomTap(_ tapGesture: UITapGestureRecognizer) {
  print("tap tap")

}

override func viewDidLoad() {
    super.viewDidLoad()

     view.addSubview(imageView)
    imageView.fillSuperview()

}
}

When I tap the image, I expect that it should at least print "tap tap"
Is there something else that i am missing?

A:

Delete this line:
iv.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleZoomTap)))

And add this to your viewDidLoad:
imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleZoomTap)))


Q:

AnyLogic 7: Excel access library (Apache POI) is not specified

AnyLogic 7: Excel access library (Apache POI) is not specified
I'm trying to use the AnyLogic ExcelFile class, but it appears that AnyLogic can't find the required Apache POI library:
Error during model startup:
Excel access library (Apache POI) is not specified (or is specified incorrectly) in the classpath
Caused by: org/apache/poi/openxml4j/exceptions/InvalidFormatException
Caused by: org.apache.poi.openxml4j.exceptions.InvalidFormatException
java.lang.RuntimeException: Excel access library (Apache POI) is not specified (or is specified incorrectly) in the classpath
    at com.xj.anylogic.engine.Engine.a(Unknown Source)
    at com.xj.anylogic.engine.Engine.start(Unknown Source)
    at com.xj.anylogic.engine.ExperimentSimulation.b(Unknown Source)
    at com.xj.anylogic.engine.ExperimentSimulation.run(Unknown Source)
    at generic_agent_based_model_with_births_and_deaths.Simulation.executeShapeControlAction(Simulation.java:107)
Caused by: java.lang.NoClassDefFoundError: org/apache/poi/openxml4j/exceptions/InvalidFormatException
    at generic_agent_based_model_with_births_and_deaths.ExcelDataSource.onStartup(ExcelDataSource.java:668)
    at generic_agent_based_model_with_births_and_deaths.ExcelDataSource.start(ExcelDataSource.java:652)
    at generic_agent_based_model_with_births_and_deaths.Main.start(Main.java:1046)
    ... 4 more
Caused by: java.lang.ClassNotFoundException: org.apache.poi.openxml4j.exceptions.InvalidFormatException
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    ... 7 more

How do I fix this?
Some notes:

I am working with a model initially developed by someone else. I am assuming the model was initially built for AnyLogic 6.9, but I am using AnyLogic 7.0.3.
I assume that AnyLogic is supposed to import the POI library automatically: any idea what it did wrong / what I did wrong to cause AnyLogic to fail?
To head off any confusion, ExcelDataSource is a wrapper class I've created to simplify ExcelFile for our use case.

Thanks in advance!

A:

AnyLogic uses Apache POI library for working with Excel spreadsheets. But it is disabled by default as unnecessary. You should drop Excel File element from Connectivity palette to be able to use Apache POI methods. Another way - add the library to model dependencies list (see Dependencies section of the model properties view).


Q:

How to use gwtbootstrap3 calendar with UiBinder

Can we use gwtbootstrap3 fullcalendar mentioned at http://gwtbootstrap3.github.io/gwtbootstrap3-demo/#fullcalendar with UiBinder.
I am trying to use it with UiBinder and nothing is appearing on that page.
code to my UiBinder class
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
    xmlns:g="urn:import:com.google.gwt.user.client.ui"
    xmlns:b="urn:import:org.gwtbootstrap3.client.ui.gwt">
    <g:HTMLPanel ui:field="calendarContainer">
    </g:HTMLPanel>
</ui:UiBinder>

code to the corresponding view class
public class EventView extends ReverseCompositeView<IEventView.IEventPresenter> implements IEventView {

    private static EventViewUiBinder uiBinder = GWT.create( EventViewUiBinder.class );

    interface EventViewUiBinder extends UiBinder<Widget, EventView> {
    }

    @UiField
    HTMLPanel calendarContainer;

    @Override
    public void createView() {
        //don't create the view before to take advantage of the lazy loading mechanism
        initializeCalendar();
        initWidget( uiBinder.createAndBindUi( this ) );
    }

    private void initializeCalendar() {
        final FullCalendar fc = new FullCalendar("event-calendar", ViewOption.month, true);
        fc.addLoadHandler(new LoadHandler() {
            @Override
            public void onLoad(LoadEvent loadEvent) {
                addEvents();
            }

            private void addEvents() {
                for (int i = 0; i < 15; i++) {
                    Event calEvent = new Event("id "+ i, "this is event "+i);
                    int day = Random.nextInt(10);
                    Date start = new Date();
                    CalendarUtil.addDaysToDate(start, -1 * day);
                    calEvent.setStart(start);
                    if(i%3 ==0){
                        calEvent.setAllDay(true);
                    }else{
                        Date d = new Date(start.getTime());
                        d.setHours(d.getHours()+1);
                        calEvent.setEnd(d);
                    }
                    fc.addEvent(calEvent);
                }
            }

        });

        calendarContainer.add(fc);
    }

}

and I am using mvp4g framework.

A:

initializeCalendar();
initWidget( uiBinder.createAndBindUi( this ) );

You should first init the widget and then initialize the calendar. This is because you are adding your FullCalendar to the calendarContainer HTMLPanel in initializeCalendar. And before the call to initWidget, calendarContainer is null.
I think you can go a step further and do it like this:
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
    xmlns:g="urn:import:com.google.gwt.user.client.ui"
    xmlns:b="urn:import:org.gwtbootstrap3.client.ui.gwt"
    xmlns:f="urn:import:org.gwtbootstrap3.extras.fullcalendar">
    <g:HTMLPanel>
        <f:FullCalendar ui:field="fullCalendar" />
    </g:HTMLPanel>
</ui:UiBinder>

And then in your EventView:
@UiField(provided = true) FullCalendar fullCalendar;

@UiField(provided = true) means it's up to you to initialize this widget before calling initWidget. So, in this case, the order:
initializeCalendar();
initWidget( uiBinder.createAndBindUi( this ) );

is OK. Additionally, you don't have to add the FullCalendar to any panel anymore - it's already added, you just have to initialize it.


Q:

Passing Structures between Managed and Unmanaged Code

I call c++/cli method from c# in this method:
        bool SetProperty(Element element, Node referencePoint, List<Materializer> materializers, List<ulong> properties)
    {

        // Loop over STLs
        for (int i = 0; i < materializers.Count; i++)
        {
            Materializer materializer = materializers[i];
            PentalTreeNode pentalTreeRoot = pentalTreeDatasets[i].top;

            if (materializer.IsPointInside(referencePoint.X, referencePoint.Y, referencePoint.Z, pentalTreeRoot))
            {
                element.PropertyId = properties[i];
                return true;
            };

        }

        return false;
    }

C++/cli method is this:
bool IsPointInside(double x, double y, double z, PentalTreeNode ^root)
    {
        int intersectionCount = 0;

        Math3d::M3d rayPoints[2], intersectionPoint;

        rayPoints[0].set(x,y,z);
        rayPoints[1].set(x,y,1.0e6);

        if(_box->IsContainingPoint(x,y,z))
        {
            intersectionCount=CountIntersects(x,y,z,root);
            return (intersectionCount%2!=0);

        }

    }

What is wrong, because c++/cli method doesn't return always the same result?
How to pin or marshal?
Method in c++/cli(Maybe this not ok?):
int CountIntersects(double x, double y, double z, PentalTreeNode ^root)
    {

        Math3d::M3d rayPoints[2], intersectionPoint;

        rayPoints[0].set(x,y,z);
        rayPoints[1].set(x,y,1.0e6);

        if(!root)
            return 0;
        else
        {
            int special = CountIntersects(x,y,z,root->special);
            if (x <= root->xMax && x >= root->xMin && y <= root->yMax && y >= root->yMin)
            {

                if( _stlMesh->IsRayIntersectsPoly(root->index, rayPoints, intersectionPoint))
                {
                    return (1 + special);
                }
                else
                    return special;
            }
            else
            {
             if (y>root->yMax)
              {
                    return (CountIntersects(x,y,z,root->top)+special);
              }
              else if(y<root->yMin)
                    {
                        return (CountIntersects(x,y,z,root->bottom)+special);
                    }
                    else if(x<root->xMin)
                            {
                                return (CountIntersects(x,y,z,root->left)+special);
                            }
                            else if(x>root->xMax)
                            {
                                return (CountIntersects(x,y,z,root->right)+special);
                            }
                            else
                                return special;
            }

        }

    }

A:

if( _stlMesh->IsRayIntersectsPoly(root->index, rayPoints, intersectionPoint))

There's one possible flaw in this particular statement, you've never initialized intersectionPoint.  C++ lets you get away with this, it doesn't have anything similar to C#'s definite assignment rules.  It isn't 100% clear whether that's the real problem, the variable might be passed by reference.
In the Debug build, such an uninitialized variable will have a predictable value.  Something you can easily see in the debugger when you switch it to hexadecimal display mode.  Fields in this struct or class will contain the value 0xcccccccc, a value that's apt to generate nonsensical results or crash your code with an access violation.  In the Release build, the /RTC option isn't turned on and you'll get entirely random values in the variable.
Which corresponds very well with the description of your problem, so high odds that this is indeed the problem.  Be sure to use the debugger to find problems like this, you can easily see the value of local variables with the Autos debugger window as you single-step through the code.


Q:

How many records does SNSEvent Object's getRecords() return?

How many records will be returned and how does it actually work?
public String handleRequest(SNSEvent snsEvent, Context context) {
        List<SNSRecord> records = snsEvent.getRecords();
        System.out.println("Size "+ records.size());
        return "success";
}

A:

Read the docs:

Q: Will a notification contain more than one message?
No, all notification messages will contain a single published message.


Q:

Error when using STXXL Autogrow

I'm currently working on a project that requires about 20 vectors to be written to individual files. I also need my STXXL disk file to grow automatically to account for very large vectors. I understand that STXXL provides autogrow functionality for disk files if you specify the size in the .stxxl file to be 0. I have done this but I get an IO error when creating my first vector.
My .stxxl file is as follows:
disk=c:\stxxl,0,wincall
and I'm creating my vectors like so:
stxxl::wincall_file file("file.dat", stxxl::file::CREAT | stxxl::file::RDWR);
stxxl::vector<double, 2, stxxl::lru_pager<8>> vector1(&file, 1000000);
Can anyone help me fix this?
Thanks!

A:

So, to answer my own question here, I believe the problem was trying to create a disk file directly at the root of the C drive. Once I changed the path in my .stxxl file to an absolute path off my user directory, it worked no problem, autogrow and all!


Q:

Passing text-box value from view to action method and return true false on given condition

I have a text box and a button. If I put "adm" in the text box and click on the button, the value will get passed to the controller to an action method. There it will check whether the given value in the text box is "adm" or not. If its "adm" then it will show "true" in an alert box and if its not "adm" then it will return "false" in an alert box.
I am confused how to implement the whole thing. Please help.
I have been told to use jquery for that by my faculty.
This is my Controller.
public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
                public ActionResult Download(string name)
                {
                    return View();
                }
    }

This is my view.
<script type="text/javascript">
    $(document).ready(function () {
        $('#button1').click(function () {

        });
    });
</script>
<input type="text" id="text1" value="" />
<input type="button" id="button1" value="Button" />

A:

You need to change your controller method to
public ActionResult Download(string name)
{
  if (name == "adm)
  {
    return Json(true, JsonRequestBehavior.AllowGet);
  }
  else
  {
    return Json(false, JsonRequestBehavior.AllowGet);
  }
}

and then in the script
$(document).ready(function () {
  var url = '@Url.Action("Download")'; // add controller name is necessary
  $('#button1').click(function () {
    $.getJSON(url, { name: $('#text1').val() }, function(response) {
      alert(response);
    });
  });
});

although you could avoid the server call and just do the check on the client using
$('#button1').click(function () {
  alert($('#text1').val() == 'adm')
});


Q:

Insert an element into a sorted array

I wrote this function to insert an element into a sorted array such that array would still be sorted after adding the element.
But something is wrong. I know that my code has a lot of edge cases and probably I'm over complicating the algorithm but I really want to fix it.

My Code :

private static <E> void insert(E e, E[] arr, int count, Comparator<E> comp) {
    if (count == 0) arr[0] = e;

    for (int i = 0; i < count; i++) {
        if (comp.compare(arr[i], e) >= 0) {
            // we found an element that is >= to e
            // we want to add new element at index i, currently arr[i] is occupied
            // by larger element, so we need to adjust
            if (i != 0) {
                i--;
            } else {
                // do nothing
            }
        } else if (i + 1 == count) {
            // this is the last iteration of the loop so we want to add element at i + 1
            i++;
        } else {
            // keep looping to find an element
            continue;
        }

        // we need to move elements to the right to make space
        for (int j = count; j > i; j--) {
            arr[j] = arr[j - 1];
        }

        arr[i] = e;
        break;
    }
}

My repo

A:

I fixed the code, I should have not decremented i
private <E> void insert(E e, E[] arr, int count, Comparator<E> comp) {
    if (count == 0) {
        arr[0] = e;
        return;
    }

    for (int i = 0; i < count; i++) {
        if (comp.compare(arr[i], e) >= 0) {
            // we found an element that is >= to e
            // we want to add new element at index i, currently arr[i] is occupied
            // by larger element, so we need to adjust
        } else if (i + 1 == count) {
            // this is the last iteration of the loop so we want to add element at i + 1
            i++;
        } else {
            // keep looping to find an element
            continue;
        }

        // we need to move elements to the right to make space
        for (int j = count; j > i; j--) {
            arr[j] = arr[j - 1];
        }

        arr[i] = e;
        break;
    }
}


Q:

The $ dollar sign

I have something simple like this:
$(selector).append("somestuff");

But since I'm going to reuse the selector I cache it with:
var $selector = $(selector);

So I end up with:
$selector.append("somestuff");

My question is, should I be doing that, or should I be doing:
var selector = $(selector);
selector.append("somestuff");

Trying either one, both works. Which method is correct, and why?  Is the $ in $selector unnecessary because the jquery object has already been declared in $(selector)?

Edit
Thanks for the answers. It seems very simple and quite clear. Still, there seems to be disagreement over whether or not I should use $ in the variable. It would be nice for everyone to vote up an answer. :)

A:

$ is just a name - names in JavaScript can contain dollar signs, and can consist of just a dollar sign.
Whether you use a dollar sign in your name isn't relevant to jQuery - there's nothing special about the dollar sign, except that jQuery defines a function called $.

A:

I've seen it done both ways.  All you are doing is creating a variable with the name '$selector', so they are functionally equivalent.  The nice thing about it is that it does make them easy to pick out as jQuery objects.

A:

The cash sign is just an alias for the jQuery function. Starting the variable name with $ has no effect on that variable.
It is customary though, especially in jQuery plugin development, to use variables already wrapped in jQuery with a cash sign, so you know you can call jQuery methods, without having to wrap them.


Q:

Storyboard Zoom In/Out Keyboard Shortcut

What shortcut key combination can I use in Xcode to zoom in and out? Yes, I know this is a silly question but a Google search didn't give me any result. Even the Xcode keyboard shortcuts didn't give me much info. Maybe I must ask for a better updated keyboard shortcut doc for Xcode 4.5

A:

You can also double click with mouse on empty area of storyboard. First time will zoom out, second time - zoom in. Sometimes it's easier than use difficult hotkey.

A:

Try this
Zoom Out = shift+command+alt+{
Zoom In = shift+command+alt+}
This worked for me!

A:

From Mouse or Trackpad -> Right Click will show you options. Hope this will help


Q:

Drag and drop function is not working in chromedriver using selenium webdriver and Node js for Test automation

Is there a way where I can make drag and drop to in selenium using Node.js? I am using the function shown below but it does not seem to work.
driver.actions().dragAndDrop(source,destination).perform())

A:

First of all, you forgot the build() method.
Second of all, inspect the html code and find if your drag&drop is into Iframe tag.
If it is, then you need to switch to that Iframe.
So:
driver.switchTo().frame(driver.findElement(By.xpath("PutYourXpathIframe")));

Actions a = new Actions(driver);
WebElement source = driver.findElement(By.id("PutYourSourceId"));
WebElement target = driver.findElement(By.id("PutyourTargerId"));
a.dragAndDrop(source,target).build().perform();

In the end you may want to switch back to default content:
driver.switchTo().defaultContent();