text:
Q: Adding Twitter API to my app I want to be able to add a Twitter timeline into my app and also allow the user to update his/her status. The problem is I can't figure out how to get to the login screen. I tried searching online, but all the ones on their are outdated and I want to develop for version 4.0+.
Here is what I have so far: The code doesn't seem to work at all because I used this for an Android app for Android > 4.0, So it will not compile with a SDK of 15 or higher. Also this time I am using the Twitter4J library and the files have all been updated.
package com.shirwa.texthero.fragments;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.shirwa.texthero.R;

public class TwitterTab extends Activity implements OnClickListener {

    static final String TAG = "MyTwitter";

    TwitterTab twitter;
    SharedPreferences prefs;

    Button buttonUpdate;
    Button buttonPrefs;
    EditText textStatus;

    @Override
    public void onClick(View src) {
        String status = textStatus.getText().toString();

        Log.d(TAG, "Clicked on " + status);

        // Toast
        Toast.makeText(this, textStatus.getText(), Toast.LENGTH_LONG).show();

        // set twitter status
        twitter.updateStatus(status);

        // reset status string
        textStatus.setText("");
    }

    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // find views by id
        buttonUpdate = (Button) findViewById(R.id.buttonUpdate);
        textStatus = (EditText) findViewById(R.id.textStatus);

        // Add listener
        buttonUpdate.setOnClickListener(this);

        // Initialize twitter
        prefs = PreferenceManager.getDefaultSharedPreferences(this);
        String username = prefs.getString("username", "n/a");
        String password = prefs.getString("password", "n/a");
        if (username != null && password != null) {
            twitter = new Twitter(username, password);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

    // Called when menu item is selected //
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.menuPrefs:
            // Launch Prefs activity
            Intent i = new Intent(TwitterTab.this, Prefs.class);
            startActivity(i);
            Log.d(TAG, "MenuPrefs starting Prefs");
            Toast.makeText(TwitterTab.this, textStatus.getText(),
                    Toast.LENGTH_LONG).show();
            break;
        }
        return true;
    }
}

A: Before I begin, let me start by saying, I don't typically post link, only answers. I may have done so as a beginner, but hardly any more. Unless the post is a legit and valid one which cannot be answered in it's entirety without links.
To get started with logging in to Twitter via your app, here is a brilliant little tutorial that should get you started:
Android Twitter oAuth Connect Tutorial plus posting a Status Update after having logged in.
You can also take a look at an example hosted on GitHub, T4JTwitterLogin. This is another example for logging in to Twitter with your app and posting a Status Update too.
As for the bonus goodies (well, just the one actually). Once you are a little comfortable with Android developed in it's entirety, or perhaps when you can start deciphering other developers code, here is a complete functioning Android Application for Twitter that is open source, available on the Google Play store and is fairly popular on it.
This is a link to the search results on GitHub with the keywords Android and twitter4J: https://github.com/search?q=android+twitter4j&type=Repositories&s=updated

A: I have developed TWITTER in my APP.It is working sucessfully..Here is the LINK
You can develop for your app.

A: What API is it that you actually using there?
There is no official twitter SDK built for android, just their REST API. For that purpose, I can personally recommend the library "Scribe" to handle integration with twitter. It can handle authentication, posting and any other function specified in the REST API.
https://github.com/fernandezpablo85/scribe-java
https://dev.twitter.com/docs/api/1.1

A: First you have to authenticate your app which will require 2 secretkey (which will be provided to you by twitter during you app registration).
Second, you need to authenticate using Oauth, you can can Google it,(try singly).
Third ,handle the callback and handle the required response.
use this for reference


text:
Q: Javascript accessing ejs variable in Node.js context I am trying my javascript code inside an HTML file to access an ejs variable.
This is the Node.js code:
res.render('target.ejs', {data:user});

When i do this in HTML:

<%= data %>

evertything is ok.
But when I try to access the variable inside a

then nothing happens. I also tried with a console.log(name); and still it didn't work.

A: Seems like you need some quotes.
Try
  var name = '<%= data %>';

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sliding UITextField on iPad when Keyboard Shows I have code from Cocoa with Love that scrolls a UITextField when the keyboard comes up so that the keyboard does not cover the UITextField.
Here's the code:
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    CGRect textFieldRect = [self.view.window convertRect:textField.bounds fromView:textField];
    CGRect viewRect = [self.view.window convertRect:self.view.bounds fromView:self.view];

    CGFloat midline = textFieldRect.origin.y + 0.5 * textFieldRect.size.height;

    // Issue is that numerator isn't big enough for bottom 3rd of the screen

    CGFloat numerator = midline - viewRect.origin.y - MINIMUM_SCROLL_FRACTION * viewRect.size.height;

    CGFloat denominator = (MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION) * viewRect.size.height;

    CGFloat heightFraction = numerator / denominator;

    NSLog(@"Midline: %g Fraction: %g / %g", midline, numerator, denominator);

    if (heightFraction < 0.0)
    {
        heightFraction = 0.0;
    }
    else if (heightFraction > 1.0)
    {
        heightFraction = 1.0;
    }

    UIInterfaceOrientation orientation =
    [[UIApplication sharedApplication] statusBarOrientation];
    if (orientation == UIInterfaceOrientationPortrait ||
        orientation == UIInterfaceOrientationPortraitUpsideDown)
    {
        animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction);
    }
    else
    {
        animatedDistance = floor(LANDSCAPE_KEYBOARD_HEIGHT * heightFraction);
    }

    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y -= animatedDistance;

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];

    [self.view setFrame:viewFrame];

    [UIView commitAnimations];
}

For debugging purposes I output the midline, etc to see what was happening.  This is from tabbing from top to bottom.  You can see about the 6th one down the numerator becomes negative, because the UITExtField.size.height that was converted for it's parent view is a low number.  I can't figure out why the number would be a negative.  The height should up just like all the others do as you go down the view.
2011-05-24 09:36:08.600 Baby Bloom[27794:207] Midline = 246 + 0.5 * 167
2011-05-24 09:36:08.601 Baby Bloom[27794:207] Midline: 329.5 Fraction: 22.3 / 409.6
2011-05-24 09:36:09.535 Baby Bloom[27794:207] Midline = 246 + 0.5 * 167
2011-05-24 09:36:09.536 Baby Bloom[27794:207] Midline: 329.5 Fraction: 22.3 / 409.6
2011-05-24 09:36:09.929 Baby Bloom[27794:207] Midline = 246 + 0.5 * 246
2011-05-24 09:36:09.930 Baby Bloom[27794:207] Midline: 369 Fraction: 61.8 / 409.6
2011-05-24 09:36:10.313 Baby Bloom[27794:207] Midline = 246 + 0.5 * 246
2011-05-24 09:36:10.314 Baby Bloom[27794:207] Midline: 369 Fraction: 61.8 / 409.6
2011-05-24 09:36:10.793 Baby Bloom[27794:207] Midline = 246 + 0.5 * 97
2011-05-24 09:36:10.794 Baby Bloom[27794:207] Midline: 294.5 Fraction: -12.7 / 409.6
2011-05-24 09:36:11.785 Baby Bloom[27794:207] Midline = 246 + 0.5 * 148
2011-05-24 09:36:11.786 Baby Bloom[27794:207] Midline: 320 Fraction: 12.8 / 409.6

A: Turns out that when in Landscape on the iPad it switches up the origin (x is now y and width is now height.
Here is the code to make it work:
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    CGRect textFieldRect = [self.view.window convertRect:textField.bounds fromView:textField];
    CGRect viewRect = [self.view.window convertRect:self.view.bounds fromView:self.view];

    float origin;
    float textFieldHeight;
    float viewOrigin;
    float viewHeight;

    UIInterfaceOrientation orientation =
    [[UIApplication sharedApplication] statusBarOrientation];

    if (orientation == UIInterfaceOrientationPortrait ||
        orientation == UIInterfaceOrientationPortraitUpsideDown)
    {
        textFieldHeight = textFieldRect.size.height;
        origin = textFieldRect.origin.y;
        viewOrigin = viewRect.origin.y;
        viewHeight = viewRect.size.height;
    }
    else
    {
        textFieldHeight = textFieldRect.size.width;
        viewOrigin = viewRect.origin.x;
        viewHeight = viewRect.size.width;
        origin = viewHeight - textFieldRect.origin.x;
    }

    CGFloat midline = origin + 0.5 * textFieldHeight;

    // Take the current middle y location of the textfield
    // If it is in the top 20% of the view don't move it
    // If it is in the middle 60% move it by a fraction of the keyboard size
    // If it is in the bottom 20% move it by the whole size of the keyboard

    CGFloat numerator = midline - viewOrigin - MINIMUM_SCROLL_FRACTION * viewHeight;

    CGFloat denominator = (MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION) * viewHeight;

    CGFloat heightFraction = numerator / denominator;

    if (heightFraction < 0.0)
    {
        heightFraction = 0.0;
    }
    else if (heightFraction > 1.0)
    {
        heightFraction = 1.0;
    }

    if (orientation == UIInterfaceOrientationPortrait ||
        orientation == UIInterfaceOrientationPortraitUpsideDown)
    {
        animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction);
    }
    else
    {
        animatedDistance = floor(LANDSCAPE_KEYBOARD_HEIGHT * heightFraction);
    }

    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y -= animatedDistance;

    //NSLog(@"Denom: %g", denominator);
    //NSLog(@"Distance: %g", animatedDistance);

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];

    [self.view setFrame:viewFrame];

    [UIView commitAnimations];
}

A: origin = viewHeight - textFieldRect.origin.x;

I think you don't need this, because it makes incorrect field origin and very big middle value, which perform scrolling, where it isn't needed.
So generally you should just use x origin as y.
origin = textFieldRect.origin.x;


text:
Q: Sticky nav makes header jump I am working with sticky nav and seems like when I scroll the header jumps up, and it is not smooth.
DEMO
Maybe a CSS problem? or JS?
JS used:
var win      = $(window),
    fxel     = $('nav'),
    eloffset = fxel.offset().top;

    win.scroll(function() {
    if (eloffset < win.scrollTop()) {
        fxel.addClass("fixed");
    } else {
        fxel.removeClass("fixed");
    }
    });

A: Remove the margin / padding on both html and body, and remove the margin-top of #container :
body, html{
    margin:0px;
    padding:0px;
}

#container {
  /*margin-top:10px;*/
}

Check the demo, I might have misunderstood your problem!

A: The problem is that when the header is asigned the fixed position, the height of the header is gone above the rest of the elements so it jumps up to the top of the document. I changed some of your CSS, so that the header is absolute and the content has a margin from the top. See: http://jsfiddle.net/FZpf7/2/ and you will see the jumping is gone.
Changed CSS:
nav {
  background-color:#FBFBFB;
  color:white;
  position:absolute;
  top:0px;
  left:0px;
  width:100%;
}

