text:
Q: Where do overtones in a 555 generated square wave come from? I have built a 555 oscillator and connected it to a speaker.
Using an oscilloscope I adjusted the 555 to generate a 2.5kHz square wave.
I then held a microphone up to the speaker and fed the input into a spectrum analyser.
What I expected to see was a single peak at 2.5kHz. However, what I actually got was this:

My question is, where have these harmonics come from if the 555 is only generating a 2.5kHz signal?
I know that a square can be constructed from sine waves:

However, the 555 does not generate sine waves or multiple frequencies, it generates a single square pulse. So where have these harmonic frequencies come from?

A:
I know that a square can be constructed from sine waves.
  However, the 555 does not generate sine waves or multiple frequencies, it generates a single square pulse. So where have these harmonic frequencies come from?

Congratulations on your explanation of what you are seeing and your experimentation.
The key issue is that not only CAN a square wave be constructed from sine waves, it fundamentally IS a collection of sine waves.
You can generate a square wave by summing appropriate sine waves, but, however you do it, what you arrive at IS a waveform that can be represented by a collection of sine waves.
In ideal circumstances you would not expect to see on the spectrum analyser quite what you show, but impedance matching and a 555 and .... can easily combine to produce a non ideal result.
A square wave = a summation of \$ f + \frac{3f}{3} + \frac{5f}{5} + \frac{7f}{7} + ...\$ (if my brain has correctly retrieved the relevant long ago stored facts). So you would expect to see every second harmonic, and amplitudes should decrease.

A: our ears are correlators. The FFT is a correlator. The analog spectrum analyzers of Hewlett Packard are correlators: they use narrow-band analog filters.
Square waves and rectangular waves, and many other (non-pure-sin) waveforms will strongly correlate with ( Positive_Integer * Fundamental) sin basis functions.
Square waves are not composed of sinusoids. The 555, and any FlipFlop, do not build the rail-rail outputs using a big bucket of handy sinusoids.
You ask a fine question.
We model, and we measure, using sinusoidal basis functions, harmonically related.
Examine the integral of sin(1,000 * time) multiplied by sin(3,000 * time).
Do this for 1 cycle, for 1.5 cycles, for 1.6 cycles, for 1.9 cycles, for 2 cycles, for 200 cycles.
Harmonics do not exist. Its the behavior of the correlators that confuse us.

A: A square wave can be viewed as a sum of the odd harmonics of a single frequency.
A square wave can be generated by summing a bunch of sine waves.
A square wave can also be generated by simply toggling the power on and off at the primary frequency of the square wave.
In either case, the spectrum will look the same.
You cannot tell how a square wave was generated by looking at the spectrum.
The simple act of turning the power on and off generates the primary frequency, but it also generates the harmonics.

Your spectrum shows even as well as odd harmonics.
The even harmonics are an artifact of distortion coming from your microphone or the microphone amplifier.  Too much gain or the microphone too close to the speaker.  Alternatively, the signal from the 555 caused distortion in the speaker.
In any case, you should only see odd harmonics (2.5kHz, 7.5kHz, 12.5kHz, etc.) for a 2.5kHz square wave.   The even harmonics (5kHz, 10kHz, etc.) are not part of the square wave.
Connect the 555 output to the line in of your PC.  You may need to use a voltage divider to reduce the level.
That should be cleaner, and closer to an undistorted square wave.
Baudline (the spectrum analyser you are using) has an oscilloscope view.  Use it to check if your square wave is distorted.  Check the signal from the speaker and microphone setup as well as the direct connection to the 555.

A: I would suggest that it's due to semantics, and those semantics falsely colour our perspective of a square wave. The following is the internal architecture within a 555 chip:-

You can clearly see that it's a digital circuit (rise/fall times excepted). It does not output a series of sine waves, exactly as you suspect. The output toggles between high and low voltage levels. So you're correct.
But mathematically (and taking from Wikipedia), a theoretical square wave can be represented as an infinite summation of odd sine harmonics, thus:-

You can see the \$sin\$ operator in there. It's just that your spectrum analyser can't tell the difference.  After all, you might be feeding it an analogue summation of a few sine wave oscillators all running at odd harmonic frequencies. It would be indistinguishable from a square wave.

Also don't forget the speaker, microphone and recording equipment, which are inherently analogue and have physical mass i.e. smoothing. Some peaks will therefore come from a unintentional filtering effects of your audio equipment.

A:
What I expected to see was a single peak at 2.5kHz.

I don't know why. You need to reset your expectations.
Think of this this way: If you just had a single peak, then the input would by definition be a sine wave. But you're feeding it a square wave, so how do you account for the difference?

I know that a square can be constructed from sine waves.

Change that to: A square wave is equivalent to an infinite series of sine waves.
That's what the math of Fourier analysis is all about.

the 555 does not generate sine waves or multiple frequencies, it generates a single square pulse.

They are exactly equivalent. So it's actually doing both.

So where have these harmonic frequencies come from?

You can think of them as "coming from" the fast edges on the square waves. You can see in your own graphs that as you consider higher harmonics, the edges of the sum get steeper. In the limit (infinitely many harmonics), the edges become vertical.

A: When you are holding a hammer, the world looks like a nail.
Roughly speaking, a spectrum analyser captures a time record and represents the resulting capture as a unique linear combination of sinusoids.
It does not mean that whatever generated the signal generated separate sinusoids, only that the resulting signal can be represented in this (very useful) way.
As other answers have pointed out, a square wave can be represented by the sum of sinusoids at odd harmonics, hence the harmonics on your analyser.
There are other systems of representation (cf. Walsh functions) that represent signals in terms of square waves, however these representations are not practical from current perspective. However, if one had a mythical Walsh spectrum analyser and you looked at a sinusoid, your question might then be asking where do all the square waves come from.


text:
Q: Custom view click listener cover all the screen instead of just the view I've created a class that extends View in order to draw it myself, in a specific position.
I have overriden the onDraw method:
@Override
public void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawBitmap(pic, x, y, null);
}

When I set a click listener and add the view to a layout, the event fires even when I'm not clicking on the view's area.
I tried setting the layout parameters to wrap content with no help, tried delete "super.onDraw" didn't help too.
If I'm doing the same actions with a built in view (like button or image view), it's not happening.
What's the problem? Am I doing something wrong?
More code:
public class FlowingPicture extends View {

    private float x,y;
    private Bitmap pic;
    private int screenWidth;
    private int screenHeight;

    public FlowingPicture(Context context, Bitmap pic, int x, int y, WindowManager screenSize) {
        super(context);
        screenHeight = screenSize.getDefaultDisplay().getHeight();
        screenWidth = screenSize.getDefaultDisplay().getWidth();
        this.pic = pic;
        this.x = x;
        this.y = y;
    }

    public void move(float x, float y){
        this.x += x;
        if(this.x > screenWidth)
            this.x = -(this.pic.getWidth());
        this.y += y;
        this.postInvalidate();
    }

    public float getX(){
        return x;
    }

    public float getY(){
        return y;
    }

    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawBitmap(pic, x, y, null);
    }
}

The part of the code that creates the view:
for(int i=0; i<arr.size(); i++){
    Bitmap b = arr.get(i).getFlowProfilePic();
    int x, y;
    do{
        y = rand.nextInt(screenHeight - b.getHeight() - 30);
        x = rand.nextInt(screenWidth);
    }
    while (!checkPoint(x, b.getWidth(), y, b.getHeight()));
    takenPoints.add(new Point(x, y));
    FlowingPicture fp = new FlowingPicture(FlowingFeeds.this, b, -(x + b.getWidth()), y, getWindowManager());
    fp.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Toast.makeText(FlowingFeeds.this, "I'm working!", Toast.LENGTH_SHORT).show();
        }
    });
    fp.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    flowingObjectsList.add(fp);
}
parseHandler.sendEmptyMessage(0);

The parseHandler adding the views to the layout:
for(FlowingPicture fp : flowingObjectsList){
    layout.addView(fp);
}
flow = new Thread(FlowingFeeds.this);
flow.start();

And the last part:
layout = new FrameLayout(this);
layout.setBackgroundColor(Color.WHITE);
setContentView(layout);

A: Try calling super.onDraw(canvas) last in your method, but that may or may not get your where you want to go.
Hard to tell what your are doing wrong, but have you tried declaring BitmapField in your layout.  Unless there is more that needs to be shown, it looks like all your are doing a drawing an image to the screen.
Also in your main.xml, you can create what you need inside a RelativeLayout, and include TextFields, BitmapFields, and what ever other fields you need, that way, you won't have to worry about onDraw().
The beauty of using the XML resources is there is a property android:onClick="someMethod".  In the activity, you would then need a method:
public void someMethod( View view ) {
    // do stuff here
}

This way, there is no need to mess around with listeners.

A: Ok, I didn't solved it, but I think I know what the problem was.
Because I'm moving the view all across the screen, it gave the view a space in the size fo the screen.
So I just add a touch listener to the layout that the views are on, that take the x and y of the touch and check if this touch is on a some view.
Not the most elegant solution, but I did my best!
Thanks for everyone who tried to help! :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can we describe all forces as a curvature in space-time? If we have Einstein's field equation
$$R_{\mu\nu} - \frac{1}{2}g_{\mu\nu}R=kT_{\mu\nu}$$
could we generalize it to
$$R_{\mu\nu} - \frac{1}{2}m_{\mu\nu}R=kS_{\mu\nu}$$
where $S_{\mu\nu}$ is the source of the curvature and $m_{\mu\nu}=\eta_{\mu\nu}+f_{\mu\nu}$ where $f_{\mu\nu}$ is the perturbation caused by the force. Could we write one of these equations for each force, solve the equation for $f_{\mu\nu}$, sum up all of the $f_{\mu\nu}$ into one perturbation and add it to $\eta_{\mu\nu}$ to get one metric $g_{\mu\nu}$.
For example, since the electromagnetic field is extremely similar to the gravitational field, we could solve for the acceleration and find Poisson's equation. Using Einstein's "derivation" of general relativity one could find that
$$R_{\mu\nu} - \frac{1}{2}g_{\mu\nu}R=\frac{2q}{m\epsilon_0 c^2}Q_{\mu\nu}$$
Where
$$g_{\mu\nu}=\eta_{\mu\nu}+A_{\mu\nu}$$
$A_{\mu\nu}$ is the electromagnetic pertubation and
$$Q_{00}=\rho_Q$$
$$Q_{ij}=\frac{1}{c}v^i v^j\rho_Q$$
$$Q_{i0}=\frac{\vec{J}}{c}$$
and $\rho_Q$ is the charge density
These are all the components since the tensor is symmetric.
With this you can derive Maxwell's equations. But is this a valid approach, to describing how electromagnetism curves space-time?
There is a related question https://physics.stackexchange.com/qu/148028/ but this is about describing the forces using a Yang-Mills approach i.e. a curvature in the connection. In this question I am excluding gauge curvature and only talking about space time curvature.

