Pytorch: TypeError: 'str' object cannot be interpreted as an integer

Question: Whatever I do, I encounter this error, what should I do?
TypeErrorTraceback (most recent call last)
<ipython-input-10-4ea723df6eea> in __init__(self, steps, multiplier, prev_prev_C, prev_C, curr_C, reduction, prev_reduction)
     36
     37     self.layers = nn.ModuleList()
-->  38     for i in range(steps):
     39         for j in range(2+i):
     40             stride = 2 if reduction and j < 2 else 1
TypeError: 'str' object cannot be interpreted as an integer

class SearchCell(nn.Module):

  def __init__(self, steps, multiplier, prev_prev_C, prev_C, curr_C, reduction, prev_reduction):
    super(SearchCell, self).__init__()
    self.steps = steps
    self.multiplier = multiplier
    self.reduction = reduction

    if prev_reduction:
      self.prep0 = FactorizedReduce(prev_prev_C,curr_C, affine=False)
    else:
      self.prep0 = ReLUConvBN(prev_prev_C, curr_C, 1, 1, 0, affine=False)
    self.prep1 = ReLUConvBN(prev_C, curr_C, 1, 1, 0, affine=False)

    self.layers = nn.ModuleList()
    for i in range(steps):
        for j in range(2+i):
            stride = 2 if reduction and j < 2 else 1
            op = MixedOp(curr_C, stride)
            self.layers.append(op)

  def forward(self, s0, s1, weights):
    s0 = self.prep0(s0)
    s1 = self.prep1(s1)
    states = [s0, s1]
    offset = 0
    for i in range(self.steps):
      s = sum([self.layers[offset + j](h, weights[offset + j]) for j, h in enumerate(states)])
      offset += len(states)
      states.append(s)

    return torch.cat(states[-self.multiplier:], dim=1)

Comment: you passed a string for steps, instead of an integer.
Comment: please review [mre]
Comment: **identical question**: https://stackoverflow.com/questions/73597607/pytorch-typeerror-str-object-cannot-be-interpreted-as-an-integer
Answer: according to your error steps is a string while range(steps) means that steps must be an integer cause range iterates over an integer n ( from 0 to n-1). Check if steps integer or not using print(type(steps)) if it  is a string  try using this steps = int(steps) it will type convert it to integer. If there is an character in steps it will return another error can convert str to string.  If that occours trace every occourance of steps and check where steps(int) is converted to str using print(type(steps))
    class SearchCell(nn.Module):

  def __init__(self, steps, multiplier, prev_prev_C, prev_C, curr_C, reduction, prev_reduction):
    super(SearchCell, self).__init__()
    self.steps = int(steps)     # change here
    self.multiplier = multiplier
    self.reduction = reduction

    if prev_reduction:
      self.prep0 = FactorizedReduce(prev_prev_C,curr_C, affine=False)
    else:
      self.prep0 = ReLUConvBN(prev_prev_C, curr_C, 1, 1, 0, affine=False)
    self.prep1 = ReLUConvBN(prev_C, curr_C, 1, 1, 0, affine=False)

    self.layers = nn.ModuleList()
    for i in range(int(steps)):  change here
        for j in range(2+i):
            stride = 2 if reduction and j < 2 else 1
            op = MixedOp(curr_C, stride)
            self.layers.append(op)

  def forward(self, s0, s1, weights):
    s0 = self.prep0(s0)
    s1 = self.prep1(s1)
    states = [s0, s1]
    offset = 0
    for i in range(int(self.steps)):  #change here
      s = sum([self.layers[offset + j](h, weights[offset + j]) for j, h in enumerate(states)])
      offset += len(states)
      states.append(s)

    return torch.cat(states[-self.multiplier:], dim=1)

I have edited the code again check if this works or not. I type converted stpes everywhere cause i can run the code myself and tell  where the typeconverion of steps is happening so i used int(steps) where ever steps is used. And check my comment below as well
Comment: I tried it, it still gives an error
type(steps) is string.
Comment: How can I contact you?
Comment: How can I contact Naman and  Christoph Rackwitz ?
Comment: if it still gives an error check weather when you called the function ;  did u passed the parameter steps?? if yes check during the function call steps was `string` or `int` if its string then convert it if int only give us more info. And about contact detail u can ask questions here we all are here to help.


(Ray tracing) Trouble converting to screen coordinates, objects being stretched

Question: I followed along with Ray Tracing in One Weekend and managed to get the final output but I wanted to understand more about creating a camera and "painting" the screen since he didn't go over it much.
When I tried using a different way of creating a camera by spheres actually get elongated, making them look like more like ellipses. I've tried modifying the x and y assignments in screenCords but I've only managed to make more errors (such as objects wrapping around to the opposite side)
Camera.h:
#pragma once

#include "../Matrix.h"
#include "../Defs.h"
#include "Defs.h"

template<typename O>
using Point3 = Vec3<O>;

template<typename O>
using Color = Vec3<O>;

template <typename O>
class Camera{
  O Height;
  O Width;
  Vec3<O> Forward, Right, Up;
  Point3<O> Origin;

public:
  Camera(O fov, O aspect_ratio, Point3<O> origin, Point3<O> target, Vec3<O> upguide) {
    Height = atan(degrees_to_radians(fov));
    Width = Height * aspect_ratio;

    Origin = origin;

    Forward = target - origin;
    Forward.normalize();
    Right = Forward.cross(upguide);
    Right.normalize();
    Up = Right.cross(Forward);

    }

    Ray<O> get_raydir(O right, O up){
      Vec3<O> result(Forward + right * Width * Right + up * Height * Up); result.normalize();

      return Ray<O>(Origin, result);
    }

    void screenCords(O &x, O &y, O width, O height){
      x = ((2.0f * x) / width) -1.0f;
      y = ((2.0f * y) / height);
    }
};

Main.cpp
#include <iostream>
#include <cmath>
#include "../Matrix.h"
#include "Camera.h"
#include <vector>
#include "Image.h"
#include "Shapes.h"
#include "Tracer.h"
#include "../Defs.h"

template<typename O>
using Point3 = Vec3<O>;

template<typename O>
using Color = Vec3<O>;

int main(){
  const int img_ratio = 2;
  const int img_width = 640;
  const int img_height = 480;
  const int depth = 50; float t_Max = infinity; float t_Min = 0.001;

  float inv_width = 1 / float(img_width);
  float inv_height = 1 / float(img_height);

  std::vector<Sphere<float>> shapes;

  Camera<float> cam1(20.0f, img_ratio, Point3<float>(0.0f, 0.0f, 0.0f), Point3<float>(0.0f, 0.0f, -1.0f), Vec3<float>(0.0f, 1.0f, 0.0f));

  Sphere<float> cir1(0.2f, Point3<float>(0.2f, 0.0f, -1.0f));
  Sphere<float> cir2(7.0f, Point3<float>(0.0f, -7.0f, -1.0f));
  Sphere<float> cir3(0.5f, Point3<float>(1.0f, 0.0f, -1.0f));
  shapes.push_back(cir1);
  //shapes.push_back(cir2);
  //shapes.push_back(cir3);

  Tracer<float> tracer(shapes);

  std::cout << "P3\n" << img_width << ' ' << img_height << "\n255" << std::endl;

  Ray<float> ray(Point3<float>(0.0f), Vec3<float>(0.0f));

  for (int j = 0; j < img_height; j++)
  {
    std::cerr << "\rScanlines remaining: " << j << ' ' << std::flush;
    for (int i = 0; i < img_width; i++){

        float x = i;
        float y = j;

        cam1.screenCords(x, y, img_width, img_height);

        ray = cam1.get_raydir(x, y);
        //ray = Ray<float>(Vec3<float>(x1, y1, 1), Point3<float>(0.0f, 0.0f, 0.0f));
        tracer.iterator(ray, depth, t_Max, t_Min);
    }
  }
  std::cerr << "\n done " << std::endl;
}

I suspect the error is in one of these files since the spheres are actually being drawn with the colors based on normals (with the top and bottom normal colors unsurprisingly being bugged)
Here are a few examples of the output:
Answer: It looks like the parameters to your camera class are not correct
 const int img_ratio = 2;
 ...
 Camera<float> cam1(20.0f, img_ratio, Point3<float>(0.0f, 0.0f, 0.0f), Point3<float>(0.0f, 0.0f, -1.0f), Vec3<float>(0.0f, 1.0f, 0.0f));

In your code you set img_ratio to 2, I would expect it should be something like img_width/img_height (or the reverse img_height/img_width). img_ratio should also be also be a floating point to match the  type the camera class is being instantiated with.
Comment: Thank you so much! Someone already answered on the main stackoverflow site but that was basically the error.


How to create Google/Apple map style interface with pinch, zoom, rotate in any direction

Question: I am looking to replicate Google Map or Apple Maps style interface with ability to pinch, zoom, scroll right/left, up/down, diagonally, and rotate in any direction but with no Maps. I can likely use UIScrollView but I am not sure how to scroll diagonally or rotate in any direction based on touch. Any suggestions?
Answer: Basically UIViuew property transform allow you to make all 2d transforms. But to create something like Maps you need to know Open GL well.


Can one interpret the derivative of $f(x)=x^2$ as a way to predict a value under which $f(x)$ cannot fall at a given point? and $f'$as a minimum rate?

Question: Note : my questions is not about the application of derivatives to determine the max / min values of a function ; also, t is not about linear approximation ( though it is related to this topic); what I am interested in is a possible alternative definition of the derivatve of a function

If P and Q are two points on the graph of $f(x)=x^2$, with $P=( x_0, f(x_0))$ and $Q = ( x_0 + \Delta x, f(x_0+\Delta x))$ the change in $y$ related to the change in $x$  is :
$R = \frac {f(x_0+\Delta x) - f(x_0)}{\Delta x}= 2x+\Delta x$.
If I am asked what is the value of $f(3,1)$ knowing that the value of $f(3)=9 $ I can use the ratio $R$ and write :
$f(3,1) = f(3)+ (\Delta x.R) = f(3) + (\Delta x .(2x+\Delta x))= f(3)+(\frac{1}{10}.((2\times 3)+\frac{1}{10}))= 9,61$ .
Now, if I were asked, not what is $f(3,1)$ but the greatest value under which $f(3,1)$ cannot fall I could take the limit of $R$ as $\Delta x$ goes to $0$  and say that $f(3,1)$ cannot fall under the value :
$f(3)+(\Delta x . 2x)=9,6$.
In other words, even  if I can't manage to find precisely $f(3,1)$, I can predict that it must be greater than  $9,6$.
So the derivative at $x_0=3$ gives me the minimum value of the rate $R= \frac{\Delta y}{\Delta x}$ at $3$, that is $6$ .
My question is : (1) is it correct to view the derivative as a minimum ( or maximum) not of function f itself but of the rate $R$ ( as defined above)? (2) how to make this idea of minimum / maximum rigorous? (3) is the notion of supremum needed here?
In bref, is there an alternative definition of the dervative that embeds these notions of maximum / minimum/ supremum?
Comment: The graph of $y=x^2$ lies above the line tangent to the graph at $x=3$ (in fact, at every value of $x$), which is why your lower bound for the growth of the function serves as the derivative of the function. If the graph lies above the tangent line (but the function is still increasing), you'll be looking at an upper bound for the growth as the derivative. And you have to modify everything if the function is decreasing. And another ballgame if the graph lies above the tangent line in one direction and below it in the other. Essentially, you have to take the 2nd derivative into account.
Comment: Do you understand the situation now, Floridus?
Comment: Earth to Floridus: come in, please.
Comment: @Gerry Myerson.- Thanks Gerry for taking care of my state of understanding. Why not not consider turnng  your comment into an answer?
Comment: Will do ... later.
Answer: Your basic premise is wrong, I'm afraid. The only reason it works here is that the derivative $f'(x)=2x$ is increasing as $x$ increases. If you try it with a function that has a decreasing derivative, it doesn't work. For instance, if $$f(x)=-x^2+12x-18$$
then we have $f(3)=9$ and $f'(3)=6$, just as in your example; but $f(3.1)=9.59$, which is less than $9.6$ because the derivative $f'(x)=-2x+12$ is decreasing as $x$ increases.
Answer: [Comment promoted to answer at request of OP]
The graph of $y=x^2$ lies above the line tangent to the graph at $x=3$ (in fact, at every value of $x$), which is why your lower bound for the growth of the function serves as the derivative of the function. If the graph lies above the tangent line (but the function is still increasing), you'll be looking at an upper bound for the growth as the derivative. And you have to modify everything if the function is decreasing. And another ballgame if the graph lies above the tangent line in one direction and below it in the other. Essentially, you have to take the second derivative into account.