div.header_med {
 margin-top:  95px;
}

Edit:
This is the second JSFiddle link http://jsfiddle.net/FZpf7/3/


text: Q: Difference between $\sin(\arcsin(x))$ and $ \arcsin(\sin x)$ What's the difference between $\sin(\arcsin(x))$ and $ \arcsin(\sin x)$ ? I think these are equal each other and equals to $x$ . Also , what's the plot of these functions ? I'm really confused about inverse function and its concept that is appearing in many situations and problems like this.


text:
Q: Angular 2 - Cannot read property 'x' of undefined in [null] I'm actually learning Angular 2, but I found an error on i'm stuck. I don't know to fix that, can help me with that?
EXCEPTION: TypeError: Cannot read property 'specieSelected' of undefined in [null]
angular2.dev.js:21835 EXCEPTION: TypeError: Cannot read property 'specieSelected' of undefined in [null]
.....

The files I have are these:
file: navigation.ts
import { Component, View, NgFor } from 'angular2/angular2'
import { RouterLink, Location } from 'angular2/router';
import { SpecieService, SpecieModel } from "../services/specie/specieService";

@Component({
  selector: 'navigation',
  providers: [SpecieService]
})
@View({
  directives: [RouterLink, NgFor],
  template:
  `
  some html tags
  `
    })

export class Navigation{
  public title = 'Rol';
  public home = 'Home';
  public species = "Especies";
  public professions = "Profesiones";
  public talents = "Talentos";
  public about = "Información";
  public contact = "Contacto";

  specieSelected:SpecieModel;
  location: Location;
  constructor(
    location: Location,
    public specieService:SpecieService
  ) {
    this.specieSelected = this.specieService.species[0];
    this.location = location;
  }
  getLinkStyle(path) {
      return this.location.path() === path;
  }
}

file: species.ts
import { Component, View } from 'angular2/angular2'
import { RouterLink, RouteParams } from 'angular2/router';
import { Navigation } from '../navigation';

@Component({
  selector: 'species'
})
@View({
  directives: [Navigation],
  templateUrl: 'app/views/specie/species.html'
})

export class Species{
  constructor(

  ){
  }

}

On the template, i try to access to specieSelected.name and is where i get the error.

{{navigation.specieSelected.name}}

I think i miss something, but don't know what.
Thanks!


text:
Q: If no forms are open upon closing a form, open a specific form I have a database with multiple little forms spread out across the database (as most are I'd assume, lol).  There are multiple ways to get to multiple different forms, however I ran into a bit of a naviational issue that in certain circumstances, when a user closes a form, nothing else opens or is open.  So I'd ideally like Access to check if any forms are open at any given moment, and if not, then to open a specific form (the databases "main" form).  I googled this and couldn't find what I was looking for (possible I google the wrong thing?), so I honestly don't really know where to even start.

I would like to create a function that I execute on Form_Close in order to check if any forms are currently open, and if not, to open a specific form.  Again, I'm not even remotely sure of where to even start looking for this answer, so I don't really have anything to start off my journey.

A: An easy way would be this:
Add this procedure in a standard module and edit the main forms name in there:
Public Function OpenMainFormIfThisIsTheLastForm()
    If Forms.Count = 1 Then DoCmd.OpenForm "YourMainForm"
End Function

In each form you want to open the main form before itself closes place this in the On Close-event:
=OpenMainFormIfThisIsTheLastForm()

That should be all.


text:
Q: Android SoundPool problem on some devices I everyone, I'm trying to make a simple piano application, for each note I have a .wav file and I'm using soundpool class to make It play.
BUT
On a couple of Xiaomi devices and on Asus zenfone a kind of white noise is all I can hear and it's very annoying, also despite my effort I couldn't find any solution on the web, help me please!! ))
Here my declaring of aAttributes and soundPool objects in class scope:
private SoundPool soundPool;
private AudioAttributes aAttributes;
volumeNote = 1.0f;
volumeFeedBack = 0.6f;

here the code on onCreate method:
aAttributes = new AudioAttributes.Builder()
                .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                .setUsage(AudioAttributes.USAGE_GAME)
                .build();
soundPool = new SoundPool.Builder()
                .setMaxStreams(10)
                .setAudioAttributes(aAttributes)
                .build();

here an example of the code on the onClick method:
case R.id.btFaLow:
                    soundPool.play(faL,volumeNote,volumeNote,0,0,1);
                    break;

I hope these information can help to find the issue. Thank You all in advance!

A: There are some practical advises on the link below.
Android can't play some wav file with soundpool?
Personally, I've used Soundpool with .mp3 files with no white noise issues.
After some searching, I've found this link where CONTENT_TYPE_SONIFICATION is used instead of CONTENT_TYPE_MUSIC, which I believe may be more suited to what you're looking for.

CONTENT_TYPE_SONIFICATION
Content type value to use when the content type is a sound used to
accompany a user action, such as a beep or sound effect expressing a
key click, or event, such as the type of a sound for a bonus being
received in a game.

You can also checked out the code samples at coding in flow:
https://codinginflow.com/tutorials/android/soundpool
(I'm not associated with the site.)

A: FWIW, experienced the same problem on a Xiaomi Redmi 6, and @Peppinhood's suggestion to use .mp3 did the trick
For some reason, both .m4a and .wav produced heavily distorted sounds on that device.


text:
Q: CMake CEGUI / GTK2 Configuration Error I am trying to build and use CEGUI (Crazy Eddie's GUI) as a library for Ogre. I am using CMake, but during the configuring step for the dependencies, I got the following error:

Some or all of the gtk libraries were not found. (missing:  GTK2_GTK_LIBRARY GTK2_GTK_INCLUDE_DIR GTK2_GDK_INCLUDE_DIR GTK2_GDKCONFIG_INCLUDE_DIR GTK2_GDK_LIBRARY GTK2_GLIB_INCLUDE_DIR GTK2_GLIBCONFIG_INCLUDE_DIR GTK2_GLIB_LIBRARY)
  CMake Error: The following variables are used in this project, but they are set to NOTFOUND.
  Please set them or make sure they are set and tested correctly in the CMake files:
  Boost_INCLUDE_DIR (ADVANCED)
     used as include directory in directory C:/Cegui/cegui-0.8.3/cegui/src/RendererModules/Ogre

CEGUI 0.8.3
cegui-deps-0.8.x-src.zip

A: *

*Make sure that you have GTK2 installed on your machine (as far as I can tell, it is not part of the CEGUI dependency download archive).

*Ensure that CMake can find the library and all it needs. From having a look at the official CMake FindGKT2 script (and I couldn't find a custom one for CEGUI, so the official one is most likely used), the following locations are checked:

*

*/usr/local/lib64

*/usr/local/lib

*/usr/lib64

*/usr/lib

*/opt/gnome/include [and /lib]

*/opt/openwin/include [and /lib]

*/sw/include [and /lib]

*/opt/local/include [and /lib]

*/usr/pkg/lib

*/usr/pkg/include/glib

*$ENV{GTKMM_BASEPATH}/include [and /lib]

*[HKEY_CURRENT_USER\SOFTWARE\gtkmm\2.4;Path]/include

*[HKEY_CURRENT_USER\SOFTWARE\gtkmm\2.4;Path]/lib

*[HKEY_LOCAL_MACHINE\SOFTWARE\gtkmm\2.4;Path]/include

*[HKEY_LOCAL_MACHINE\SOFTWARE\gtkmm\2.4;Path]/lib

So if you are on windows, setting the environment variable GTKMM_BASEPATH will probably be the easiest way. Alternatively, you can also directly enter the paths to your GTK2 installation in the advanced CEGUI view.


text:
Q: Creating range (corridor) plot in ggplot2 Given the example available through r-statistics website, I would like to modify it create a range plot
Example
# Notes -------------------------------------------------------------------

# Stacked are chart
# Source: http://r-statistics.co/Top50-Ggplot2-Visualizations-MasterList-R-Code.html#Stacked%20Area%20Chart

# Graphic -----------------------------------------------------------------

library(ggplot2)
library(lubridate)
theme_set(theme_bw())

df <- economics[, c("date", "psavert", "uempmed")]
df <- df[lubridate::year(df$date) %in% c(1967:1981),]

# labels and breaks for X axis text
brks <- df$date[seq(1, length(df$date), 12)]
lbls <- lubridate::year(brks)

# plot
ggplot(df, aes(x = date)) +
    geom_area(aes(y = psavert + uempmed, fill = "psavert")) +
    geom_area(aes(y = uempmed, fill = "uempmed")) +
    labs(
        title = "Area Chart of Returns Percentage",
        subtitle = "From Wide Data format",
        caption = "Source: Economics",
        y = "Returns %"
    ) +  # title and caption
    scale_x_date(labels = lbls, breaks = brks) +  # change to monthly ticks and labels
    scale_fill_manual(name = "",
                      values = c("psavert" = "#00ba38", "uempmed" = "#f8766d")) +  # line color
    theme(panel.grid.minor = element_blank())  # turn off minor grid

Desired results

Attempts
"white"
Setting one series colour to white, is close but I would like to make the grid visible. Controlling legend could be easily done later.

A: You sure need to use geom_ribbon.
Adopted from the docs:
library(tidyverse)

data.frame(year = 1875:1972, level = as.vector(LakeHuron)) %>%
  ggplot(aes(year)) +
  geom_ribbon(aes(ymin = level - 1, ymax = level + 1), fill = "grey70") +
  geom_line(aes(y = level))


text:
Q: Displaying Program Icons in the Title Bar and Task Bar I'm a brand new, first-time Ubuntu user, so any suggestions or info requests will need to be very specific and step-by-step. I'm not afraid of the terminal or anything else; I just don't usually know what to do without being explicitly told.
I have the 64-bit version of 11.04, from the alternate installer, and am dual-booting with Windows 7. I'm using the 'Ubuntu Classic (no effects)' desktop option.
That said...
Manually installed (from tar.bz2, as opposed to .deb/Synaptic) programs (or possibly only manually installed Mozilla programs; I haven't tested other programs) don't seem to display their icons in the title bar, nor in the task bar.  An icon is shown, but it's only the default 'there is no icon' one. Currently, I'm having this problem with SeaMonkey and Thunderbird.

*

*SeaMonkey was originally installed through Synaptic (I can't remember if the icon showed then, but I don't believe it did.), then later uninstalled so I could manually install a non-buggy version, and has since been upgraded to the current 2.4.1.

*Thunderbird was manually installed from the start, first the most recent version, then later downgraded to an older version. Since then, I have manually installed several versions, including the same one available through Synaptic, and also installed Thunderbird through Synaptic.  Currently, I have both the Synaptic and a fairly recent 6.something version installed, in different locations.  Only the Synaptic install shows the Thunderbird icon.  None of the other versions ever have, whether newer or older, so it's clearly not a version issue.

After some time spent with Google, I found /chrome/icons/default in each program's folder, and all the necessary window icons seem to be there, but it doesn't look like the programs can find them. Why not? How can I fix this?

A: Compiling programs from source normally doesn't add shortcuts and links for those programs on your user UI, mostly they will create a link to the compiled binary in /usr/bin so that the user can type the program's command on the terminal and start using it right away but icons, shortcuts on desktop, nice menu links are not included unless the program was made to do so after you compiled it.
The icons probably will be on the folder from the compiled application, its part of the source code most of the times and will be copied, but that doesn't mean that your install used to to create shortcuts and menus.
Packages that come from apt or software center are designed to created such links and shortcuts using the icons supplied on the program of a theme icon for the application.
Think of packages (deb, rpm, etc) as archives with instructions on where and how to create links, place configuration files, modify other files for integration. In Windows if you want to use a software you have to use and installer that will do the same (ie: if you install firefox in Windows) for you. The other option is to use compiled binaries without an installer, that means that the program is there, it will work perfectly but no links, shortcuts, integration will be done for you automatic.
An example of this is firefox and firefox portable, the first you download, run the installer that will create the files and links and will integrate the program with your OS, the 2nd will open, run, let you use the full program with no limitations but there is no links, no integration, no links, etc, you need to run the compiled binary and that's it.
So, if you want to have integration in to your Ubuntu desktop you need to use the pre-compiled, assembled packages (deb files, or installer files for Ubuntu/Debian), either by downloading them or using apt or you do everything by hand using source or compiled binaries for your system. The easiest and most common is to use the .deb files since they do all the nasty work for you.


text:
Q: I am new in using ArrayLists. Array Out of Bounds, Array seems to be empty, but have been adding Strings to it already My instructor suggested to use ArrayList, and this is my first time using one. I keep getting ang error of ArrayList OutofBounds. I get teh idea that is empty, but i have been adding to the ArrayList. Maybe it couldn't add, and i'm stuck. T^T
for(; pizza.i<3;pizza.i++){
        if(jComboBox5.getSelectedIndex()==pizza.i){
            pizza = new Pepperoni(pizza);
            pizza.count();
            //pizza.toppings.add(""+i+" Pepperoni");
            //pizza.toppingctr++;
            System.out.println(pizza.i+"Pepperoni"+(++pizza.toppingctr));

        }
        if(jComboBox6.getSelectedIndex()==pizza.i){
            pizza = new Mushroom(pizza);
            pizza.count();

            System.out.println(pizza.i+"Mu"+(++pizza.toppingctr));
        } ........
}for(int i=0; i<pizza.toppingctr;i++){
        System.out.println(pizza.toppings.get(i));
    }

The System.out.println and the i, works how it should be working. I think the problem is on pizza.count (found in Pepperoni, Mushroom, and etc) where i actually add Strings to my ArrayList.
public int count(){
        pizza.toppings.add(""+pizza.i+" Pepperoni");
        return (pizza.toppingctr+1);
    }

Pepperoni (and others) extends to PizzaDecorator, and PizzaDecorator extends to Pizza, where the arraylist is initialized.
ArrayList<String> toppings =new ArrayList<String>();

update:
Exception in thread "AWT-EventQueue-0"     java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:635)
at java.util.ArrayList.get(ArrayList.java:411)
at pizzabasedresto.PizzaPanel.jButton1ActionPerformed(PizzaPanel.java:832)
at pizzabasedresto.PizzaPanel.access$2300(PizzaPanel.java:18)
at pizzabasedresto.PizzaPanel$24.actionPerformed(PizzaPanel.java:422)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6516)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6281)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4872)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4698)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4698)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:747)
at java.awt.EventQueue.access$300(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:706)
at java.awt.EventQueue$3.run(EventQueue.java:704)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:720)
at java.awt.EventQueue$4.run(EventQueue.java:718)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:717)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:

