Can a file upload function be vulnerable without it the file name getting passed?

Question: From googling, a lot of file upload vulnerabilities rely on injecting something into the filename and also rely on the picture being stored on the server, is it safe to just do a post request of the picture's content (file-contents: ‰PNG...... via post request) then display it on the browser like, as  ?
Comment: or use a library that is hopefully tested for bugs.
Comment: @VipulNair Not interested in implementing anything myself (I don't own a website), rather to know if the process of uploading a PNG and displaying it in the way I described, is vulnerable
Comment: there are some malformed images that cause problems in some browsers in some contexts from time to time. There's not a universal well-known issue with displaying image data, only targeted bugs that creep up sporadically and generally get patched-out quickly.
Answer: Most definitely!
File uploads can be very tricky and there is a lot that can go wrong.  There are (at least) two further steps you should take:
1. Verify that the file is actually a PNG
If you are expecting only PNGs, then you should verify that the file is actually a PNG.  To be clear, checking the extension is useless here - you want to check the actual file contents themselves.  If you don't do this you open yourself up to a few potential attacks of varying levels of severity:

An attacker can upload a JS file.  This can help as part of a multi-step attack by bypassing a CSP or other restrictions.
An attacker could host their own HTML files/images/an entire website on your website, potentially making phishing or other attacks much, much easier.
Depending on your server setup, an attacker may be able to upload scripts and have your server execute them, compromising your system.

2. Make sure the file cannot be executed by the server
Even if you check to verify that the file is a valid PNG, this may not be enough to stop an attacker from using your file upload to upload and execute scripts.  In particular, most image formats allow for comments and meta data in headers.  It is possible to put actual code in these comments, and in the event of permissively configured servers, the attacker may be able to trick the server into executing it.  Most modern servers with default configurations will be immune to such attacks, but attacks like this are possible and definitely have happened.
Bonus: Host somewhere else
The most straight-forward way of mitigating the above attacks is by hosting your uploaded files elsewhere.  Most modern cloud providers have buckets that are a perfect use case for this (AWS, GCP, Azure), but you can always manage it yourself with a separate server on a different domain that only serves static files.  By hosting the uploaded files on a different domain you skip the risk of CSP bypass, and by hosting it on a server that is incapable of treating files as code, you don't have to worry about missed vectors for RCE.  In essence, by immediately transferring uploaded files to a separate system, you're putting them in a sandbox for safety.


Yearling badge not awarded since assocation bonus

Question: Since I got the association bonus, November 6 2015, I didn't get the yearling badge. As I understand it, the association bonus doesn't count for the yearling badge. So I understand I didn't get the badge when I passed 800 points of reputation. But now I passed 900 points (910 as I wrote this question), and I didn't get it either. Has somebody an explanation for this ?
Answer: You already have yearling 3 times on both SO and Meta.
Seeing as you've been a member for for 3 years and 7 months, everything seems to be correct.
Comment: Basically, you're wrong. The badge is awarded for each year you've been a member, as long as you have at least 200 rep.
Comment: Ok, my bad. Thank you for your explanations. That's seem more logical that the way I understood it :p
Comment: That's not how I understand the badge: as soon as a user got 1 year on a stackexchange site, the badge is awarded every 200 points of reputation. I am wrong ?
Comment: Does second Yearling badge don't give +100 reps?
Comment: @Sandeep: badges don't give rep. None of them do.
Comment: I was asking about association bonus. Do we get +100 reps after getting 2nd Yearling badge (i,e completed second year and got yearling badge) ?
Comment: The association bonus is not related to yearling. They're two different things.


Cartodb-Displaying Mode and Averages in Infowindow

Question: I have some Boolean and string variables that I want to display in the info window on carto db. But it seems to be only showing one individual data point. How do I get it to show modes or averages of the entire data set?
Answer: You need to add some SQL to make that information available. If you open the SQL tray and change SELECT * FROM your_table to:
SELECT *, avg(interesting_column) OVER () AS table_avg
FROM your_table

Now toggle the new variable on in your infowindow to make it available. Just fill in interest_column with the numeric column you want information from, and make sure to update your_table with the appropriate name.
Comment: The SQL trick mentioned here is called a _Window Function_ and you can get more details about them [here](https://www.postgresql.org/docs/9.5/static/tutorial-window.html). They are really useful!!


May you download images dropped in your app as mime type uri-list?

Question: If your app supports drag and drop and receives a drop with mime type subtype uri-list, is it possible to look for image-like suffixes in the uri's (e.g. .jpg) and then download the images?  For example if your app is a drawing program?
Answer: Outline of solution in Qt:
Get a QMimeData in an event handled by dropEvent() handler.
Get a uri-list from the mimeData if it hasFormat('uri-list').
Iterate over the strings of the uri-list until you find one that satisfies:
Create a QUrl from the string.
Use QMimeDatabase.mimetypeForUrl(string) to get a QMimeType.
Is the mime type one that your app supports?
Use QNetworkAccessManager to download the url (in the background, with signals for completion.)  Meanwhile, your app might display a placeholder or a busy cursor.  It doesn't matter if the url is to a local file, the mechanism will still 'download' the url (just more quickly.)
Your app prioritizes mimetypes in a mimedata, and only looks at the uri-list mime type (a reference, or indirection) if a mime type format is not directly (embedded) in the mime data.
The whole process of drag and drop is highly dependent on platform and the pair of sending and receiving apps.  One sending app may choose to embed a mime type while another may choose to send a url in a uri-list (url pointing to data whose content has the mime type, and url whose suffix indicates a mime type.)  On a platform, most receiving apps may prefer a certain mime type (e.g. image/jpeg) and not accept similar mime types (e.g. image/png.)


Delete one specific fragment from the Android backstack

Question: For a android tablet application I use 2 fragments. One on the left side on the screen and one on the right side. When you click on a button at the right fragment, another fragment wil be added on the top of the right fragment. This fragment is added to the backstack.
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.fragmentlayout, fragment2);
ft.addToBackStack("Fragment2");
ft.commit();

The backstack is now:
[fragment 1] -> [fragment 2]
On the left side is also a button that opens a fragment on top of the left fragment (same as fragment2) and adds it to the backstack. The backstack is now
[fragment 1] -> [fragment 2] -> [fragment 3]
On fragment 2 is a button to close that fragment.
getFragmentManager().popBackStack("Fragment2", FragmentManager.POP_BACK_STACK_INCLUSIVE);

The problem is when I only want to close [fragment 2], [fragment 3] will also be destroyed. I can remove the fragment manualy by calling
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.remove(fragment2).commit();

But the backstack will remain
[fragment 1] -> [(ghost) fragment 2] -> [fragment 3]
So you need to press back one time more to close the application.
Is there a way to only remove [fragment 2] from the backstack and leave [fragment 3] on the screen?
Comment: AFAIK, it's not possible. This is a reason it's called stack.
Comment: You need to remove the previous fragment by replacing it with the empty fragment ,only then you will be able to leave Fragment 3.
Answer: You could simply make your own back stack and override onBackPressed() and handle it in any fashion you see fit. I don't think there is any other way to achieve the desired behavior.
Your own back stack could simply be an ArrayList of tags for your fragments.
Answer: I just answered a similar question, so here's a link to that answer.
The implementation allows you to remove a Fragment from anywhere in the backstack and this is achieved by using refrection to modify the internal variables that store the backstack information in FragmentManagerImpl and BackStackRecord.
Although I do not encourage the use of it, I hope it helps.
Answer: This solution only works for your case.
You needn't put Fragment2 into backstack.What you can do is removing the code 'ft.addToBackStack("Fragment2");'.
The Fragment2 is not in the stack.So you close the Fragment2, and leave [fragment 3] on the screen.
Answer: You can create your own fragment manager/observer. It will be just a simple list or map inside. Track them using tag or simply class name (getClass). This way you'll be able to avoid new fragment creation and reuse cached one, thus controlling your memory consumption.
You will also be able to manipulate fragments the way you want (override onBackPressed and push which ever fragment you like), instead of using only the way Google says it should/can be done.


Can I replace casper-rw file from another live usb to have its content copied?

Question: I have a live ubuntu 16.01.1 usb A and B
I would like to copy the contents of A to B
Is it convenient to just copy and replace the file from A to B.
Comment: Sounds pretty simple to me, the op wants to copy the casper-rw persistence file from one persistent install on USB A, to another install on USB B. This has uses such as backup and sharing persistent installs. A search on Google does not mention this. Software can be installed and shared without transferring the whole install. This is a good question.
Comment: This sounds like an [XY Problem](//meta.stackexchange.com/q/66377/271411). What are you actually trying to achieve? About what kind of "contents" are you talking?
Comment: I just wanted to have a backup of my live usb to try sth that could crash or remove most of my data in my installed live usb. But anyway thanks. Replacing casper-rw worked for me.
Answer: Copying a casper-rw file or partition has always worked for me.
You have to make sure that the word persistence is included in txt.cfg for an install made with Startup Disk Creator or in syslinux.cfg for an install made with UNetbootin.
For a grub2 type install made with mkusb the word persistence should be located in grub.cfg.
You can place the word persistence on the kernel line one space after --.
The following is similar for each case:
<code> linux (loop)/casper/vmlinuz.efi boot=casper iso-scan/filename=/ubuntu-16.10-desktop-amd64.iso splash -- persistent
</code>
You can not reuse the casper-rw file or partition in an upgrade of Ubuntu.
You can reuse a home-rw file or partition after an upgrade.
If you are using mkusb as the installer you can even place the persistence partition on your hard drives root or on a second flash drive with a partition formatted ext2 or ext4 and labeled casper-rw.
You can copy and paste a persistent partition using gparted.
Backing up persistent partitions should be done with dd or mkusb which puts a layer of safety around dd. Clonezilla is even a better choice as it ignores empty space.
These preserve the partition's UUID so that programs such as VBox do not require re-installation.
Comment: Please add a simple of the makeusb opción que recheck for typos


What does it mean when someone says: "King me"?

Question: When two children are playing chess or something like that, what does it mean when one kid says: "King me"?
Comment: Check out [the rules of checkers](https://en.wikipedia.org/wiki/English_draughts).
Comment: Yes, checkers/draughts (as seen in the answers) but not chess.  In chess you may hear "queen me", though.
Answer: It is a phrase drawn from the verb form of king that originated in checkers and draughts, but has shifted to include other games such as chess through mix-ups and misuse ("king me" does not end the game in checkers; rather promotes the piece, as opposed to "checkmate" in checkers [Source:  Reddit])

12. verb To promote a piece of draughts/checkers that has traversed the board to the opposite side, that piece subsequently being permitted to move backwards as well as forwards.

I was about to make a move that would corner a piece that she was trying to get kinged, but I slid my checker back.

From Wiktionary.
Answer: Well "King" in this sense is a verb that means to make superior akin to the ruler of a monarchy or independent state and "me" is a pronoun used by a speaker to refer to himself or herself as the object of a verb or preposition.
king me = means to bestow king like qualities on to someone, however, in the common context it generally means to elevate the rank of a checker piece.
"King Me" = Reference to the game of checkers where a player moves a piece to the last row on the enemies side of the board and gets to elevate the rank of his piece by stacking another piece on top of it.
King me = A command, given by one checkers player to another, to place a single checker on top of another checker that has reached the last row on the enemies side of the board.
King = Elevate to the social rank of King
Me = used by the speaker to refer to himself as the object of a verb or preposition.
The interesting thing about that statement though is not only is it a two word statement that adheres to the subject - verb - object syntax but it does it in reverse... object - verb - subject. And! the king in this sense is both the verb and subject...
This is my thought process so I deleted nothing.


Find the area under the curve: $r = 2 \sin (3\theta)$

Question: Find the area under the curve: $r = 2 \sin (3\theta)$ using the polar coordinate system.
Since we are working in the polar coordinate system, the radius may not be negative, and so we will need to take the collective area from three regions of integration: $[0, \pi/3] \cup[2\pi/3, \pi] \cup [4\pi/3, 5\pi/3]$.
Since this region is not normal with respect to $\theta(r)$, it can only be iterated with respect to $r(\theta)$.
And so, the integral will be:
$$3\int_{\theta=0}^{\theta= \pi/3}\int_{r=0}^{r=2 \sin(3\theta)}drd\theta$$
Have I set up the correct integral for this problem?
Answer: Since you are working with polar coordinates you need to use the correct formula for the area traced by your function.
The formula is  $$ A= 1/2 \int r^2(\theta ) d\theta $$
Your function is $$r(\theta ) = 2 \sin (3\theta)$$
Be careful with the limits of integration for the  area of each loop.
Comment: @Aemilius  You may fix your method by replacing your $drd\theta$ with $ rdrd\theta $
Comment: I don't know this formula. What's wrong with my solution?
Comment: Your formula works for rectangular coordinates. You need to learn the formula which I gave you for the area of polar curves. It is not too complicated, just integrate your $r ^2(\theta) $ from $0$ to $\pi/3$ for one loop.
Comment: But of course, I need to use the Jacobian! now i get it!


Numbering a bunch of files according to the date modified timestamp?

Question: So I downloaded a bunch of documents in chronological order, but I have to copy and edit them, which would change the date modified. I would like to prefix them with a number (001_, 002_...) in the order I downloaded them in.
Comment: And what have you tried so far? That's part of the *research* for each question.
Comment: I found a solution on this site that appends the date modified at the end of the filename, but that one doesn't do much for me. There's only 667 files so I could do it by hand, but this is not the first nor is it the last time I need to do something like this.
Comment: The idea is to come here with a question. If you want to add information to your original question, you edit it (instead of posting an answer). By the way "that doesn't do much for me" doesn't do much either for those trying to help. Please add to you question the problem you have with the solution you found. An error message, for example.
Answer: With zsh:
autoload zmv
n=0; zmv -n '*(#qOm)' '${(l[3][0])$((++n))}_$f'

(remove the -n (for dry-run) when happy).
That's:

zmv: autoloadable function to rename files using zsh extended globs and substitution operators
*: all non-hidden files in the current directory
(#q...): the verbose form of introducing glob qualifiers
Om: order in reverse by age. So newest last.
${(l[3][0])$((++n))}: left-pad the expansion of $((++n)) on width 3 with 0s.
_$f and append _ and the original filename
Comment: Doesn't do anything for me. I'm using Linux Mint, if that helps. This zsh is installed but "autoload zmv" gives "command not found".
Comment: @user471414, you need to run those commands from within the zsh shell. The default shell on Linux Mint is bash, a shell with a similar syntax but much more limited. You can start zsh from bash, by just entering zsh at the prompt, or make zsh your default interactive shell instead of bash with `chsh`.
Answer: Found the solution here.

ls -1tr | rename -v 's/.*/our $i;if(!$i){$i=1;} sprintf("%04d.pdf", $i++)/e'
Answer: find . -type f -printf '%C@ %p\0' |
  sort -z -n |
  awk  'BEGIN{RS=ORS="\0"};{print $2}' |
  rename -0 -n 'our $i;
                s:(^.*/)([^/]*):sprintf("%s%04d_%s",$1,++$i,$2):e'

This uses GNU find to print NUL separated filenames (%p, so the full path) prefixed by their modification timestamp (%C@) and a space character in unix seconds-since-the-epoch numerical format.
If required, you can use any of find's other options here to refine the file search (e.g. -name "*.pdf", -maxdepth 2, etc)
find's output is then piped into GNU sort using the -z -n options to sort the NUL-separated input numerically (by the timestamps), and then into awk to strip the timestamp and the space, and then finally piped into a perl rename script.
The perl rename script uses the -0 option to read NUL separated records from STDIN, and then:

uses sprintf() with '%s%04d_%s' (%04d_ is zero-padded, 4 digits wide and an underscore), using $i as a counter to replace the filename portion of the name.
$1 is the path portion of the full filename, $++i is an auto-incrementing counter variable, and $2 is the base filename.

$i is declared with our to make it a global variable, so it keeps its value for each iteration of the loop (otherwise it gets reset to zero every time).

The -n option turns this into a dry-run operation, so that it only shows what would be renamed.  Once you're sure it's going to do what you want, remove -n to quietly rename the files with no output, or replace it with -v for verbose output.
Unlike using ls -1tr this will NOT break if any of the filenames contain newlines.   It will work with any valid filename.

FYI, to append a nicely-formatted date to each filename, see my rename script at Renaming a bunch of files with date modified timestamp at the end of the filename?.  This is easily modified to prefix the filename with date & time. It runs stat on each file to get the timestamp, so the filenames wouldn't need to be pre-sorted.
e.g.
rename -n 'BEGIN {use Date::Format};
           die $! unless -f $_;
           next if (m/^\d{8}-$/);
           my $ts=(stat($_))[9];
           my $dt=time2str("%Y%m%d-%H%M%S",$ts);
           $_ = "$dt-$_"' *.pdf


French drain - emitter or other water dispersal method?

Question: I am building a french drain about 20 feet long that is only needed during very heavy storms, sloped correctly, that will terminate at the spot I want a few inches below the ground surface. Will the flowing pipe water be strong enough to make the short upward turn to utilize an emitter, or should I end the drain with some other method like a box, etc?
Answer: Ending the perf pipe slightly below grade will cause the water to back up and not drain.
I like placing large rocks (2" - 6") around the pipe outlet. This allows the water to flow out and is dispersed out on the surface without eroding the ground. (I try not to use small rocks, because they get "washed" out in heavy rain.)


How do I make a large set of objects appear over a period of time?

Question: My data assigns a specific time (say a calendar day or shorter) to the appearance of each of its several hundred objects. To show this I'd like to run through say a year of time in about 10 seconds and have the objects appear on the 3D display sequentially. Should I set out to write a python script that simulates time passage and then changes the layer or transparency of each object depending on whether its time has arrived? This sounds like a lot of processing, rechecking the status of all objects every unit of time. Is there some standard efficient strategy for minimizing the processing time so the computing time doesn't slow everything down?
Answer: Keyframes or Drivers on hide and hide_render
I would suggest either creating ether a keyframed action, or setting up drivers on the hide and hide_render properties of your object.
How you convert from your time to frames is up to you. In bpy.utils there is a convenience method that converts a datetime object to a frame.
Drivers
Each object from data will be hidden (both in viewer and to render) until the scene frame is greater than the data frame. Test script below.
import bpy

context = bpy.context
scene = context.scene

data = [[0, 0, 1, 12],
        [0, 10, 3, 30],
        [3, 3, 4, 40],]

for line in data:
    x, y, scale, frame = line
    bpy.ops.mesh.primitive_uv_sphere_add(
            location=(x, y, 0))
    ob = context.active_object
    # set scale
    ob.scale *= scale
    # add drivers
    for dp in ["hide", "hide_render"]: # xxx
        driver = ob.driver_add(dp)
        driver.driver.expression = "frame < %f" % frame

Keyframes
Keyframe as hidden at frame 1, show at data frame.
    # add keyframes
    for dp in ["hide", "hide_render"]: # xxx
        setattr(ob, dp, 1)
        ob.keyframe_insert(dp, frame=0)
        setattr(ob, dp, 0)
        ob.keyframe_insert(dp, frame=frame)


My bonsai tree is dying

Question: Both of the trees are very brittle and dry. They are both either pices mariana or one of them may be a pinus aristata. I started growing them in the summer and they were fine but when winter came along they started to look like this. I water them when the soil starts to look dry. Also I keep them in my window seal at all times (there's a radiator right below) I got them from a kit off of amazon also.
Comment: I think "is dying" is being optimistic. To be honest, those plants look "dead" to me.
Answer: Regardless of what species of pine they may be, they would be far better off outside in than indoors.As long as they experience deepening overnight cold, as is characteristic of normal fall weather, they will be able to tolerate freezing temperatures. Alpine species, such as p. aristata can tolerate cold approaching 40 degrees below zero.
The primary problem with being indoors is that light levels are too low to sustain the plant. Bright light indoors is about the same luminance as deep shade outdoors. Pines do best in full sun.
To the point of your seedlings, they are dead. After you have killed enough of them you will come to recognize the off color (sort of grey-ish) green that is the first indicator of serious trouble. Death occurs as long as months before needles turn brown.
When you try again, time it so that the seeds sprout in spring and leave them outside. Your results will be more enjoyable that way. Smaller pots, say 2 to maybe 4 inches across, will be better until they are at least 2 years old.
Comment: Totally agree with this answer, and to add a small point to this: the radiator is also problematic for bonsai plants, they evaporate more water then they can take up with their small roots. Keep your bonsai outdoors, unless you have a tropical species.

My bonsai tree is dying


Can I apply Kirchhoff's current law to two separate nodes which are connected only by an ideal wire?

Question:
Suppose there are 2 nodes A and B in the above circuit. If A has 2 incoming currents $I_1$, $I_2$, and B has 1 incoming currents $I_3$, $I_4$, is it correct to write the equation of whole nodes and circuit as $I_1+I_2-I_3+I_4=0$?
Answer: For (truly) distinct nodes in a Kirchhoff circuit network, it is not appropriate to formulate the Kirchhoff current law taking in the currents from separate nodes and mixing an incomplete set from both.
For the specific circuit in your question, however, the "nodes A and B", as you have described them, are not actually distinct. Any two points linked by a zero-resistance wire are effectively the same node, so for your circuit there are effectively only two nodes. You should re-draw the diagram in a way that minimizes the number of nodes (and thus eliminates any superfluous nodes), and then you can formulate the Kirchhoff current law at each of the remaining nodes.
Comment: @lalala Yes. But it needs to be done carefully, which cannot be ascertained from the description given by OP.
Comment: You could though draw any circle (or any closed shape) into the Diagramm and formulate kirchoffs current law for all the lines crossing this circle, couldn't you? Since it is basically Div j=0, so the sum over all currents crossing any closed shape are zero.
Comment: I agree. I just thought I mention it, I haven't had this insight before thinking about this question.
Answer: In your drawing A and B are not separate nodes, they are different points on the same node. All points connected by a single contiguous conductor are a single node.
If you tried to treat them as separate nodes then you would have to consider the conductor between them to be a 0 ohm resistor. This would do nothing but add some additional equations which would be more complicated but would eventually boil down to $V_A=V_B$, which we already knew by inspection of the circuit diagram.


Does Ubuntu One sync symbolic links with Windows?

Question: I noticed that the Windows Ubuntu One client currently doesn't support folders outside of the main ~/Ubuntu One folder.  I'm wondering if I can symlink to my other folders from within ~/Ubuntu One and have Ubuntu One synchronize them properly.  If this isn't supported yet, is it planned for the future?
Comment: you should probably rephrase your question as **"Does Ubuntu One sync symbolic links with Windows?"**.
Comment: No I don't think so.
Answer: Symlinks won't be followed in Ubuntu One for Windows. The way it will work is the same way as the existing Ubuntu One for Ubuntu: you'll be able to mark any folder as synchronised with Ubuntu One. We're working on that right now. :-)
Comment: Great.  Will you send a notification to beta users when you finish with that?
Comment: The windows client currently has part of the code that will notify you about updates, will download them and install them. As soon as we have updates for this, we will do so. I'm also planning to move to use omaha rather than the custom code that we currently have.
Answer: (removed - consider Stuart's answer)

Say for example you want to synchronise /home/matt/test, instead of making a symbolic link to this directory in ~/Ubuntu One, make test be a symlink to ~/Ubuntu One/test, which is a proper directory.
that's
mkdir Ubuntu\ One/test
ln -s Ubuntu\ One/test test
cd /home/matt/test

This should alaways work, since Ubuntu One doesn't need to know about any of it.
Answer: Until Ubuntu One for Windows implements a way to mark folders for synchronization, you could try creating Junctions (a sort of special link) on the folders you you wish to synchronize.
To do this without having to use the Windows command prompt or a separate microsoft toolkit, look for a program called Link Shell Extension (which seems to work in 32-bit and 64-bit Windows). After installing it, you can simply right-click-and-drag any folder into your Ubuntu One folder, and then select Drop --> Junction.
Individual files can be sync'd as well; the only difference is that you would select Drop --> Hard Link after right-click-dragging the desired files.
Hope this helps!


What is the difference between volatility and dispersion in finance?

Question: I am confuse whether the volatility and dispersion is same or not because are use
to measure the risk associated with asset. Even if they are different than what is the relationship between, if exist.
Comment: Volatility is a measure of dispersion - please see here (thinking vol ~ std dev) https://en.wikipedia.org/wiki/Statistical_dispersion
Answer: Dispersion (also called variability, scatter, or spread) is the extent to which a distribution varies (to the left and right) from its central tendency. Sample variance, $\sigma^2$ is the most common measure of dispersion. The square root of variance, $\sqrt{\sigma^2}$, is standard deviation, $\sigma$.
In finance, risk is proxied with volatility, which is measured using the standard deviation, $\sigma$.
Answer: Regarding terminology, dispersion is sometimes used to refer to a trade which is short index correlation, i.e. you are betting that the constituents of a certain index (usually an equity one like the S&P 500) will be decorrelated. This involves being (1) long individual component volatilities, and (2) short overall index volatility.
For an index $I$ with constituent prices $S_1,\dots,S_n$ and weights $w_1,\dots,w_n$ the volatility $\sigma_I$ of index returns is:
\begin{align}
\sigma_I
=\sqrt{\sum_{i,j}w_iw_j\sigma_i\sigma_j\rho_{ij}}
\end{align}
where $\sigma_i$ are constituents' price volatilities and $\rho_{ij}$ their pairwise correlations. When you are long dispersion you are betting that these pairwise correlations will go down; you short index options but you hedge any change in the component vols $\sigma_1,\dots,\sigma_n$ by being long options on the individual components.
Hence in this context dispersion relates to correlation - and not volatility per se.


How to have a Joomla module on top of another module

Question: Is it possible to have a module on top of another module? If so how would I go about doing this. Can anyone help me out please?
Comment: Have you tried assigning the 2 modules to the same position?
Comment: Yes I have but it just goes underneath the first module. I am wanting to have the first module as a white background and then text on the second module. So basically the text will be on a white background.
Comment: Why would you want to do that? Why not simply have a white background with text on 1 module?
Comment: I can't seem to get it to work that way so I am wanting to do the 2 modules on top of each other. How do I go about doing this?
Answer: I'll put this as an answer so I can go into further detail.
So you basically need a module with a white background and text on top of it. You initially wanted to have 2 modules. 1 on top of the other. Simply fact is that this is a bad approach and not required at all.
To suit your needs, you only need 1 module, so go to your Module Manager, create a new module and set the type to Custom. Once done, you will see a field called Module Class Suffix. Type in something which will act as a CSS class. For example white.
Note: Make sure you put a space before the word
Once done, open the CSS file for your template and add the following code:
.white {
    background: #FFF;
    color: #000;
}

This will make the background for your module white an d the colour of the text black. You can of course add additional styling to suit your needs.
Hope this helps


Difference between  割合 vs 率

Question: 割合  and  率 both mean ratio, rate, and percentage. What is the difference?
Answer: Neither means percentage. Percentage is one hundred times ratio or rate. The Japanese word for it is 百分率. Likewise, permillion is one million times ratio or rate. The Japanese word for it is 百万分率.
My impression is that 割合 and ratio are the general terms for a quantity divided by another quantity (usually but not always of the same dimension). 率 and rate are especially for cases where its lowness or highness is connected to its preferred amount in an ideal situation. For example, 率 or rate is used for 誤差~ or error ~ because the ideal case would be zero. It can be also used for 正解~ or correctness ~ because the ideal situation will be one. It is also used in 転送~ or bit ~ because the larger the better.
Comment: @ZarNge Accept the answer, please? Click on the "tick" on the left of the answer, which will turn green when you highlight it.
Answer: these two words literally share the similar meanings of ratio,rate.
translation of the the explaination from the yahoo 知惠袋 website
割合 normally is used to refer to the proportion of sth,the relationship of one thing to another in size, amount, etc.
eg: 1. The proportion of men to women in the college has changed dramatically over the years.
近年学校の男女の割合を大きく変化しています。
 2. Limestone and clay in the proportion 2: 1.
石灰石と粘土の割合は2対1also :
石灰石と粘土の比率は2対1

率 is often used after a sort of noun in order to express the percent of ...;for instance percentage "百分率", percent of pass "合格率", percent of attendance "出勤率" etc.
and as mentioned above, when use with "比" as"比率", 比率shall substitute "割合".
Comment: Your first example is ungrammatical. You are wrong in that `合格率` etc. does not mean percentage by itself, although it can be measured in terms of percentage.

Difference between  割合 vs 率


Does English obey the maximal onset principle?

Question: Does English always obey the maximal onset principle?
Answer: Not obviously, but one can concoct analyses that dispose of counterexamples. The consonant [ŋ] does not appear in a syllable onset, thus orangutan has /ŋ/ in the coda, not the onset, unless you decide that because of the maximum onset principle it must be in the onset as well, in which case you could posit syllable-initial ŋ. If you work through the facts in Daniel Kahn's dissertation, you will see that there is no compelling case where C in the environment V_V must is exclusively in the coda, it can always be shared between the preceding coda and following onset. In which case, the discussion turns to whether max-onset is an absolute linguistic universal that can never be overridden by language-specific facts (therefore it defines how you have to analyze the facts), or is it a scientific hypothesis that might be entertained in a language, but might not be if there isn't good evidence for it in the language.
Incidentally, the name "maximum onset principle" refers to a class of related ideas, one being "onset first", the other being "everything possible goes into the onset". Kahn's rule was to put as much possible into the onset but this was just a fact of English grammar and not a "principle" in any sense. Clements & Keyser on the other hand had a "principle" of first building a CV core syllable, then adding more things to the onset and coda, which is another view of "onset maximization". So you have to also say exactly what you mean by "maximal onset principle".


Hide attribute for configurable product in frontend

Question: I have a configurable product which shows 4 dropdowns in the frontend on the product detail page. I'd like to hide some of them, and was hoping to achieve this using "Visible on Product View Page on Front-end" setting for the attributes, but they still appear in the frontend. Any help would be greatly appreciated!
Comment: You add a simple product and then assign into configurable product right
Answer: That means you chose all four attributes when you created your configurable product.
Now these values must be chosen by customer. You can not hide it.
Solution:
Create same configurable product but only select what attributes you need to show in frontend.


Is daydreaming bad (outside of meditation)?

Question: A advise that I was given is to be "mindful" when I'm not meditating. However, it seems that mindfulness is incompatible with daydreaming (especially those in which we can get really engrossed and lose our sense of the present moment). Therefore, is daydreaming/fantasizing bad?
Answer: It is hard to be mindful yet it is beneficial.

SN1.18:2.1: "Few are those constrained by conscience, who live always mindful.

It is easy to daydream yet it is fatal while driving.
Which would you choose moment by moment?
Answer: Yes, in general it's a giving of wrong attention.

Whatever a monk keeps pursuing with his thinking & pondering, that becomes the inclination of his awareness. https://www.accesstoinsight.org/tipitaka/mn/mn.019.than.html

Thoughts based on perception of attractiveness, of honor & fame and of sensuality are going to wreck havoc on your training and discipline.
If it's rooted in delusion, aversion or greed then the thought should not be tolerated and is classed as distracting thought.
Removal of distracting thoughts is taught in a likewise named sutta.
In general if one sees these thoughts it's due to lack of development of good perceptions and due to the development of bad perceptions.
If one doesn't even take note of these circumstances then one lacks mindfulness.
If one does take note as one sees the arising, persistence & the cessation of thoughts, feelings and perceptions,then one can make adjustments like ie countering perception of attractiveness by focusing on the unpleasant.
If one can both take note and make the necessary adjustments then one will eventually become quite great;

When, indeed, bhikkhus, evil unskillful thoughts due to reflection on an adventitious object are eliminated, when they disappear, and the mind stands firm, settles down, becomes unified and concentrated just within (his subject of meditation), through his reflection on an object connected with skill, through his pondering on the disadvantages of unskillful thoughts, his endeavoring to be without attentiveness and reflection as regards those thoughts or through his restraining, subduing, and beating down of the evil mind by the good mind with clenched teeth and tongue pressing on the palate, that bhikkhu is called a master of the paths along which thoughts travel. The thought he wants to think, that, he thinks; the thought he does not want to think, that, he does not think. He has cut down craving, removed the fetter, rightly mastered pride, and made an end of suffering."https://www.accesstoinsight.org/lib/authors/soma/wheel021.html#ch-1


What feats expand a character's critical range?

Question: What dnd 4e feats exist that expand a character's critical range?  For example, my cleric took the paragon path Radiant Servant and was granted the feat Illuminating Attacks, which makes his radiant attack a critical on 19 or 20.  I would like to know this to keep in mind for other characters that I may make in the future.
Comment: Be sure to check with your DM. There are some well known commentators that think expanding crit range is one of the ways 4e is broken. Particularly, how the "on crit" based powers, combined with these feats leads to "outrageous" chains of effects. See: http://slyflourish.com/dd_essential_conversations_with_kato_katonian.html
Comment: @F. Randall Farmer, this'll be our first foray into paragon tier.  if we decide that the expanded crit range is too powerful i'll change to something else.  but thanks for the heads up!
Answer: From a search on the compendium for "critical 19-20" under feats

Power of Luck: 19-20 for Bond of Censure, Holy Strike, Lance of Faith, Vanguard's Lightning
Ogremight Bruiser: Fighter, Ogremight Student, 19-20 on charging and 2h hammer (what's that, Mordenkrad and Avalanche hammer?)
Ogremight Ravager: Warlord, Ogremight Student, as above.
Steel vanguard captain: Warlord, 19-20 on certain encounter powers with 2h heavy blade
Steel Vanguard Soldier, Fighter, as above
Steel Vanguard Student, 19-20, 2h weapon, cleave and viper's strike
Defiling Adept, 19-20 on daily arcane with defiling
Phantasmal Destruction, 19-20 on wizard illusion powers with combat advantage. Note "Illusion Master" from mage, Illusion Master: When you hit or miss a target using an arcane illusion power, the target grants combat advantage for the next attack made against it before the end of your next turn.
Violent Joy: 19-20 on... ardent edge case.  When you target a bloodied ally with your ardent surge and that ally regains enough hit points to no longer be bloodied, he or she can score critical hits with melee attacks on a roll of 19–20 until the end of your next turn.
Advantageous Perspective: Small creature, When you make a melee weapon attack, you score a critical hit on a natural roll of 19 or 20 against Large or larger creatures granting combat advantage to you.
Plunging Blade: Fighter, OA with light blade.

Epic Feats:
They fall into two categories: class based implement and stat based melee weapon. Most older classes have them. Some builds get royally screwed.
Implement Mastery:

Bard
Sorcerer
Warlock
Wizard
Avenger(special)
Swordmage
Psion
Comment: +1. Interesting enough is the same search on DDI with "critical 18-20" ^_^
Answer: To start there are the following feats:

Weapon Mastery Feats give expanded crit range (19-20) to weapons by category (heavy blades, light blades etc). These have a stat prerequisite and are available in epic.

There are also some paragon paths that give expanded crit range for instance:

Dagger Master (Rogue) expands crit range to 18-20 on dagger attacks.
Radiant Servant (Cleric) expands crit range to 19-20 on radiant attacks.


How to import a live Drupal site into Acquia Drupal Dev Desktop?

Question: I would like to make some major changes to our live Drupal website. I'd prefer to do it in a safe local development environment on my laptop. What are the steps/process to exporting a live Drupal 7 and importing it into the Acquia Drupal Dev Desktop?
Answer: First, use the Backup and Migrate module to create a copy of the database. Then download all the Drupal site files to your machine as well.
You can set up a local version by using the import option Acquia Drupal Dev Desktop instead of creating a new site and importing the Drupal files you just downloaded.
Then use the Backup and Migrate module again on the local site to synchronise the database.
Answer:
Back up your Drupal folder on the live server.
Access PhpMyadmin, and export the database, put it in a folder.
Write down the name of your database and any prefix that may have.
Create a Folder on your pc where you plan to use as a Dev environment.
Copy the backup folder from your live server to this folder.
Launch Acquia Drupal Dev Desktop, click Settings -> Sites -> Import
Click Browse, select your local folder with the Drupal files from your live server.
On Database select "I have a MySQL database dump file for may site".
Click to Browse the dump file exported on step 2.
Write a Server URL for the Dev environment (on Domain).
Click import.
Profit.

I wrote this from memory, so if you have any problem just post back.
Answer: One method of importing an existing Drupal application to Acquia Cloud is to create a Drupal site archive and then use the Acquia Cloud interface to install the site archive. This method works best for applications that aren't very large (website archives smaller than 100MB).
To import an existing Drupal application to Acquia Cloud using a site archive file, complete the following steps:
Prepare your application before you export it from your current environment.
Create a Drupal site archive file for import by exporting your existing Drupal application.
You can use the tools provided in your existing application environment (including Acquia Dev Desktop), or you can use the Drush archive-dump command. The archive-dump command is available in Drush 4.5 or later. For more information about importing your application using Drush, see Importing an existing application using Drush.
Import your website into the Development environment of your Acquia Cloud application. Acquia Cloud commits your application code to your Acquia Cloud code repository, installs the database, and uploads your files.
from:
https://docs.acquia.com/acquia-cloud/create/import/archive/


Transfer from Italy to Turkey still pending

Question: I made a transfer on 02/07/2019 from Italian EUR account to a Turkish Eur account. The status at that time was empty but the very next day the status became as "Preso in carico" which means taken charge. If we count the days from Wednesday onwards, it makes 6 working days. I also did not see any amount deducted from my account but a few hours back I see that my available balance shows the wrong amount. The amount has not appeared yet in my statement and does not show there. I have called the helpline too but no help. Does this mean that the transaction is still in process?
Answer: In general there are only two sets of people that can help give you useful information - the sending bank and the receiving bank.
I have always started with the receiving bank, and ask them for an update and timeline. For instance I once called a bank that said they saw the incoming transfer in the system, so they had it, and said they try to complete all transactions within X hours - of course it had already been X + 8 hours when they said that, but basically that just meant that they had the money and they would get to it when they get to it. I asked for a time frame and planned to call back if they didn't do it, but they said end of day and they ended up doing so with 1 hour to spare.
If the receiving bank can't confirm they see/received the transaction, call the issuing bank and see what is up on their side. Confirm all relevant numbers to ensure there is no error in the transaction, on your end or theirs.
Once you have relevant updates from them, about the only thing you can do is wait, or try to annoy them into doing their job more quickly - calling the company or individual branch, asking for an update/timeline, and then calling back again when that time is near or passed. Escalate to higher levels of management as the screw up seems to be more severe.
About the only time you can usefully do something else is when there is an officially published timeline that they have wildly violated, such as promising 24-48 hours but taking more than a week or two. You can then try to complain to a relevant regulating authority if your continued calls and requests to escalate don't work, but banks are pretty resilient to small-scale individual complaints, and most regulating authorities are slow enough that they will only help in severe situations or if you are seeking some sort of recompense that the law requires (such as a refund of fees, etc., and this will take weeks or months generally).
Comment: @indexOutOfBounds Also, they may be counting working days, not elapsed natural days - so weekends and bank holidays don't count.
Comment: Thank you for the information. The amount was not deducted from my account on the successful transfer? Now somehow after 6 days the total available balance shows a reduced amount? I already called my bank and they said it can take up to 7-10 days. Tomorrow its going to be the 7th day haha
Comment: Yup. I am counting working days.
Answer: Depends on individual luck, a cross country money transfer using bank service is never pleasant. Because there are more than 2 levels of clearing system involved and nobody can tell you which level mess up.
For any individual wants to transfer money to foreign bank account, always using peer-to-peer money transfer services such as transferwise and its alternatives.
They offer lower rates and faster clearing (In fact, money change hand locally than wired over). Those services are perfectly legal and abide to local law.


Hec Ras Error Message

Question:
I am getting this error when I am running unsteady flow analysis.I run geometric correction mesh calculation but still, the error is same.
Comment: Please do not post images of error messages, or at least *only* images. Questions should contain the actual error message as ASCII text in the body of the question, so that 1) others may search for the same error, and 2) the error will be legible on all display devices. Failure to do this conveys the message, "I only care if I get my answer,  not if the question is of general use to the community," and generates downvotes in response.
Answer: Looks like your ERDAS was installed on a network drive that you lost connection to.
Try installing ERDAS locally and trying again.

Hec Ras Error Message


Increasing Frequency of a Signal

Question: I was wondering if it would be possible to increase the frequency of a signal by a fixed amount. Basically, I have a negative wire soldered to a speaker and a positive wire that very quickly breaks/unbreaks the circuit. As expected, this causes the speaker to pulse each time the positive wire breaks and unbreaks. However, the frequency is very low and I was wondering if it would be possible to have a circuit that "adds some frequency" to the current frequency so that I would get a continuous beeping instead of some pulsing with noticeable space in between. The circuit would have to be pretty simple since I'm making it myself. Is this feasible or should I just be happy with what I have?
Comment: To clarify: you're a beginner to electronics, and you're trying to make a speaker play a simple sound?
Answer: A mixer might be what you're looking for.
A mixer multiplies two signals together. \$x_{out}(t) = x_1(t) \times x_2(t)\$ if \$x_1\$ and \$x_2\$ are two input signals. From the multiplicative property of the Fourier transform, this means that in frequency space, the output contains sum and difference frequencies of the input.
Say \$x_1(t)\$ is the signa produced by you moving your wire around. And \$x_2(t)\$ is a sine wave at some frequency \$f_0\$. Then if you put these two signals into a mixer, the output will be your \$x_1\$ signal shifted up in frequency by \$f_0\$. There is also a shifted version of the negative-frequency part of your input signal, but that might not be important or it might be what you actually want, depending what you're trying to do.
You can also see that if \$x_1(t)\$ is a square wave that's sometimes 1 V and sometimes 0 V, and you multiply it by a sine wave, you get out a pulsed sine wave, or a series of beeps, if \$f_0\$ is an audio frequency.
Comment: Thank! This seems perfect. The end noise from the speaker will still be reflective of how fast the wire is disconnecting/connecting but also makes it a continous noise and not just spaced out beeps.
Answer: Assume your signal is a square wave and that its frequency is \$f_0\$. This square wave is actually the sum of sines of frequencies \$f_0\$, \$3f_0\$, \$5f_0\$, and so on. You can design a band-pass filter around one of these higher-frequency harmonics to produce a continuous sine wave of a higher frequency.
These sines are known as the signal's harmonics, and they decrease in amplitude as they increase in frequency; you may need to amplify the signal after filtering. You could do all this with two or three op-amps. Search for Texas Instruments application report SLOA093 for easy recipes for filter design.
Comment: This might be what OP wants, but it would not increase the frequency of the input by "a fixed amount" as requested.
Comment: @ThePhoton, OP can't choose any arbitrary frequency, that is correct. Unless s/he can control the frequency of the square wave. However, he also wants the speaker to play a "continuous tone", which can be achieved by what I proposed. Using a mixer, he will get the sum of many tones, not a single one.
Answer: I don't think anyone's actually read the question properly.
"As expected, this causes the speaker to pulse each time the positive wire breaks and unbreaks. However, the frequency is very low and I was wondering if it would be possible to have a circuit that "adds some frequency" to the current frequency so that I would get a continuous beeping instead of some pulsing with noticeable space in between."
"This causes the speaker to pulse each time the postive wire breaks and unbreaks". "Add frequency", it sounds like he actually wants to generate an audible tone from the speaker, which means constructing an oscillator.
Search for "Square wave oscillator" on the net, which will produce a square wave or a "Wien bridge oscillator" which will produce a pure tone - a sinewave only.
You can look for circuits using a 555 timer chip, "audio circuits using 555 timer"
You should find some that will drive a speaker directly.
If your request is actually different to this, and you have a signal which is too low in frequency, and you want to shift the frequency, then a mixer circuit might be a good way to do it, but it's a little more complicated because you'll end up with effectively two signals (side bands) and you will need a filter to remove one of them.

Increasing Frequency of a Signal


Travelling through Moscow - visa for transit?

Question: I am a Norwegian arriving terminal E (from Oslo) and leaving from terminal F (to Beirut) at the Moscow (Sheremetyevo) airport.
Will I need a visa for this travel?
Answer: No, both terminals E and F are designed for international flights and are connected through the corridor which doesn't have any passport control check points.
Check out the map of the airport.
Answer: The answer from @OleksandrKravchuk is correct only if you stay in Sheremetyevo less than 24 hours. If your transfer is longer than that, you'll need the visa. Refer to official documentation for more details and connection times.


What is the percentage of recent graduates with a 4-year degree who have passed a Calculus I course?

Question: I'm fairly certain that this exact statistic doesn't exist, so educated estimates are welcome. According to the Education Data Initiative, almost exactly 2 million Americans graduated with a bachelor's degree in 2022.
Answer: The Conference Board on the Mathematical Sciences (CBMS) conducts a survey every five years that includes data on enrollments in Calculus courses.  Sadly the 2020 report isn't yet available, but the 2015 report has some relevant data:
https://www.ams.org/profession/data/cbms-survey/cbms2015-Report.pdf
The survey shows about 950,000 enrollments in calculus level courses in 2015.  That includes both Calc I and Calc II, counts students who enrolled but did not pass, and includes various kinds of "Calculus Lite" courses such as business calculus, so it's not perfect. A reasonable order of magnitude estimate is about 500,000 graduates per year who had passed Calc I, out of a total of roughly 2.1 million college graduates per year (various sources) and about 450,000 STEM graduates per year (various sources).  Various sources say that about 20% of college students are in STEM majors.
Some non-STEM students take calculus, and some STEM majors don't require calculus of their students (For example, it's becoming common for biology programs to not require any calculus.) Overall, 25% seems to be in the right ballpark (I'd be surprised if it was lower than 5% or higher than 50%), although there will be considerable variation across institutions and degree programs.  For example, two semesters of calculus are part of the general education requirements for all BS degrees at my institution.
Comment: Some students complete Calculus I or II in high school. So they graduate from college with calculus but might never be enrolled as undergraduates. While this number is small it adds to your estimate.
Comment: The number of students who take calculus in high school is quite large (hundreds of thousands) but many of them do not earn college credit (by passing the AP exam or taking a dual credit course) and many of these students end up taking calculus again in college.


Legal - Will code-naming a project after Marvel property be a problem?

Question: I am developing a game, and since I haven't decided on a name yet, I've named it say, Project Deadpool. I plan to release the game as a beta. Will this cause any problems. It is just a name until a proper name can be decided.
Comment: Its literally impossible to say for sure. If Marvel want to sue you, they can sue you. Suing someone requires money, not a legitimate reason. The courts determine if the reason is legitimate; why risk it for something as pointless as a beta name
Comment: Legal questions are usually more appropriate on https://law.stackexchange.com
Comment: As others have said, don't risk it. Apple codenamed a programming language they did years ago "Dylan" and got sued by Bob Dylan. No matter that "Dylan" is an old proper name... you don't want to get in such a situation if you can avoid it.
Answer: Imagine your game attracts the attention of Marvel or any other company's lawyer sometime in the future. For whatever reason, sound or unsound, they claim your game is infringing on their intellectual property and tell you to take it offline.
If you go to court to argue that you didn't use any of their IP, and they present evidence showing the original name of the project was literally the name of one of their properties, that doesn't help your case. To a neutral observer it may look very much like you set out to deliberately infringe on their IP, later name changes and other differences notwithstanding. You'd have to work that much harder to change a judge's mind in your favour.
So why put yourself in that position in the first place?
Generally it's better to avoid getting into such a situation from the start. Getting into a legal battle with a huge company can be astronomically expensive, whether or not you've broken any law. The economics and systems of IP law tend to encourage these companies to be very protective of their properties, so the general not-legal-advice recommendation is don't go out of your way to bait them. ;)
Comment: Aka a trademark dispute. Marvel does not want people confusing your game for something Marvel owns. This is why Bethesda took Mojang to court.


Field inside cavity of charged conductor

Question: Can we use gauss law to prove that field in a cavity of charged conductor of any shape is zero?? If so how as the shape may lack symmetry? If not how can we prove the field to be zero? I know that the charge resides on the surface of conductor but I am not satisfied by the reasoning that since charge enclosed is zero field is zero as per my book. Is there a quantitative way to explain it?
Comment: Do you know the proof of gauss law using solid angle? If not I will suggest you to go through it thoroughly. You might check it out over here:https://www.scribd.com/document/247926626/Gauss-Theorem-Proof The proof can also be found in *Concepts of Physics-Vol2-Gauss Law*
Answer: If there is no symmetry, Gauss law wont't help you (it's still true, but less useful).
You can prove that field lines on the surface $S$ of the conductor must be normal to the surface, otherwise there will be a net force rearranging the charges until this becomes true. This means the surface of the conductor is an equipotential, say $V_S=V_0$, which implies $V=V_0$ in the entire volume enclosed by $S$ due to Laplace's equation. Since $\mathbf{E}=-\nabla V\implies\mathbf{E}=0$.
Answer: Yes, we can use Gauss Law $\oint \vec E\cdot d\vec{A}=Q_{net}/\epsilon_{o}$ to prove that electric field inside the cavity of conductor is zero.
Consider a closed surface inside the cavity then the net charge enclosed by Gaussian surface will be zero i.e. $Q_{net}=0$
$$\oint \vec E\cdot d\vec{A}=0$$$$\oint |\vec E|dA\cos\theta=0$$
$$\implies |\vec E|=0\quad (\because dA\ne 0, \theta\ne90^\circ )$$


Any possible way to make $wpdb->get_results() return anything else than array?

Question: So I'm using $wpdb->get_results() to query my database and then make AJAX call from JS file. The problem is that I need to get the value itself, like a string, instead of array, but as much as I know, get_results return only array. Is there any way around this to get string value from database? Or should I use something else than get_results()?
Comment: Why not use that array and get the string from it?
Comment: I converted it to JSON but still don't know how to access the string in the loop. I have an array of json objects here. Any hints?
Answer: $wpdb->get_results() only returns arrays( associative or numeric) or an object.  It does not return a string value.
If you want a string value, you need to use $wpdb->get_var() instead


Showing related products in product view page

Question: I'm working on a website where I'm using Magento 1.7. I want to display the related product of the current product on product view page. I tried many links like these, but none of them worked for me. Please help me on this. I'm newbie to magento.
Comment: which page layout is used for product view page? generally related product are display in right bar by default on product view page.
Comment: I don't want that to be display on right bar or left. I want to be displayed on product detail page. that is view.phtml of product.
Comment: Yes i am asking you which page layout is used for product detail page? if you are using 1column layout then you will consider philwinkle answer
Comment: I used two columns with left bar.
Comment: Ok so your related products are not display, look for my answer for display related product
Answer: This is built in to most themes and all of the base themes. So I'm guessing what you want is to relocate the related products to another area.
This is possible in a few different ways:
Via layouts
Using layout XML you can provide the following block declaration to any <reference> -
<block type="catalog/product_list_related" name="catalog.product.related" before="-" template="catalog/product/list/related.phtml"/>

This should call and render the block and associated template file.
Roll your own
Why not? You're a capable developer! In this case, you can do something very similar to what you posted in the links above. This particular example is fairly trivial but shows you what may be possible:
Edit
My what a difference a year makes. Don't load models in loops. Bad Phillip, BAD.
$related_prods = Mage::getModel('catalog/product')
                    ->getCollection()
                    ->addAttributeToSelect('name')
                    ->addAttributeToSelect('sku')
                    ->addAttributeToFilter('entity_id',array('in'=>$_product->getRelatedProductIds()));
foreach($related_prods as $related){
    echo $related->getName() . " " . $related->getSku();
}

This can be placed anywhere on the product page or view.phtml but best practice dictates that you should place this in a Block method and reference that inside the template. Bottom line, you either need to have $_product available or use Mage::registry('current_product').
Comment: Why not load product collection instead? Something like ```Mage::getModel('catalog/product')->getCollection()->addAttributeToFilter('product_id', array('in' => $relatedIds));``` Better than loading Model inside a loop IMHO.
Comment: Absolutely, this is just an example.  I also didn't include the standard warming against using getmodel in a loop.
Comment: Or even easier: ```$product->getRelatedProductCollection()```
Comment: There's a missing semicolon after `$related_prods = $_product->getRelatedProductIds()`.
Comment: @shmuli I have updated this (ancient) answer for a best practice approach and to fix the error. Thanks!
Answer: Check this block in catalog.xml
 <block type="catalog/product_list_related" name="catalog.product.related" before="-" template="catalog/product/list/related.phtml"/>

just put like this if you want to display in your content area
 <reference name="content">
            <block type="catalog/product_list_related" name="catalog.product.related" after="upsell_products" template="catalog/product/list/related.phtml"/>
        </reference>

save file and clear your cache.
Answer: Remove the reference to the block related_products from view.phtml
<?php //echo $this->getChildHtml('related_products') ?>

Then add this to anywhere you want in view.phtml
<?php echo $this->getBlockHtml('catalog.product.related'); ?>


How to start going to gym the right way?

Question: I'm doing some home exercises for quite some time, but I also want to start going to the gym, the problem is I don't know how to do the exercises there, nor I know how any of the fitness instruments and how to use them. The fitness trainers are very expensive and I don't know how to start on my own. Watching youtube videos might help, but I won't be able to remember everything, how to exercise right and all the instruments. What do you guys suggest?
Answer: Start by picking 4-5 exercises, remember them, learn the form.
Start by performing these exercises with lighter weights to begin with so you can get used to controlling the weights.
Once you are used to these 4-5 exercises, start adding more and have an alternating routine until eventually you build up and you have a full "split" which is training all your body parts on different days.
As a beginner it would be very good if you looked up a full body beginners workout and do this 3 times a week with rest days in between to get started. Once you start with this you can progress from there.
I also recommend taking a friend (who doesn't have to be experienced either) just to get over the fear of going alone and having someone to keep you motivated with going.
Comment: @CritingZ Try watching Athlean-X, hes a trusted youtuber who shows you the right ways to do things
Comment: All my friends go to gyms that are in the other part of the city and this fitness is right next to my building so I guess I will have to go alone. As for the exercises I will try to remember some from youtube and do them in the fitness and see how it goes. Otherwise I can save up for a trainer, for like 2-3 times and show me everything so I can go from there, but I will try alone first to see if it's gonna work out. Thank you!
Comment: thank you very much! I will look into his videos right after work! +


How do I convert a svg to a png using dithering for gradients?

Question: If I create a gradient between two similar colours in Inkscape and export it to a png it looks something like this:

If you look closely you can see rings.
If I create a gradient in GIMP, there's the option to use dithering to prevent such rings or lines.
How do I convert my svg to a png using dithering for gradients?
Comment: Can you link your problematic SVG file?
Comment: Here you go: http://pastebin.com/download.php?i=0hYYxEGV Just rename the file to end on .svg
Comment: Well, I don't know how you expect dither to work, but usually you dither hires signal to lores, while you seem to expect to dither lores, which can't work of course. If you want to dither in Gimp change image color mode, there is dithering option, but you wont make anything of it on your sample. I'm sure there is DSP process which will let you do what you want, but I don't know. Why don't you use Gimp's gradient feature? Here is you SVG image converted to PNG using Gimp: http://i.imgur.com/EwaBl.png
Comment: The posted image just shows the problem. The actual image I want to convert is a lot more complex and it would take some time to recreate it in GIMP and it would have some major drawbacks (after all there is a reason people are using vector graphics). Thanks for your help, anyway.
Answer: Try Gimp "Spread" filter (Filter > Noise > Spread) with 40px value for your sample
I found it in a comment in Inkscape bug tracker and it produces great results IMHO
Comment: This works only if you have one single gradient (and then I could just create it in GIMP without Inkscape). As soon as you have a more complex image (with sharp edges for example) it kind of blurs the whole image.
Comment: On image you posted it works great, or? You can select regions of interest in Gimp and apply filter only on part of image, but you can't expect from me to imagine your original design or filter that will automagically correct everything - it does not exist
Comment: Just because you don't know how to solve my problem properly (btw you mentioned the idea to use Illustrator which is the best solution so far), it does not mean a solution does not exist. You posted a link to a patch that would probably fix the problem in Inkscape, so a solution does exist. It just has to be implemented in Inkscape. Maybe it is already implemented in an other program but you and I don't know which one so let's wait for someone who does. Cheers
Comment: You have some attitude - I was trying to help and provide some info to potentially interested users, not to necessarily solve your problems.
First, your question is misleading, because as already said dithering is done other way around - not like you assumed.
Then, if you focus on image/file you provided as example, and anyone can test that result from Gimp spread filter is best you can get - no other tool or wisdom can apply noise filtering with different parameters and only on regions where different gradients exist - you'll have to do selections and filter parameters by hand if it's worth.
Comment: Also Illustrator, CorelDraw or compiling Inkscape with patch from source, are solutions for your future and not for your current problem, as SVG file which you created with Inkscape is already with problematic gradient.
Comment: The problem doesn't lie in my current svg file (the svg file doesn't contain any pixel data, just the information that there is a gradient) but in the png converter of Inkscape. So I should be able to open it in Illustrator (or even in a future version of Inkscape with the bug fixed) and render it correctly.
Comment: Why don't you try to open it in Gimp first and see if you are right?
Answer:
Well, I don't know how you expect dither to work, but usually you dither hires signal to lores, while you seem to expect to dither lores, which can't work of course.

Yeah, no.
Dithering in gradients is not done for reasons of resolution, but for reasons of bit-rate. You get banding effects because InkScape's export to PNG incorrectly rounds down the (floating-point) RGB values of the interpolated gradient to 8-bit values (256 steps).
This results in a very annoying and noticeable type of banding noise (as opposed to aliasing noise which would be the case if we were talking about resolution). Applying dither is a form of noise-shaping, which doesn't reduce the noise but spreads it out in spatial domain so it doesn't correlate into noticeable shapes any more (I'll spare you the signal theory).
Your "solution" of applying the spread noise filter in GIMP really is no better than someone encountering jagged edges in line-art, asking directly about the anti-aliasing option, and telling them to apply a Gaussian blur!
Consider: A photo, reduced to 4 colours with no dither, and a spread noise filter applied afterwards. A photo reduced to 4 colours with dither. Which one looks better?
How do you "hide" jagged edges -> blur.
How do you solve jagged edges -> anti aliasing when rendering.
How do you "hide" banding in gradients -> spread noise, etc (there's better tricks but you always end up throwing away fidelity).
How do you SOLVE banding in gradients -> apply dithering during render!
So yeah, I can actually understand the attitude, when asking how to solve a problem, being told to sort of brush it under the carpet. That's not a solution for a serious graphics designer.
I'm currently wrestling with the same problem. The question also was perfectly clear, I know because I arrived at this page looking for the same answer. What I'm trying to do is applying a slight layer of noise with a filter or extension in InkScape, which is hopefully applied before rendering, bumping the rounding error around a bit, resulting in a not-optimal but better-than-nothing poor man's noise-shaper. But at least it'll preserve the detail that doesn't require dither :)
Answer: Please don't consider this as answer. I'm writing it as answer as writing comment is limiting
This seems to be known problem with Inkscape. Quick googling showed to me:

Patching source (0.48.0), then compiling Inkscape
Applying some filter (by editing <code>/usr/share/inkscape/filters/filters.svg</code>) like posted here or here, which is BTW useless on your sample
Additionally search the web for resolving Inkscape gradient banding problem
Try other tool if possible

I'll just add that last step is my suggestion and while you could try Xara or sK1 it seems to me that only commercial tools (CorelDraw, Illustrator...) offer flawless features, which has to be indeed considered when doing serious work, as you won't like things like this happen after rendering
Cheers


When did my computer went to sleep the last time? Window 7

Question: I wanted a windows service I'm building to run overnight. So I changed my power options and set my computer to never sleep. Started the windows service and went home. This morning I found my computer sleeping and was curious if someone manually put it to sleep after I left. Is there a log file or some way to find the last time my computer went to sleep? I'm using a Windows 7 operating system.
Comment: Are you just trying to figure out what happened last night, or make something to run today and in the future that logs it?
Comment: filter event ID 42 in System in Event viewer. ref: https://answers.microsoft.com/en-us/windows/forum/windows_7-performance/logging-power-events-sleep-wake-up-to-the-event/e004a68c-f9a9-4982-86ba-a1cee05f9e4d
Comment: Just trying to figure out what happened last night.
Answer: Have you consulted Event Viewer? To start Event Viewer by using a command line

Open a command prompt. To open a command prompt, click Start, click All Programs, click Accessories and then click Command Prompt.
Type eventvwr.

Information about scheduled / unscheduled sleeps and reboots should be found by expanding the tree view in the left plan to Event Viewer > Windows Logs > System.
You can also get the last boot time by using the WMI service object to query the LastBootUpTime property of the Win32_OperatingSystem class. Note that the returned date is in WMI date time format which you'll need to use tools to convert into a human readable date.
Here's a VBScript sample:
<code>' LastBoot.vbs
Option Explicit
Dim wmiService, objDateTime, OS
Set wmiService = GetObject("winmgmts://localhost/root/cimv2")
Set objDateTime = CreateObject("WbemScripting.SWbemDateTime")
Set OS = wmiService.ExecQuery("SELECT * FROM Win32_OperatingSystem").ItemIndex(0)
WScript.Echo OS.LastBootUpTime ' Example: 20180801131622.495364+660
objDateTime.Value = OS.LastBootUpTime
WScript.Echo objDateTime.GetVarDate ' Example: 01/08/2018 12:16:22 PM
</code>
Here's a PowerShell example:
<code>(Get-WmiObject Win32_OperatingSystem).LastBootUpTime
# Outputs: 20181009160558.495300+660

(gcim Win32_OperatingSystem).LastBootUpTime
# Outputs: Wednesday, 1 August 2018 12:16:22 PM
</code>
Here's a Command Prompt example (uses PowerShell):
<code>powershell -command "(Get-WmiObject Win32_OperatingSystem).LastBootUpTime"
REM Outputs: 20180801131622.495364+660

powershell -command "(gcim Win32_OperatingSystem).LastBootUpTime"
REM Outputs: Wednesday, 1 August 2018 12:16:22 PM
</code>
References:

https://learn.microsoft.com/en-us/windows/desktop/cimwin32prov/win32-operatingsystem
http://powershell-guru.com/powershell-tip-7-convert-wmi-date-to-datetime/
https://www.thewindowsclub.com/find-system-uptime-windows
Answer: Inside eventvwr you will see the entry in System Logs --> "Kernel Power". Double click to see when your computer entered into sleep mode.
Comment: Simple and just what I needed. Thank you.


Temp-to-Perm Question

Question: Ok.. so let's start with the fact that the staffing agency I work for is an unusual one. They told me when in a temp-to-perm position, like I am in now, that they keep you as a temporary employee until you have met your 90 day/3 month probationary period. Now... about the position. I absolutely love what I do. It's great work and the environment of the company is absolutely calming. I started working here under the temp agency on March 31, 2016. I met my 3 month probationary period Friday, July 1, 2016. My boss has already paid me for two holidays [which most companies don't do] and has told me if I need anything [even a day off] to let her know. During the three months I have been here I have only taken one day off. I took that day off due to having a fever of 102 degrees and feeling very sick. I notified my boss my email, work phone and cell phone. I have been to work 15 minutes early or more every single day. My question is... how can I professionally ask if there are new tasks I need to learn as well as tasks I need to improve on to help me get a permanent position? Also how can I make it to where she understands that I really want the permanent position? See.. I really need the extra time and money. My (2) children are about to start pre-k in a month and I am going to have to pay $162 a week for before and after care due to noone being close enough who can watch them every day while I work. So it is pretty crucial of me knowing because if I am not going to go permanent I am going to have to have a second job. My boss is the Vice President and she is the one I have to confirm my career with.
Comment: Have you gone to your boss yet and asked?  A straight forward approach may be the best.
Comment: 3 months temp-to-perm or any time frame given to you, advertising these type of jobs are just approximately when they will need someone permanent. It is not a hard figure, set in stone. You just completed your 3 months. According to what you said, you did well. Wait for a few more days for your boss to come to you with a permanent offer. Your child may go to school and you may need extra money for that, but it is not the employer's concern. Until you have the perm position, you might need an additional job if you are strapped for it. Understand that you are not entitled to a perm position
Comment: I'm confused. You were told to work 3 months as a temp until you would be hired as full time, but this hasn't happened? Is that the issue?
Comment: This needs some edit work because I can't find the real question in this wall of text. OP hasn't returned so this is another one-and-done. VTC, VTD
Answer:
My question is... how can I professionally ask if there are new tasks
  I need to learn as well as tasks I need to improve on to help me get a
  permanent position?

Talk to your boss.
Something like "Hey, boss. Are there any new tasks I need to learn or tasks I need to improve on in order to get a permanent position here?" should work.
Comment: It's amazing the number of questions on this site that could simply be answered by "Talk to your boss..." or "Just ask..."

Temp-to-Perm Question


How to restart Ubuntu 12.04 using Autokey

Question: To restart Ubuntu 12.04 you now have to open a terminal (ctrl+alt+t), type "sudo shutdown -r 0" , followed by your password. I have been trying to write a script in Autokey to do this automatically, but can't manage to bring up the terminal window:                keyboard.send_keys("++t")    doesn't seem to work, so presumably an instruction to open gnome-terminal is needed.
If anyone has a quick answer to this I would be very grateful - otherwise I'll try to learn some Debian coding.....
Thanks in advance,  Kaspin"
Comment: If you're running GNOME 3 or Unity, let me know because my answer may not work then.
Answer: If you're open to an easier suggestion not using AutoKey, you can go to System -> Preferences -> Keyboard Shortcuts.

From there click "Add".

Now name it "Shutdown" or something, and use "gksu shutdown -r 0" as the command.

Now click the "Shortcut" cell for its row, and press you're desired key combination.

NOTE: I am running Ubuntu 11.04 but this should be applicable.
Answer: To shutdown your system using an AutoKey script here's what you need to do.

Select a folder in AutoKey ("New Script" will only be available when a folder is selected)
Go to File -> Create -> New Script
Enter the following for the script:
system.exec_command("gksu shutdown -r 0", False)

NOTE: Looking at the AutoKey sample scripts it looks like you use system.exec_command() to execute shell commands which would be the equilivlent to calling the standard python function subprocess.call("Some shell command", shell=True) (if you're familiar with python).
Click the "Set" button to the right of "Hotkey". Click "Press to Set", press your desired shortcut key, and then click any desired modifiers for that key ("Control", "Alt", "Shift", "Super"), and then "OK".
NOTE: Alt+Control+T is the shortcut combo for opening gnome-terminal.
Click "Save" and you're done.


Getting index of a custom ACF block with PHP?

Question: I have created a custom block using Advanced Custom Fields. The blocks will have an alternating layout for even/odd blocks. I want to set this up automatically, rather than adding style options or another field to manually select the layout in the backend, so I was hoping to be able to add a class to every other block programmatically. Is there a way to get the index of a block on a page with PHP and conditionally add a class if it's an odd number? Or is there some other method of applying a class to every other block?
Answer: For those looking for a PHP solution. A good place to do this is in the render_callback function. One thing to keep in mind with this solution is that this only works on first load, which is good enough for the frontend, but it will not work accurately in the Gutenberg editor itself once you start editing and/or moving blocks.
acf_register_block_type([
  'name' => 'blockname,
  'render_callback'  => 'my_acf_block_render_callback',
]);

function my_acf_block_render_callback($block) {
  global $block_index;
  $index = $block_index++;

  // Do whatever else you need to do and make sure you pass the $data array to your template.
}

Answer:
Or is there some other method of applying a class to every other block.

You could use JavaScript to apply classes to the block, but this should be doable with CSS' nth-child:

.block,
.advert {
  height: 100px;
}

* + .block,
* + .advert {
  margin-top: 10px;
}

.advert {
  background-color: #900;
}

.block {
  background-color: #00f;
}

.block::before {
  content: "EVEN";
}

.block:nth-child( odd of .block ) {
  background-color: #0f0;
}

.block:nth-child( odd of .block )::before {
  content: "ODD";
}

Comment: Thank you for the suggestion, but I would prefer to use PHP to render the classes server-side in order to avoid the content shifting around on the frontend
Comment: Yep, I wouldn't recommend JS, but FWIW, CSS will not cause the content to shift.
Comment: The issue there is that the block content is at the same level in the DOM as the rest of the page content (i.e. the page header and other blocks). Is there a way to add a wrapper in the block template that encompasses all blocks of a certain block name?
Comment: Your custom block should already have a unique class name being applied. If you replace `.block` with your block's class name, the CSS above will only apply to siblings of the same parent, so as long as the blocks are all siblings, it should work, regardless of other blocks (as proved by the `.advert` usage).


triggering JQuery 'autocomplete' in a secondary textarea

Question: We currently have two HTML textareas 'tinput'(primary) and 'toutput' (secondary) where we mimic the input in the primary to be reflected in the secondary as if someone is really typing in the secondary. The idea is to trigger an 'autocomplete' (over ajax) on the secondary.  We have this working but not optimally.
We have attached a JQuery UI 'Autocomplete' (JQAC) to the secondary with a minLength:3 set.  You may know that, normally, after 3 characters have been entered, JQAC 'buffers' the char entries thereon after and doesn't make an ajax call for every char that has been entered.  Which is ideal.
However, with our secondary mimicking we have subverted this behavior, unfortunately, where after the 3rd char entry a JQAC ajax call is being made for every char after-- which is not optimal.  We know why but don't know how to get around it.  We believe we've subverted this because we are calling
<code>  $('#tinput').autocomplete('search',$('#tinput').val())
</code>
in the secondary's key handle, which by JQAC's documentation forces an ajax call.
To summarize, we need the secondary, that has JQAC attached to it, to behave as if someone were really typing into it and the JQAC behaving normally.
Here is JS for what we have as our char input mimic handling(we've changed variable names for this post so please ignore typos):
<code>$("#tinput").on('input', function (e) {
    $("#toutput").val($("#tinput").text());

    var newEvent = jQuery.Event("keypress");
    newEvent.which = e.which; // # Some key code value
    $("#toutput").trigger(newEvent);
});

$("#toutput").keypress(function(e) {

   $("#toutput").autocomplete('search',$("#toutput").val());
});

$( "#tinput" ).autocomplete({
  appendTo: "#modalparent",
  source: function( request, response ) {
    $.ajax({
      url: "https://xxxxxx",
      type: "POST",
      dataType: "json",
      data: JSON.stringify({ "ourterm": request.term}),
      success: function( data ) {
        response( $.map( data.data.suggestions, function( item ) {
          return {
            label: item,
            value: item
          };
        }));
      }
    });
  },
  minLength: 3,
  select: function( event, ui ) {
    // console.log( ui.item ?
    //   "Selected: " + ui.item.label :
    //   "Nothing selected, input was " + this.value);
  },
  open: function() {
    $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
  },
  close: function() {
    $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
  }
});
</code>
Any thoughts would be appreciated.  Thanks!
Answer: We have found an elegant solution.  It was a minor modification to our original.

change the trigger event by the primary to 'input' instead of the original 'keypress'.
remove the handler for the secondary.

here is the updated JS:
<code>$("#tinput").on('input', function (e) {
   $("#toutput").val($("#tinput").text());

   var newEvent = jQuery.Event("input");
   newEvent.which = e.which; // # Some key code value
   $("#toutput").trigger(newEvent);
});
</code>
and delete:
<code> //$("#toutput").keypress(function(e) {

 //   $("#toutput").autocomplete('search',$("#toutput").val());
 // });
</code>
DONE.


Reducing the size of MyISAM table

Question: I have a MyISAM table that currently contains about 54 million records and is 20 GB in size. Poor choices were made when this database was designed. I'm no DB pro but since this table is constantly being written to and infrequently being queried, it seems InnoDB would have been a better choice. The problem is this table has to be available for writing to almost always. One of the fields is a timestamped field. Records go back 5 years--I only need to keep the last 6 months. I've tried some deletes, it takes about 20 minutes to delete 200,000 rows during which the table is locked and cannot be written to. Does anyone have suggestions on how I can reduce the size of this table without it being locked for several hours? Is there a faster way to delete the unneeded rows? I have never converted a MyISAM table to an InnoDB table. Is this a lengthy process?
Comment: If it's infrequently being queried is it possible for you to make a new innodb table with same definitions, copy a maintenance windows worth of data to it and switch them to writing to that table instead?  You could copy of 6 months of data over time ?
Comment: Do you really need to delete 200,000 rows at once?
Comment: The conversion process can be tricky depending on your constraints and you have a very large table size; some details: https://dev.mysql.com/doc/refman/5.0/en/converting-tables-to-innodb.html
Comment: I really need to delete about 50 million rows in total. I've been doing this a little and a long during maintenance windows. I have only one 2 hour maintenance window per week that I'm authorized to do this work and can delete about 1 million rows during this time. By the time next week rolls around, there has been almost 500,000 new rows entered.If I was able to convince management that 5-6 hours and its done, I can get the window extended. (This is my first post on here, thank you for the quick response).
Comment: Martin, I like this solution and I'm looking into implementing it.
Answer: MyISAM is only good for SELECT. Innodb has separate READ and WRITE queue. So when you are deleting 200,000 rows tables will not be locked.  Table locks is the one big limitation of MyISAM when comes to production. InnoDB is slower than MyISAM for most uses, but can perform faster in certain conditions due to a better locking mechanism; MyISAM locks the whole table for reading while inserts/updates are executing. InnoDB can do row-level locking, thus allowing multiple concurrent writes and read on the table
http://kakadba.blogspot.in/2014/02/innodb-vs-myisam.html
Converting MyISAM to INNODB
You can do it table by table
ALTER TABLE table_name ENGINE=InnoDB;

Or you may try script to do it all at once
https://stackoverflow.com/questions/3856435/how-to-convert-all-tables-from-myisam-into-innodb
Answer: I finally had time to revisit this project and for completeness sake wanted to post what I ended up doing. The original problem with the DELETE FROM taking so long, I believe, is related to how I was specifying rows to be deleted. I was using a statement similar to
DELETE FROM table WHERE starttime < 20150101 limit 200000;

The starttime field is actually a DATETIME. I ended up creating a new table using
CREATE TABLE new_table LIKE existing_table;

and then changing the new table's engine
ALTER TABLE new_table ENGINE=InnoDB;

and then renaming
RENAME TABLE existing_table TO old_table, new_table TO existing_table;

After this I needed to get 6 months worth of data from the old table into the new table
INSERT INTO existing_table SELECT * FROM old_table WHERE starttime BETWEEN DATE_SUB(NOW(), INTERVAL 6 MONTH) AND NOW();

Thank you Martin for the suggestion. I'm new on serverfault so I'm not sure how I would mark his comment as an answer.

Reducing the size of MyISAM table


Log into VNC as ROOT rather than pi

Question: I am doing some hardware development and I need to run my apps as root to access the low level hardware on my pi 4.  I do my development over VNC and the default VNC user is 'pi' rather than root.  How do I set up a vnc server that uses root rather than pi?
Answer: You do not need to do that. This would imply that the desktop runs as root, which might be possible, but is neither desirable nor really useful. VNC just shows the remote desktop for whichever user is logged in there (pi by default). This has nothing to do with who's running a particular application, though. You can always run any application as root by calling it using sudo. Or do sudo -i to get a root shell.
Comment: And extra tip: With everything up-to-date, you should not need to run anything as root to access gpio, spi or i2c busses.

Log into VNC as ROOT rather than pi


How to Convert KeyValuePair to Dictionary in C#

Question: How does one convert a KeyValuePair to a Dictionary, given that ToDictionary is not available in C#?
Comment: It is a duplicate, Robin incorrectly says C# has no ToDictionary
Comment: @doctorlove KeyValuePair does not have a ToDictionary method - it's on IEnumerable, and the question (as written) is not talking about an IEnumerable.
Comment: Isn't it? Well you could just use `var dict = new Dictionary()` then `dict.Add(kvp.Key, kvp.Value)`
Comment: @JasonEvans Strictly, it's not a dupe - he is asking how to convert a KeyValuePair, not a List[KeyValuePair]. Of course, this does demand the question "Why does he want to do this"?!!
Comment: Do a loop and add each KeyValuePair in a new Dictionary.
Comment: Not duplicate, he asks without `ToDictionary()`.
Answer: var dictionary = new Dictionary<string, object> { { kvp.Key, kvp.Value } };

ToDictionary does exist in C# (edit: not the same ToDictionary you were thinking of) and can be used like this:
using System;
using System.Collections.Generic;
using System.Linq;

var list = new List<KeyValuePair<string, object>>{kvp};
var dictionary = list.ToDictionary(x => x.Key, x => x.Value);

Here list could be a List or other IEnumerable of anything. The first lambda shows how to extract the key from a list item, and the second shows how to extract the value. In this case they are both trivial.
Comment: how can I do that with C# 2.0
Comment: Please add note that you need to use System.Linq
Answer: If I understand correctly you can do it as follows:
new[] { keyValuePair }.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

Answer: Use System.Linq.Enumerable.ToDictionary() extension method to convert a collection of one or more KeyValuePairs
Dictionary<string,string> result = new[] {
    new KeyValuePair ("Key1", "Value1"),
    new KeyValuePair ("Key2", "Value2")
}.ToDictionary(pair => pair.Key, pair => pair.Value);

Answer: Create a collection of KeyValuePair and make sure System.Linq is imported in a using statement.
Then you will be able to see the .ToDictionary() extension method.
public IList<KeyValuePair<string, object>> MyDictionary { get; set; }

Answer: Upgrade to .net 5 or higher and pass them to the constructor:
    var x = new Dictionary<string, string>(new[] { new KeyValuePair<string, string>("key1", "val1"), new KeyValuePair<string, string>("key2", "val2") });

Answer: Implement it yourself as an extension method.
public static class MyExtensions
{

    public static Dictionary<T1,T2> ToDictionary<T1, T2>(this KeyValuePair<T1, T2> kvp)
    {
      var dict = new Dictionary<T1, T2>();
      dict.Add(kvp.Key, kvp.Value);
      return dict;
    }

}

see this in action: https://dotnetfiddle.net/Ka54t7
Comment: Jazimov. T1 & T2 are generic type references. You would not substitute them. They are inferred by the KeyValuePair instance being extended.

With that said, while this literally answers the question, it isn't useful because you're creating a dictionary collection with only 1 item in its collection. It would be better to extend an IEnumerable of KeyValuePairs, like an array or List.
Comment: It may not be obvious to some people that the above code cannot be used as-is: One would need to substitute the actual type for T1 and T2, such as string and object...
Comment: Oh no, I just forgot one bit
Answer: Alternatively (if you can't use Linq.. although I'm curious why..).. implement ToDictionary yourself...
public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector) {
    if (source == null)
    {
        throw new ArgumentNullException("source");
    }
    if (keySelector == null) {
        throw new ArgumentNullException("keySelector");
    }
    if (elementSelector == null) {
        throw new ArgumentNullException("elementSelector");
    }

    var dictionary = new Dictionary<TKey, TElement>();
    foreach (TSource current in source) {
        dictionary.Add(keySelector(current), elementSelector(current));
    }
    return dictionary;
}

Example usage:
var kvpList = new List<KeyValuePair<int, string>>(){
    new KeyValuePair<int, string>(1, "Item 1"),
    new KeyValuePair<int, string>(2, "Item 2"),
};

var dict = ToDictionary(kvpList, x => x.Key, x => x.Value);


JSON to features not working while performing ST_Buffer

Question: My objective is to create a buffer of 1000 m for enode.
I used the following query.
CREATE external table enodebuffer (shape binary);
INSERT OVERWRITE TABLE enodebuffer
    SELECT ST_Buffer(enodeaggregate.shape,100) FROM enodeaggregate;

I am able to retrieve the columns and their values (in binary) on hive and also able to get an accurate count of the features. I am also able to get a json fil after using copu from HDFGS (esri git hubtool for hadoop)
However when I use Json to features tool of github I get the following error:

I get the same error whenevr I use the ST_Buffer geometry query. I also tried creating multiple columns with the shape column but to no use.

I took into account all your suggestions but I am not able to get the desired result when I want to create a buffer for 1000's of points.
1) SO for the table, as you had suggested

create external table enodebuffer1 (EnodeBStatus string,shape binary)
  ROW FORMAT SERDE 'com.esri.hadoop.hive.serde.JsonSerde'
  STORED AS INPUTFORMAT 'com.esri.json.hadoop.UnenclosedJsonInputFormat'
  OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat';

2) Then I inserted the values in the table enodebuffer1  using the select query as below

Insert into table enodebuffer1 select enodeaggregate.EnodeBStatus,ST_Buffer(enodeaggregate.shape,1000)from enodeaggregate;

3) I got the result showing that the data has been loaded into the table succesfully, and am also able to retrieve the values using select and limit query.
4) Now the main part is I want to able to see the above results in ArcMap. So I used the esri github tools for hadoop COPY FROM HDFS and JSON TO FEATURES.
Copy from HDFS was successful, no error. But json to features it shows the following error (I hope you can see the images)

5) So as Evil Genius had suggested I had tested it with 100 points and it worked fine.Possibly the error is it cannot handle too many vertices.
But there has to be a solution because we are planning to migrate terabytes of data into HDFS and using multiple geometry queries to retrieve the desired results.
Comment: Please include error messages as text rather than links to pictures.
Comment: Have you tried testing this on a small set of data? Offhand, it looks like a memory issue, which could mean something along the lines of a feature having more vertices than the conversion script can handle.
Comment: Hi,Yes i tried it with few points, and it worked. thanks a lot.
Comment: This issue is cross posted [here](https://github.com/Esri/gis-tools-for-hadoop/issues/44), but with a different error message?
Answer: This is an issue with using the Enclosed JSON option when running JSON to Features.  When this option is selected, the entire file is read into memory (json_fc = json.load(json_file)).  You will want to use the Unenclosed JSON option, which means that you will also need to create your Hive table using the UnenclosedJsonInputFormat.
For Example:
CREATE EXTERNAL TABLE IF NOT EXISTS enodebuffer (shape binary)
ROW FORMAT SERDE 'com.esri.hadoop.hive.serde.JsonSerde'
STORED AS INPUTFORMAT 'com.esri.json.hadoop.UnenclosedJsonInputFormat'
OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'

Comment: With Spatial-Framework-For-Hadoop v1.2+, use `.....EsriJsonSerDe` and `....UnenclosedEsriJsonInputFormat`.