Is this the proper way to extend wiring from a split receptacle?

Question: I understand some of the basics like piggy backing on a receptacle to add additional ones but need some help with split receptacles.
I currently have a split receptacle in my kitchen that I would like to add a switch to so that I can control some under cabinet LED lighting that I will install. In addition I would also like to add 2 additional receptacles to my kitchen island off this same receptacle.
So to recap my original receptacle is a split receptacle that has a dual breaker which I understand adds 120V to top and 120V to bottom plugs. I would like to use this receptacle and convert the box to 2 gang box and add a new switch to control LED cabinet lights, and add 2 new (120v) receptacles to the island.
I have attached a diagram of what my old and new setup would be and what I think I'm supposed to do. Would some confirm whether this wiring is correct? Specifically, please check I am doing with the red wire.
Comment: Note, you can simply pigtail off the original outlet for the white wire, and then you only have 3 wires in your wire nut.  Same for the first added outlet—connect the black and white wires from the nuts in the 2-gang box to the appropriate terminals on the outlet, then use the other terminals to the last outlet.
Comment: Aside: You can get receptacles that are marked to indicate that one half is controlled by another device (Switch, timer, photocell, ... .), e.g. [this receptacle](https://store.leviton.com/products/20-amp-125-volt-marked-controlled-receptacle-spec-grade-self-grounding-ivory-cr020-1pi?variant=35318252803). (Both halves marked is also available.) I thought it would cut down on the confusion when someone can't get a lamp/fan/vacuum to work some of the time. The local electrical inspector came through, looked at it and asked what it was. When I explained it he thought it wasn't a bad idea.
Answer: Your diagram looks correct. I assume the wire and breaker are sized correctly.
The original outlet will be split, with power supplied from the black and red wire separately.  You can leave the red wire as shown in the diagram.
The black wire then, obviously provides power to all outlets downstream and to the switch for the LED lights.
This gives you what you want. Great job.
Comment: Thank you for the information and confirmation.
Answer: Here is another idea, which puts the double-source double-current capability of the wall outlet on the island too, for more balanced current draw:

The difference is to run /3+ground cable of the correct gauge to the island, instead of /2+ground. Then both breakers' power will be at the island.
Wire the black from the island /3 run to the black on the wall outlet. Red on the island run to the red on the wall outlet. Neutral and ground same as before. In the island, wire one outlet to the red wire, the other to the black wire, and neutral & ground common to both island outlets.
This will give double power capability to the island as well as the wall outlet. (Your original sketch, though correct, had the whole island running only from the black side of the wall outlet, which would limit island power usage, in combination with the black half of the wall outlet.)
Comment: Thanks for the info, I was also considering this setup. The 2+ wire is already run so not sure if I'd want to re run although would your idea give me a superior setup? If it's only used for maybe a laptop or to charge phones, or potentially for a blender once and a while. Thoughts?
Comment: For low-current items like chargers, the extra line won't be needed. For blenders, probably not needed too, as you'd probably have to run several blenders at once to overdrive the current draw for a few minutes. The extra line would be good if you wanted to put a microwave in the island, or an undercounter fridge.
Comment: If someone plugged in a vacuum at the island while the counter microwave was running, then the two circuits would help, if the two appliances were on the different lines.
Comment: Oh man I have another addition to my question here....So I just realized that I need the main "Split Receptacle" to also be a GFCI receptacle since its close to the sink. I purchased one but it only has ins for a black, white, and ground then has outs for load with a black and white wire....it does not seem to have an area for the red wire to make it a split receptacle. Do they have GFCI receptacles that allow for red split? Any help here would be helpful.
Comment: To the best of my knowledge and reading here and other places, no, they don't have GFCIs that can also handle split power like your outlet has.  A dual GFCI circuit breaker could do it. Alternatively, you could use two GFCI outlets in a dual-gang box to replace the split outlet in the single-gang box, one handling the black side and the other handling red, and the island fed off the load sides of one of the GFCI outlets.
Comment: I was thinking the same as you described with the two GFCI outlets although a bit differently...i was thinking of doing the two GFI but I can't have them in the same box since I have an outlet and a switch in the two gang. What I was thinking is using the red hot for the 1st GFI outlet on the wall then using the black in the wall box and pigtail over to the one in the island and adding the second GFI to the island like that. Would that work? is it okay if they 2 GFI are not in the same box?
Comment: I think that would work, yes.


can shell themes be used with gnome fallback mode?

Question: I was wondering what truly "gnome fallback" means in ubuntu? I am using gnome classic, which is lovely, but I wanna install some new themes. Do these themes only work with gnome 3? Do I have to get gnome 3 and then get themes activated in the advanced settings?
Thanks
Answer: A desktop theme is broken into several components: window decorations, cursor theme, icon theme, GTK theme and the shell theme.
A shell theme doesn't do anything in a "Classic" environment as Gnome Shell isn't running, but you can still use the same window decoration and GTK theme settings.
I suggest you install gnome-tweak-tool and have a play around with the theme settings.


MongoDB sort by custom calculation in Node.JS mongodb driver

Question: I'm Using Node.JS MongoDB driver. I have a collection of job lists with salary and number of vacancies, I want to sort them according to one rule, if either salary or number of vacancies are greater they will get top priority in sorting, and I came up with this simple formula
( salary / 100 ) + num_of_vacancies
eg:
Top priority ones
{ salary: 5000 , num_of_vacancies: 500 }   // value is 550
{ salary: 50000 , num_of_vacancies: 2 }    // value is 502

And Less priority for
{ salary: 5000 , num_of_vacancies: 2 }     // value is 52

But my Problem is, As far as I know, MongoDB sort takes arguments only to sort in ascending or descending order and a property to sort. How do I sort with custom expression.
The data in MongoDB looks like this // not the full varsion
{
    title:"job title",
    description:"job description",
    salary:5000,
    num_of_vacancy:50
}

Answer: This is just an option. Adjust it for a mongo driver.

$addFields we create the field to sort, named toSortLater just for semantic purposes.
add a $sort stage, and sort high values first. Change to 1 for the opposite behaviour.

db.collection.aggregate([{
$addFields:{
toSortLater:{
   $add:[
       {$divide:["$salary", 100]},
       "$num_of_vacancies"]
}}}, {$sort:{"toSortLater":-1}}
])

Comment: @27px yes, that's the most powerful feature, called "aggregation". You can search in mongo docs, it's quite good.
Comment: Thanks, this is what I have been looking for. I didn't knew it is possible to create temporary fields to store expressions.


(Conceptual) Continuity of binary relation $\succsim$ and definition using contour sets

Question: Some background information: $\succsim$ is a binary relation that represents preference between two goods. $\succsim$ means "x is at least as good as y." Continuity of this relation is defined to be that if it is preserved in limits: if for any pair of sequences $(x^n,y^n)$ converging to x and y respectively and $x^n\succsim y^n$ $\forall n$, then $x\succsim y$. Also, $x\in\mathbb{R^L_+}$. So, X is a set of possible goods we can choose and these goods are L-vectors.
I am trying to understand that an equivalent way of stating "a preference relation that is continuous on $X$" is to say "the upper and lower contours sets are closed". What I don't understand is authors in a book says the following:
The continuity of $\succsim$ on X implies that for any sequence of points $\{y^n\}$ with $x\succsim y^n$ $\forall n$ and $y^n$ converging to $y$, we have $x\succsim y$. And, this implies the lower contour $L(x)=\{y\in X:x\succsim y\}$ set is closed.
My instinct was to show the lower contour set is closed is equivalent to showing the set contains all its limit points. And how do you do this? Well, in this case, it is to show whether, say the lower contour set, contains its boundary points. These points in collection is just the indifference set $I(x)=\{y\in X:y\sim x\}$.
Then, I want to show $I(x)\subset L(x)$.
Proof
: (1) Suppose $x\in I(x)$.
(2) By definition, $x\succsim y$ and $y\succsim x$ $\iff x\sim y$. Hence, $I(x)=\{y\in X:y\succsim x\}\cap\{y\in X:x\succsim y\}$.
(3) Hence, $x\in L(x)$ and $I(x)\subset L(x)$. Q.E.D.
Is my approach incomplete and how should I make sense of MWG's claim above? Please help. Thank you!!
Comment: I believe that this is not true in a general topological space. Did the author make some assumptions about $X$?
Comment: @StanCoreyCarter : Also, $x\in\mathbb{R^L_+}$. So, X is a set of possible goods we can choose and these goods are L-vectors. Sorry, should've included this.
Answer:
Continuity of this relation is defined to be that if it is preserved in limits: if for any pair of sequences $(x^n,y^n)$ converging to x and y respectively and $x^n\succsim y^n$ $\forall n$, then $x\succsim y$.

This statement easily implies

for any sequence of points $\{y^n\}$ with $x\succsim y^n$ $\forall n$ and $y^n$ converging to $y$, we have $x\succsim y$.

if you fix the constant sequence $x^n=x$ for all $n$. Then note that this statement is equivalent to saying "if $y^n\in L(x)$ and $y_n\to y$, then $y\in L(x)$." You'll see that this is exactly the definition of $L(x)$ being sequentially closed (see Wikipedia). Thus you know that the statement

the lower contour $L(x)=\{y\in X:x\succsim y\}$ set is closed.

is definitely true as long as "sequentially closed" implies "closed." But counterintuitively, this is not always the case! Topologies in which this is true are called sequential topologies. You can guarantee you are in one of these if $\mathbb L$ is at most countable since then $\mathbb R^\mathbb L$ will be first countable (see the same Wikipedia page).
Comment: Stan, thanks for the answer. Can you please elaborate the second part when you explained "Note ... sequentially closed."?
Comment: Does this help?
Comment: Stan, thank you for the more elaborate version. While I digest this, how would this be different or similar to the definition of a set is closed IFF it contains all its limit points. This definition is something I learned dealing with the real line.
Comment: The limit point definition is what is meant by saying a set is closed. In most situations, that definition is equivalent to the sequential definition. For example, on metric spaces (like $\mathbb R$) the two are equivalent (which isn't hard to prove). By contrast, if in your example $\mathbb L$ is uncountable, I don't believe the equivalence would hold anymore. Fortunately, most spaces you deal with in analysis and economics are metric spaces so you don't have to worry about it.
Comment: Stan, this is a silly question but I am compelled to ask cause I am confused. The set $L(x)=\{y\in X:x\succsim y\}$ is called lower contour set, which is basically a lower half under the indifference curve in the cartesian plane in $\mathbb{R^2_+}$ when we only consider two goods. My question is shouldn't the argument in the set be y such that $L(y)=\{y\in X:x\succsim y\}$ not x? I am confused about the set notation.
Comment: No, when you write $\{y:\cdots\}$, $y$ is a dummy variable so it doesn't make sense outside of the curly brackets. Think of $L(x)$ as the set of things that $x$ is preferred to.
Comment: Stan, thanks for the comment. It makes sense. I actually looked at this on real line and treated the relation as the good old inequality, and it makes a perfect sense.


Netbeans Profiler throwing - saved calibration data file does not exist error

Question: I am getting this error message saved calibration data file does not exist even after doing calibration on the remote tomcat server? Does anyone have any clue..
Answer: You probably ran calibration with one user, and the application to profile with a different user. Check Netbeans bug 154300. Newer Netbeans versions will show where calibration expects the file to be.


skypeforlinux 220.127.116.11 fails to start on ubuntu 14.04 LTS

Question: Updating my Ubuntu 14.04 LTS today also installed a new skypeforlinux 220.127.116.11 replacing 184.108.40.206.
skypeforlinux 126.96.36.199 does not start, I just get a blank with a menu bar. The menu entries are selectable, but nothing appears to happen.
Starting the new skypeforlinux from the command line does not produce any output in the terminal window.
Comment: Maybe worth watching the [official forum here](https://answers.microsoft.com/en-us/skype/forum/skype_linux-skype_startms-skype_installms/upgraded-to-the-latest-skype-linux-version-but/34553112-f42c-4740-a435-a64ddf3ad89f), as many people having the same problem (check the last page).
Comment: Just to note, a new version just came out today, 126.96.36.199. However, it still does not work for me, I wonder if anyone got lucky with that...
Comment: Same here except that sometimes after logging in, I do see my normal chat overview in a blink before the window turns all white. Switching back to 18.104.22.168 works for me.
Comment: Same here on Linux Mint 17.1 as well (based on Ubuntu 14.04)
Comment: And still broken in 188.8.131.52 as well.
Answer: Use old package:
sudo apt-get install skypeforlinux=126.96.36.199

Thanks to @Sleeper9 for pointing to official forum.
Update from @Sleeper9: 126.96.36.199 also works.
Comment: Sadly, I do not have enough rep to post a new answer, but finally, the latest 188.8.131.52 version solved the problem. Try to update now, and see if it works for you too!
Answer: I had the same symptoms with Skype 8.75 running on a Dell XPS13 7390, it looks like there was a problem detecting which video driver to use (that machine has a Intel UHD Coffee Lake), so I fixed it by running:
LIBVA_DRIVER_NAME=iHD skypeforlinux
Answer: If you run the newest skypeforlinux (as normal user) in /usr/bin/skypeforlinux in terminal, nothing happens.
i.e. no output.
If you run it in /usr/share/skypeforlinux/skypeforlinux, you get a Segmentation fault.
But an interesting solution is to run it with sudo, then you can work with it.
sudo /usr/share/skypeforlinux/skypeforlinux

and it should run.
I have also deleted my .skypeforlinux in my home folder. Interestingly you run it as root, but the config are written correctly. Looks like some coding error.
Tested in Ubuntu 17.10 GNOME Shell
Comment: Running proprietary application as root is not secure. It is bad idea.

skypeforlinux 8.13.0.2 fails to start on ubuntu 14.04 LTS


Why would lights plugged in to lamp holder outlet adapter be testing as live?

Question: We bought an old pendant light for our flat, with a two prong plug.  Rather than rewiring it in to the existing outlet, I just bought one of those $2 lamp holder outlet adapter.  To be on the safe side, I checked it with my contact volt tester, which lit up when it came within a few inches of the unit (not even in contact).
I plugged the pendant in to a standard wall fixture and all was fine (no charge on the casing, the tester only lights up with contact on the cable).  What's more, when I plugged our bedside lamp in to the ceiling adaptor the same thing happened - a good 2-3 inches out the fluke lit up.
Is there something about those outlet adapters which may be causing the pendant and lamp to be live?  Or perhaps the ceiling fixture is rated too high for the pendant and lamp?
Comment: That's weird.  Screw out the adapter and see if it happens when you put it close to the socket.  If not see if you can trade the socket adapter for another one, or a different type.  By the way, what kind of lamp(s) are you lighting up?  Incandescent, LED, fluorescent, uranium...(:
Answer: I would advise checking the wiring of the switch.  It sounds like it might be a case of the switch for the lamp is switching the neutral instead of hot. The result of this is that when the switch is off, there is no visible light because there is no return path for the electricity (broken by the switch), but there is still eletricity making it up to the fixture.
Comment: I concur.  This was my first guess as well.
Answer: It is posible that when the house was wired the light fixture was not switched.The light was controlled with a pull chain.If a wall switch was added later they may wired the switch by breaking the hot wire inside the fixture mounting box.If that is the case you would have power in the box with the switch off.
Answer: Another possibility not yet mentioned would be that some kinds of light switches will 99.9% interrupt current but still let through a tiny residual amount.  This is particularly true of electronic dimmers that don't use a neutral connection (many need a tiny amount of power for their control circuitry) and for self-illuminated light switches.  When using such a light switch, it would be normal for an open circuit to read "hot" all the time, but adding any sort of load should eliminate that effect.  For example, if you were to plug in a lamp then its power cord may read as "hot" when both the lamp and the wall switch are "off", but turning on the switch for the lamp itself should cause it to cease reading "hot" when the wall switch isn't on; turning on the wall switch should then cause it to read "hot" while also making the lamp glow.
If things behave as described here, especially if the wall switch is an electronic dimmer or a self-illuminated model, that would suggest that everything is fine.


Replace existing element with another from an external XML

Question: I would like to replace an element from an external XML file. Currently I have an XSLT which adds elements, but not replacing them.
Input.xml:
<all>
   <item>
      <sku>3850950</sku>
      <name>Macbook Pro</name>
      <qty>3</qty>
      original.jpg
   </item>
   <item>
      <sku>3859955</sku>
      <name>iPhone 12</name>
      <qty>9</qty>
      original-apple.jpg
   </item>
</all>

XSLT:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="node()|@*">
          <xsl:copy>
             <xsl:apply-templates select="node()|@*"/>
          </xsl:copy>
</xsl:template>

<xsl:key name="group" match="additem" use="sku" />

<xsl:template match="item">
    <xsl:copy>
        <xsl:copy-of select="*"/>
        <xsl:apply-templates select="key('group', sku, document('./extra-info.xml'))"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="additem">
     <xsl:for-each select="img">

        <xsl:value-of select="."/>

     </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

Extra-info.xml:
<all>
   <additem>
      <sku>3850950</sku>
      aaaaaaa
      bbbbbbb
   </additem>
   <additem>
      <sku>3859955</sku>
   </additem>
</all>

I would like to match img elements from extra-info.xml, the common key is sku. Replace  in the input.xml if same exists in extra-info.xml and add all of them.
Example output:
<all>
   <item>
      <sku>3850950</sku>
      <name>Macbook Pro</name>
      <qty>3</qty>
      aaaaaaa
      bbbbbbb
   </item>
   <item>
      <sku>3859955</sku>
      <name>iPhone 12</name>
      <qty>9</qty>
      original-apple.jpg
   </item>
</all>

Answer: AFAICT, you want to do:
XSLT 2.0
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:key name="additem" match="additem" use="sku" />

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="item">
    <xsl:variable name="additem" select="key('additem', sku, document('extra-info.xml'))"/>
    <xsl:copy>
        <xsl:copy-of select="* except img"/>
        <xsl:choose>
            <xsl:when test="$additem/img">
                <xsl:copy-of select="$additem/img"/>
            </xsl:when>
            <xsl:otherwise>
                <xsl:copy-of select="img"/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>


Sizing an MFC Window

Question: I have an MFC app which I have been working on for a few weeks now, I want to manually set the dimensions of the main frame when it is loaded, can someone give me a hand with this, specifically where to put the code as well?
Thanks!
Answer: You can also set the size (with SetWindowPos()) from within CMainFrame::OnCreate(), or in the CWinApp-derived class' InitInstance. Look for the line that says pMainFrame->ShowWindow(), and call pMainFrame->SetWindowPos() before that line. That's where I always do it.
Answer: Find your screen size with ..
CRect rect;
SystemParametersInfo(SPI_GETWORKAREA,0,&rect,0);
screen_x_size=rect.Width();
screen_y_size=rect.Height();

use these values to calculate the X and Y size of your window then ..
::SetWindowPos(m_hWnd,HWND_TOPMOST,0,0,main_x_size,main_y_size,SWP_NOZORDER);

Where main_x_size and main_y_size are your sizes.
Comment: SPI_GETWORKAREA only gets the size of the primary mnonitor. For the entire virtual desktop, use this:

    int desktopW = GetSystemMetrics(SM_CXVIRTUALSCREEN);
    int desktopH = GetSystemMetrics(SM_CYVIRTUALSCREEN);
Answer: I think you're looking for PreCreateWindow and that your app isn't dialog based.
It's a virtual member function of CWnd class and it's called by framework just before a window is created. So it's a right place to place your changes.
You should write something like this:
BOOL CMyWindow::PreCreateWindow(CREATESTRUCT& cs)
{
   cs.cy = 640; // width
   cs.cx = 480; // height
   cs.y = 0; // top position
   cs.x = 0; // left position
   // don't forget to call base class version, suppose you derived you window from CWnd
   return CWnd::PreCreateWindow(cs);
}
Comment: It works, but you have to edit `PreCreateWindow` in `MainFrm.cpp`, not your View class.
Answer: you can use this:
CRect rect;
SystemParametersInfo(SPI_GETWORKAREA, 0, &rect, 0);
left = -3, right = 3;
rect.top = 100;
rect.bottom = 500;
rect.left = 100;
rect.right = 800;
//or use
CRect cr;
cr.SetRect(POINT{ 100,100 }, POINT{ 500,800 });
MoveWindow(rect);

Comment: You haven't answered the full question nor have you explained how your code works. Please help the asker out by providing a little context around your answer.
Answer: BOOL YourProjectApp::InitInstance()
{
        :
        :
    m_pMainWnd->MoveWindow(0, 0, 1900, 1000);  // add this line for fixing the default size of mainWindow
    m_pMainWnd->ShowWindow(SW_SHOW);
    m_pMainWnd->UpdateWindow();
    return TRUE;
}

Comment: Please read [answer].
Comment: See "[Explaining entirely code-based answers](https://meta.stackoverflow.com/q/392712/128421)". While this might be technically correct, it doesn't explain why it solves the problem or should be the selected answer. We should educate along with helping solve the problem.

Sizing an MFC Window


imitate browser zoom with JavaScript

Question: How is it possible to zoom out an entire document with JavaScript ?
My goal is to imitate the built-in browser zoom and zoom the entire document to 90%.
I have tried using
document.body.zoom

This works only with explorer and the page gets messy (a lot of elements are moving around).
Is there a way to do this?
Answer: There you go:
Use:
document.body.style.zoom=1.0;this.blur();

1.0 means 100%
150% would be 1.5
1000% would be 10.0
this.blur() means that the curser, maybe you selected an input field, looses focus of every select item.
or:
You can use the css3 element zoom (Source)
Firefox does not allow zooming with the browser because you can't access the user properties via javascript or sth.
So you can just use some CSS styles which allow to zoom (CSS3: zoom, as mentioned above) or to increase the text size! Which you could do with including a different CSS file for example. But here you have the "jumpy" problem, because the styled css elements (floated etc.) have to "interact" different in fact of their attributes.
The zoom I posted above works well in Chrome and IE8+ (FF not supported as mentioned)
--
Additional information:
Here is an example on how to zoom exactly with the zoom option.
Example application can be found here
The zoom option normally handles the zoom as your browser does!
But this is still all stuff, which is not supported by Firefox, or maybe Safari & Opera? In chrome and IE it works!
Another solution would be: Place your main sizes in "em", and then work around by setting sizes like 100%, 110% (all over the css). So you could have differen CSS files, and "just" need to replace the % attributes!
Yet I don't think there might be other solutions! :(
Comment: Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.
Comment: thanks , while your solution does work it does not imitate the exact action caused by ctrl+ or ctrl-. the css zoom feature messes up some of the page structure (especially when dealing with margin:auto) while the ctrl+- does not ... is there any other way for doing this ?
Comment: Edited my post! I hope I understood what you want? :) (Still you have the issue that Firefox / Safari? / Opera? does not support zooming!)
Answer: Here is my solution using CSS transform: scale() and JavaScript / jQuery:

jQuery(document).ready(function($) {
    // Set initial zoom level
    var zoom_level = 100;

    // Click events
    $('#zoom_in').click(function() {
        zoom_page(10, $(this))
    });
    $('#zoom_out').click(function() {
        zoom_page(-10, $(this))
    });
    $('#zoom_reset').click(function() {
        zoom_page(0, $(this))
    });

    // Zoom function
    function zoom_page(step, trigger) {
        // Zoom just to steps in or out
        if (zoom_level >= 120 && step > 0 || zoom_level <= 80 && step < 0) return;

        // Set / reset zoom
        if (step == 0) zoom_level = 100;
        else zoom_level = zoom_level + step;

        // Set page zoom via CSS
        $('body').css({
            transform: 'scale(' + (zoom_level / 100) + ')', // set zoom
            transformOrigin: '50% 0' // set transform scale base
        });

        // Adjust page to zoom width
        if (zoom_level > 100) $('body').css({
            width: (zoom_level * 1.2) + '%'
        });
        else $('body').css({
            width: '100%'
        });

        // Activate / deaktivate trigger (use CSS to make them look different)
        if (zoom_level >= 120 || zoom_level <= 80) trigger.addClass('disabled');
        else trigger.parents('ul').find('.disabled').removeClass('disabled');
        if (zoom_level != 100) $('#zoom_reset').removeClass('disabled');
        else $('#zoom_reset').addClass('disabled');
    }
});

zoom in

zoom out

reset zoom

Comment: This is great only thing is i want the page to zoom in and out but then refresh to take up the full screen like it does when you manually zoom using the browser. In this case for me it just zooms the body in and out to the size. I want the page to remain the same size but just increase or decrease the size of the items contained within it.
Answer: Try using transform: scale(). Mozilla Docs
.className {
    transform: scale(0.9)
}

You can change the scale amount with Javascript.
let scaleAmount = 1 - 0.1
document.body.style.transform = `scale(${scaleAmount})`

scale() reduces or increases the width and height of an element. If you'd like the width to remain the original size, while all inner elements scale, the algorithm looks something like this:
let scaleAmount = 1 - 0.1
document.body.style.transform = `scale(${scaleAmount})`
document.body.style.width = `${100 * (1 / scaleAmount)}%`
document.body.style['transform-origin'] = `0 0`

If you use a UI framework like React, you can pass the scaleAmount as it exists in the state to inline CSS.
<header className="App-header" style ={{
    transform: `scale(${scaleState})`,
    transformOrigin: '0 0',
    width: `${100 * (1 / scaleState)}%`
}}>

Example in React
Answer: I did this with jquery, works with Firefox, Safari, Chrome and IE9+:

window.onload = function() {
  var currFFZoom = 1;
  var currIEZoom = 100;

  $('#In').on('click', function() {
    if (navigator.userAgent.indexOf('Firefox') != -1 && parseFloat(navigator.userAgent.substring(navigator.userAgent.indexOf('Firefox') + 8)) >= 3.6) { //Firefox
      var step = 0.02;
      currFFZoom += step;
      $('body').css('MozTransform', 'scale(' + currFFZoom + ')');
    } else {
      var step = 2;
      currIEZoom += step;
      $('body').css('zoom', ' ' + currIEZoom + '%');
    }
  });

  $('#Out').on('click', function() {
    if (navigator.userAgent.indexOf('Firefox') != -1 && parseFloat(navigator.userAgent.substring(navigator.userAgent.indexOf('Firefox') + 8)) >= 3.6) { //Firefox
      var step = 0.02;
      currFFZoom -= step;
      $('body').css('MozTransform', 'scale(' + currFFZoom + ')');

    } else {
      var step = 2;
      currIEZoom -= step;
      $('body').css('zoom', ' ' + currIEZoom + '%');
    }
  });
};

<input type="button" id="Out" value="Zoom Out"/>
<input type="button" id="In" value="Zoom In"/>
Answer: You can do the following thing:
document.body.style.zoom = "120%"

Answer: you have to set the zoom property in style for top level element (html).
Now interesting part is how to calculate it. This is what I did.
You can put this code inside window.onresize function to make the whole page zoom automatically.
window.onresize = function(){
    let zoom = Number((window.innerWidth / window.screen.width).toFixed(3));
    document.firstElementChild.style.zoom = zoom;
  }

This will calculate the ratio of current window width to actual device width.
Then set that value to top level html element zoom property.
Top level html element can be accessed using document.firstElementChild
set the height of main wrapper div to 100% to prevent white space on zoom.

imitate browser zoom with JavaScript


AmqpProvider - Transport connection remotely closed

Question: I am using ServiceMix alongside Apache camel and Qpid libraries to connect to a remote node to fetch JMS queues.
My Bean config is ::
<code>  <bean id="amqp" class="org.apache.camel.component.amqp.AMQPComponent">
    <property name="connectionFactory">
       <bean class="org.apache.qpid.jms.JmsConnectionFactory">
          <property name="remoteURI" value="amqp://esesslxjks.se:9443" />
       </bean>
    </property>
  </bean>

 <camelContext xmlns="http://camel.apache.org/schema/blueprint">
    <!-- Master Data Queue -->
    <route>
      <from uri="amqp:queue:///CS_output" />
      <log message="Copying o the output directory"/>
      <to uri="amqp:queue:///CS_input" />
    </route>
</code>
Using this bean I start my application and see some positive response ::
<code>| DEBUG | mix-7.0.0/deploy | JmsProducer                      | 43 - org.apache.camel.camel-core - 2.16.4 | Starting producer: Producer[amqp://queue:///CSDP_input]
| DEBUG | mix-7.0.0/deploy | JmsConsumer                      | 43 - org.apache.camel.camel-core - 2.16.4 | Starting consumer: Consumer[amqp://queue:///CSDP_output]
| DEBUG | mix-7.0.0/deploy | BlueprintCamelContext            | 43 - org.apache.camel.camel-core - 2.16.4 | Route: route1 >>> EventDrivenConsumerRoute[Endpoint[amqp://queue:///CS_output] -> Pipeline[[Channel[Log(route1)[Copying o the output directory]], Channel[sendTo(Endpoint[amqp://queue:///CS_input])]]]]
| DEBUG | mix-7.0.0/deploy | faultJmsMessageListenerContainer | 154 - org.apache.servicemix.bundles.spring-jms - 3.2.17.RELEASE_1 | Established shared JMS Connection
</code>
But then I get the below ERROR ::
<code>| DEBUG | esesslxjks.se:9443] | AmqpProvider                     | 226 - qpid-jms-client.jar - 0.0.0 | Transport connection remotely closed
| DEBUG | esesslxjks.se:9443] | JmsConnection                    | 226 - qpid-jms-client.jar - 0.0.0 | Async exception with no exception listener: java.io.IOException: Connection remotely closed.
java.io.IOException: Connection remotely closed.
     at org.apache.qpid.jms.provider.amqp.AmqpProvider$18.run(AmqpProvider.java:727)[226:qpid-jms-client.jar:0.0.0]
     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)[:1.8.0_121]
     at java.util.concurrent.FutureTask.run(FutureTask.java:266)[:1.8.0_121]
     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)[:1.8.0_121]
     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)[:1.8.0_121]
     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)[:1.8.0_121]
     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)[:1.8.0_121]
     at java.lang.Thread.run(Thread.java:745)[:1.8.0_121]