The stack trace doesn't show what line it is, but when i remove the
for(int i=0; i<pizza.toppingctr;i++){
        System.out.println(pizza.toppings.get(i));
    }

the exception is gone. so the statement who throws exception is that

A: First of all, and that's supposed to solve the problem. If you use an ArrayList you should check its documentation. When you supposed to go through a simple array you use "nameOfArray.length", right? Well, the ArrayList has the method ".size()" which bascialy has the same use.
So your loop would be better this way :
for(int i=0; i<pizza.toppings.size();i++){
    System.out.println(pizza.toppings.get(i));
}

This way you're sure you'll never get out of your array's length.
Now of course there is still a problem with your value. And it's hard to tell where it is for two reasons :

*

*We miss the important parts of your code (such as the constructor)

*Because the pizza.toppingctr is public and shouldn't be.
You'd better increment it in your count() method and have it private.
And in fact, if you use the ".size()" method, you shouldn't need it at all.


text:
Q: Customize - Ola Hallengren script Trying to incorporate Date wise folder in the script. Following is the original code
  INSERT INTO @CurrentDirectories (ID, DirectoryPath, Mirror, DirectoryNumber, CreateCompleted, CleanupCompleted)
      SELECT ROW_NUMBER() OVER (ORDER BY ID), DirectoryPath + CASE WHEN RIGHT(DirectoryPath,1) = '\' THEN '' ELSE '\' END + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + '\' + @CurrentDatabaseNameFS + '\' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END, Mirror, ROW_NUMBER() OVER (PARTITION BY Mirror ORDER BY ID ASC), 0, 0
      FROM @Directories
      ORDER BY ID ASC

I added '\' + REPLACE(CONVERT(varchar(10), GETDATE(), 101), '/', '') +'\' + to the above code to have folders by date
INSERT INTO @CurrentDirectories (ID, DirectoryPath, Mirror, DirectoryNumber, CreateCompleted, CleanupCompleted)
      SELECT ROW_NUMBER() OVER (ORDER BY ID), DirectoryPath + CASE WHEN RIGHT(DirectoryPath,1) = '\' THEN '' ELSE '\' END + '\' + REPLACE(CONVERT(varchar(10), GETDATE(), 101), '/', '') +'\' + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + '\' + @CurrentDatabaseNameFS + '\' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END, Mirror, ROW_NUMBER() OVER (PARTITION BY Mirror ORDER BY ID ASC), 0, 0
      FROM @Directories
      ORDER BY ID ASC

Now after modifying the code with the above syntax , I could see the DateFolder gets created but somehow backup is not happening. See the error below

DECLARE @ReturnCode int EXECUTE @ReturnCode =
  [master].dbo.xp_create_subdir
  N'N:\Test\FullUserDBBackups\10152017\CLU-DBSQL-TEST$DB2012_TEST\AX_TEST\FULL_COPY_ONLY'
  IF @ReturnCode <> 0 RAISERROR('Error creating directory.', 16, 1)
BACKUP DATABASE [] TO DISK =
  N'N:\Test\FullUserDBBackups\10152017\CLU-DBSQL-TEST$AX2012_PROD\AX_TEST\FULL_COPY_ONLYCLU-DBSQL-TESTAX2012_TEST_AX_TEST_FULL_COPY_ONLY_20171015_042734.bak'
  WITH CHECKSUM, COMPRESSION, COPY_ONLY


text:
Q: Loading details from multiple tables I was using this:
SELECT res.*, rac.*, u.*, t.*, c.*
FROM Results res
INNER JOIN Races rac USING (RaceID)
INNER JOIN Users u USING (UserID)
INNER JOIN Teams t USING (TeamID)
INNER JOIN Cars c USING (CarID)
WHERE res.SeasonNumber = '$SeasonNumber' AND res.LeagueID = '$LeagueID' AND Position = '1' AND ResultConfirmed = '1'
ORDER BY Position ASC

Which works fine, but I've since realised I need to have CarID added in to Results table, but when I add it in, it gives me the error that the field is ambiguous. What I'd like to do is get the Car name from Cars table where CarID joins Cars and Results. When I try to do this though:
SELECT res.*, rac.*, u.*, t.*, c.*
FROM Results res
INNER JOIN Races rac USING (RaceID)
INNER JOIN Users u USING (UserID)
INNER JOIN Teams t USING (TeamID)
INNER JOIN Cars c USING (res.CarID)
WHERE res.SeasonNumber = '$SeasonNumber' AND res.LeagueID = '$LeagueID' AND Position = '1' AND ResultConfirmed = '1'
ORDER BY Position ASC

I get the following error:

You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near '.CarID) WHERE res.SeasonNumber = '1' AND res.LeagueID = '1' AND
  Position = '1' ' at line 6

A: You can replace your USING clause with ON(),in USING() clause i guess you add the columns name that are same in other table you are joining but you placed the join in last and using alias res mysql won't allow this
INNER JOIN Cars c ON(res.CarID =c.CarID)

If you need to use USING() clause you need to adjust the join placements like
SELECT res.*, rac.*, u.*, t.*, c.*
FROM
Cars c
INNER JOIN Results res USING (CarID)
INNER JOIN Races rac USING (RaceID)
INNER JOIN Users u USING (UserID)
INNER JOIN Teams t USING (TeamID)
WHERE res.SeasonNumber = '$SeasonNumber' AND res.LeagueID = '$LeagueID' AND Position = '1' AND ResultConfirmed = '1'
ORDER BY Position ASC

But ON() clause is more readable form


text:
Q: Countdown timer is restarting evertime I hit refresh Whenever I refresh my browser its restarting from the start. I uploaded  it on server..I'm getting the same result.
Here's my code:

function getTimeRemaining(endtime) {
  var t = Date.parse(endtime) - Date.parse(new Date());
  var seconds = Math.floor((t / 1000) % 60);
  var minutes = Math.floor((t / 1000 / 60) % 60);
  var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
  var days = Math.floor(t / (1000 * 60 * 60 * 24));
  return {
    'total': t,
    'days': days,
    'hours': hours,
    'minutes': minutes,
    'seconds': seconds
  };
}

function initializeClock(id, endtime) {
  var clock = document.getElementById(id);
  var daysSpan = clock.querySelector('.days');
  var hoursSpan = clock.querySelector('.hours');
  var minutesSpan = clock.querySelector('.minutes');
  var secondsSpan = clock.querySelector('.seconds');

  function updateClock() {
    var t = getTimeRemaining(endtime);

    daysSpan.innerHTML = t.days;
    hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
    minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
    secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);

    if (t.total <= 0) {
      clearInterval(timeinterval);
    }
  }

  updateClock();
  var timeinterval = setInterval(updateClock, 1000);
}

var deadline = new Date(Date.parse(new Date()) + 33 * 24 * 60 * 60 * 1000);
initializeClock('clockdiv', deadline);
#clockdiv {
  font-family: Calibri;
  color: #001a00;
  display: inline-block;
  font-weight: 10;
  text-align: center;
  font-size: 30px;
}