A: There are some reasons why this will not work.
The obvious point is that we can write gravity as curvature because gravity is universal, i.e. gravitationaly interactions act in the same way on everything (roughly speaking). In the end, that's a reason why it makes sense to consider gravity as a property of spacetime itself.
For example, all free particles, that is, particles that only feel gravity, move on geodesics determined by the metric, so all particles "pervceive" the curvature. Furthermore, the energy-momentum tensor on the right-hand side of your first equation contains contributions from all fields and/or particles in your theory, charged an uncharged.
On the other hand, electromagnetism is not universal: The path of a particle in an electromagnetic field depends on the charge. Hence, you shouldn't have an energy-momentum tensor of uncharged matter influnce the electromagnetic force on a chraged particle.
Second, gravity is always attractive -- for example,there are no "repulsive" geodesics in Schwarzschild spacetime.
Third, upon quantisation, the electormagnetic (also weak, strong) force become spin-1 fields, while the metric is (presumably) described by a spin-2 field (graviton). Also, you would expect that there can be only one graviton field in a consistent theory.
Finally, note that there is a formulation of electordynamics in a manner very similar to gravity in a certain way via bundles -- here, the correspondence is between, e.g., the electromagnetic field strength and the Riemann tensor, not between photon and graviton field directly.

A: No, this doesn't work.  There are several reasons - first, electric charge is a Lorentz scalar, which means that electric charge density transforms like the time component of a 4-vector, namely $J^\mu = (c\rho,\mathbf J)$.  Contrast this with energy density; since energy is not a Lorentz scalar, energy density transforms like the time-time component of a rank 2 tensor (the stress-energy tensor on the right hand side of Einstein's equations).
Furthermore, electromagnetism is not universal in the same way that gravity is.  The motion of a test mass in the presence of a gravitational field is independent of its mass, while the motion of a test charge in the presence of an electromagnetic field is not at all independent of its charge.

There have been more exotic attempts to unify electromagnetism and general relativity.  The Kaluza-Klein theory postulates the existence of a compact $4^{th}$ spatial dimension; under suitable assumptions (in particular the assumption that $\partial_4g_{\mu\nu}=0$, the so-called cylindrical condition), one can show that this predicts the existence of two additional fields - one 4-component field $B_\mu$  and one scalar field $\Phi$.  If the latter is ignored (i.e. set equal to a constant) and the compact extra dimension is integrated over, then the remaining $B_\mu$ field and the 4-metric $g_{\mu\nu}$ obey the laws of electromagnetism and general relativity, respectively.
This isn't good enough, however.  By coupling this 5-dimensional version of GR to a Dirac field (like an electron field), we obtain a relationship between the electric charge and mass of the electron which is off by something like 30 orders of magnitude.  Kaluza-Klein is a fairly elegant idea but it falls apart under closer inspection.  Other theories of this type have been (and continue to be) investigated, but as yet all have been problematic.


text:
Q: Right alignment error in print() I am trying to right align the numerical values which I get from print, but I am getting an error:
'float' object has no attribute 'rjust'

Here is my code where I am trying to use it at. How should I go about right aligning all the numerical values I get with print:
enterValue = float(input("The input value is: "))

# We know that the circumference of a circle is 2*pi*r.
CircumferenceV = (2*math.pi*enterValue)
print("The Circumference is : %0.2f" %(circleCircumference.rjust(10)))

A: You're applying rjust on a float when it is defined for str objects. An alternative is to right align with the :fill.precision notation on format:
>>> print("{:10.2f}".format(3.142059))
       3.14

Applied on circleCircumference :
print("The Circumference is : {:10.2f}".format(circleCircumference))

Using only % one can do the same thing with:
>>> circleCircumference = 3.29920
>>> "Circle circumfence: %10.2f" % circleCircumference
'Circle circumfence:        3.30'

A: If you'd only like 2 decimal places, you can use the same answer that Jim suggested but modify it slightly.
print("The Circumference is : {:>10.2f}".format(circleCircumference))

This tell the print statement to print circleCircumference to 2 places as a float, while right justifying it in a 10 character column.


text:
Q: Image won't display in app when using bitmap in Android Studio I'm attempting to write my first application and am having issues with using images. I am able to get the image to display in the app but found due to its high resolution the load time was slow. I went to add a bit map and found sample code from developers.android.com but when I implemented it the image was no longer seen. The image view is still there to my knowledge since the text set to be directly below it is in the right place.
I'll state that also I am unsure where to properly implement the bit map code and it may be in the wrong class file.
Activity where picture is shown:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_ion"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.michael.titanfall2apptest.Ion">

<ImageView
    app:srcCompat="@drawable/ion"
    android:id="@+id/ionimageView"
    android:layout_centerHorizontal="true"
    android:layout_width="175dp"
    android:layout_height="175dp"/>

<TextView
    android:text="Ion"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/ionimageView"
    android:layout_centerHorizontal="true"
    android:id="@+id/textView"/>
</RelativeLayout>

Class for Activity:
public class Ion extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ion);
    ImageView ionImageView = (ImageView) findViewById(R.id.ionimageView);
    ionImageView.setImageBitmap(
            decodeSampledBitmapFromResource(getResources(),        R.id.ionimageView, 500, 500));
}

public static int calculateInSampleSize(
        BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        // Calculate the largest inSampleSize value that is a power of 2 and keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) >= reqHeight
                && (halfWidth / inSampleSize) >= reqWidth) {
            inSampleSize *= 2;
        }
    }
    Log.d("test", "Look here");
    return inSampleSize;
}

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
                                                     int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}

Any resource suggestions would also be appreciated. I haven't quite found a video explaining this exactly.

A: It happens because, you pass id of ImageView, which is only a container for image:
ionImageView.setImageBitmap(decodeSampledBitmapFromResource(getResources(), R.id.ionimageView, 500, 500));
You need pass id of drawable image (not ImageView):
ionImageView.setImageBitmap(decodeSampledBitmapFromResource(getResources(), R.drawable.ion, 500, 500));
Remove also:
app:srcCompat="@drawable/ion"

in your layout.


text:
Q: $\{x: 2x^2\cos(1/x) \le 1\} \cup \{0\}$ is complete. Prove or disprove that $$ \{x: 2x^2\cos(1/x) \le 1\} \cup \{0\}\
\text{is complete}.  $$
Define $$f(x)=\begin{cases} 2x^2\cos\left(\frac{1}{x}\right), & x\neq 0\\ 0, &  x=0  \end{cases}$$ Clearly, $f$ is continuous and $T=f^{-1}\big((-\infty,1]\big)$ which is closed and hence $T$ is complete.
Am I right?


text:
Q: knockoutjs, How to detect css animation changes I am currently working to modify a plugin. I need to detech changes of css animation. How can i do this.

Hello!

<input data-bind="click:Animate" type="button" value="Animate" >

Viewmodel
function vm(){
    var self = this
    self.Width = ko.observable('70%')
    self.Width.subscribe(function(data){
        console.log(data)
    })

    self.Animate = function(){
        $( "#block" ).animate({
            width: self.Width(),
        }, 1500 );
    }
}

$('document').ready(function () {
    ko.applyBindings(new vm())
})

subscribe is not called. How can i detect css animation change with observable?
Fiddle

A: There's nothing currently updating the Width observable, it won't automatically track things for you like this.  You could use the progress option of animate to do so:
function vm(){
    var self = this
    self.Width = ko.observable('70%')
    self.Width.subscribe(function(data){
        console.log(data)
    })

    self.Animate = function(){
        $( "#block" ).animate({
            width: self.Width(),
        }, {
            duration: 1500,
            progress: function() {
                self.Width($(this).width());
            }
        });
    }
}

Though this is still a bit odd, as you're then using the Width observable to both set the width to animate to as well as report progress.


text:
Q: Disabling div based on condition in ng-repeat I'm having an ng-repeat that repeats n times..
HTML:

<fieldset ng-disabled="item.activityId==lockResourceId">

Hello

</fieldset>

Controller:
onWebSocketFired();
  function onWebSocketFired(isLock){
        $scope.lockResourceId=isLock;
}

Here each time the function onWebSocketFired() is fired with the lockResourceId and if that is equals to item.activityId then the div will be disabled.
Now this happens for one div inside the ng-repeat on each of the onWebSocketFired() call.But I would like to keep the previously disabled field as it is until and unless any other call has been called.
Can anyone suggest a fix please?

A: Since you want to keep previously disabled fieldsets disabled when new one gets disabled too, you want to store lockResourceId in form of array or object.

  <fieldset ng-disabled="lockResourceId[item.activityId]">

Hello {{ item.activityId }}

    <input type="checkbox">
  </fieldset>

Then in controller you would use it like this:
$scope.lockResourceId = {};

// Lock some id
$scope.lockResourceId[id] = isLock;


text:
Q: Chart.js compress vertical axis on barchart I have a dataset in which the last value is always very high. This causes an issue with my bar chart; almost all the other values are hard to get a feeling for without hovering over them.
Here is a screenshot:

This is what I am trying to achieve;

So my question; is this possible within vanilla Chart.js or do I need a plugin? And if so; is there an existing plugin or do I need to write one myself?
I am also open for alternative solutions to the initial problem.
I've looked all over the internet for something like this but unfortunately without much luck.

A: You can use logarithmic type yAxis
Default: linear
https://www.chartjs.org/docs/latest/axes/cartesian/logarithmic.html

var ctx = document.getElementById('myChart');