</code>
I am currently clueless as to why this would happen ? What other possible debugging can I do ? Any pointers would be highly recommended.
Answer: I don't have your use case with your spring camel running like in your example.  But I ran into this same exact stack trace you were having during one of my unit tests.  What I found out was that after I would explicitly try to close my broker instance then my qpid jms client would also try to close the connection.  Thus throwing that exception.  I know my use case isn't exactly like yours, but I hope this helps a little bit.  Good Luck.
Answer: On your remoteURI property use amqps protocol instead of amqp.
ServiceBus will be rejecting it because it is using an unsupported protocol.
<code>  <bean id="amqp" class="org.apache.camel.component.amqp.AMQPComponent">
    <property name="connectionFactory">
       <bean class="org.apache.qpid.jms.JmsConnectionFactory">
          <property name="remoteURI" value="amqps://esesslxjks.se:9443" />
       </bean>
    </property>
  </bean>
</code>


Query works in PLSQL Developer but doesn't in SQL Developer

Question: So, I have this query that's just making me go crazy. For some crazy reason, the query runs and brings the desired output on PLSQL Developer, but on SQL Developer it doesn't! As far as I know, the exact same query should work on both, not just one or the other. Not everybody at my team has PLSQL Dev, so it has to work on both. This query also shows different behaviour on my BI Application. Has anyone seen this crazy behaviour before?
Here's the query:
with t1 as (
SELECT
  case  when CLG_STATUS.NM_STATUS in ('1 - ATIVO','5 - BLOQUEADO','7 - AGUARDANDO AUTENTICAÇÃO') then 'LG Club Member'
    else 'Non  Member'
  end membership,
  Round(
    Round(SUM(NVL(CASE WHEN CLG_VENDA.CD_TP_VENDA = 'D' THEN -1*CLG_VENDA.QTD_VENDA ELSE CLG_VENDA.QTD_VENDA END,0)), 1)
    /
   Count(distinct CLG_PARTICIPANTE.ID)
  , 1) as average_sales ,
  Round(
    SUM(NVL(CASE WHEN CLG_VENDA.CD_TP_VENDA = 'D' THEN -1*CLG_VENDA.QTD_VENDA ELSE CLG_VENDA.QTD_VENDA END,0))
  , 1) as sellout,
  Count(distinct CLG_PARTICIPANTE.ID)
  as "qty members"
FROM
  CLG_VENDA_PONTO,
  CLG_PARTICIPANTE,
  CLG_STATUS,
  CLG_VENDA,
  CLG_CARGO  CLG_CARGO_VENDA,
  CLG_CANAL  CLG_CANAL_VENDA,
  CLG_REDE  CLG_REDE_VENDA,
  CLG_PRODUTO,
  CLG_TP_MOVIMENTO,
  DIM_PERIOD_DAY  PERIOD_VENDA_DATA,
  CLG_LOJA  CLG_LOJA_VENDA
WHERE
  ( CLG_VENDA_PONTO.ID_VENDA=CLG_VENDA.ID(+)  )
  AND  ( CLG_VENDA_PONTO.ID_PROD=CLG_PRODUTO.ID(+)  )
  AND  ( CLG_VENDA_PONTO.ID_CARGO=CLG_CARGO_VENDA.ID  )
  AND  ( CLG_LOJA_VENDA.ID=CLG_VENDA_PONTO.ID_LOJA  )
  AND  ( CLG_REDE_VENDA.ID=CLG_LOJA_VENDA.ID_REDE  )
  AND  ( CLG_CANAL_VENDA.ID=CLG_VENDA_PONTO.ID_CANAL  )
  AND  ( CLG_PARTICIPANTE.ID_LOJA=CLG_LOJA_VENDA.ID  )
  AND  ( CLG_LOJA_VENDA.ID_REDE=CLG_REDE_VENDA.ID  )
  AND  ( CLG_PARTICIPANTE.ID=CLG_VENDA_PONTO.ID_PARTCPTE  )
  AND  ( CLG_VENDA_PONTO.ID_TP_MOVIMENTO=CLG_TP_MOVIMENTO.ID  )
  AND  ( CLG_STATUS.ID=CLG_PARTICIPANTE.ID_STATUS  )
  AND  ( CLG_VENDA_PONTO.DATA_VENDA=PERIOD_VENDA_DATA.YYYYMMDD  )
  AND  ( CLG_CARGO_VENDA.NM_CARGO = '5 - VENDEDOR' OR CLG_VENDA.ID_CARGO = 8  )
  AND
  (
   CLG_PRODUTO.NM_PRODUTO  NOT IN  ( 'M4338 - FRETE','R39745 - FRETE SOBRE VENDAS'  )
   AND
   CLG_TP_MOVIMENTO.NM_MOVIMENTO  IN  ( '1 - VENDA','3 - DEVOLUCAO'  )
   AND
   CLG_REDE_VENDA.NM_REDE  =  '21540901 - RABELO'
   AND
   PERIOD_VENDA_DATA.YYYYMMDD_DATE  BETWEEN  to_date('01-01-2013', 'DD-MM-YYYY')  AND  to_date('31-12-2013', 'DD-MM-YYYY')
   AND
   CLG_CANAL_VENDA.NM_CANAL  IN  ('1 - VAREJO')
   AND
   CLG_PRODUTO.FG_MAPEADO  IN  ( 'SIM'  )
  )
GROUP BY
  case  when CLG_STATUS.NM_STATUS in ('1 - ATIVO','5 - BLOQUEADO','7 - AGUARDANDO AUTENTICAÇÃO') then 'LG Club Member'
    else 'Non  Member'
  end
), t2 as (
SELECT
  case  when CLG_STATUS.NM_STATUS in ('1 - ATIVO','5 - BLOQUEADO','7 - AGUARDANDO AUTENTICAÇÃO') then 'LG Club Member'
    else 'Non  Member'
  end membership,
  Round(
    Round(SUM(NVL(CASE WHEN CLG_VENDA.CD_TP_VENDA = 'D' THEN -1*CLG_VENDA.QTD_VENDA ELSE CLG_VENDA.QTD_VENDA END,0)), 1)
    /
   Count(distinct CLG_PARTICIPANTE.ID)
  , 1) as average_sales ,
  Round(
    SUM(NVL(CASE WHEN CLG_VENDA.CD_TP_VENDA = 'D' THEN -1*CLG_VENDA.QTD_VENDA ELSE CLG_VENDA.QTD_VENDA END,0))
  , 1) as sellout,
  Count(distinct CLG_PARTICIPANTE.ID)
  as "qty members"
FROM
  CLG_VENDA_PONTO,
  CLG_PARTICIPANTE,
  CLG_STATUS,
  CLG_VENDA,
  CLG_CARGO  CLG_CARGO_VENDA,
  CLG_CANAL  CLG_CANAL_VENDA,
  CLG_REDE  CLG_REDE_VENDA,
  CLG_PRODUTO,
  CLG_TP_MOVIMENTO,
  DIM_PERIOD_DAY  PERIOD_VENDA_DATA,
  CLG_LOJA  CLG_LOJA_VENDA
WHERE
  ( CLG_VENDA_PONTO.ID_VENDA=CLG_VENDA.ID(+)  )
  AND  ( CLG_VENDA_PONTO.ID_PROD=CLG_PRODUTO.ID(+)  )
  AND  ( CLG_VENDA_PONTO.ID_CARGO=CLG_CARGO_VENDA.ID  )
  AND  ( CLG_LOJA_VENDA.ID=CLG_VENDA_PONTO.ID_LOJA  )
  AND  ( CLG_REDE_VENDA.ID=CLG_LOJA_VENDA.ID_REDE  )
  AND  ( CLG_CANAL_VENDA.ID=CLG_VENDA_PONTO.ID_CANAL  )
  AND  ( CLG_PARTICIPANTE.ID_LOJA=CLG_LOJA_VENDA.ID  )
  AND  ( CLG_LOJA_VENDA.ID_REDE=CLG_REDE_VENDA.ID  )
  AND  ( CLG_PARTICIPANTE.ID=CLG_VENDA_PONTO.ID_PARTCPTE  )
  AND  ( CLG_VENDA_PONTO.ID_TP_MOVIMENTO=CLG_TP_MOVIMENTO.ID  )
  AND  ( CLG_STATUS.ID=CLG_PARTICIPANTE.ID_STATUS  )
  AND  ( CLG_VENDA_PONTO.DATA_VENDA=PERIOD_VENDA_DATA.YYYYMMDD  )
  AND  ( CLG_CARGO_VENDA.NM_CARGO = '5 - VENDEDOR' OR CLG_VENDA.ID_CARGO = 8  )
  AND
  (
   CLG_PRODUTO.NM_PRODUTO  NOT IN  ( 'M4338 - FRETE','R39745 - FRETE SOBRE VENDAS'  )
   AND
   CLG_TP_MOVIMENTO.NM_MOVIMENTO  IN  ( '1 - VENDA','3 - DEVOLUCAO'  )
   AND
   CLG_REDE_VENDA.NM_REDE  =  '21540901 - RABELO'
   AND
   PERIOD_VENDA_DATA.YYYYMMDD_DATE  BETWEEN  add_months(to_date('01-01-2013', 'DD-MM-YYYY'), -12)  AND  add_months(to_date('31-12-2013', 'DD-MM-YYYY'), -12)
   AND
   CLG_CANAL_VENDA.NM_CANAL  IN  ('1 - VAREJO')
   AND
   CLG_PRODUTO.FG_MAPEADO  IN  ( 'SIM'  )
  )
GROUP BY
  case  when CLG_STATUS.NM_STATUS in ('1 - ATIVO','5 - BLOQUEADO','7 - AGUARDANDO AUTENTICAÇÃO') then 'LG Club Member'
    else 'Non  Member'
  end
)
select t1.*, coalesce((t1.average_sales - t2.average_sales) / t2.average_sales, 0)    as variation
from t1 join t2 on t1.membership = t2.membership