#clockdiv>div {
  padding: 10px;
  border-radius: 3px;
  display: inline-block;
}

.smalltext {
  padding-top: 5px;
  font-size: 16px;
}

Days

Hours

Minutes

Seconds

Here's the fiddle- code
What am I doing wrong here?
At first I thought it'll be fine if I upload it on server..but still getting the same result.
If there's another code..please help me out or guide me..how to do it!
Thanks!

A: It is because of this line
var deadline = new Date(Date.parse(new Date()) + 33 * 24 * 60 * 60 * 1000);

You keep setting the date to 33 days in the future, so every time the page loads this is set.
If you change this line to the following and pass in your desired date.
var deadline = new Date(Date.parse('2017-10-30'));

Run code snippet below.

function getTimeRemaining(endtime) {
  var t = Date.parse(endtime) - Date.parse(new Date());
  var seconds = Math.floor((t / 1000) % 60);
  var minutes = Math.floor((t / 1000 / 60) % 60);
  var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
  var days = Math.floor(t / (1000 * 60 * 60 * 24));
  return {
    'total': t,
    'days': days,
    'hours': hours,
    'minutes': minutes,
    'seconds': seconds
  };
}

function initializeClock(id, endtime) {
  var clock = document.getElementById(id);
  var daysSpan = clock.querySelector('.days');
  var hoursSpan = clock.querySelector('.hours');
  var minutesSpan = clock.querySelector('.minutes');
  var secondsSpan = clock.querySelector('.seconds');

  function updateClock() {
    var t = getTimeRemaining(endtime);

    daysSpan.innerHTML = t.days;
    hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
    minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
    secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);

    if (t.total <= 0) {
      clearInterval(timeinterval);
    }
  }

  updateClock();
  var timeinterval = setInterval(updateClock, 1000);
}

var deadline = new Date(Date.parse('2017-10-30'));
initializeClock('clockdiv', deadline);
#clockdiv {
  font-family: Calibri;
  color: #001a00;
  display: inline-block;
  font-weight: 10;
  text-align: center;
  font-size: 30px;
}

#clockdiv>div {
  padding: 10px;
  border-radius: 3px;
  display: inline-block;
}

.smalltext {
  padding-top: 5px;
  font-size: 16px;
}

Days

Hours

Minutes

Seconds

A: When you set
var deadline = new Date(Date.parse(new Date()) + 33 * 24 * 60 * 60 * 1000);

every time you load the script, it will always be 33 days (and so on) from now. So you'll have to give the script a fixed deadline like so:
var deadline = new Date(Date.parse('2017-10-12'));


text:
Q: Need help for proving: $f(f^{−1}(A)) ⊆ A$. Informations:
$f:X \longrightarrow X$ and $A \subseteq X$.
How can i prove this statement:
$f(f^{-1}(A)) \subseteq A$
This is my thoughts until now:
$f^1(A)=\{x\in X |f(x)\in A\} \subseteq X$.
$f(A)=\{f(x)|x\in A\}$
$f(f^1(A))=\{y\in A:\exists \in f^1(A):y=f(x)\} \in A$

A: Hint: If $x \in f^{-1}(A)$, what does that say about $f(x)$?

A: First off, welcome to Math SE! It is encouraged here to use LaTeX formatting in your posts; you can find a tutorial here.
Second, it is encouraged that when you make a post, you include some information about how you've already tried to solve this problem, and where you're stuck.
For instance, this is a very straightforward problem, and you just need to follow definitions. That is, let $x\in f^{-1}(A)$. What does that mean? If you write out what is immediately implied by the definition, you'll find your proof writes itself.

A: Take $y \in f[f^{-1}[A]]$. So $y = f(x)$, where $x \in f^{-1}[A]$, and the latter means that $f(x) \in A$, so $y \in A$ and the inclusion has been shown.


text:
Q: Poor battery life Windows 8 I have an Acer laptop (AS4820TG, it's about 2 years old), and I recently installed Windows 8 to a partition I made on my SSD (now I'm dual booting 7 and 8).  My laptop's always had pretty good battery life.
On Windows 7, fully charged, windows sometimes estimates that I'll get 8.5 hours.  Of course, that never happens, but nonetheless I can still squeeze a good 5-6 out of it if I'm saving power in as many ways as possible.
However, with Windows 8, on a full charge, I only get a prediction of perhaps 1.5-2 hours.  It usually lasts not much more than one, even if I keep it in power saving mode and don't do anything intensive.
The one thing I know is hurting me is that with the fresh install, I lost the ability to automatically power off the optical drive.  Other than that, I can't figure out what's slashing my hours!  Even if it's unsolvable, can someone suggest what else might be the culprit?  Thanks!

A: probably a really late reply but if you have an Nvidia graphics card download the actual Nvidia driver so optimus can disable the card when it's not needed, the fan is most likely the graphics card one. Exact same problem as you and that worked for me

A: Sorry for the late answer, it happens to me and I think I found out the reason.

*

*Open your Intel Graphics and Media Control Panel, and right click for properties.

*Open the Power tab

*Change all the power settings to Maximum Battery Life.

A: I had similar situation when I installed windows 8 too. I used to get 4 hours of backup on 7, but only 2-2.5 on 8.
Things I've done:

*

*Ran Windows Update.

*Installed all latest device drivers.

*Set my brightness to minimum, and battery mode to Power Saver.

Installing latest device drivers is very important because, in my case, it turned out my wifi and bluetooth drivers weren't written, and optimized for 7.
Now, I have solid 3.5 hours of backup on 8.

A: these may help you:

*

*Set up a lower brightness for your screen

*Reduce CPU maximum work percentage in energy settings (you do this by creating or editing a profile)

*disable your wireless when not needed and any other plugged usb devices


text:
Q: React.createRef() won't work for first component that is created but will work for subsequent components I am having difficulty with using React.createRef() to get the height of an element in a child component.
The difficulty is only in the first of three child components created with a map.
The child component displays like an actual ticket (see below).
The left hand side and the right hand side are different divs.
The (red) background color to the ticket title ('early bird' etc) will have a larger height if the user submits a ticket with a long name that takes up more space than is available in one line.
I want the height of the red div on the right hand side of the ticket to match the height of the h1 containing the ticket title on the left hand side.
I am using React.createRef() to find the height of the h1 and apply it through inline style to the div on the right hand side.
This works for the second and third tickets but won't work for the first ticket.

//Parent Component
{this.state.userEvent.tickets
  .map((e, i) => {
    return (

        <ColmTicket
          ticketType={e.ticketType}
          description={e.ticketDescription}
          price={e.price}
          refunds={e.refunds}
          chargeForNoShows={e.chargeForNoShows}
          hold={e.hold}
          quantity={e.buy.numTicketsSought}
          changeQuantity={this.changeQuantity}
          i={i}
        />

    );
  })}

//Child Component

class ColmTicket extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      height: 0,
    };
    this.containerRef = React.createRef();
  }
  componentDidMount() {
    const { offsetHeight } = this.containerRef.current;

    this.setState({
      height: offsetHeight,
    });
  }

  render() {
    return (

          {this.props.ticketType}

    );
  }
}

I am also running console.logs in componentDidMount. The first ticket - the one with the problem - does not display the prop that gives the name of the ticket when it is console logged (line 17 below). The other two tickets do provide this prop when it is console.logged.
This leads to believe that, for the first component, the prop has not been rendered when componentDidMount is called? Is this possible and, if so, can I fix it?
// Console Log results
    ColmTicket.js:17
    ColmTicket.js:18 this.containerRef {current: h1.event-ticket-title}
    ColmTicket.js:19 this.containerRef.current
…

    ColmTicket.js:22 offsetHeight 20
    ColmTicket.js:23 ---------
    ColmTicket.js:17 General Admission
    ColmTicket.js:18 this.containerRef {current: h1.event-ticket-title}
    ColmTicket.js:19 this.containerRef.current
…

    ColmTicket.js:22 offsetHeight 48
    ColmTicket.js:23 ---------
    ColmTicket.js:17 Skip The Queue
    ColmTicket.js:18 this.containerRef {current: h1.event-ticket-title}
    ColmTicket.js:19 this.containerRef.current
…

    ColmTicket.js:22 offsetHeight 48
    ColmTicket.js:23

A: I solved this by switching using a functional component and useEffect.
I followed the code here


text:
Q: Matplotlib automatically scale vertical height of subplots for shared x-axis figure I want to automatically scale the vertical height of subplots for shared x-axis figures based on their data span! I want to compare the relative intensity of the displayed data. If i use the sharey=True kwarg for the subbplots the data is displayed in a way that the relative intensity is  recognizable:
    import matplotlib.pyplot as plt
    from matplotlib import gridspec
    import numpy as np

    SIZE = (12, 8) #desired overall figure size

    # Simple data to display in various forms
    x = np.linspace(0, 2 * np.pi, 400)

    y = np.sin(x ** 2)
    y2 = 2*(np.sin(x ** 2))
    y3 = 3*(np.sin(x ** 2))

    fig, ax = plt.subplots(3,ncols=1, sharex=True, sharey=True)
    fig.set_size_inches(SIZE[1], SIZE[0])
    fig.subplots_adjust(hspace=0.001)

    ax[0].plot(x, y)
    ax[1].plot(x, y2)
    ax[2].plot(x, y3)
    plt.show()

All subplots have the same height now and the data span in the y-Axis is recognizable as the data is displayed with the correct relative proportion.
What i would like to achieve is that the scales of each plot end where the data ends. Essentially eliminating the not used white space. The size of the subplot would than represent the relative height ratios of the data. They should still have the same scaling on the Y axis in order for the viewer to estimate the relative data height ( which cold be a countrate for example).
I found the following links to  similar problems but none really helped me to solve my issue:
Link1 Link2

A: Here an example that determines the ratio for you and creates the subplots accordingly:
import matplotlib.pyplot as plt
from matplotlib import gridspec
import numpy as np

SIZE = (12, 8) #desired overall figure size

# Simple data to display in various forms
x = np.linspace(0, 2 * np.pi, 400)

# the maximum multiplier for the function
N = 3

# the y-ranges:
ys = [i * np.sin(x**2) for i in range(1,N+1)]

# the maximum extent of the plot in y-direction (cast as int)
hs = [int(np.ceil(np.max(np.abs(y)))) for y in ys]

# determining the size of the GridSpec:
gs_size = np.sum(hs)
gs = gridspec.GridSpec(gs_size,1)

# the figure
fig = plt.figure(figsize = SIZE)

# creating the subplots
base = 0
ax = []
for y,h in zip(ys,hs):
    ax.append(fig.add_subplot(gs[base:h+base,:]))
    base += h
    ax[-1].plot(x,y)

##fig, ax = plt.subplots(3,ncols=1, sharex=True, sharey=True)
##fig.set_size_inches(SIZE[1], SIZE[0])
fig.subplots_adjust(hspace=0.001)