var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ["January", "February", "March", "April", "May", "June"],
    datasets: [{
      label: "Series 1",
      backgroundColor: "rgba(255,99,132,0.2)",
      borderColor: "rgba(255,99,132,1)",
      borderWidth: 2,
      hoverBackgroundColor: "rgba(255,99,132,0.4)",
      hoverBorderColor: "rgba(255,99,132,1)",
      data: [65, 59, 43, 81, 56, 950],
    }]
  },
  options: {
    scales: {
      yAxes: [{
        type: 'logarithmic',
        ticks: {
          callback: function(tick, index, ticks) {
            return tick.toLocaleString();
          }
        }
      }]
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
<canvas id="myChart" width="400" height="200"></canvas>

Optimized ticks
50 * (Math.floor(i / 50)), // lower 50
50 * (Math.ceil(i / 50)) // higer 50

var ctx = document.getElementById('myChart');

var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ["January", "February", "March", "April", "May", "June"],
    datasets: [{
      label: "Series 1",
      backgroundColor: "rgba(255,99,132,0.2)",
      borderColor: "rgba(255,99,132,1)",
      borderWidth: 2,
      hoverBackgroundColor: "rgba(255,99,132,0.4)",
      hoverBorderColor: "rgba(255,99,132,1)",
      data: [65, 59, 43, 81, 56, 950],
    }]
  },
  options: {
    scales: {
      yAxes: [{
        type: 'logarithmic',
        ticks: {
          callback: function(tick, index, ticks) {
            return tick.toLocaleString();
          }
        },
        afterBuildTicks: function(pckBarChart) {
          pckBarChart.ticks = pckBarChart.chart.data.datasets[0].data.flatMap(i => [
            50 * (Math.floor(i / 50)), // lower 50
            50 * (Math.ceil(i / 50)) // higer 50
          ])
        }
      }]
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
<canvas id="myChart" width="400" height="200"></canvas>


text:
Q: how much fragments do I require? I currently have 10 activities. One is the menu activities and the rest are the categories activities and I currently have created one fragment called menu fragment. How much more fragments will I need to create?
I want to create from fragments from menu pages to other pages as well. for example I want to display menu page on one side and the categories on the other side once clicked on one of the activities.
I can only find list view and detail examples. Do I need to create fragments for each activity and how much fragments need creating. Do I create a new large layout xml.file Please advise.
actvitymain.XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    tools:context=".MainActivity">

    <include
        android:id="@+id/tool_bar"
        layout="@layout/tool_bar"
        ></include>

    <RelativeLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="170dp"
        android:id="@+id/linearLayout"
        android:weightSum="1"
        android:background="#ffffff"
        android:layout_below="@+id/tool_bar">

        <ImageButton
            android:layout_width="125dp"
            android:layout_height="170dp"
            android:id="@+id/museum_icon"
            android:background="#ffffff"
            android:src="@drawable/museumicon"
            android:scaleType="fitXY" />

        <ImageButton
            android:layout_width="125dp"
            android:layout_height="170dp"
            android:id="@+id/theatre_icon"
            android:background="#00000000"
            android:src="@drawable/theatreicon"
            android:layout_alignParentTop="true"
            android:layout_toRightOf="@+id/museum_icon"
            android:layout_toEndOf="@+id/museum_icon"
            android:scaleType="fitXY" />

        <ImageButton
            android:layout_width="125dp"
            android:layout_height="170dp"
            android:id="@+id/fooddrink_icon"
            android:src="@drawable/foodicon"
            android:background="#ffffff"
            android:layout_gravity="center_vertical"
            android:layout_alignParentTop="true"
            android:layout_toRightOf="@+id/theatre_icon"
            android:layout_toEndOf="@+id/theatre_icon"
            android:scaleType="fitXY" />

    </RelativeLayout>

    <RelativeLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="170dp"
        android:layout_below="@+id/linearLayout"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:id="@+id/linearLayout2"
        android:background="#ffffff">

        <ImageButton
            android:layout_width="125dp"
            android:layout_height="170dp"
            android:id="@+id/leisure_icon"
            android:background="#ffffff"
            android:scaleType="fitXY"
            android:src="@drawable/leisureicon" />

        <ImageButton
            android:layout_width="125dp"
            android:layout_height="170dp"
            android:id="@+id/shopping_icon"
            android:background="#00000000"
            android:scaleType="fitXY"
            android:src="@drawable/shoppingicon"
            android:layout_alignParentTop="true"
            android:layout_toRightOf="@+id/leisure_icon"
            android:layout_toEndOf="@+id/leisure_icon" />

        <ImageButton
            android:layout_width="125dp"
            android:layout_height="170dp"
            android:id="@+id/histroy_icon"
            android:src="@drawable/historicalicon"
            android:scaleType="fitXY"
            android:background="#ffffff"
            android:layout_alignParentTop="true"
            android:layout_toRightOf="@+id/shopping_icon"
            android:layout_toEndOf="@+id/shopping_icon" />
    </RelativeLayout>
    <RelativeLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="170dp"
        android:id="@+id/linearLayout3"
        android:layout_below="@+id/linearLayout2"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:background="#ffffff"
        android:layout_alignParentBottom="true">

        <ImageButton
            android:layout_width="125dp"
            android:layout_height="170dp"
            android:id="@+id/park_icon"
            android:background="#ffffff"
            android:scaleType="fitXY"
            android:src="@drawable/parkicon" />

        <ImageButton
            android:layout_width="125dp"
            android:layout_height="170dp"
            android:id="@+id/familyfun_icon"
            android:background="#00000000"
            android:scaleType="fitXY"
            android:src="@drawable/familyfunicon"
            android:layout_alignParentTop="true"
            android:layout_toRightOf="@+id/park_icon"
            android:layout_toEndOf="@+id/park_icon" />

        <ImageButton
            android:layout_width="125dp"
            android:layout_height="170dp"
            android:id="@+id/travelinfor_icon"
            android:src="@drawable/travelicon"
            android:scaleType="fitXY"
            android:background="#ffffff"
            android:layout_alignParentTop="true"
            android:layout_toRightOf="@+id/familyfun_icon"
            android:layout_toEndOf="@+id/familyfun_icon" />
    </RelativeLayout>

</RelativeLayout>

menufragment.XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    tools:context=".MenuFragment">

    <include
        android:id="@+id/tool_bar"
        layout="@layout/tool_bar"
        ></include>

    <RelativeLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="170dp"
        android:id="@+id/linearLayout"
        android:weightSum="1"
        android:background="#ffffff"
        android:layout_below="@+id/tool_bar">

        <ImageButton
            android:layout_width="125dp"
            android:layout_height="170dp"
            android:id="@+id/museum_icon"
            android:background="#ffffff"
            android:src="@drawable/museumicon"
            android:scaleType="fitXY" />

        <ImageButton
            android:layout_width="125dp"
            android:layout_height="170dp"
            android:id="@+id/theatre_icon"
            android:background="#00000000"
            android:src="@drawable/theatreicon"
            android:layout_alignParentTop="true"
            android:layout_toRightOf="@+id/museum_icon"
            android:layout_toEndOf="@+id/museum_icon"
            android:scaleType="fitXY" />

        <ImageButton
            android:layout_width="125dp"
            android:layout_height="170dp"
            android:id="@+id/fooddrink_icon"
            android:src="@drawable/foodicon"
            android:background="#ffffff"
            android:layout_gravity="center_vertical"
            android:layout_alignParentTop="true"
            android:layout_toRightOf="@+id/theatre_icon"
            android:layout_toEndOf="@+id/theatre_icon"
            android:scaleType="fitXY" />

    </RelativeLayout>

    <RelativeLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="170dp"
        android:layout_below="@+id/linearLayout"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:id="@+id/linearLayout2"
        android:background="#ffffff">

        <ImageButton
            android:layout_width="125dp"
            android:layout_height="170dp"
            android:id="@+id/leisure_icon"
            android:background="#ffffff"
            android:scaleType="fitXY"
            android:src="@drawable/leisureicon" />

        <ImageButton
            android:layout_width="125dp"
            android:layout_height="170dp"
            android:id="@+id/shopping_icon"
            android:background="#00000000"
            android:scaleType="fitXY"
            android:src="@drawable/shoppingicon"
            android:layout_alignParentTop="true"
            android:layout_toRightOf="@+id/leisure_icon"
            android:layout_toEndOf="@+id/leisure_icon" />

        <ImageButton
            android:layout_width="125dp"
            android:layout_height="170dp"
            android:id="@+id/histroy_icon"
            android:src="@drawable/historicalicon"
            android:scaleType="fitXY"
            android:background="#ffffff"
            android:layout_alignParentTop="true"
            android:layout_toRightOf="@+id/shopping_icon"
            android:layout_toEndOf="@+id/shopping_icon" />
    </RelativeLayout>
    <RelativeLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="170dp"
        android:id="@+id/linearLayout3"
        android:layout_below="@+id/linearLayout2"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:background="#ffffff"
        android:layout_alignParentBottom="true">

        <ImageButton
            android:layout_width="125dp"
            android:layout_height="170dp"
            android:id="@+id/park_icon"
            android:background="#ffffff"
            android:scaleType="fitXY"
            android:src="@drawable/parkicon" />

        <ImageButton
            android:layout_width="125dp"
            android:layout_height="170dp"
            android:id="@+id/familyfun_icon"
            android:background="#00000000"
            android:scaleType="fitXY"
            android:src="@drawable/familyfunicon"
            android:layout_alignParentTop="true"
            android:layout_toRightOf="@+id/park_icon"
            android:layout_toEndOf="@+id/park_icon" />

        <ImageButton
            android:layout_width="125dp"
            android:layout_height="170dp"
            android:id="@+id/travelinfor_icon"
            android:src="@drawable/travelicon"
            android:scaleType="fitXY"
            android:background="#ffffff"
            android:layout_alignParentTop="true"
            android:layout_toRightOf="@+id/familyfun_icon"
            android:layout_toEndOf="@+id/familyfun_icon" />
    </RelativeLayout>

</RelativeLayout>

museumactivity. XML
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"

        tools:context=".MainActivity">

        <include
            android:id="@+id/tool_bar"
            layout="@layout/tool_bar"
            ></include>

        <RelativeLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="170dp"
            android:id="@+id/linearLayout"
            android:weightSum="1"
            android:background="#ffffff"
            android:layout_below="@+id/tool_bar">

            <ImageButton
                android:layout_width="125dp"
                android:layout_height="170dp"
                android:id="@+id/museum_icon"
                android:background="#ffffff"
                android:src="@drawable/museumicon"
                android:scaleType="fitXY" />

            <ImageButton
                android:layout_width="125dp"
                android:layout_height="170dp"
                android:id="@+id/theatre_icon"
                android:background="#00000000"
                android:src="@drawable/theatreicon"
                android:layout_alignParentTop="true"
                android:layout_toRightOf="@+id/museum_icon"
                android:layout_toEndOf="@+id/museum_icon"
                android:scaleType="fitXY" />

            <ImageButton
                android:layout_width="125dp"
                android:layout_height="170dp"
                android:id="@+id/fooddrink_icon"
                android:src="@drawable/foodicon"
                android:background="#ffffff"
                android:layout_gravity="center_vertical"
                android:layout_alignParentTop="true"
                android:layout_toRightOf="@+id/theatre_icon"
                android:layout_toEndOf="@+id/theatre_icon"
                android:scaleType="fitXY" />

        </RelativeLayout>

        <RelativeLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="170dp"
            android:layout_below="@+id/linearLayout"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:id="@+id/linearLayout2"
            android:background="#ffffff">

            <ImageButton
                android:layout_width="125dp"
                android:layout_height="170dp"
                android:id="@+id/leisure_icon"
                android:background="#ffffff"
                android:scaleType="fitXY"
                android:src="@drawable/leisureicon" />

            <ImageButton
                android:layout_width="125dp"
                android:layout_height="170dp"
                android:id="@+id/shopping_icon"
                android:background="#00000000"
                android:scaleType="fitXY"
                android:src="@drawable/shoppingicon"
                android:layout_alignParentTop="true"
                android:layout_toRightOf="@+id/leisure_icon"
                android:layout_toEndOf="@+id/leisure_icon" />

            <ImageButton
                android:layout_width="125dp"
                android:layout_height="170dp"
                android:id="@+id/histroy_icon"
                android:src="@drawable/historicalicon"
                android:scaleType="fitXY"
                android:background="#ffffff"
                android:layout_alignParentTop="true"
                android:layout_toRightOf="@+id/shopping_icon"
                android:layout_toEndOf="@+id/shopping_icon" />
        </RelativeLayout>
        <RelativeLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="170dp"
            android:id="@+id/linearLayout3"
            android:layout_below="@+id/linearLayout2"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:background="#ffffff"
            android:layout_alignParentBottom="true">

            <ImageButton
                android:layout_width="125dp"
                android:layout_height="170dp"
                android:id="@+id/park_icon"
                android:background="#ffffff"
                android:scaleType="fitXY"
                android:src="@drawable/parkicon" />

            <ImageButton
                android:layout_width="125dp"
                android:layout_height="170dp"
                android:id="@+id/familyfun_icon"
                android:background="#00000000"
                android:scaleType="fitXY"
                android:src="@drawable/familyfunicon"
                android:layout_alignParentTop="true"
                android:layout_toRightOf="@+id/park_icon"
                android:layout_toEndOf="@+id/park_icon" />

            <ImageButton
                android:layout_width="125dp"
                android:layout_height="170dp"
                android:id="@+id/travelinfor_icon"
                android:src="@drawable/travelicon"
                android:scaleType="fitXY"
                android:background="#ffffff"
                android:layout_alignParentTop="true"
                android:layout_toRightOf="@+id/familyfun_icon"
                android:layout_toEndOf="@+id/familyfun_icon" />
        </RelativeLayout>

    </RelativeLayout>

theatreactivity.XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    tools:context=".MainActivity">

    <include
        android:id="@+id/tool_bar"
        layout="@layout/tool_bar"
        ></include>

    <fragment
        android:id="@+id/Menufragment"
        android:name="com.bradvisor.bradvisor.MenuFragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        tools:layout="@layout/fragment_menu" />

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="260dp"
        android:layout_below="@+id/tool_bar"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:weightSum="1"
        android:id="@+id/linearLayout4">

        <ImageButton
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/logo"
            android:scaleType="fitCenter"
            android:src="@drawable/logofinal"
            android:background="#ffffff" />
    </LinearLayout>

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="260dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/linearLayout4" >

        <ImageButton
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/theatrehead"
            android:scaleType="fitXY"
            android:src="@drawable/theatrehead"
            android:background="#ffffff" />
    </LinearLayout>

</RelativeLayout>

A: As per Google documentation,

A Fragment represents a behavior or a portion of user interface in an Activity. By dividing the layout of an activity into fragments, you become able to modify the activity's appearance at runtime and preserve those changes in a back stack that's managed by the activity.

How to divide and when to divide is, as the developer, up to you. If you think an activity is too heavy to handle, break it down as modular and reusable fragments. If multiple activities share same UI portions, pull it as fragment.
From the code given what I can suggest is, layouts for actvitymain.XML, menufragment.XML and museumactivity. XML has almost the same UI. So you can pull it as a fragment and include it in those 3 XML files.


text:
Q: How to bind classes in vue.js? I wanted to know about class and style binding in Vue.js.
So I made a small app, but I can't get the expected behavior.
A simple app that displays points,
I wanted to change text color depend on the subject point.
But all row's color changed.
Does anyone help me?
    <template>

      <li
        v-for="item in list"
        :key="item.id"
        class="failure"
        :class="{ failure: item.point < 60 }"
      >
        >ID:{{item.id}}/Subject:{{item.subject}}/Point:{{item.point}}
        <span v-if="item.point < 60"
          >you need to take a test! one more time!

</template>

A: I don't need "class='failure'" just below.
    <template>

      <li
        v-for="item in list"
        :key="item.id"
        :class="{ failure: item.point < 60 }"
      >
        >ID:{{item.id}}/Subject:{{item.subject}}/Point:{{item.point}}
        <span v-if="item.point < 60"
          >you need to take a test! one more time!

</template>


text:
Q: Vigenere cipher C++ HZVIG.cpp:
#include "HZVIG.h"

char ROTEncode(char inchar, int rot)
{
    if (IsBigLetter(inchar))
        return ((int)inchar - (int)'A' + rot) % 26 + 'A' - 1;
    else if (IsSmallLetter(inchar))
        return ((int)inchar - (int)'a' + rot) % 26 + 'a' - 1;
    else
        return inchar;
}
char ROTDecode(char inchar, int rot)
{
    if (IsBigLetter(inchar))
        return ((int)inchar - (int)'A' - rot + 26) % 26 + 'A' - 1;
    else if (IsSmallLetter(inchar))
        return ((int)inchar - (int)'a' + rot + 26) % 26 + 'a' - 1;
    else
        return inchar;
}
std::string VIGDecode(std::string instring, std::string key)
{
    std::string result;
    for (int i = 0; i < instring.length(); i++)
        result += ROTDecode(instring[i], key[i % key.length()] - 'A' + 1);
    return result;
}
std::string VIGEncode(std::string instring, std::string key)
{
    std::string result;
    for (int i = 0; i < instring.length(); i++)
        result += ROTEncode(instring[i], key[i % key.length()] - 'A' + 1);
    return result;
}

HZVIG.h:
#include <string>

#define IsBigLetter(a) a >= 'A' && a <= 'Z'
#define IsSmallLetter(a) a >= 'a' && a <= 'z'

std::string VIGDecode(std::string instring, std::string key);
std::string VIGEncode(std::string instring, std::string key);

This code works, but has wrong output:
C:\Users\adm1n\Desktop\C\HZToolkit>HZToolkit --evig --key ALPHA HZU18{CLASSICAL_CIPHER}
HKJ18{NAHSSTRHL_NXWHEC}

It should be: HKJ18{JLADHPCAW_RPPHPG}
I think input is ok, something goes wrong in functions.
C:\Users\adm1n\Desktop\C\HZToolkit>HZToolkit --evig --key ALPHA ALPHA
Outputs: AWEOA

A: Why do you think this is wrong? Note that even if the plaintext is not a letter, you still "advance" the key (at least, that's what your program currently does).
Lining up the plain text and duplicating the key:
     Plain: HZU18{CLASSICAL...
       Key: ALPHAALPHAALPHA...
            ^        ^^   ^
   You get: HKJ18{NAHSSTRHL...
You expect: HKJ18{JLADHPCAW...

Note the places marked with ^: those are where the key equals A, so no encryption takes place (the plaintext letter becomes the ciphertext letter).
Seems fine to me.
(The decryption is broken though. As a hint, note that ROTDecode doesn't treat lowercase and uppercase letters in the same way).


text:
Q: Typescript Function returns before promise.all finishes I have a code as follow
export class MyHandler {
    entry = async (data: string[]): Promise<Map<string, string>> {
        const response: Map<string, string> = new Map();
        Promise.all(
            data.map(async (item) => {
                const apiGetDataRequest = {
                    data: item
                };
                const apiGetDataResponse = await this.client.apiCall(apiGetDataRequest);
                return apiGetDataResponse.data;
            });
        ).then((results) => {
            for (const result of results) {
                const value = myFirstMethod([1, 2, 3]);
                response.set(result, value);
            }
        });

        return response;
    };

    myFirstMethod = (items: number[]): string {
        const result = mySecondMethod(items, 'Test');
        console.log(result);
        return result;
    };

    mySecondFunction = (items: number[]): string {
        let finalResult = "";
        Promise.all(
            items.map(async (item) => {
                const apiCallRequest = {
                    data: item
                };
                const apiCallResponse = await this.client.apiCall(apiCallRequest);
                return apiCallResponse.data;
            });
        ).then((results) => {
            for (const result of results) {
                finalResult = finalResult + ', ' + result;
            }
        });

        return finalResult;
    };
}

The issue that I'm running into is that mySecondFunction returns before all promises are done and as the result, result in myFirstMethod always has a empty string value.
How can I have mySecondFunction to wait for all promises before returning?

A: Your mySecondFunction method is synchronous, you will need to await on Promise.all.
mySecondFunction = async (items: number[]): string {
    let finalResult = "";
    await Promise.all(
        items.map(async (item) => {
            const apiCallRequest = {
                data: item
            };
            const apiCallResponse = await this.client.apiCall(apiCallRequest);
            return apiCallResponse.data;
        });
    ).then((results) => {
        for (const result of results) {
            finalResult = finalResult + ', ' + result;
        }
    });

    return finalResult;
};

A: Though Matthieu's answer is correct, you can also make this same upgrade to mySecondFunction without using async. This is because async is just syntactic sugar for a function that returns a Promise. That would look like this:
// not async
mySecondFunction = (items: number[]): string {
    // Return the chained promise.
    return Promise.all(
        items.map(async (item) => {
            const apiCallRequest = {
                data: item
            };
            const apiCallResponse = await this.client.apiCall(apiCallRequest);
            return apiCallResponse.data;
        })
    ).then((results) => {
        // Style nit: Move the definition of finalResult closer to its use.
        let finalResult = "";
        for (const result of results) {
            finalResult = finalResult + ', ' + result;
        }
        // Return finalResult within the promise chain, so this becomes
        // the result of the Promise the function returns.
        return finalResult;
    });
};

If you're in an environment that supports async/await—and you are, because you're doing so within map—then there's not much reason to prefer this over the other style. That said, much of the value of async is to avoid explicit promise chains with then, and you still have one in your code. You may find your code easier to read if you avoid mixing styles.
mySecondFunction = async (items: number[]): string {
    let finalResult = "";
    let results = await Promise.all(
        items.map(async (item) => {
            const apiCallRequest = {
                data: item
            };
            const apiCallResponse = await this.client.apiCall(apiCallRequest);
            return apiCallResponse.data;
        })
    );

    // Instead of putting this in a `then` method,
    // just use the results you've awaited above.
    for (const result of results) {
        finalResult = finalResult + ', ' + result;
    }

    return finalResult;
};

(With either style, you'll need to change myFirstMethod to await the result of mySecondFunction and also change your entry function to ensure it is awaiting the result of myFirstMethod. Such is the nature of asynchronous code: you have to wait for everything you depend on.)


text:
Q: Kotlin RecyclerView Content Size Height Been trying to find the Android (in Kotlin) equivalent to the following iOS code (in Swift):
myViewController.collectionView.contentSize.height

Attempted the following, but it's yielding a value of 0 when I run it via the debugger:
recyclerView.height

Any suggestions or concepts I'm unaware of are welcomed.

A: override fun getItemCount(): Int = itemList.size


text:
Q: How to include erb file on another? I have template file .erb with HTML code inside.
How to include it in another file erb?
I tried to use section but this is not that I need

A: You are looking for render:
<%= render('file_folder/other_file') %>

Note, that you can omit .html.erb part of the file name.

A: Following code work for me
 <%= render :partial => 'yourFile' %>


text:
Q: Unable to get Ubuntu One working I can't find Ubuntu One in my Ubuntu 14.04 installation, i get this in the app center
There isn't a software package called "ubuntuone-control-panel-qt" in your current software sources.

A: UbuntuOne for online storage doesn't exist anymore!
http://blog.canonical.com/2014/04/02/shutting-down-ubuntu-one-file-services/


text:
Q: Requests: How to access a session that was initiated by the user from the backend? I'm working in a little project that scrapes a website but to scrape the content I need to be logged in as a user. This website only provides Facebook login as authentication method.
My app will prompt the user to login in the mentioned website and after that my program goes in and makes the scraping of the specific content I'm looking to extract.
So in other words the user initiates the session in their browser but I need that session to persist to my backend so I can access the section of the website that is only accesible after you login.
I'm a bit lost here. I don't know what is the best way to achieve this. Any ideas?
Best!


text:
Q: Datagridview showing different results from the query builder I have an issue where the data returned by the query builder is different to the data displayed by the query builder or data preview on Visual Studio 2015.
My SQL Query is :
SELECT
    COUNT(Date_Order_Despatched.[Order Number]) AS Orders,
    CONVERT(varchar(10), DATEADD(DAY, @day * (DATEDIFF(day, @fromdate, Date_Order_Despatched.[Date Order Desptached]) / @day), @fromdate), 20) AS DateDespatched,
    (CASE
         WHEN scheme.waopheadm.courier_serv_name = 'Generic Next Day'
            THEN 'B2B'
         WHEN scheme.waopheadm.courier_serv_name = 'Generic Pallet Service'
            THEN 'B2B'
         ELSE 'B2C'
     END) AS B2BorB2C
FROM
    Date_Order_Despatched
INNER JOIN
    scheme.waopheadm ON Date_Order_Despatched.[Order Number] = scheme.waopheadm.orderkey
WHERE
    (Date_Order_Despatched.[Date Order Desptached] BETWEEN @fromdate AND @todate)
GROUP BY
    (DATEADD(DAY, @day * (DATEDIFF(day, @fromdate, Date_Order_Despatched.[Date Order Desptached]) / @day), @fromdate)),
    (CASE WHEN scheme.waopheadm.courier_serv_name = 'Generic Next Day' THEN 'B2B' WHEN scheme.waopheadm.courier_serv_name = 'Generic Pallet Service' THEN 'B2B' ELSE 'B2C' END)

This is the results I get from this query are:
989 2016-08-01  B2C
575 2016-08-06  B2C
432 2016-08-11  B2C
678 2016-08-16  B2C
870 2016-08-21  B2C
840 2016-08-26  B2C
678 2016-08-31  B2C
3   2016-09-05  B2C

This is the results as per the datagridview with the same parameters :
257 01/08/2016
240 02/08/2016
147 03/08/2016
195 04/08/2016
150 05/08/2016
193 08/08/2016
165 09/08/2016
217 10/08/2016
164 11/08/2016
128 12/08/2016
140 15/08/2016
186 16/08/2016
140 17/08/2016
169 18/08/2016
183 19/08/2016
223 22/08/2016
205 23/08/2016
181 24/08/2016
261 25/08/2016
255 26/08/2016
333 29/08/2016
252 30/08/2016
237 31/08/2016
211 01/09/2016
230 02/09/2016
3   05/09/2016

Any help here is be appreciated.
c# code to bind data :
using (SqlConnection sqlConnection = new SqlConnection(sqlConnectionString))
                    {
                        sqlConnection.Open();
                        cs3liveDataSet.EnforceConstraints = false;
                        order_Despatched_ScreeTableAdapter.FillChartPerXDaysAll(cs3liveDataSet.Order_Despatched_Scree,Convert.ToInt16(otherNumericUpDown.Value), Convert.ToDateTime(fromDateTimePicker.Value), Convert.ToDateTime(toDateTimePicker.Value), B2BOrB2CComboBox.Text);
                        OrderDataGridView.Refresh();
                        OrderDataGridView.Visible = true;
                        OrderDataGridView.Enabled = true;
                        sqlConnection.Close();
                    }

I have redone the code so that it pulls from the sqlcommand :
using (SqlConnection sqlConnection = new SqlConnection(sqlConnectionString))
                    {
                        sqlConnection.Open();
                        SqlCommand cmd = new SqlCommand(@"SELECT COUNT([Order Number]) AS Orders, CONVERT(varchar(10), DATEADD(DAY, (5*(DATEDIFF(day, @FROMDATE, [Date Order Desptached])/5)), @FROMDATE), 103) AS DateDespatched FROM Date_Order_Despatched WHERE ([Date Order Desptached] BETWEEN @FROMDATE AND @TODATE) GROUP BY CONVERT(varchar(10), DATEADD(DAY, (5*(DATEDIFF(day, @FROMDATE, [Date Order Desptached])/5)),@FROMDATE), 103)", sqlConnection);
                        //cmd.Parameters.AddWithValue("@DAY",otherNumericUpDown.Value);//@DAY
                        cmd.Parameters.AddWithValue("@FROMDATE", SqlDbType.DateTime).Value = fromDateTimePicker.Value;//@FROMDATE
                        cmd.Parameters.AddWithValue("@TODATE", SqlDbType.DateTime).Value = toDateTimePicker.Value;//@TODATE
                        SqlDataAdapter SDA = new SqlDataAdapter(cmd);
                        DataTable dt = new DataTable();
                        SDA.Fill(dt);
                        OrderDataGridView.DataSource = dt;
                        OrderDataGridView.Refresh();
                        OrderDataGridView.Enabled = true;
                        sqlConnection.Close();
                    }


text:
Q: NullPointerException while getting excel Cell despite having non NULL Row in Apache POI Java I am using Apache POI to read and write Excel files.Following is the code snippet generating NullpointerException:
   int rowcount = 0;
   while (rowcount < Header.MAX_ROW_COUNT) {
       try {
            gpnameRow = gpNameSheet.getRow(rowcount);
            } catch (Exception e) {
            rowcount++;
            continue;
          }

        int index = 0;
        Cell indexCell = gpnameRow.getCell(0);
        index = (int) indexCell.getNumericCellValue();
        System.out.println(index);
        rowcount++;
       }

Cell indexCell = gpnameRow.getCell(0); this line producing the NullPointerException.
What can be the possible reason of this error?

A: Please post stacktrace, are you sure that gpnameRow.getCell(0) is throwing exception, I think it should be next line i.e. indexCell.getNumericCellValue()
You need to check if the cell is null or not before invoking any method of it.
if( indexCell != null ){
        index = (int) indexCell.getNumericCellValue();
        System.out.println(index);
        rowcount++;
}

While going through the sheet there might be some cells that are blank and those may cause null pointer exception.

A: Please verify your excel once..
here 100% sure that you are not getting your rows. row is null here so you are getting the exception.If some other cause let us know.hope we can fix.


text:
Q: Fibonacci sequence and Pigeonhole principle Consider set $A:= \{F_{n} \mid n, \, 1 \leq n \leq 1000002\}$ where  $F_{n}$ denotes the $n$th Fibonacci number.
Prove that exist at least two numbers $F_a$ and $F_b$, such that $F_a,F_b \in A$ and $F_a$,  $F_b$ are divisible by $1000$.
I trying to use the Dirichlet's box principle, but I have problem, how to define pigeonhole.

A: Every sixth element is divisible by $8$ and every $125^{th}$ is divisible by $125$, just by computation.  Then every $750^{th}$ is divisible by $1000$
Note that we just have to find the first element divisible by any prime power.  The next number after that may not be $1$, but the recurrence is linear.  In this example, $F_7\equiv 5 \pmod 8$, but the next block is just the first block multiplied by $5$ and $0 \cdot 5=0$


text:
Q: Can't urlencode deviceToken (Swift) I would like to send the deviceToken using NSURL session to my server, but it crashes every time. I've tried to find a way to convert the DataObject (the deviceToken) into NSString but did not succeed so far.
Error: "fatal error: unexpectedly found nil while unwrapping an Optional value"
Any help s greatly appreciated. Here's my code
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken   deviceToken: NSData!) {
    let urlPath = "http://example.com/deviceToken=\(deviceToken)"
    let url = NSURL(string: urlPath)
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
        if(error != nil) {
            // If there is an error in the web request, print it to the console
            println(error.localizedDescription)
        }
        var err: NSError?

    })

    task.resume()
}

A: Can you pinpoint what variable is being unwrapped and returning nil? I can't see anything that would cause that, except the URL, so your error might be an invalid URL. Remember NSURL validates the string given according to a strict syntax (RFC 2396). Try this URL (without the deviceToken) and see if that makes any difference:
let urlPath = "http://example.com/?deviceToken"

On a sidenote, the device token needs to be URL encoded, please see this answer. Your whole method would then be as follows:
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
    let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
    var tokenString = ""

    for var i = 0; i < deviceToken.length; i++ {
        tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
    }
    let urlPath = "http://example.com/?deviceToken=\(tokenString)"
    let url = NSURL(string: urlPath)
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
        if(error != nil) {
            // If there is an error in the web request, print it to the console
            println(error.localizedDescription)
        }
        var err: NSError?

    })

    task.resume()

}


text:
Q: Sort numeric field used in hierarchy I have a hierarchy that is Year-Month-Day, and it sorts the day as if it were a text field (i.e, 1,10,11,12,etc). When the same fields are used without the hierarchy the sort is correct. The model is SSAS 2012 tabular, and the field is properly set up as a Whole Number data type/format.
I can't think of, or find anything else to change this behaviour - there's no properties on the hierarchy for setting a sort field, and nothing else that I can find that changes this.
Does anyone know how to get a numeric field to sort properly in a hierarchy?

A: This appears to have been resolved by shutting down both Visual Studio and Excel and re-starting them.


text:
Q: Morphisms from an open set of an affine variety to a projective space Let $X$ be an affine variety, with coordinate ring $A(X)$, and take an open set $U\subset X$. Is it true that any morphism of varieties $U\to \mathbb P^{n-1}$ is of the form $x\mapsto (g_1(x):\dots:g_n(x))$, for $g_1,\dots,g_n\in A(X)$ such that $X-Z(g_1,\dots,g_n)\supset U$?
The converse implication seems easily true; instead the direction of the part in italics is surely true if $X=\mathbb A^1$, or $X=\mathbb A^1-\{0\}$, and $n=2$; but if $X=\mathbb A^2$ or $X=\mathbb A^2-\{0\}$, I already don't understand how to extend the proof. Am I trying to prove something true at least? Thank you

A: I'll explain Sasha's comments in a bit more detail, since they comes from a more sophisticated understanding of morphisms into projective space. Overall, what you've written is generally incorrect since it usually gives a strict subset of the set of maps from a given variety to $\mathbb{P}^n$.
Rather than regular functions, we recognize the $g_i$ as sections of a certian line bundle on $U$(ie. an algebraic vector bundle of rank one). With the tensor product, the isomorphism classes of line bundles form a group called the Picard group. When the Picard group is trivial, every line bundle is isomorphic to the trivial bundle, so we see that sections correspond to regular functions. This should explain Sasha's comments.
Conceptually let's understand why line bundles come up here. For simplicity assume we're working over $\mathbb{C}$, and let $V$ be any variety. Note that the data of a map $f: V \to \mathbb{CP}^n$ can be contained in the set $L = \{(v, x) \in V \times \mathbb{C}^{n + 1}\;|\;x \in \langle f(v) \rangle \}$. Now, we have a natural projection $\pi: L \to V$ which is in fact regular, and turns $L$ into an algebraic line bundle. Although it's natural, this line bundle isn't as useful as its dual, which lets us recover $f$ from its sections.
In this setup, instead of taking $L_v \subset \mathbb{C}^{n + 1}$ we take its dual to be the quotient $\mathbb{C}^{n + 1} \to L_v^*$ to get a global map of vector bundles $V \times \mathbb{C}^{n + 1} \to L^*$. Now $V \times \mathbb{C}^{n + 1}$ has $n + 1$ global sections $e_0, \dots, e_n$ corresponding to the coordinates, and we denote $s_0, \dots, s_n$ the induced sections of $L^*$. Then, it follows from the preceding construction that $f(v) = [s_0(v), \dots, s_n(v)]$, so we do in fact recover a similar formula to the one you mentioned. Conversely, given an algebraic line bundle and $n+1$ sections which don't simultaneously vanish, we can define a morphism $f: V \to \mathbb{P}^n$ as above.
With some work you can actually show that this defines a universal property for projective space. It also lets us give a cases when what you stated is true.
Theorem: Let $X$ be a normal affine variety. If $A(X)$ is a UFD, then every line bundle on $X$ is trivial.
From this, we see that any map from $\mathbb{A}^n \to \mathbb{P}^m$ will be given by regular functions which don't all simultaneously vanish. I based the discussion of line bundles and projective morphisms on chapter 5 of the paper 'The Structure of Algebraic Threefolds' by Kollár. This theorem can be found in more generality in Hartshorne II.6.


text:
Q: RewriteRule not working with PHP-FPM Ubuntu 18 I have just installed successfully PHP-FPM in Ubuntu 18.04.5 and PHP Version 7.4.11.
However there is one problem with the Rewrite in a .htacess file. This works fine on another server and is known to work everywhere else.
# Rules to set ApplicationContext based on hostname

RewriteCond %{HTTP_HOST} ^www\.example\.de$
RewriteRule .? - [E=TYPO3_CONTEXT:Development]

It never detects the variable TYPO3_CONTEXT set to Development on the url www.example.de .
All the installation has been done following https://www.digitalocean.com/ .
What is wrong here?


text:
Q: How can python packages be installed for ipython located in a special location on a Mac? I have Mac OS X 10.7. I have a "default" ipython, but also a different ipython installed at a different location /sw/bin/ipython. When I install packages with pip install, though, I can't access them with the ipython at /sw/bin/ipython. How would I install packages for this other ipython?

A: Use the pip/easy_install binary located in /sw/bin to install packages. If you want this to be the default when the command is called, just put /sw/bin before /usr/bin in your .profile.


text:
Q: Is it a bad idea not to store data in a persistent store? e.g. database; file etc My question is similar to this one: Storing data in code
Please see the code below:
public class EnglishCurrency
    {
        public override System.Collections.Generic.IEnumerable<decimal> Values()
        {
        yield return 0.01M;
        yield return 0.02M;
        yield return 0.05M;
        yield return 0.1M;
        yield return 0.2M;
        yield return 0.5M;
        yield return 1M;
        yield return 2M;
        yield return 5M;
        yield return 10M;
        yield return 20M;
            yield return 50M;
        }
    }

It does not seem right from a maintainability point of view to store the currency values in the source code.  However, currencies don't change often (the £2 coin was introduced in 1998).  Like the other question; I have a few options:
1) The above
2) Store values as XML.  Is a WPF app best for this?
3) Store values as JSON
4) Another approach?
In the example in my link; the asker talks about storing countries in source code.  Countries are likely to change a lot more than currencies so I can understand why the answerer talks about XML files.  Does this also apply to me with values that are less likely to change?