On SQL Developer it displays this:
ORA-00928: missing SELECT keyword
00928. 00000 -  "missing SELECT keyword"

I'm totally at a loss here. How can a query parse at one tool and not the other ? I tried searching around the net but to no avail.
Thanks in advance!
Comment: "doesn't work" **HOW**?
Comment: Sorry, just updated here, it gives a parsing error. Which is what amazes me the most, since the exact same query, copy and paste, works at plsql developer
Comment: @RaoniMedinilha Hm
could you try to change all the non-ASCII characters to ASCII counterparts? just to rule out the character encoding settings
Comment: @micklesh I can do that, but most of my queries involve non-ASCII characters, since it's part of my language, and I've never had this kind of issue before, some I'm a little skeptic about this being the issue.
Comment: Maybe the version of the SQL Developer is too old. Otherwise rewrite it as good old subselects.
Comment: Have seen similar behavior with TOAD not returning the same query results as seen for same exact query executed in SQL Plus. IIRC, TOAD would tell me no rows returned while SQL Plus would return rows. Left me with a real distaste for TOAD.
Comment: Remove all the excess ()'s around the where's that you don't need.  When I tried the error changed to a missing table (understandable since I don't have them!)
Answer: It might be the line,
    /

SQL Plus uses / by itself to mark the end of a sql query, and SQL Developer most likely follows. However, the preceding whitespace may change the meaning, so this may not be the problem.
To test this hypothesis move the / to the preceding line. Change
    Round(SUM(NVL(CASE WHEN CLG_VENDA.CD_TP_VENDA = 'D' THEN -1*CLG_VENDA.QTD_VENDA ELSE CLG_VENDA.QTD_VENDA END,0)), 1)
    /
   Count(distinct CLG_PARTICIPANTE.ID)