##ax[0].plot(x, ys[0])
##ax[1].plot(x, ys[1])
##ax[2].plot(x, ys[2])
plt.show()

The code determines the maximum y-extend for each set of data, casts it into an integer and then divides the figure into subplots using the sum of these extends as scale for the GridSpec.
The resulting figure looks like this:

Tested on Python 3.5
EDIT:
If the maximum and minimum extents of your data are not comparable, it may be better to change the way hs is calculated into
hs = [int(np.ceil(np.max(y))) - int(np.floor(np.min(y))) for y in ys]


text:
Q: Realmente é necessário o "Then" no final do bloco If? O Compilador do Visual Basic .NET parece ignorar a palavra reservada Then, a que fica no final do bloco If.
 If (1 + 1 = 2) Then
      Console.WriteLine("Passou no teste.")
 End If

E agora, sem o Then:
 If (1 + 1 = 2)
      Console.WriteLine("Também passou no teste.")
 End If

Esse foi o resultado no Console:

Passou no teste.
Também passou no teste.

A Keyword Then é realmente necessária no Visual Basic .NET? Ela tem uma função especial ou é algum tipo de "Melhora a leitura de código"?

A: Ele é obrigatório apenas quando vai usar comandos em uma linha, assim ele é o separador. Quando vai executar um bloco de comandos ele é opcional mesmo.
Documentação.
Exemplo de single line:
If x > 0 Then y = 0

Ou mais de um comando em uma linha:
If x > 0 Then y = 0 : z = 0

Bloco de código:
If x > 0
    y = 0
    z = 0
End If

Também funciona igual:
If x > 0 Then
    y = 0
    z = 0
End If

Coloquei no GitHub para referência futura.


text:
Q: Change UIImageView size to match image with AutoLayout I want to change my UIImageView height/width to match the image i choose from photo album and i found a snippet on here that does that.
-(CGRect)frameForImage:(UIImage *)imgs inImageViewAspectFit:(UIImageView *)imagev
{
  float imageRatio = imgs.size.width / imgs.size.height;
  float viewRatio = imagev.frame.size.width / imagev.frame.size.height;
  if(imageRatio < viewRatio)
  {
    float scale = imagev.frame.size.height / imgs.size.height;
    float width = scale * imgs.size.width;
    float topLeftX = (imagev.frame.size.width - width) * 0.5;
    NSLog(@"image after aspect fit: width=%f",width);
    imagev.frame = CGRectMake(topLeftX, 0, width, imagev.frame.size.height);
    return CGRectMake(topLeftX, 0, width, imagev.frame.size.height);
  }
  else
  {
    float scale = imagev.frame.size.width / imgs.size.width;
    float height = scale * imgs.size.height;
    float topLeftY = (imagev.frame.size.height - height) * 0.5;
    NSLog(@"image after aspect fit: height=%f", height);
    imagev.frame = CGRectMake(0, topLeftY, imagev.frame.size.width, height);
    return CGRectMake(0, topLeftY, imagev.frame.size.width, height);
  }
}

The problem is that it changes the UIImageView height/width when i call it from a button
- (IBAction)changeSize:(id)sender
{
  [self frameForImage:image inImageViewAspectFit:self.imageView];
}

But i want it to do that as soon as i choose a image from photo album and this is how i have it set up.
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
  image = [info objectForKey:UIImagePickerControllerOriginalImage];
  [self.imageView setImage:image];
  [self frameForImage:image inImageViewAspectFit:self.imageView];
  [self dismissViewControllerAnimated:YES completion:NULL];
}

A: Here is a Swift class that will help return the correct sizing for an image based on a width or height limit that you choose:
class func returnImageSizeForHeightLimit(heightLimit:CGFloat?, orWidthLimit widthLimit:CGFloat?, forImage theImage:UIImage)->CGSize?{

    if let myHeightLimit = heightLimit {

        let theWidth = (myHeightLimit/theImage.size.height) * theImage.size.width

        return CGSizeMake(theWidth, myHeightLimit)
    }

    if let myWidthLimit = widthLimit {

        let theHeight = (myWidthLimit/theImage.size.width) * theImage.size.height

        return CGSizeMake(myWidthLimit, theHeight)
    }

    return nil
}

A: Auto Layout solution
Since establishing that you're using Auto Layout in your project, I have made a demo app to show you how you could change the image of the image view and adjust the height. Auto Layout will do this for you automatically, but the catch is that the photo you'll be using is coming from the users gallery and so they're likely to be very big and this.
So check out the app: https://bitbucket.org/danielphillips/auto-layout-imageview
The trick is to create a reference of the NSLayoutConstraint of the height of the image view. When you change your image, you need to adjust it's constant to the correct height given the fixed width.
Your other solution could be to set a contentMode on your image view, by using UIViewContentModeScaleAspectFit your image will always appear in full but will be locked to the bounds of the image view, which can change based on the Auto Layout constraints you have.
Initial reply
It looks like you've really over complicated this, unless I've missed something.
When you get a new image from the image picker, all you need to do is change the frame of the image view according to the UIImage size.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
  image = [info objectForKey:UIImagePickerControllerOriginalImage];
  [self.imageView setImage:image];
  self.imageView.frame = CGRectMake(self.imageView.frame.origin.x
                                    self.imageView.frame.origin.y
                                    image.size.width
                                    image.size.height);
  [self dismissViewControllerAnimated:YES completion:NULL];
}