A: These currency denominations are constants - i.e. those stable, never-changing values which nobody expects to change except in rare circumstances, similar to Pi, the gravitational constant, etc.
Of course, some constants do inevitably sometimes change in the real world, but the commercial cost of re-compiling code for these rare occurrences (and distributing a software update) is usually low/insignificant.
It is completely normal for such constants to exist in a domain, therefore also normal to hard-code constants into the program rather than keeping them in an external persistent store / retrieving from a service / etc.
Related to your example - two potential issues with the yield keyword:

*

*Potential violation of the Princple of Least Astonishment

*It doesn't support Random Access - which may or may not be an issue, but I see no reason not to allow this

As a possible alternative to yield, you might consider an array - e.g.
public class EnglishCurrency
{
    private static readonly decimal[] _values =
    {
         0.01M,  0.02M,  0.05M,
         0.10M,  0.20M,  0.50M,
         1.00M,  2.00M,  5.00M,
        10.00M, 20.00M, 50.00M,
    };

    public override IEnumerable<decimal> Values() => _values;
}

Edit - The above code uses C# 6.0 Syntax for the Values() method.  If that doesn't work due to running an older version of Visual Studio or older version of the C# compiler, then use this instead:
    public override IEnumerable<decimal> Values()
    {
        return _values;
    }