To
    Round(SUM(NVL(CASE WHEN CLG_VENDA.CD_TP_VENDA = 'D' THEN -1*CLG_VENDA.QTD_VENDA ELSE CLG_VENDA.QTD_VENDA END,0)), 1) /
   Count(distinct CLG_PARTICIPANTE.ID)

If that is the problem, then it is a matter of reformatting to something that works for you that doesn't leave / on a line by itself.
Comment: What would I use as the division symbol then ?
Comment: @RaoniMedinilha he just moved the division symbol to the line above
Comment: for pete's sake! couldn't oracle use another symbol instead of the division sign ? Once I did that, the query started working properly. I just can't believe I lost an entire work day because of that

Thanks a lot Shannon!


How to enable undo in nano?

Question: How can I enable Undo in nano?
I am using a ssh connection with a server. I can not update the version of nano that is installed on the server. Is there anyway to use GNU nano 2.3.1 to have Undo function?
Comment: I managed to find out the solution. I hope this helps.
Use this command:
nano -u
Then use Alt+U for undo and Alt+E for redo.
Comment: Does this answer your question? [How to use Undo functionality in Nano?](https://askubuntu.com/questions/332961/how-to-use-undo-functionality-in-nano)
Comment: This problem is just for the cases with nano 2.3.1.
Comment: This problem have been solved in newer version.
Comment: See [https://askubuntu.com/questions/332961/how-to-use-undo-functionality-in-nano#672091](https://askubuntu.com/questions/332961#672091).
Comment: Yes actually it does. Thank you!
Answer: Alt-U to undo,
Alt-E to redo,

More hotkeys:
Ctrl-K to cut,
Ctrl-U to paste,
Ctrl-Z to send to background (fg to bring back)
Comment: Thank you for your help!
Comment: Don't forget Alt+6 to copy.

How to enable undo in nano?


How to initiate two arrays storing 16 bits each and creating a third array by XOR on the first two in C?

Question: I am in the process of building a drum machine and I want to have two 16 bit arrays defining the state of the machine. One array "current_led" which has a 1 set at the index corresponding to the current 16th note being played.
When the user programs a sound to be played, for instance at step 1 and 4, I want one 16 bit array "selected_steps" to have a 1 set at index 0 and 3.
So I want, at each step update defined by the beats per minute, the "current_led" to shift the bit but the "selected_steps" is static.
I want a final array "led_array" which is constructed by
led_array = XOR(selected_steps,current_led)

This is such that I can use a shift register to light up the correct LED's at each step update.
But since I have some trouble defining and working with bits and arrays in C I do not understand how to initialize the arrays correctly and work with them.
What I would want it something like
  int current_led[16];
  int selected_steps[16];
  int led_array[16];

  //Function is called every 0.5 s if BPM 120.
  void step(void) {
  step_number = step_number < 15 ? step_number +1 : 0;
  }

I am using 2 PISO shift registers to take the input from 16 buttons to my micro controller. I have the parallell load pin set to high constantly, such that whenever the user pushes a button, that corresponding pin on the shift register is set to 1. Therefore I am reading each 16 pins every time to see if the user has pushed down any buttons.
  //Check which steps are selected by the user. This function is called every 1 ms
  void scan_buttons() {
  for (int j = 0; j<16 ; j++) {
      if (PIND & 0b01000000){
            selected_steps[j] = 1;
            } else {
            selected_steps[j] = 0;
        }

  void update_led(void) {
     current_led = (1 << step_number);
     led_array = current_led^selected_steps;

     for (int j = 15; j>=0 ; j--) {
        if (led_array[j] == 1) {
           do something...
        } else {
           do something else...
        }
     }
  }

So for clarity, here is an example of how the LED's should represent that state.
If the BPM is set to 120, and we have 16 steps (4 beats), the step should increment every 60/BPM seconds (0.5 seconds). The current step is indicated by a bright LED. I also indicate to the user which step he/she has programmed a sound on by always having the LED light up at that current step.
Step 1: step_number = 0
LED: [1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]

Step 2: step_number = 1
LED: [0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0]

Step 3: step_number = 2, selected_step[7] = 1, selected_step[11] = 1,
(User has chosen to input a sound on step 8 and 12 by pressing button 8 and 12)
LED: [0 0 1 0 0 0 0 1 0 0 0 1 0 0 0 0]

Step 4: step_number = 3, selected_step[7] = 1, selected_step[11] = 1,
(User has not pressed any buttons since last step)
LED: [0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 0]

But I do not understand how to declare the arrays, and write the correct code to set the bits correctly and perform XOR operations.
Comment: No need to use an array, just use a `uint16_t`, and have each bit track the state of one led.
Comment: So how do I correctly initiate uint16_t object with 0:s and set for instance bit 8 to 1 in scan_buttons? Something like "uint16_t selected_steps;". selected_steps[8] = 1;?
Comment: Your problem is not fully clear to me. Maybe you should [edit] your question and add more details to your description. How does the user enter the data using buttons, how should the LEDs show the state, how and when do the LEDs change. An example what the user might have entered and the expected LED output might help to understand. Without this it is difficult to suggest "the correct code". Your function `scan_buttons` looks suspicious. It seems to poll the same input pin 16 times very fast which is probably not what you want. Add more comments to your code what you expect it to do.
Comment: I edited the post, have I been able to explain it better now?
Answer: Here is how you may set and clear bits in a uint16_t (the same goes for any unsigned ints, just change the types accordingly)
It is a long time since i have done any bit-manipulations, so you should double check this
before you use it, don't have any time to do it myself.
/*
   `set_bits`, `unset_bits` and `flip_bits` modifies multiple bits in v.

    The bits you want to modify are selected by setting the corresponding bit
    in `mask` to 1.
*/

uint16_t set_bits(uint16_t v, uint16_t mask)
{
   return v | mask;
}

uint16_t unset_bits(uint16_t v, uint16_t mask)
{
   return v & ~mask;
}

uint16_t flip_bits(uint16_t v, uint16_t mask)
{
   return v | ((~v) & mask)
}

/*
 `set_bit`, `unset_bit`, `flip_bit`, `overwrite_bit` modifies a single bit in `v`.
 The bit to modify is given by the index `i`
*/

uint16_t set_bit(uint16_t v, int i)
{
   return set_bits(v, 1 << i);
}

uint16_t unset_bit(uint16_t v, int i)
{
   return unset_bits(v, 1 << i);
}

uint16_t flip_bit(uint16_t v, int i)
{
   return flip_bits(v, 1 << i);
}

uint16_t overwrite_bit(uint16_t v, int i, int new_val)
{
   /* ensure `new_val` is either 0 or 1 */
   new_val = new_val ? 1 : 0;

   uint16_t mask = 1 << i;
   uint16_t mask_x = ~mask;

   uint16_t nv = new_val << i;

   return v & (mask_x | nv);
}

int read_bit(uint16_t v, int i)
{
   uint16_t mask = 1 << i;
   return (v & mask) ? 1 : 0;
}

/* How to initialize all the bits in `selected_steps` to zero */
selected_steps = 0;

/* How to initialize all the bits in `selected_steps` to 1 */
selected_steps = 0xffff;  /* or  = 0b1111111111111111 */

/* How to read the value of bit 8 in `selected_step` */

int val = read_bit(selected_steps, 8);

/* How to set the value of bit 8 to 1 */
selected_steps = set_bit(selected_steps, 8);
/* or */
selected_steps = overwrite_bit(selected_steps, 8, 1);
/* or */
selected_steps = set_bits(selected_steps, 0b100000000);

/* How to set the value of bit 8 to 0 */
selected_steps = unset_bit(selected_steps, 8);
/* or */
selected_steps = overwrite_bit(selected_steps, 8, 0);
/* or */
selected_steps = unset_bits(selected_steps, 0b100000000);

/* Setting bits 1 and 4 to 1 */
selected_steps = set_bits(selected_steps, 0b10010);
/* or */
selected_steps = set_bits(selected_steps, (1<<4) | (1<<1));

/* Calculating xor of two bitsets */
uint16_t xor_a_b = a ^ b;

Depending of your use case, you may choose to define these functions as static inline. It may also make sense to turn step_number into a mask rather than index.


Can barcode Misread code?

Question: in my asp.net mvc application on Register Form when users are using barcode scanner to insert data to textbox ,they say that it misses some portion of code like if they  scan 02501603566 they get 02501602566 or 01301103564 can be 01301403564 after register.can barcode misread some data? i tested on my barcode and everything works fine.customers have big amount of data so they cant check every time what they have scanned in input.this can happen 1 times in 100..
Comment: In most barcode format there is a checksum which prevents this errors. A mis-scan can always happen, you could prevent is by enabling the checksum-verification on the scanners
Comment: please ask them to scan the barcode using a different scanner is it possible that barcode scanner is not configured properly. secondly, check your label printing code is there any mistake in passing wrong data to the printer.
Answer: Yes its not only possible that a scanner misreads are barcode,  it definitely happens. 1D barcodes are the worst, but also cheap readers and readers configured improperly for the type of barcode being read can also be a problem.

If you are in control of the code, use a barcode with the appropriate error checking (and there are many).
Also check your barcode reader settings (they all have them).
If all else fails check the barcode with a different scanner or barcode reader app and check if its the fault tolerance of the scanner itself.

Misreads in the form of a perfectly scanning but wrong barcode can be
  caused by scanner number substitution

Somehow the printed barcode image is wrongly  decoded by the scanner. A poor quality printed barcode can contribute to this, but barcode structure also contributes. UPC is notoriously vulnerable to number  substitution of 1 and 7, and 2 and 8 characters

Low ISO Decodability scores can contribute to barcode misreads,
  especially when they are caused by pixel rounding in the print process

This is most common in a thermal or thermal transfer printing but it can also occur in ink jet, DOD and other digital printing systems

Scanners can also misread otherwise acceptable barcodes. Most often
  the cause can be traced to damaged or dirty optics, but faulty decode
  algorithms area known cause, albeit a rare one

Older, high-mileage scanners such as lasers tend to be more prone to misreads than newer, more sophisticated digital area imager scanners.
If a calibrated, ISO compliant verifier decodes and assigns an acceptable grade to a misreading barcode, one can be confident the cause lies with the scanner      and not the barcode itself. This is yet another example of how a scanner cannot effectively serve as a verifier
Comment: They will get new barcode scanner.hope problem will be gone

Can barcode Misread code?


How to lock grub2 default selection?

Question: This morning linux-image-3.5.0-26-generic was installed during a software update. On my laptop this proved to be unusable after 10 minutes. I changed to linux-image-3.5.0-24-generic and all seems fine. I have updated the default grub2 selection to the 24-generic. How can I lock the default grub selection to this value so subsequent updates don't overwrite and make themselves default?
Answer: you can use this tool, Grub Customizer. To download,
Open terminal and type:

sudo add-apt-repository ppa:danielrichter2007/grub-customizer [enter]
sudo apt-get update [enter]
sudo apt-get install grub-customizer [enter]

Open dash and search grub customizer, and run it. Edit configuration with this tool.it's easy . Go to General Settings to edit the default, time boot etc
Comment: Thanks - I installed that and was able to edit the default entry so to the version I desired. I did NOT notice how to "lock" the default so that new kernels wouldn't overwrite and make themselves default
Answer: how to lock a kernel grub entry
With a bit of command line trickery, you can get the default of grub to always be a particular grub entry no matter when a new kernel is installed or updated.
In a terminal type:
fgrep menuentry /boot/grub/grub.cfg

This will display all your grub entries - for example

Highlight the entry you want to default to - for example 'Ubuntu, with Linux 3.2.0-31' in the screen-shot.  Right click and choose copy
Type
gksu gedit /etc/default/grub

Change the entry
GRUB_DEFAULT=0

to
GRUB_DEFAULT='2>Ubuntu, with Linux 3.2.0-31-generic'

i.e. paste the entry you want (including the quotes) BUT PREFIX with the text 2>
Save, then type
sudo update-grub

The text 2> is important because this informs Grub that the entry to boot from exists in the sub-menu called "Previous Linux entries"
Answer: I just searched and found this file:
/etc/default/grub

Command grub-mkconfig (or update-grub) uses this file for default values. Try editing line GRUB_DEFAULT=0 to GRUB_DEFAULT=1.
Comment: Thats only good until the next kernel upgrade happens.
Comment: I want to insure that on subsequent kernel updates grub2 default selection REMAINS on whatever I've modified in the grub2 menu. Or is it possible to have a dual boot config based on kernel level?
Comment: Oh, I understand. This way `Kernel3` would take `Kernel2` place and `default=1` would point to `Kernel 2`, instead of `Kernel1`. But it seems `GRUB_DEFAULT` can be set to a string. I don't have the exact answer, but I thinks it's here: [link](http://www.gnu.org/software/grub/manual/html_node/Simple-configuration.html#Simple-configuration).

How to lock grub2 default selection?


AWS CodePipeline: source action has insufficient permissions for CodeStar connection

Question: I'm setting up a CodePipeline, and I created an action to fetch the source from GitHub.
This requires to set up a connection, which I did, and things look fine also on GitHub's side.
However, if I release a change to the pipeline, I see the following error at the source stage:
Insufficient permissions
Unable to use Connection: arn:aws:codestar-connections:us-east-1:REDACTED:connection/REDACTED. The provided role does not have sufficient permissions.

I added full CodeStar access to the pipeline's service role (which I found in the pipeline settings) and looks like this:
arn:aws:iam::REDACTED:role/service-role/AWSCodePipelineServiceRole-us-east-1-REDACTED

Does anybody have any idea of what might be missing? Thanks!
Answer: The solution was to add this bit to the policy of the service role:
{
        "Effect": "Allow",
        "Action": "codestar-connections:UseConnection",
        "Resource": "insert ARN of the CodeStar connection here"
}

Comment: I sometimes wonder if it weren't for these answers anyone would be able to use AWS!
Comment: Thank you, it helped me.
Comment: I am using the CDK v2, my pipeline role `PipelineRole-12345` includes a policy that allows it to assume several other roles  (i.e. `*Sourceproject-2B2Z1X5W31VD` ).  If you're still having problems try adding to one of the roles that are assumed.


How to update github libraries consumed in project

Question: I am using an open source library project from GitHub in my Android Application. I've modified that library to work with my specific needs. Now that library has been updated with more cool features.
If I want to use the updated library, I've to download it and again I've to put my older modifications manually. Instead of that is there any process, so that I can use latest libraries from GitHub still with my modifications.
Your help is appreciated.
Comment: I don't think so there is a way for Git same as using library from Maven repository.
Comment: http://stackoverflow.com/questions/8897019/git-how-to-handle-git-libraries-in-project
This questions has the answer
Answer: You want to fork that repository on Github, add your changes onto that, then merge the upstream changes once they come out. You could even add your fork of this library as a submodule in your main project.
Hope that helps. Good luck!


"[drm:intel_dp_complete_link_train] *ERROR* failed to train DP, aborting"

Question: I've just installed Ubuntu 14.04 server on Dell Latitude E7440 and then installed Cinnamon 2.4.5 on top of it. The laptop has an external monitor connected through Display Port and a docking station.
On the first day the system worked perfectly.
On the second day, the system booted to the login screen (leaving the external screen empty but otherwise seemed to be under X11's control), it then let me type my username and password but then X exits, shows a bit of VT1 with errors then gets back to the login page.
I found the following error in /var/log/kern.log:
[drm:intel_dp_complete_link_train] *ERROR* failed to train DP, aborting

I found a page which claims to solve this error for 12.04 in the second comment in this bugzilla thread on libreoffice.org, but I don't understand how to apply this patch on my system. So far I failed to find the source file intel_dp.c in any Ubuntu source package.
Does anyone know how can I apply this patch on Ubuntu 14.04?
Answer: I found the answer - the file was inside linux-source-3.13.0.tar.bz2 which comes in package linux-source-3.13.0. I filed a request to include this in the Ubuntu kernel at:
https://bugs.launchpad.net/ubuntu/+source/xorg/+bug/1403275


Order by "best match" based on relational tables values

Question: I have the following entity:
Project

Having multiple related tables:
Project >-< ProjectAttribute >-< AttributeType
Project >-< ProjectAttribute >-< AttributeValue
Project >-< ProjectTask >------< Task
Project >-< ProjectTask >------< Employee
...

Involving about 15 tables including subjoins.
Now I'm required to find the best matching Projects for a single Project given, by comparing the values and counting the occurrences. e.g. a match of AttributeType and AttributeValue increases the "best match" indicator of a Project by 1.
How can I achieve this?
Answer: I think I found out how to query similarities:
SELECT
    sp.*,
    ((
        SELECT COUNT(spa.id) FROM project_attribute AS spa WHERE spa.project = sp.id AND spa.attribute = pa.attribute AND spa.attribute_value = pa.attribute_value
    ) * 1)
    +
    ((
        SELECT COUNT(spt.id) FROM project_task AS spt WHERE spt.project = sp.id AND spt.address = pt.address
    ) * .25)
    +
    ((
        SELECT COUNT(spc.id) FROM project_campaign AS spc WHERE spc.project = sp.id AND spc.campaign = pc.campaign
    ) * 2)
    AS similarity
FROM project AS p
LEFT JOIN project_attribute AS pa ON (p.id = pa.project)
LEFT JOIN project_task AS pt ON (p.id = pt.project)
LEFT JOIN project_campaign AS pc ON (p.id = pc.project)
LEFT JOIN project AS sp ON (p.id != sp.id)
WHERE
    p.id = <PROJECT-ID>
GROUP BY sp.id
ORDER BY
    similarity DESC

I also added a multiplicator to control the impact of similar rows.
The performance isn't the best (~200ms for 235 projects), but it fits my current needs.


Uploading video to youtube in right format

Question: I have a Sony CX115 and I have a little footage I'd like to put on youtube.
I've downloaded Arista from the Ubuntu Software Center and then I've downloaded its Youtube HD plugin.
I've converted my video and uploaded it to youtube...
The result is a flashy video with a lot of grey in it:
http://www.youtube.com/watch?v=1V08e5PkVDI
What could I do to publish it in high quality so it'll be viewable?
Comment: Related question: [best video converter](http://askubuntu.com/q/27864/6969)
Answer: As an alternative, can I suggest you use OpenShot to edit video and also upload HD quality video to Youtube.
You export the video similar to this picture.

You can then use the inbuilt upload feature to send to Youtube
Comment: Oh great!
It looks easy: I was looking for that.
Can I also convert a folder full of videos or I have to export one video at a time?
Comment: Oh that's great...
Any info about how to set the openshot-renderer using cli to export hd videos to youtube?
Comment: @pitto - having investigated further, I dont think openshot-renderer will do what you want.  Your question referred to converting and uploading a video.  If you want to do lots then see the link @lekensteyn above - handbrake would be my choice.
Answer: This may help:
Transcoding is made easy by using several GUI's or command line tools. Of which I previously posted this answers, I hope this help you.
What is the best tool for converting and reading video to be played on DVD players?
How can I maximum compress video files?
Additionally, there are a few other answers in this forum under the "video" tag which may be useful for you.
Good luck!
P.S. If you are using a 64 bit system you may be interested in this: How to install 32 bit software in 64 bit system from within the Israel Linux Remix Team, posted by me in the past. Certain software may misbehave when using this procedure but it is yet good for transcoding or downloading from youtube the appropiate video file (.flv).
BTW: You can upload almost any video file with almost any codec which Youtube will transcode, suggested by Youtube:
Best Formats for Uploading

YouTube can accept almost any video
  format for upload, but for most users
  we have found the following settings
  give the best results.
Video Format: H.264, MPEG-2 or MPEG-4
  preferred Aspect Ratio: Native aspect
  ratio without letterboxing (examples:
  4:3, 16:9) Resolution: 640x360 (16:9)
  or 480x360 (4:3) recommended Audio
  Format: MP3 or AAC preferred Frames
  per second: 30 Maximum length: 10
  minutes (we recommend 2-3 minutes)
  Maximum file size: 1 GB
Answer: Upload mp3 to youtube on ubuntu 14.04
Here's a shell script that uses avconv (which is available on Ubuntu 14.04):
<code>#!/bin/sh

PIC=$1
SND=$2

if [ -z "$SND" ]; then
    echo "Usage: $0 [image] [audio]"
    exit 1
fi

OUT=`echo "$SND" | sed s/\.[a-z0-9]*$/.mp4/`

avconv -loop 1 -f image2 -i "$PIC" -i "$SND" -acodec copy -shortest "$OUT"
</code>
Also available as gist.
Answer: Probably YouTube made some adjustments but I managed to upload an ogv video file directly on YouTube.
Comment: Results may vary. When I first tried to upload an Ubuntu 10.04 screencast I made using Gtk-RecordMyDesktop to YouTube, the result was solid green video. It's a safer bet to convert videos into an officially supported format like WebM first before uploading.


If two complex vectors are orthonormal, does conjugating one of them preserve orthonormality?

Question: Suppose $x_1$ and $x_2$ are two orthonormal vectors with complex elements. I wonder if $x_1$ and $\bar x_2$ still orthonormal to each other? Thanks for any help!
Answer: The question is whether for complex numbers $x_1,x_2,\cdots,x_n$ and $y_1,\cdots,y_n$, we have the implication
$$
\sum_{i=1}^n x_i \overline{y_i} = 0 \quad \Longrightarrow \quad \sum_{i=1}^n x_i y_i = 0.
$$
Of course if $n=1$ this is true since $x_1 \overline{y_1} = 0$ implies that $x_1$ or $y_1$ is zero, hence conjugating doesn't change the sum. But with $n=2$ there are already counter-examples : pick $\begin{bmatrix} x_1 \\ x_2 \end{bmatrix} = \begin{bmatrix} 1 \\ i \end{bmatrix}$ and $\begin{bmatrix} y_1 \\ y_2 \end{bmatrix} = \begin{bmatrix} 1 \\ -i \end{bmatrix}$. Then
$$
x_1 \overline{y_1} + x_2 \overline{y_2} = 1 \cdot 1 + i \cdot \left( \overline{-i} \right) = 1+i^2 = 0, \quad x_1 y_1 + x_2 y_2 = 1 \cdot 1 + i \cdot (-i) = 1-i^2 = 2.
$$
Hope that helps,
Comment: Yeah, I've deleted my "valuable" answer.


how can i create a custom ?

Question: I want to enlarge the arrow of the select tag and set its background to green.
The width of the box must be 100px and the height 50px. I tried a lot of css but it didn't worked out

.select_box{
    width: 100;
    overflow: hidden;
    border: 1 solid #000;
    position: relative;
    font-size: 12;
    padding: 10 15;
    margin-left: 10;
    margin-top: 5;
}
.select_box:after{
    width: 10;
    height: 50;
    border-left: 6 solid transparent;
    border-right: 6 solid transparent;
    border-top: 6 solid white;

    position: absolute;
    top: 40%;
    right: 5;
    content: "";
    z-index: 98;
    background-color: green;
    background-size: auto;
}
.select_box select{
    width: 110;
    border: 0;
    position: relative;
    z-index: 99;
    background: none;
}

  <select>
    <option > Position</option>
    <option > Height</option>
    <option > Width</option>
  </select>

Comment: there are a ton of questions about this. Please search before posting here. Possible duplicate of [CSS Select box arrow style](https://stackoverflow.com/questions/12668404/css-select-box-arrow-style) or other
Comment: https://www.w3schools.com/howto/howto_custom_select.asp
Answer: You can't use after, before for select, but you can use background like this:
https://codepen.io/Lincox/pen/mQRpPm

/*Remove style of select*/
select{
    -webkit-appearance: none;
    -moz-appearance: none;
}

.custom-select{
  width: 100px;
  height: 50px;
  background: url(https://mbtskoudsalg.com/images/arrow-keys-png-image-7.png) right 10px center/10px 10px no-repeat;
  background-color: green;
}

.custom-select2{
  width: 100px;
  height: 50px;
  background: url(https://static.thenounproject.com/png/4350-200.png) right 10px center/20px 20px no-repeat;
  background-color: red;
}
<select class="custom-select">
  <option>1</option>
  <option>2</option>
  <option>3</option>
</select>

<select class="custom-select2">
  <option>3</option>
  <option>4</option>
  <option>5</option>
</select>

Accept and let me know if it works
Answer: Try this one:

.select-style {
  position: relative;
  padding: 0;
  margin: 0;
  border: 1px solid #ccc;
  width: 100px;
  heigh: 30px;
  overflow: hidden;
  background: transparent
    url("https://i.imgur.com/qJolQ2D.png") no-repeat
    93% 50%;
}
.select-style select {
  padding: 5px 8px;
  width: 150%;
  border: none;
  background-color: transparent;
  background-image: none;
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
}
.select-style select:focus {
  outline: none;
}
.select-style:after {
  position: absolute;
  content: "";
  width: 30px;
  height: 100%;
  background-color: #77d800;
  top: 0;
  right: -1px;
  z-index: -1;
  border-radius: 0 1px 1px 0;
}

  <select>
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
        <option value="mercedes">Mercedes</option>
        <option value="audi">Audi</option>
   </select>

Sorce: How to put background-color only a section of a select? CSS

how can i create a custom ?


How to post Facebook Score using JS SDK, without hardcoding the app access token?

Question: I'm trying to post a score using the JS SDK. Here's the code that I'm using:
FB.api("/[USER_ID]/scores", 'post', {score:score, access_token:"APP_ACCESS_TOKEN"}, function(response){
           if (!response || response.error) {
              log(response);
           } else {
              log(response);
           }
    });

However, I need to do this without hardcoding the APP_ACCESS_TOKEN. Any idea on how to do it using the JS SDK?
Answer: /me/ refers to the current user - when using the app access token there is no 'current' user - you're acting as the app - make the request to /[USER ID]/scores using the app access token
Comment: _"Any idea how to grab it dynamically using JS?"_ – __Don't!__ Whatever this "anything" might be – everyone who sees your JS code could do the same thing, or even stept through it in their browser's JS debugger, and they would have your app access token. __N-E-V-E-R__ publish your app access token client-side or transfer it to the client, in whatever way. If you need to publish something with your app access token (scores, OG actions) – __then do it server-side!__
Comment: That solved the problem of the "official" code not working Igy! Thanks!

However, I still have to put the APP_ACCESS_TOKEN in my JS code... Any idea how to grab it dynamically using JS?
Answer: You can grab access_token through JS by using FB.getLoginStatus. More can be found in the doc.
.
Comment: No, it's not Ratul. I need the app access token. That's the user access token.
Comment: The token you're referring is not the app access token, which is what's needed for posting a score.
Comment: Oh, I am so sorry. I messed up.
Answer: There is no way, that I know of.
And, nor should there be, when you consider that the App will only have one app access_token.
Think of it like your app secret, keep it safe!
Especially when you consider how you get the access_token to start with, just by making a formatted request to FB with your ID and App Secret.
If you put that client side, then ANYONE could grab it and do stuff on behalf of your app!!
I would suggest one of two things:

Try making a call to /me/scores, and use the normal access token.
Even though the API docs don't suggest this being possible, you never know.

OR
2. Encapsulate it as an AJAX call to your server, and make the Graph call from there.
Sucks, but there seems to be a few things that aren't quite designed to work on the client side yet. :-/
Comment: Thanks for your answer Owen.

1. It doesn't work.
2. I'll give it a try! ;)


stack around the variable 'tabRatio' was corrupted

Question: I use this code to see the course of the function sin:
#include <stdio.h>
#include<stdlib.h>
#include<math.h>
#include<locale.h>
#include<time.h>
#define PI 3.14159265

void ratio(double *tabRatio)
{
    int i;
    for (i = 0; i < 4; i++)
    {
        do {
            printf("Enter %d wspolczynnik:", i + 1);
            scanf("%lf", tabratio + i);
        } while (!*(tabratio + i));
        printf("%f", *(tabratio + i));
    }
}
void scope(int* fieldmin, int* fieldmax, int* frequency, int *size)
{
    do {
        printf("Podaj dolny zakres dziedziny :");
        scanf("%d", fieldmin);
        printf("Podaj gorny zakres dziedziny :");
        scanf("%d", fieldmax);
    } while (*fieldmin >= *fieldmax);
    do {
        printf("Podaj czestotliwosc probkowania :");
        scanf("%d", frequency);
    } while (*frequency > *fieldmax - *fieldmax);
    // printf("%f",*dolnyzakres);
    *size = *fieldmax - *fieldmin;
}
void function(double*tabRatio, int* fieldmin, int* fieldmax, double*result, int* size)
{
    double x;
    int j;
    x = *fieldmin;
    //int rozmiar = 10;
    printf("The course of the function:");
    printf(" %d", *size);
    for (j = 0; j < *size; j++)
    {
        result[j] = tabRatio[0] * sin(((tabRatio[1] + tabRatio[2])*PI / 180)*x + tabRatio[3]);
        printf("\ny(%lf)=%lf", x, result[j]);
        x += ((*fieldmax - *fieldmax) / *size);
    }
}
int main()
{
    int *fieldmin, *fieldmax, *frequency, *size;
    double tabRatio[4];
    double *result;
    ratio(&tabRatio);
    scope(&fieldmin, &fieldmax, &frequency, &size);
    function(&tabRatio, &fieldmin, &fieldmax, &result, &size);
}

Visual Studio gives me the following error:
Stack around the variable 'tabRatio' was corrupted.
Stack around the variable 'result' was corrupted.
Please help!
Comment: Your code does not compile please correct it and add the needed lines.
Comment: I've incorporated the code from your comments so that what is in the question can be compiled. Code that can be compiled is much easier to debug.
Answer: Your problem is how you pass your variables. You declare your functions to expect pointers to variables which is not a wrong thing to do but in this case completely unnecessary. Then you declare pointers in your main and pass their addresses to the functions where your compiler should warn you about incompatible pointer types. If it does not warn you enable warnings of your compiler they are important especially for beginners!
Back to your problem. Not only do you unnecessarily use pointers, if you would pass them correctly you would pass uninitialized pointers. If you declare a pointer you need to initialize it with the address of allocated memory.
int * num = malloc(sizeof(int)); /* Do not forget to free it */

otherwise it points to somewhere in your memory and accessing it is undefined behaviour which can lead to every possible outcome. In your case however you are not needed to use most of the pointers. Use pointers only if you want to modify a value inside a function and expect it to be available outside of the functions scope. Otherwise you can pass it by value. So the only variable which would be needed to be passed by reference is propably result and tabRatio. And even these would not be needed to be declared as a pointer (tapRatio is an array which decayes to a pointer but still). So you can simply declare result as an int and then pass its address
int result;
function(&result);

I did not look for other bugs in your code but this is what triggers you error message.
EDIT:
If nothing of the above makes sense to you consider to get a good C book before continuing
Comment: Thanks for answer, but the message still appears, if I should change in int main double result* to double result


How do I get default.aspx working

Question: My ISP needs a default.aspx page for my website.  They said rename the index.aspx.
Problem is default is a keyword.  If I rename index to default in index.aspx.cs file is gives the default keyword error:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace china
{
    public partial class default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }
}

How to get around it.  Any idea.
Regards
Tea
Comment: You most likely need to rename the class in the CodeBehind attribute in your Default.aspx page from index to default as well.
Comment: Have you tried @default? I am not sure if this will work, just the first thing that got on my mind.
Comment: you can use Default with capital D
Answer: One other way would be rename your file with Default.aspx, Uppercase D, this will remove the error since Default in C# is different to default (case senstive) and would work for the file system as well. (since file system on Windows would be case insenstive)
Otherwise rename only the file name, not the class name in the code. One way to do that would be to rename on File Explorer, but remember to correctly specify the file name in CodeBehind attribute in ASPX page.

How do I get default.aspx working


Alternative proof to, "every subgroup of a cyclic group is cyclic".

Question: In Artin's "Algebra", he recommends proving this by "working with exponents, and use the description of the subgroups of (Z,+)." The recommended proof makes sense to me, but I have been unable to confirm if this alternative proof is also valid. Is it even possible to prove this fact without resorting to relative primality, Lagrange, or the first isomorphism theorem?
"Suppose a group (G,* ) is cyclic. Then there exists x in G such that (x)=G. Let H be a subset of G. Suppose that H is not cyclic. Then x is not a member of H, since otherwise (H,* )=(x)=(G,* ). So suppose that H is a proper subset of G.
Suppose that (G,* ) has other proper subgroups, and let F be a proper subset of G. That is, there exists y in G such that (y)=(F,* ). Since H is not cyclic, for all y in G such that (y)=(F,* ), H is not equal to F and y is not in H.
Suppose that (H,* ) is a group. For all x and y in G and with F a proper subset of G, either (x)=(G,* ) or (y)=(F,* ). If (H,* ) is a group then it is closed under the product. Closure implies that neither x or y are in H, since (H,* ) would cyclic in either case. So if (H,* ) is not cyclic, then it is not equal to G or a nonempty proper subset of G, so H is empty.
But if H is empty then (H,* ) is not a group, and so there is a contradiction with all of the suppositions. Therefore H must be cyclic."
Comment: I am having some trouble following. It looks like a proof by contradiction, so it seems that you would want to begin by supposing $H \subset G$ is a non-cyclic subgroup. I am not sure why you postpone the assumption that $H$ forms a group; after all, the proposition is about subgroups. Also, I am not sure about the assumption that $G$ has *other* proper subgroups. This seems potentially problematic since the cyclic group $\mathbb{Z}/2\mathbb{Z}$ has only one proper subgroup. You end by contradicting "all of the suppositions," which (again) confuses me. Suppose just *one* thing; contradict!
Comment: I guess the reason that I postponed the assumption that H was a non-cyclic subgroup was because it seemed difficult to argue from that point of view without first establishing that both the lack of and the existence of other generated subgroups of G contradicted the existence of H. I definitely recognize the issues with the order of the proof, but the only alternative I could see was supposing that H was a cyclic subgroup of G and then providing a long list of disjunctive possibilities that would all contradict the existence of H.
Comment: One last question: why would it be improper to suppose that G has other subgroups? I know that it's possible that a group has only a single subgroup, but wouldn't it also be possible to suppose that this weren't the case so as to show that H couldn't be such a subgroup?
Thanks for your answers. The proof is confusing to me as well, but I also can't see a reason it could be wrong other than making the supposition that G had other subgroups distinct from H. So I wanted to check.
Comment: The goal is to prove *every subgroup is cyclic*. So, a sensible supposition to contradict would be, *there exists a subgroup that is not cyclic*. That way, if/when you arrive at a contradiction, you have shown the proposition at hand. Still, I cannot quite follow the reasoning in this proof, and I suspect "relative primality" is, indeed, a key ingredient (in some guise or another). Nothing in your proof seems (to me) to get at any feature of the integers, which feels problematic since every cyclic group is isomorphic to (the groups) $\mathbb{Z}$ or $\mathbb{Z}/n\mathbb{Z}$.
Comment: Proving with euclidean division on the exponents of members of G and H is definitely a much easier way to prove it, and the reason I was curious in the first place is that it "felt" logical despite not utilizing any features of the integers.

But I'm still not great at writing proofs, as evidenced by the lack of a good supposition, and so I have an unclear idea of how much validity to to attribute to that feeling. Thanks again for your time.
Comment: "Since H is not cyclic, for all y in G such that (y)=(F,* ), H is not equal to F and y is not in H." Why not?  There's no reason we can't have $F\subsetneq H $.
Comment: " Suppose that (G,* ) has other proper subgroups, and let F be a proper subset of G. That is, there exists y in G such that (y)=(F,* )." Why would F be cyclic?  Isn't that what you are trying to prove,
Answer: After reading this a few times, I think one of the major problems (not already mentioned in the comments) can be found here:

Suppose that $(G, *)$ has other proper subgroups, and let $F$ be a proper subset of $G$. That is, there exists $y \in G$ such that $(y)=(F, *)$.

In this excerpt -- specifically, the second sentence -- you are saying that just because $F \subset G$ proper, you can write $(F, *)$ as a cyclic group generated by some $y \in G$. But this assumption -- that a proper subgroup must be cyclic -- is exactly what you are trying to prove.
In fact, a subset $F$ of $G$ (inheriting the group operation from $G$) need not form a subgroup at all. And if it does form a subgroup, then (again) you cannot assume it'll be cyclic or you are simply assuming that which you've set out to prove.
Comment: This was definitely what I was missing. Thanks


TypeError: $(...).msDropDown is not a function

Question: I am getting type error in jquery , please help me
TypeError: $(...).msDropDown is not a function
$("#time_zone").msDropDown();

replace $ by jQuery but same error occure
 $(document).ready(function(arg) {
     $("#time_zone").msDropDown();
     $("#time_zone").hide();
 });

Comment: What are you trying to achieve? Which browser are you using? Why do you think `msDropDown` should exist?
Comment: Did you include the `script src` for it?
Comment: Because DOM elements do not have a `.msDropDown()` method. If you are using a library please say so
Comment: there are a number of different reasons this can occur. Loading jQuery more than once, forgetting to load plugin file or bad path to plugin file, noConflict being used in page (very common in wordpress and other CMS's), incorrect code loading order. You need to isolate these issues and gather as much detail as you can
Comment: yes i m forgetting to include jquery.dd.js file where msDropDown() is declare so this type of error occured..
now I m including, no error occured
Answer: I think you are using an external js file for dropdown right ?
  If So that error is due to not including your js file .
  You should call your external js above just or above your code snippet.
eg:-

then your code comes below
$(document).ready(function(arg) {
     $("#time_zone").msDropDown();
     $("#time_zone").hide();
 });

Hope this helps you !!
thank you
Comment: yes only one possibilities,but he could try atleast this suggestion too


Issue with distance point-to-line

Question: I am having a small issue with the distance calculation of a point-to-line and I cannot find the mistake.
I have the line:
$$x + 2y + 3 = 0$$
And I am trying to compute its distance to point $(x_0, y_0) = (0,0)$. According to the well-known formula:
$$ d = \frac{\left|ax_0+by_0+c\right|}{\sqrt{a^2 + b^2}} = \frac{\left|3\right|}{\sqrt{5}} = 1.3416$$
Now, I try to compute the same distance on a different manner. The line intersects the $y$ axes at $p=(0, -1.5)$. I am trying to solve the following triangle (sorry for the cheap plotting):

The distance computed before should correspond to the length of the red segment (perpendicular to the line that goes through the desired point), which could also be computed as:
$$ d = 1.5 \cdot cos(30^{\circ}) = 1.299$$
Both results for the length of the red segment do not match. What am I doing wrong?
Thank you in advance!
Answer: The angles are wrong - instead of $30^0$ it should be $\arctan(0.5) = 26.56^0$
Comment: Ah, that's it! I knew it was a small mistake somewhere I forgot to check. Thank you!
Answer: Let's go through the process step by step instead of using a calculator/grapher, and (ultimately) verify Dhanvi's claim.
So, to find the distance from the line (call it $\ell$) to $(0,0)$, we will want the line perpendicular to $\ell$ through the origin (call this one $p$).
The equation of $p$ will have negative reciprocal slope to $\ell$ and $y$-intercept $0$. Then we have that
$$y_p (x) = 2 x$$
Meanwhile, $\ell$ has the equation
$$y_\ell(x) = -\frac 1 2 x - \frac 3 2$$
So your triangle has two points already: $(0,0)$ and $(0,-3/2)$. The third is where $\ell$ and $p$ intersect. Set the two equations equal and solve for $x$:
$$2x = - \frac 1 2 x - \frac 3 2 \implies x = - \frac 3 5$$
Substitution can get us that, then, the corresponding $y$ is at $y = -6/5$.
We can then find the distances between these points, and we get that
\begin{align*}
\Big( \text{distance from } (0,0) \text{ to } (0,-1.5) \Big) &= 1.5 \\
\Big( \text{distance from } (-3/5,-6/5) \text{ to } (0,-1.5) \Big) &= \frac{3}{2 \sqrt 5} \\
\Big( \text{distance from } (-3/5,-6/5) \text{ to } (0,0) \Big) &= \frac{3}{\sqrt 5}
\end{align*}
Obviously, one angle is formed by the first and last sides. It has angle $\theta$, and it will be given by
$$\theta = \arccos \left( \frac{3 / \sqrt 5}{1.5} \right) \approx \boxed{26.57^\circ}$$
This is where your problem lies. That top angle of your triangle is not $30^\circ$.
Answer: THe equation of  line:
$y=-\frac 12 x-\frac32$
Equation of red line:
$y=2x$
So the coordinates of intersection is : $(x=-\frac 35, y=\frac 65)$
The distance is:
$d=\sqrt {(-\frac 35)^2+(\frac{6}5)^2}=1.3416$
Comment: @Javi, Yes. corrected.
Comment: Thank you. I think you mixed up the signs a bit of the x for both lines, right?
Answer: The polar form of the straight line is
$$ x\cos \alpha + y \sin \alpha = p =1.3496$$
where $\alpha = \cos^{-1}\dfrac{-1}{\sqrt 5}$ is counter-clockwise rotation of the red normal reckoned from x-axis lying in the third quadrant.

Issue with distance point-to-line