Of course this is going to be potentially very large (it's using the original image which may be very large).
So let's lock the width to 280 points... this way we can always have the full image on screen in portrait mode.
So assuming your image size is 1000x800, and our image view perhaps is 280x100. We can calculate the correct height for the image view retaining the image view's width like this:
CGSize imageSize        = CGSizeMake(1000.0, 800.0);
CGSize imageViewSize    = CGSizeMake(280.0, 100.0);

CGFloat correctImageViewHeight = (imageViewSize.width / imageSize.width) * imageSize.height;

self.imageView.frame = CGRectMake(  self.imageView.frame.origin.x,
                                    self.imageView.frame.origin.x,
                                    CGRectGetWidth(self.imageView.bounds),
                                    correctImageViewHeight);


text:
Q: Code is written to support multiple arguments, but fails when only one argument is given. sys.argv[1] + sys.argv[2] My current code uses a variable "word", so word = sys.argv[1] + sys.argv[2], which works great when I have two arguments, but when I only have one argument then i get IndexError: list index out of range
I am writing a program that Defines words by pulling the info from dictionary .com. I am following very closely a video tutorial because I am just trying to learn how to get a basic dictionary to work, (long term goal being write a translation app that is independent of google translate api or anything like that). I have a code that works in that it pulls the definition when you type in the word, but not when you type in 2 words, examples will be below. SO I added an argument, which worked for 2 words but no longer works for one word.
import requests
from bs4 import BeautifulSoup as bs
import sys

url = "https://www.dictionary.com/browse/"

word = sys.argv[1] + sys.argv[2]

url+= word
r = requests.get(url)
soup = bs(r.content, "lxml")

try:
    pos = soup.findAll("span", {"class" : "luna-pos"})[0].text #luna-pos is an html tag
    definitions = soup.findAll("ol")
    meanings = definitions[0].findChildren("li", recursive=False)
    print(word + ": " + pos)
    for (i,meaning) in enumerate(meanings):
        print(str(i + 1), meaning.text)
except:
     print("Word not found")

Expected results:
Print word, part of speech, and definition.
I.e Define the word (being a single argument) "Proper"
Also Define "Self Control" (two word argument)

A: Slicing:
You can use list slicing to avoid the error:
word = ''.join(sys.argv[1:]  # joins 1st to last ..

or
word = ''.join(sys.argv[1:3]  # 1st and 2nd without error

List slicing works even if the slice index is larger then the amount of elements in the list.

Testing:
The other way to handle it would be to test first then append:
if len(sys.argv) == 2:
    word = sys.argv[1]
elif len(sys.argv) >= 3:
    word = sys.argv[1]+sys.argv[2]
else:
    word = "" # no input given

Error handling:
Try it and handle the error if it happens (see Ask forgiveness not permission below)
try:
    word = sys.argv[1]+sys.argv[2]
except IndexError:
    word = sys.argv[1]

Readup:

*

*Understanding Python's slice notation

*len() check

*"Ask forgiveness not permission" - explain

*try: except:

A: This is a good use-case for slicing. You want everything after the first argument in the list, so as a slice this translates to [1:]. So just use:
word = ''.join(sys.argv[1:])

For example:
>>> args = ['scriptname.py', 'the']
>>> ''.join(args[1:])
'the'
>>> args = ['scriptname.py', 'self', 'control']
>>> ''.join(args[1:])
'selfcontrol'


text:
Q: Cucumber JS: How to export/update global variable outside Given/When/Then step? I try to update/export global variable (firstString) to use and validate it in 'Then' step.
How do I export it correctly? When I'm doing it this way, the firstString is undefined.
It works only when I export/import it inside steps. How can I update it globally and use it in 'Then' file?
helpers.js:
let firstString;

given.js:
let { firstString } = require('./helpers')

Given('I have first {string}', function (stringValue) {
    return stringRequest(stringValue).then(response => {
        firstString = response
    });
});

module.exports = { firstString }

then.js:
firstString = require('./helpers').firstString
Then('blablabla {string}', function (stringType) {
    console.log(firstString)
});

A: If I am correct in understanding what you want to do you are wanting to store data across steps. Todo that you will want to use the world instance that cucumber provides for you. You can access the world instance in steps via the this keyword.
So what you would do is
Given('I have first {string}', function (stringValue) {
return stringRequest(stringValue).then(response => {
    this.firstString = response
});

});
Then('blablabla {string}', function (stringType) {
    console.log(this.firstString)
});

For more information on the world instance check out https://github.com/cucumber/cucumber-js/blob/master/docs/support_files/world.md


text:
Q: java.lang.NullPointerException error in Android I am new to android, i am trying to retrieve data from mysql database to android text field.when i add the below line to my java file
JSONObject json = jsonParser.makeHttpRequest(
                url_product_detials, "GET", params);

it shows the error. if i remove the above  (jsonParser.makeHttpRequest) line it works fine. the error i got in log files are,
01-02 11:16:50.418: W/System.err(968):  ... 17 more
01-02 11:16:50.418: E/Buffer Error(968): Error converting result java.lang.NullPointerException
01-02 11:16:50.418: E/JSON Parser(968): Error parsing data org.json.JSONException: End of input at character 0 of
01-02 11:16:50.428: D/AndroidRuntime(968): Shutting down VM
01-02 11:16:50.428: W/dalvikvm(968): threadid=1: thread exiting with uncaught exception (group=0x40015560)
01-02 11:16:50.428: E/AndroidRuntime(968): FATAL EXCEPTION: main
01-02 11:16:50.428: E/AndroidRuntime(968): java.lang.NullPointerException
01-02 11:16:50.428: E/AndroidRuntime(968):  at com.example.matrixarc.Syl$GetProductDetails$1.run(Syl.java:153)
01-02 11:16:50.428: E/AndroidRuntime(968):  at android.os.Handler.handleCallback(Handler.java:587)
01-02 11:16:50.428: E/AndroidRuntime(968):  at android.os.Handler.dispatchMessage(Handler.java:92)
01-02 11:16:50.428: E/AndroidRuntime(968):  at android.os.Looper.loop(Looper.java:130)
01-02 11:16:50.428: E/AndroidRuntime(968):  at android.app.ActivityThread.main(ActivityThread.java:3683)
01-02 11:16:50.428: E/AndroidRuntime(968):  at java.lang.reflect.Method.invokeNative(Native Method)
01-02 11:16:50.428: E/AndroidRuntime(968):  at java.lang.reflect.Method.invoke(Method.java:507)
01-02 11:16:50.428: E/AndroidRuntime(968):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-02 11:16:50.428: E/AndroidRuntime(968):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-02 11:16:50.428: E/AndroidRuntime(968):  at dalvik.system.NativeStart.main(Native Method)
01-02 11:16:52.808: I/Process(968): Sending signal. PID: 968 SIG: 9

I  have initialized url_product_detials as
private static final String url_product_detials = "http://localhost/connection/ggg.php";

A: In android localhost stands for the device/emulator . If you want to connect to your computer/local machine use IP 10.0.2.2
Change private static final String url_product_detials = "http://localhost/connection/ggg.php";
to private static final String url_product_detials = "http://10.0.2.2/connection/ggg.php";


text:
Q: Django + postgreSQL. user specific table I am currently working on a Django based service that will gather users' data from their Shopify shops and provide some insights. I use PostgreSQL as my DB server. The problem I am facing is whether it is more efficient to create a separate table for every particular user and store their data there or rather keep everything in one big table. Approximate data length - about 100k-1mln rows per user. Data is unrelated among users. Furthermore, I will need to store the user-specific results of my analysis. Any thoughts?

A: I suggest you have one big table (Table1) for the data of all users (one column would indicate which user it belongs to).
For example, to store all the pages a user visited on one of your sites, you could use something like this:
Table1
    pk   # maybe automatic id
    user_id
    datetime
    page_url
    query_string
    some_session_data

If Table1 gets too big (like you indicated that it may happen), you could create periodical backups with date ranges (maybe one backup file with data from a single month of Table1 rows) and later delete the older data from Table1.
backup_table1_2018_01.sql
backup_table1_2018_02.sql
backup_table1_2018_03.sql

Furthermore, you could have a second table (Table2) that stores results of analysing the data from Table1. Table2 would also have a column indicating which user it belongs to, and maybe even another column which indicates what date range it belongs to.
Continuing with the example, you could create a ranking to see the most visited page for each user in a single month:
Table2
    pk   # maybe automatic id
    user_id
    year
    month
    page_url
    number_of_visits

After calculating the results for Table2 you could remove the rows from Table1 to save some space.

This may be a silly/simple example, but I think it could be a valid approach for large amount of data. I hope it gives you some pointers to think about.

A: @Gleb: you commented on my other answer:

But may we consider a more specific example: I have a user table which stores all user-related data, from every user I gather additional data to analyse (transactions). So I was thinking of creating a new table for every user and store there transactions data, the name of the table will be stored in table1 (where I keep info about my users) to locate it when needed. Should I keep transactions of all users in one table?

So here goes a more concrete example.

For starters, you have your User model (maybe even djangos default table) where you store attributes like names and email.
from django.contrib.auth.models import User

Second, you have transactions (I made up a few basic fields):
class Transaction(models.Model):
    # default AutoField as pk
    datetime = models.DateTimeField()
    user_from = models.ForeignKey(User, related_name='transactions_from')
    user_to = models.ForeignKey(User, related_name='transactions_to')
    amount = models.IntegerField()

And third, you could have a monthly summary of transactions to sum up the received and sent amounts of each user:
class Summary(models.Model):
    # default AutoField as pk
    user = models.ForeignKey(User)
    year = models.IntegerField()
    month = models.IntegerField()
    amount_sent = models.IntegerField()
    amount_received = models.IntegerField()

Now, the Transaction model will have a lot of records (you say it could have millions per user), but the Summary model will only have one record per month per user, which is quite manageable.
Still, I don't recommend using a separate model/table of transactions for each user.
Once a month you could run a process that calculates the summaries for each user (or any other data analysis you wish to run) if you don't wish to update the Summary model instance each time a new transaction is made.
Afterwards you are free to archive the old Transactions (maybe everything older than 3 months or a year).
Once a month you could run a process to export a given set of Transaction instances to a file (CSV, JSON or a SQL dump) and remove them from the Transaction model to keep the size of the table from expanding to much. You could obtain backup files per month for easier lookup if you ever need the Transaction data again:
backup_transaction_2018_01.sql
backup_transaction_2018_02.sql
backup_transaction_2018_03.sql

I hope this gives you a few ideas to think about.


text:
Q: android -How to know if sms sent for my application I've a registration form in my application , when a user complete this form , a verification sms will be sent to his phone number .
How can I know if this sms has been sent for my application ? For example, When you log in with whatsapp , it'll send a sms and when sms arrives ,it get the activation code from the message and automatically active the the app .
How can I do so ?
thanks


text:
Q: Change the way gdb displays uninitialized data I'm debugging a program that declares an array with 1024 elements and it's not initialized until much later.  Every time I use "info locals" it shows me this really long list of uninitialized data.  Is there any way to change the way that gdb presents uninitialized variables?  Something along the lines of lot_data[1024]=UNINITIALIZED.

A:
Is there any way to change the way that gdb presents uninitialized variables?

No.
GDB doesn't know whether a memory location has been assigned or not. To GDB it's just bits, and it can't display bits differently depending on where their value came from (which it doesn't know).
P.S. Actually tracking the state of bits is possible with instrumentation (clang -fsanitize=memory -fsanitize-memory-track-origins ...), but is a fairly expensive thing to do.
Also consider that memory can remain uninitialized despite being assigned:
int buf[5];                     // uninitialized memory declared
int k = buf[0];                 // k is still uninitialized

int *ip = malloc(sizeof(buf));  // uninitialized memory created
memcpy(buf, ip, sizeof(buf));   // buf is still uninitialized, despite being written to
int j = buf[0];                 // j is still uninitialized


text:
Q: Modifying data representation in Qt model/view I am using Qt 5.4.2 and I have trouble in trying to find out, how to change data "representation" when populating a view from model. I have a QSqlTableModel to hold the database data and a QTableView that is displaying the contents of the database.
Now some of the data in the database is in a different format than what I would like to show in the View. For example I would like to show date formats differently, but I don't know where/how to implement such logic. I don't want the model to be affected in any way, only the data shown in the view.

A: You should implement a custom delegate for the specific column and set it manually. Simply implement a class derived from QStyledItemDelegate like :
#include <QItemDelegate>
#include <QDateTimeEdit>

class DateTimeEditDelegate: public QStyledItemDelegate
{
 Q_OBJECT
public:
    DateTimeEditDelegate(QObject *parent = 0);

    void *paint( QPainter *painter,
                            const QStyleOptionViewItem &option,
                            const QModelIndex &index ) const;

    QWidget *createEditor( QWidget *parent,
                            const QStyleOptionViewItem &option,
                            const QModelIndex &index ) const;

    void setEditorData( QWidget *editor,
                            const QModelIndex &index ) const;

    void setModelData( QWidget *editor,
                            QAbstractItemModel *model,
                            const QModelIndex &index ) const;

    void updateEditorGeometry( QWidget *editor,
                            const QStyleOptionViewItem &option,
                            const QModelIndex &index ) const;

    mutable QDateTimeEdit *dataTimeEdit;

private slots:

    void setData(QDateTime val);

};

DateTimeEditDelegate::DateTimeEditDelegate(QObject *parent ):QStyledItemDelegate(parent)
{

}

void*DateTimeEditDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QDateTime dateTime = index.model()->data( index, Qt::DisplayRole ).toDateTime();
    painter->drawText(option.rect().topLeft(), dateTime.toString());
    return;
}

QWidget *DateTimeEditDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    dataTimeEdit = new QDateTimeEdit( parent );
    QObject::connect(dataTimeEdit,SIGNAL(dateTimeChanged(QDateTime)),this,SLOT(setData(QDateTime)));
    return dataTimeEdit;
}

void DateTimeEditDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    QVariant dateTime = index.model()->data( index, Qt::DisplayRole );

    (static_cast<QDateTimeEdit*>( editor ))->setDateTime(dateTime.toDateTime());
}

void DateTimeEditDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    model->setData( index, static_cast<QDateTimeEdit*>( editor )->dateTime() );
}

void DateTimeEditDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    editor->setGeometry( option.rect );
}

void DateTimeEditDelegate::setData(QDateTime val)
{
    emit commitData(dataTimeEdit);
}

And finally set an instance of the delegate to a column:
ui->tableView->setItemDelegateForColumn(0, new DateTimeEditDelegate(ui->tableView));

It's just a sample for a delegate which implements custom data representation along custom data editing. You should implement you own based on your needs.


text:
Q: LIKE vs CONTAINS on SQL Server Which one of the following queries is faster (LIKE vs CONTAINS)?
SELECT * FROM table WHERE Column LIKE '%test%';

or
SELECT * FROM table WHERE Contains(Column, "test");

A: I think that CONTAINS took longer and used Merge because you had a dash("-") in your query adventure-works.com.
The dash is a break word so the CONTAINS searched the full-text index for adventure and than it searched for works.com and merged the results.

A: Also try changing from this:
    SELECT * FROM table WHERE Contains(Column, "test") > 0;

To this:
    SELECT * FROM table WHERE Contains(Column, '"*test*"') > 0;

The former will find records with values like "this is a test" and "a test-case is the plan".
The latter will also find records with values like "i am testing this" and "this is the greatest".

A: The second (assuming you means CONTAINS, and actually put it in a valid query) should be faster, because it can use some form of index (in this case, a full text index). Of course, this form of query is only available if the column is in a full text index. If it isn't, then only the first form is available.
The first query, using LIKE, will be unable to use an index, since it starts with a wildcard, so will always require a full table scan.

The CONTAINS query should be:
SELECT * FROM table WHERE CONTAINS(Column, 'test');

A: Having run both queries on a SQL Server 2012 instance, I can confirm the first query was fastest in my case.
The query with the LIKE keyword showed a clustered index scan.
The CONTAINS also had a clustered index scan with additional operators for the full text match and a merge join.