A: Everything has a cost, and sometimes the benefits aren't worth what you have to pay for them. All abstractions have a cost, either in runtime speed, development speed, or brain-cell demands. Part of the craft of software development is having a key eye where the benefits are worth it.
Hardcoding things is the easiest upfront means of putting data into a program. It's simple to do, but its cost is the difficulty of changing the code. It's also basically the fastest way you can get at the data, and it is virtually guaranteed to work every time without exception. Only people programming space probes and pacemakers have to worry about it not working.
On the other hand, say you put the data into a file or database. Now you have a relative ton of the additional work of figuring out how to get at that data. If you are using a config file, you now have to handle the file being missing, and dealing with that. What if users want defaults if they don't have a configuration? Where do you store the defaults? Where do you store the data that says where to find the file? The rabbit hole can do deep indeed. All those questions have to be answered. Hardcoding has none of those.
The more abstractions you pile on the more places bugs can lurk, the trickier it is to test, and the harder you have to think to understand what is taking place in your program.
Sure, DB libraries, OEMS, config file libraries can make some of that work easier, but they will all without a doubt be more work, more code, and more places to go wrong than a hardcoded array.
So you have to evaluate what's appropriate. I can't give you an answer you can mechanically test because so far its a judgment call only us humans can do. You need to evaluate how likely the data is to change, how expensive dealing with that change is going to cost, against the cost of dealing with the abstractions. Like many programs, you'll find a mixture of data hardcoded, in flat files, and in a database, for any reasonably defined program.
Your example code using a bunch of yield statements is one of the most extreme examples of "when all you have is a hammer, everything looks like a nail" that i've seen in a long time. When the answers come in, I think you should read them and think hard about whether a given abstraction you are using is appropriate for the task at hand, as your usage and defending that design means you still need to develop that sense.