A: I didn't understand actually what is going on with "Contains" keyword. I set a full text index on a column. I run some queries on the table.
Like returns 450.518 rows but contains not and like's result is correct
SELECT COL FROM TBL WHERE COL LIKE '%41%'  --450.518 rows
SELECT COL FROM TBL WHERE CONTAINS(COL,N'41')  ---40 rows
SELECT COL FROM TBL WHERE CONTAINS(COL,N'"*41*"') -- 220.364 rows


text:
Q: android.support.v4.view.ViewPager does not disallow child scrolling in android 2.2? i have my app with android support v4 using ViewPager, one of my views has a HorizontalScrollView inside a page, in 4.0 up it can scroll normally but running 2.2 the ViewPager is moving onto next.
Any suggestion?

A: Maybe you can try this:
public class CustomViewPager extends ViewPager {

public CustomViewPager(Context context) {
    super(context);
}

public CustomViewPager(Context context, AttributeSet attrs) {
    super(context, attrs);
}

@Override
protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) {
    if(v instanceof HorizontalScrollView){
        return true;
    }
    return super.canScroll(v, checkV, dx, x, y);
}

}

Explanation:
This will tell the viewpager that if the view in the one you scrolled is a horizontal list view, then he needs to ignore the scroll and leave the horizontal scroll to "handle it", BUT you need to have in mind that any scroll (horizontal scroll) outside the horizontal scroll view will make your viewpager to change page, ALSO that if you scroll from the exterior to the inside (your finger outside the tablet and coming in) the viewpager will ignore this behavior and will move the page.


text:
Q: Python library to aggregate git user contributions from disparate repos Is there a python library/widget that aggregates one's contributions over heterogeneous version control systems (e.g. GitHub, Bitbucket, local git repos, etc.), and creates a calendar heatmap (in the style of the GitHub profile contribution heatmap) of one's total git contributions?
I know there are several front ends available for these heatmaps:
https://github.com/DKirwan/calendar-heatmap
https://github.com/wa0x6e/cal-heatmap
But my intuition tells me there probably already exists a library to aggregate statistics/information about many git repos. And that I just haven't had any luck finding it.
Otherwise I imagine the easiest way to do this would be by querying the vcs hosting websites' apis for user contributions, and registering local repos to gather the relevant data, and piping that to the heatmap.


text:
Q: Disable Software Updater Notification? I run apt update and upgrade every week, yet I keep getting a nag screen from the software updater. How do I disable this notification?
Or does apt not update and upgrade everything installed on my system?

A: apt remove packagekit
This one line should do the trick:
$ sudo apt remove packagekit

Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages were automatically installed and are no longer required:
  appstream apt-config-icons fwupd fwupd-amd64-signed gnome-software-common irqbalance libappstream-glib8 libappstream4 libfwupd2
  libgcab-1.0-0 libsmbios-c2 libtss2-esys0 libtss2-udev libxmlb1 runit-helper tpm2-abrmd tpm2-tools
Use 'sudo apt autoremove' to remove them.
The following packages will be REMOVED:
  gnome-core* gnome-software* gstreamer1.0-packagekit* packagekit* packagekit-tools* task-gnome-desktop*
0 upgraded, 0 newly installed, 6 to remove and 2 not upgraded.
After this operation, 5,788 kB disk space will be freed.
Do you want to continue? [Y/n] y

That is all you need.
Discussion
If you're getting annoying software update nag messages, most likely you have Gnome installed. Gnome has its own special utility for installing packages (gnome-software) and its own package management system (packagekit). I've found Gnome's package tools vastly inferior to the traditional apt update && apt upgrade, but I can see how the graphical interface might make someone new to UNIX feel more comfortable. (Plus, some people are used to being nagged and told to do things: *"Updates available." "Now, you must reboot your computer for no good reason." "Updates available." "Busy doing work? You have to reboot to install these updates." "Updates available...")
However, since you stated that you use command line apt, there's really no reason for you to have packagekit running at all.
Ľubuntu, la différence
Lubuntu (the LXQt Desktop version of Ubuntu) used to not have this problem, but it now comes with packagekit pre-installed, the same as the default GNOME Desktop. Well, almost the same. According to @Juergen in the comments, Lubuntu maintains its distinction from standard Ubuntu in that it requires a different command to disable the silliness:
 sudo apt remove lubuntu-update-notifier

Unattended upgrades
I suggest also installing unattended-upgrades:
apt install unattended-upgrades

This will download and install security upgrades every night. (Or, you can configure it to install all upgrades.) This is important because, without PackageKit, you will no longer have "Automatic Updates" running. In fact, you won't have Gnome Update Manager at all.
A bit more about packagekit
By the way, technically, packagekit is a "meta" layer which sits atop other package managers, such as rpm. Theoretically, it could offer everything apt does and more, but in reality it appears limited to the lowest-common denominator; the least you can find in any package management system. Hopefully it will get better, but as of 2021, it is seriously deficient.
The main reason I used to give to people for using PackageKit was the easy graphical interface for finding programs. Unfortunately, the Gnome Software search function often omits many packages. I know they are available, because I can easily apt search and apt install them from the command line.

A: I assume that you opened the program "Software & Updates", looked at the Updates tab, and choose "Never" for "Automatically check for updates"?  This cut the frequency down for me, but I also had to disable the apt daily services:
In a terminal enter the commands
sudo systemctl disable apt-daily.service apt-daily-upgrade.service
sudo systemctl disable apt-daily.timer apt-daily-upgrade.timer
sudo systemctl stop apt-daily.timer apt-daily-upgrade.timer

Your manual updates (sudo apt update & sudo apt upgrade) will work as normal, but the apt system will not automatically look about for new updates.

A: apt update updates your software repository lists (so your system knows what software is available).
apt upgrade upgrades packages from that list within certain limitations, so NO it doesn't upgrade all packages. It allows you to delay reboots etc. until you decide to allow the upgrades that may force changes affecting the stability of currently running software/system, allowing you to choose when these are applied using apt full-upgrade
from man apt

   upgrade (apt-get(8))
       upgrade is used to install available upgrades of all packages currently installed on
       the system from the sources configured via sources.list(5). New packages will be
       installed if required to statisfy dependencies, but existing packages will never be
       removed. If an upgrade for a package requires the remove of an installed package the
       upgrade for this package isn't performed.

   full-upgrade (apt-get(8))
       full-upgrade performs the function of upgrade but will remove currently installed
       packages if this is needed to upgrade the system as a whole.

Charles Green's answer covers the nag screens, I've chosen to cover only the 'upgrade' part of your question.


text:
Q: add two digit numbers in NASM(Linux) I want to add two-digit numbers in NASM(Linux). To add two simple numbers, I use the following code:
section .text
    global _start    ;must be declared for using gcc
_start:    ;tell linker entry point
    mov     eax,'3'
    sub     eax, '0'
    mov     ebx, '4'
    sub     ebx, '0'
    add     eax, ebx
    add eax, '0'
    mov     [sum], eax
    mov ecx,msg
    mov edx, len
    mov ebx,1   ;file descriptor (stdout)
    mov eax,4   ;system call number (sys_write)
    int 0x80    ;call kernel
    mov ecx,sum
    mov edx, 1
    mov ebx,1   ;file descriptor (stdout)
    mov eax,4   ;system call number (sys_write)
    int 0x80    ;call kernel
    mov eax,1   ;system call number (sys_exit)
    int 0x80    ;call kernel

section .data
    msg db "The sum is:", 0xA,0xD
    len equ $ - msg
    segment .bss
    sum resb 1

The result of the code is 7.But when I carry number 17 in register eax forexample the result is not correct.In this case 5.Tell me please what is the problem? Thank you!

A: Here's your example with a little bit of cleaning up to help make it easier to read.
Suggestion: this kind of consistency will greatly improve your public image.
But hey; nice commenting, I could read your code and understand it (which is why I decided to answer you)
section .text

global _start               ;must be declared for using gcc

_start:                     ;tell linker entry point

    mov     eax, '3'
    sub     eax, '0'
    mov     ebx, '4'
    sub     ebx, '0'
    add     eax, ebx
    add     eax, '0'

    mov     [sum], eax

    mov     ecx, msg
    mov     edx, len
    mov     ebx, 1          ;file descriptor (stdout)
    mov     eax, 4          ;system call number (sys_write)
    int     0x80            ;call kernel

    mov     ecx, sum

    mov     edx, 1
    mov     ebx, 1          ;file descriptor (stdout)
    mov     eax, 4          ;system call number (sys_write)
    int     0x80            ;call kernel

    mov     eax, 1          ;system call number (sys_exit)
    int     0x80            ;call kernel

section .data

    msg     db              "The sum is:", 0xA,0xD

    len equ $ - msg

    segment .bss

    sum resb 1

Okay now, as for your comment, "...But when I carry number 17 in register eax forexample the result is not correct."
I can imagine !
Question, when you "...carry number 17 in register eax..." are you doing it like this ?...
    Mov     Eax,"17"

If so, slow down and take a look at your code one step at a time via debug.
I believe that what you'll see is that you are actually doing this...
    Mov     Eax, 3137h

Although it might be
    Mov     Eax, 3731h

Interesting concept. I've never done anything like that. Whatever.
What's more, if you are using this place to store that same number...
    sum resb 1

You only have one byte.
Best I can tell, your example code is limited to single digit numbers.
Now then, since your label sum has reserved only one byte; 8 bits, you can see the problem as you are storing 32 bits there. (Well, you're trying to; it won't work.) No clue what happens when you do that. You probably want to rethink that structure.
As for why 17 becomes 5, no clue here.
Let us know if any of this helps you. Assembly is great stuff. As you are personally experiencing, the initial thought adjustment can be strange for the brain, can't it !


text:
Q: How to calculate spot size of a laser focused through a microscope objective? I am trying to figure out how to approximate the spot size of a laser beam that is focused using a microscope objective where the size of the laser beam is smaller than the diameter of the objective.  I have tried googling and reading various other questions online but still haven't been able to cobble a coherent plan together.  From this excellent response I've been able to cobble together an understanding that the working distance and the focal length of a lens are different.  But I'm still at sea as to how I convert the information I'm given about an objective, e.g. magnification, NA and focal length to spot size.  Would it be sufficient to simply treat an objective as a simple optic with the focal length given by the manufacturer and then use something like this spot size calculator to figure out the focused size?  If not, would someone mind walking me through the steps to approximate (doesn't need to be exact, back of an envelope is great) spot size for a $5 \;\text{mm}$ well-collimated beam that is focused using this objective?

A: The spot size calculator is just what you need. Assuming your laser has a TEM$00$ Gaussian beam (the most common and desirable beam cross section), the math behind it is very simple. $w = 4\lambda f/\pi D$.
The calculator gives the spot diameter assuming your optics are perfect. A lens as expensive as the one you picked should be pretty good. You might investigate cheaper alternatives. You only need one wavelength. Is that lens optimized over the visible wavelengths? You don't need to worry about off axis aberrations. Spherical aberration is your primary concern.
See Cross-sectional area of a Gaussian beam of particles for more about the nature of Gaussian beams. There is a discussion of lasers.
Also see Best collimation at focal point of lens?.

A: "From Fundamentals of Photonics" by Saleh and Teich

We have an (ideal) lens of focal length $f$ and we are sending in a Gaussian beam with waist $W_0$ (Rayleigh range $z_0$) which is focused distance $z$ in front of the lens. The lens refocuses the beam distance $z'$ from the lens with waist size $W_0'$.
The textbook derives the following:
\begin{align}
W_0' =& M W_0\\
(z'-f) =& M^2(z-f)\\
M =& \frac{M_r}{(1+r^2)^{\frac{1}{2}}}\\
M_r =& \left|\frac{f}{z-f}\right|\\
r =& \frac{z_0}{z-f}
\end{align}
These expressions are not very illuminating in my opinion but we can consider two limiting cases. The first is that $z-f \gg z_0$ which says that the focus of the beam is like a point source and the equipotential lines of the gaussian beam can be treated as rays. In this case $r\ll 1$ so $M=M_r$ and this is in fact the usual ray-optics result for magnification.
The other limit, which is perhaps of more interest to you, is the opposite case in which the lens is in the Rayleigh range of the incident beam and the Rayleigh range is longer than the focal length, that is, $z_0 \gg f, z$. This is what we might call a "collimated" Gaussian beam because for the entire important space having to do with the lens the Gaussian beam keeps essentially the same radius. In this case, $r\gg 1$ so that
$$
M \rightarrow \frac{f}{z_0}
$$
Ignoring negative signs which leads to the well known and useful formula:
\begin{align}
W_0' =& \frac{\lambda f}{\pi W_0}\\
z' =& f
\end{align}
That is if you have a collimated beam of waist $W_0$ impinging on a lens with focal length $f$ you can easily calculate the resultant waist using the formula just above.
Regarding some of your other questions, if your beam is collimated then the formula I've given will work if you use only the given focal length for the lens (note that the spot size depends on the size of the beam you send in). The focus will appear distance $f$ away from the front focal plane of the lens.

*

*Note that the front focal plane is not necessarily located at the frontmost surface of the objective. This explains the difference between focal length and working distance.

*The magnification of the objective is a pretty useless parameter when thinking about the objective as a standalone optic. The magnification is defined as follows. Suppose you use the objective to collimate the light from a sample. Then you place a tube lens downstream of the objective to refocus the light and create an image. This image will have a magnification given by the ratio of the focal lengths of the objective and the tube lens. This means the magnification varies depending on the tube lens focal length.. so what tube lens focal length should you use? Different suppliers use different conventional tube lengths in their microscopes thus determining magnification when certain objectives are used. See https://www.thorlabs.com/newgrouppage9.cfm?objectgroup_id=10764. Apparently, 200 mm is a common focal length. So if your objective has a focal length of $f=4mm$ it would be described as a $50x$ objective. You could of course change the magnification by changing the tube lens. For this reason (as someone who builds imaging systems from scratch more often than using commercial microscopes) I feel the magnification is a pretty silly parameter for objectives.

*Finally Numerical Aperature. NA will not help you with this problem. NA is a subtle specification for an objective in my opinion. If you have an object distance $d$ away from an objective which has a radius $R$ you might guess that the NA is given by $NA \approx \sin\left(\arctan\left(\frac{r}{d}\right)\right)$. But then the NA would depend on the distance between the object and the lens and you could make it arbitrarily close to unity (maximal in free space) by moving the object closer and closer. Do you get better resolution in this way by increasing the NA? No! This is not how NA is specified at all for optics. Rather, you should think of NA not as the maximal collection angle for an objective but rather the maximal non-aberrated collection angle. You can always decrease the NA of an optic by placing an aperture stop. When the NA of an objective is specified this means that if the objective is used as specified (meaning with proper working distance, for example) then if you use the NA corresponding to the specced NA then aberrations will be negligible, the objective will be diffraction limited. You can reduce the NA by hand and worsen your resolution. If you can increase the NA (some objectives may have an aperture stop built into them to avoid this) you will not get an increase in resolution because you will introduce aberrations into the system due to the introduction of the ray with very large angles that are hard to pass through the imaging system without aberration.


text:
Q: Symbol/Motorola Scanner SDK BarcodeEvent Randomly Removes EventHandler I am using the Symbol/Motorola Scanner SDK with an LS3578 Scanner connected in IBM HID through USB.  The scanner works as intended on this program and several others that I have written.  My problem is that people need to leave this particular application open (so they don't have to login all the time) and after approximately five minutes the program will lose the EventHandler to capture the Barcode Scans.
I have made a work-around by allowing the scanner to be setup again (subscribe to the EventHandler) after 5 minutes but its not something I really want to release into production.
I have tried timers to perform the setup automatically and everything else I can think of to get this to at least appear as though it is staying connected and all events are intact.  Any suggestions for counting the events linked to BarcodeEvent or just keeping the event from being lost would be greatly appreciated.
Thanks!

A: Answering this myself as I found the error and it was all mine.  I was declaring the CCoreScanner (the scanner object) in a separate class which, I assume, was causing the scanner object to be Garbage Collected between 3.5 and 5 minutes after the program was opened.  I moved the scanner object and associated code into the code-behind for the form and this seems to have solved the problem.
Good luck to anyone else experiencing this issue; hope my mistakes/lack-of-knowledge can help you save some time with your debugging.


text:
Q: Vuetify: v-ripple can only be used on block-level elements I just started getting this error today, and it broke my whole site (because like a fool I'm loading Vuetify on page load).
Does anyone know what this means or how to fix it? Googling around didn't reveal anything helpful.
Edit:
To anyone who finds this because their site is also broken, it may be because of where you were loading vuetify.min.css from. For me I was getting at page load like so:
<link href="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.min.css" rel="stylesheet">

And solved the problem by importing it from the installed package instead with
import 'vuetify/dist/vuetify.min.css'

in app.js.
I'm still interested in learning about this v-ripple business, though.

A: I got into the same problem and I solved by installing

material-design-icons-iconfont

Run the following command to install:
npm install material-design-icons-iconfont

or, if you are running from yarn then:
yarn add material-design-icons-iconfont

Now import in main.js file:
import 'vuetify/dist/vuetify.min.css'
import 'material-design-icons-iconfont/dist/material-design-icons.css'

You can read the vuetify documentation for more information:
Vuetify Documentation

A: I ran into this same issue today and started going down the route of importing it as  suggested above when I noticed the header:
@charset "UTF-8";
/*!
* Vuetify v2.0.0-alpha.14
* Forged by John Leider
* Released under the MIT License.

It looks like they bumped the dist version (I'm working with 1.5.12). I updated my link href to:
https://cdn.jsdelivr.net/npm/vuetify@1.5.12/dist/vuetify.min.css

...and my site was put back together again. It's probably better practice to bring it in as a module but that'll be something for the backlog. Hope this helps somebody.

A: For me, the problem was I had both tslint and eslint installed. After I disabled eslint, it worked.


text:
Q: avro runtime exception not a map when return in Json format i have a avro schema for UKRecord, which contain a list of CMRecord(also avro schemaed):
{
    "namespace": "com.uhdyi.hi.avro",
    "type": "record",
    "name": "UKRecord",
    "fields": [
        {
            "name": "coupon",
            "type": [
                "null",
                "string"
            ],
            "default": null
        },
        {
            "name": "cm",
            "type": [
                "null",
                {
                    "type": "array",
                    "items": {
                        "type": "record",
                        "name": "CmRecord",
                        "fields": [
                            {
                                "name": "id",
                                "type": "string",
                                "default": ""
                            },
                            {
                                "name": "name",
                                "type": "string",
                                "default": ""
                            }
                        ]
                    }
                }
            ],
            "default": null
        }
    ]
}

in my java code, i create a UKRecord which has all fields populated correctly, eventually i need to return this object using a json based api, however it complained:
org.apache.avro.AvroRuntimeException: Not a map: {"type":"record","name":"CmRecord","namespace":"com.uhdyi.hi.avro","fields":[{"name":"id","type":"string","default":""},{"name":"name","type":"string","default":""}]}

the java code that write the object to json is :
ObjectWriter writer = ObjectMapper.writer();
if (obj != null) {
   response.setHeader(HttpHeaders.Names.CONTENT_TYPE, "application/json; charset=UTF-8");
   byte[] bytes = writer.writeValueAsBytes(obj);  <-- failed here
        ...
}

obj is:
{"coupon": "c12345", "cm": [{"id": "1", "name": "name1"}, {"id": "2", "name": "name2"}]}

why do i get this error? please help!

A: Because you are using unions, Avro is uncertain how to interpret the JSON you are providing.  Here's how you can change the JSON so Avro knows it's not null
{
  "coupon": { "string": "c12345" },
  "cm": { "array": [
          { "id": "1", "name": "name1" },
          { "id": "2", "name": "name2" }
        ]
  }
}

I know, it's really annoying how Avro chose to handle nulls.


text:
Q: Java GridBagLayout + Absolute Layout I am trying to make a 3 column layout, in each column i want to be able to absolute position labels and textboxes.
Problem is that my label (jLabel2) never even gets displayed..
Here is my code:
 /**
  * Top JPanel (Top)
  */
 JPanel pnlTop = new JPanel();
 pnlTop.setBackground(new java.awt.Color(223, 223, 217));
 pnlTop.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, new java.awt.Color(173, 173, 166)));
 c.gridx = 0;
 c.gridy = 0;
 c.gridwidth = 5; // five rows
 c.gridheight = 1; // one column
 c.fill = GridBagConstraints.BOTH;
 //c.weighty = 0.04;
 add(pnlTop, c);

 /**
  * Top JPanel Content (Here is where i want to put absolute content)
  */
 JPanel pnlTopContent = new JPanel();
 pnlTopContent.setLayout(null);

 jLabel2.setFont(new java.awt.Font("Lucida Grande", 1, 16)); // NOI18N
 jLabel2.setText("Hello");

 jLabel2.setLocation(150, 50);

 pnlTopContent.add(jLabel2);
 pnlTop.add(pnlTopContent);

Any ideas what i am doing wrong?

A:
Then its showing but not in the right place

What does "right place" mean to you? Why are you even adding you label to a second panel? Why not just add the label directly to the pnlTopContent?
GridBagLayout has a constraint that allows you to position the component right/left/center of the column. Read the section from the Swing tutorial on How to Use GridBagLayout. You might want to start with the anchor constraint.

A: Use layout manager for pnlTopContent. Which one is right depends on what you want. Even the default FlowLayout might work. If you want to center the label, you can for example use FlowLayout with center alignment:
pnlTopContent.setLayout(new FlowLayout(FlowLayout.CENTER));