A: Having a separate file makes it easier to update (especially if it's just text.) and distribute for updates, but you don't seem to think these values are going to change. Putting it in source code requires a recompile and possible distribution. Again, you don't think it is going to change, so none of this matters until it does.
You've created a scenario where it probably doesn't matter. As another developer who may have to support this app later on (Sort of playing Devil's Advocate here.), I wouldn't expect to have this in the source code. If a database existed, I'd be looking for some sort of currency table/node. Knowing where values come from is a big part of troubleshooting and maintaining code. If that's the only reason, it's good enough for me.
If you've already gone to the trouble of having a database for your app, why not use it?


text:
Q: Requiring named arguments in Boost Python I'm trying to make Boost Python require that arguments are named by the caller.
As Python 3 implements PEP 3102, I can easily do that in pure Python:
def foo(*, name=None, age=None):
    print("%s is %d years" % (name, age))

The above means that:
foo(name="Joe", age=33) # works
foo(age=33, name="Joe") # works
foo("Joe", 33) # raises TypeError

However, this isn't straight-forward in Boost Python. The following isn't even close:
#include <stdio.h>
#include <string>
#include <boost/python.hpp>
#include <boost/python/def.hpp>

void foo(const std::string& name, int age)
{
  printf("%s is %d years\n", name.c_str(), age);
}

BOOST_PYTHON_MODULE(hello)
{
  using namespace boost::python;
  def("foo", foo, (arg("name"), arg("age")));
}

While this works with named arguments, they are not required, so I can still do foo("Joe", 33).
I've tried:

*

*Using raw_function, but that requires me to have a C++ signature of (boost::python::tuple, boost::python::dict).

*Exposing the function with (arg("*"), arg("name")="...", arg("age")=-1), but that doesn't compile.

Is it possible at all to expose foo through Boost Python as described in the top Python example?


text:
Q: Python webtest multipart form set request payload I'd like to get webtest to run a multipart form post using Mock. The issue I have is the request payload is missing.
Here's my request using webtest:
res = app.post(
        my_url,
        upload_files=files
    )

Pyramid's DummyRequest
boundary = "my random string"
content_type = "multipart/form-data; boundary=" + boundary
headers = {"Content-Type":content_type}
from base64 import standard_b64encode
body = standard_b64encode(boundary)
body += standard_b64encode("Content-Disposition: form-data; name=\"file\"; filename=\"" + filename + "\"")
body += standard_b64encode("Content-Type: */*")
body += actual_file
from pyramid.testing import DummyRequest
request = testing.DummyRequest(path=my_path, headers=headers, body=body, post="lmnop")
request.context = testing.DummyResource()
from somewhere import MyClass
imitate = MyClass(request)
response = imitate.formMethod()
self.assertEqual('200 Success', response.status)

Has anyone had any luck to set request payload for a dummy multipart form request?
I couldn't find how to get webtest.forms.Upload to play nice, since I can create my object there. Any suggestions would be appreciated, thanks.


text:
Q: cmd prompt turned from window mode to full screen mode I was working on cmd and certainly I made changes in properties from window mode to full screen.
Now every when I open a new window or existing one using win+r [cmd] I am only getting a full screen cmd prompt.
Please provide me the solution to restore it in previous mode [window mode] cmd.

A: Change the Height and Width of the CMD window size. Open the CMD > Properties > Layout and change the size here.

Hope this helps.

A: otherwise

*

*Go to C:->Windows->system32->cmd

*right click cmd select send to->create desktop shortcut

*Go to the properties of shortcut cmd set run field as Normal windows in shortcut tab.

A: In CMD run notepad to get you out of fullscreen and then right click the top left of the minimized CMD window to reach the option window as shown in the screenshot from a previous answer (vernbutech's).

A: I ran into this  problem in windows XP  where the dos window covers the whole screen for all future execution of cmd.  Nowhere to find the tab to click properties.  None of the above works.  Properties on the shortcut only works for that cmd in windows mode.  If you ever run (cmd) in the run command is different from running from a shorcut in windows.  I changed the properties in the shortcut but still ran full screen from the run command.
The solution is to click tab key  to go to another program running so that the full
screen dos will be minimized at the taskbar.  right click properties on the minimized dos from the taskbar and set default and you're go back to the default window size.

A: press ALT+ Enter
Got it from the following link:
https://www.wikihow.com/Fix-Full-Screen-Command-Prompt


text:
Q: How to compare two time stamp in format "Month Date hh:mm:ss" to check +ve or -ve value I checked the stackoverflow site for my answer, i did not get, so i am posting it here.
My problem is:

How to compare two time stamp in format "Month Date hh:mm:ss"?

I am writing program in C and C++ and the time is in displayable string format.
Example :
time1 = "Mar 21 11:51:20"
time2 = "Mar 21 10:20:05"

I want to compare time1 and tme2 and find out whether time2 is after time1 or not and I need output as true or false, like below:
 if time2 > time1 then
       i need output as 1
 or
       0 or -1 anything

I used difftime(time2,time1) , but it returns the delta time diff between time1 and time2.
I want to check greater or not.
For any help, thanks in advance

A: FIRST-  use difftime to compare:
you can simply use difftime() function to compare time and return 1 or  -1 as follows:
int comparetime(time_t time1,time_t time2){
 return difftime(time1,time2) > 0.0 ? 1 : -1;
}

SECOND-  Convert string into time:
If you have difficulty to convert string into time_t struct, you can use two functions in sequence:

*

*char *strptime(const char *buf, const char *format, struct tm *tm); function. to convert string into struct tm
Example: to convert date-time string "Mar 21 11:51:20 AM" into struct tm you need three formate strings:

%b : Month name, can be either the full name or an abbreviation
%d : Day of the month [1–31].
%r : Time in AM/PM format of the locale. If not available in the locale time format, defaults to the   POSIX time AM/PM format: %I:%M:%S %p.

*time_t mktime (struct tm * timeptr); function to convert struct tm* to time_t
Below Is my example program:
#include <stdio.h>
#include <time.h>
int main(void){
    time_t t1, t2;
    struct tm *timeptr,tm1, tm2;
    char* time1 = "Mar 21 11:51:20 AM";
    char* time2 = "Mar 21 10:20:05 AM";

    //(1) convert `String to tm`:
    if(strptime(time1, "%b %d %r",&tm1) == NULL)
            printf("\nstrptime failed\n");
    if(strptime(time2, "%b %d %r",&tm2) == NULL)
            printf("\nstrptime failed\n");

    //(2)   convert `tm to time_t`:
    t1 = mktime(&tm1);
    t2 = mktime(&tm2);

     printf("\n t1 > t2 : %d", comparetime(t1, t2));
     printf("\n t2 > t1 : %d", comparetime(t2, t1));
     printf("\n");
     return 1;
}

And it works as you desire:
 $ ./a.out
 t1 > t2 : 1
 t2 > t1 : -1

To calculate difference between two dates read: How do you find the difference between two dates in hours, in C?

A: Look at strptime()
It converts an ASCII string formatted date/time into a struct tm

A: Here is a very easy way solution to solve your problem.
If in your case the comparing depends on the time. If so, you can turn your time variables into string so you can compare them as a string. ONLY if the base of the comparison is the hour and minute and second elements and/or the day. It will look like this:
string time1 = "Mar 21 11:51:20";
string time2 = "Mar 21 10:20:05";

cout<<time1<< endl;
cout<<time2<< endl;
cout<<endl;

if(time1>time2)cout<<time1<< endl;
else cout << time2 << endl;


text:
Q: Autocomplete onclick in jquery Actually, I have done jquery autocomplete on focus,when I click my textbox it shows focus of all data,so I want if i'm clicking any one data means it redirects to page how will do that.
Something like this: www.practo.com
This is my script:
<script>
$(function() {
$( "#skills" ).autocomplete({
source: 'search.php',
minLength: 0,
scroll: true
 }).focus(function() {
            $(this).autocomplete("search", "");
        });
});
</script>

A: You can use jQuery UI autocomplete select(event, ui) to enable redirection after user selects an item. See demo below:

var sample_skills = [
      "jquery",
      "java"
    ];

$(function() {
 $( "#skills" ).autocomplete({
  source: sample_skills,
  minLength: 0,
  scroll: true,
  select: function(event, ui) {
   console.log(ui.item.value);
   if(ui.item.value == "jquery"){
       location.href="https://api.jquery.com/";
   } else if (ui.item.value == "java"){
       location.href="https://www.w3schools.in/java-tutorial/intro/";
   }
  }
 }).focus(function() {
  $(this).autocomplete("search", "");
 });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script
  src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"
  integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU="
  crossorigin="anonymous"></script>

  <input type="text" id="skills">


text:
Q: calling nodejs module1.js from module2.js then parse some variables Me again. :-D
My next weird question is:
I have 2 nodejs modules:
//module1.js

const prompt = require('prompt');
var Excel = require('exceljs');

var wbCO = new Excel.Workbook();
var iCO = 1;
wbCO.xlsx.readFile('costumers.xlsx').then(function (){
  shCO = wbCO.getWorksheet("Sheet");
  while (iCO <= shCO.rowCount){
    console.log(shCO.getRow(iCO).getCell(1).value +" - "+ shCO.getRow(iCO).getCell(2).value);
    iCO++;
  }

});

prompt.start();

prompt.get([{name:'costumer', required: true, conform: function (value) {
  return true;
}
}], function (key_err, key_result) {
    if (key_err) { return onErr(key_err); }

    var Ccostumer = shCO.getRow(key_result.costumer).getCell(2).value;
    var user = shCO.getRow(key_result.costumer).getCell(3).value;
    var pass = shCO.getRow(key_result.costumer).getCell(4).value;

    function onErr(key_err) {
      console.log(key_err);
      return 1;
    }

});

       //module2.js

wb.xlsx.readFile('./'+Ccostumer+'/File.xlsx').then(function(){

sh = wb.getWorksheet("Sheet1");

    start_page(sh);
});

async function start_page(sh){
  var i = 2;
  var result_id = 1;

    const browser = await puppeteer.launch({headless: true});

    while(i <= sh.rowCount){
    var result_cell = sh.getRow(i).getCell(3).text;
        await open_page(browser, result_cell, result_id);
        i++;
        result_id++;
  }
  browser.close();

}

        async function open_page(browser, result_cell, result_id) {

            const page = await browser.newPage();
            page.setDefaultNavigationTimeout(100000);

            await page.goto('https://www.mywebsite.com', {
                waitUntil: 'networkidle2'
            });
                //  authentication
                await page.waitFor('input[name="ctl00$ContentPlaceHolder1$Signin1$txtEmail"]');
                await page.$eval('input[name="ctl00$ContentPlaceHolder1$Signin1$txtEmail"]', elu => elu.value = user);
                await page.waitFor('input[name="ctl00$ContentPlaceHolder1$Signin1$txtPassword"]');
                await page.$eval('input[name="ctl00$ContentPlaceHolder1$Signin1$txtPassword"]', elp => elp.value = pass);
                await page.click('input[type="submit"]');
                await page.waitForNavigation();

                //search
                await page.waitFor('input[name="email"]');
                    await page.type('input[name="email"]', result_cell);
                await page.click('input[type="submit"]');

I'm trying to call module1.js from module2.js by const md1 = require('./module1.js');
But I'm not getting the variables and both are running at same time.
So that's my questions:
1 - How to run module2.js just after I make my choice at module1.js then press ENTER.
2 - How to parse those variables from module1.js to module2.js (Ccostumer, user, pass).

A: In nodejs, every file has its own scope and the variables and functions declared in each file belong to them.
In order for you to be able to access a function or a variable from another .js file, you'll need to explicitly export them
file1.js
console.log('loading file 1') // runs when the file is loaded

function fileOneFunc () {
  // next line runs only when the function is called
  console.log('this is the fileOneFunc running')
}

module.exports = fileOneFunc

file2.js
// the following line will have access to the exported function from file1
const f1 = require('./file1')

console.log(typeof f1)

f1()

So, if you want the code from your module1.js to run only when you want from a call from within module2.js you have to wrap the code in module1.js in a function and then export it as shown above.
Then in your module2.js you do what you said you want to
const md1 = require('./module1.js')

Then you call the md1 function whenever you see fit.

A: If you want something in return from a module you simply need to return something. If you require another Node JS Script, it does not automatically return anything, it mainly just "runs" the script.
Use module.exports
Here is a basic example of 2 modules, one is called by the other and returns a value. In this example module1 is exporting a function, the function then is required and called in module2.
// module1.js
module.exports = () => {

   /* doing stuff here */

   return "someValue";

});

// module2.js

const value = require('./module1')();
console.log(value);

>> "someValue"

You have to reorder your logic a tiny bit and probably wrap somethings around functions. You want module2 to run after you made your choice in module1. Means, you want to call module2 from module1. Also means you need to require module2 in module1 and after you made your choice you run module2 with the output. In theory this would look like this :
Your example
Although I don't believe your code samples are complete, I'll try my best to give you a hint. But I won't do the work for you
// module1.js

const prompt = require('prompt');
const Excel  = require('exceljs');
const module2 = require('./module2');

const workbook = new Excel.Workbook();
let counter = 1;

workbook.xlsx.readFile('costumers.xlsx').then( function () {

  // Get Worksheet from Workbook
  const sheet = workbook.getWorksheet("Sheet");

  // Print Values of Worksheet
  while (counter <= sheet.rowCount) {
    const value1 = sheet.getRow(counter).getCell(1).value;
    const value2 = sheet.getRow(counter).getCell(2).value;
    console.log(`${value1} - ${value2}`);
    counter++;
  }

  // Open prompt
  prompt.start();

  // Get result from prompt
  prompt.get([
    {
      name:'costumer',
      required: true
    }
  ], function (key_err, key_result) {

    if (key_err) { return console.log(key_err); }

    const costumer = sheet.getRow(key_result.costumer).getCell(2).value;
    const user = sheet.getRow(key_result.costumer).getCell(3).value;
    const  pass = sheet.getRow(key_result.costumer).getCell(4).value;

    return module2(costumer, user, pass);

  });

});

// module2.js

module.exports = function (costumer, user, pass) {

  // Do something with costumer, user, pass
  // the value you get in return from the prompt in module1.js

}

Make sure your module1.js and module2.js are in the same directory, otherwise require('./module2') wouldn't work


text:
Q: What structure is used for storing CONTEXT, CTXCAT and CTXRULE Oracle text indexes? AFAIK there are three major structure types used for storing Oracle index data: B-tree, R-tree and Bitmap. All indexes use one of these structures. However, not sure about CONTEXT, CTXCAT and CTXRULE Oracle text indexes...

A: The documentation covers this thoroughly.
See this link for more detail.


text:
Q: convention for marking LaTeX in programming comments? Is there a convention for marking the beginning of LaTeX-based material placed inside the comments of (say) a C++ or Python program? Or does one simply jump into LaTeX syntax?

A: In doxygen the convention is to explain TeX environments with \f.
As doxygen documentation goes in comments, you might call this convention for comments, though it is more convention for in-code documentation.


text:
Q: Combining itertools and multiprocessing? I have a 256x256x256 Numpy array, in which each element is a matrix. I need to do some calculations on each of these matrices, and I want to use the multiprocessing module to speed things up.
The results of these calculations must be stored in a 256x256x256 array like the original one, so that the result of the matrix at element [i,j,k] in the original array must be put in the [i,j,k] element of the new array.
To do this, I want to make a list which could be written in a pseudo-ish way as [array[i,j,k], (i, j, k)] and pass it to a function to be "multiprocessed".
Assuming that matrices is a list of all the matrices extracted from the original array and myfunc is the function doing the calculations, the code would look somewhat like this:
import multiprocessing
import numpy as np
from itertools import izip

def myfunc(finput):
    # Do some calculations...
    ...

    # ... and return the result and the index:
    return (result, finput[1])

# Make indices:
inds = np.rollaxis(np.indices((256, 256, 256)), 0, 4).reshape(-1, 3)

# Make function input from the matrices and the indices:
finput = izip(matrices, inds)

pool = multiprocessing.Pool()
async_results = np.asarray(pool.map_async(myfunc, finput).get(999999))

However, it seems like map_async is actually creating this huge finput-list first: My CPU's aren't doing much, but the memory and swap get completely consumed in a matter of seconds, which is obviously not what I want.
Is there a way to pass this huge list to a multiprocessing function without the need to explicitly create it first?
Or do you know another way of solving this problem?
Thanks a bunch! :-)

A: I ran into this problem as well. instead of this:
res = p.map(func, combinations(arr, select_n))

do
res = p.imap(func, combinations(arr, select_n))

imap doesn't consume it!

A: All multiprocessing.Pool.map* methods consume iterators fully(demo code) as soon as the function is called. To feed the map function chunks of the iterator one chunk at a time, use grouper_nofill:
def grouper_nofill(n, iterable):
    '''list(grouper_nofill(3, 'ABCDEFG')) --> [['A', 'B', 'C'], ['D', 'E', 'F'], ['G']]
    '''
    it=iter(iterable)
    def take():
        while 1: yield list(itertools.islice(it,n))
    return iter(take().next,[])

chunksize=256
async_results=[]
for finput in grouper_nofill(chunksize,itertools.izip(matrices, inds)):
    async_results.extend(pool.map_async(myfunc, finput).get())
async_results=np.array(async_results)

PS. pool.map_async's chunksize parameter does something different: It breaks the iterable into chunks, then gives each chunk to a worker process which calls map(func,chunk). This can give the worker process more data to chew on if func(item) finishes too quickly, but it does not help in your situation since the iterator still gets consumed fully immediately after the map_async call is issued.

A: Pool.map_async() needs to know the length of the iterable to dispatch the work to multiple workers.  Since izip has no __len__, it converts the iterable into a list first, causing the huge memory usage you are experiencing.
You could try to sidestep this by creating your own izip-style iterator with __len__.


text:
Q: Prolog defining an ":" operator I have several predicates that have the form of flight/3
flight( new_york, boston,
     [ 9:00 /   9:40 / zz765 / everyday,
      16:10 / 16:55 / emi666 / monday ] ).

So I need to define the ":" operator.
Which is the following
:- op( 50, xfx, :).

Now, the results are extremelly strange.
1) If I compile just 1 time I get this:
X = [9:((0/9):(40/zz765/everyday)),
     16:((10/16):(55/emi666/monday))]

2) If I compile it more than 2 times:
 X = [9:0/9:40/zz765/everyday,16:10/16:55/emi666/monday]

Which this is crazy!!!!
I though it should have been
:- op(400, xfx, :).

So it has the same preceden of /
But if I compile it twice I get syntax errors on my flight/3 predicates.
At the end, I need associativity like this: (becuase I will be doing operation with those time).
[ (9:00) /   (9:40) / zz765 / everyday, ]

How do I do this.
Thanks in advance.

A: The common priority and specifier for infix : as defined in ISO/IEC 13211-2:2000 is:
:- op(600, xfy, :).

Unless you want to break a lot of programs, stick to that definition.
The problem you got was the following.

*

*You compiled flight/2 with standard operators.

*You changed priority and specifier to unusual values.

*Now, the toplevel printed terms that otherwise do not need any extra parentheses with your non-standard operator. Yes, this looks crazy, but what do you expect if you change basic syntax in a running program!
So, always stick to op(600, xfy, :).


text:
Q: combining word-wrap: break-word; and white-space: pre; I display a piece of text taken from a text file in an HTML page, I want the new-lines in that text file to be taken into account so I am using "white-space: pre;". on the other hand, I want to prevent the text from overflowing outside its containing div, so I added "word-wrap: break-word;"
unfortunately, the two properties don't seem to work together (the white-space overrides the word-wrap). how can I make it so both properties work together?

A: According to the MDN doc page, this is the desired behavior for the white-space property:

pre
Sequences of whitespace are preserved. Lines are only broken at newline characters in the source and at
 elements.
pre-wrap
Sequences of whitespace are preserved. Lines are broken at newline characters, at
, and as necessary to fill line boxes.

So, to obtain what you described, you need to use the value pre-wrap in place of pre.


text:
Q: Basic question about interface I get answer in:
Object modelling problem
that I should use interface instead class Extra in this case:
public Extra
{
public bool Paid {get;set;}
public string Name {get;set;}
public string Code {get;set;}
}

class Car
{
private List<Extra> _listOfExtras=new List<Extra>

public List<Extra> ListOfExtras
{
...
}
}

I don't understand why it is better solution

A: It really depends of the specific requirements and technical constraints. You can't expect any good advise here, because we all can just guess what you are doing with this classes.
For instance. As long as the Extra class consists of only these three values, I don't know why it should be an interface. It could be designed as a value object.


text:
Q: Some basic COM question I have just finished my first COM server DLL. And it runs smoothly. So I'd like to show my understanding for now and hear your critics.
1- How COM simply works? COM - "The Call Chain"
COM Lib methods -> Traditional DLL exports -> Classes encapsulated in the COM DLL
2- With C++, the benefits like "interface" in OOP can only be taken advantage of at the source level.
With COM, these benefits can be used at a binary level.
3- Some illustration about interface
&pInterface -------> pInterface ----------> Interface-----------------> methods
  Ixx **         Ixx *      (method table)

 (void **)

A Interface is a data structure in memory. It's nothing but a memory area containg a method table.
Is my understanding alright?
Thanks for your revision.

A:
Is my understanding alright?

Somewhat, you are summarising very heavily so hard to be sure.
If you want to know COM at this level, two of the best sources are "Essential COM", Don Box (pre-Windows 2000 so significant details of "Rental" threading model don't match the "Neutral" model); and the COM Specification (from MS, years ago, and was online but cannot quickly find a link now).

A: you can find a lot of interesting information about COM at www.codeproject.com (see http://www.codeproject.com/KB/COM/index.aspx?#COM/DCOM/COM+%20-%20Beginners for example)