Looping through Salesforce Accounts

Question: I am a new developer and I have a task I need to complete and I am totally clueless on how to tackle. This is an angular calendar App. And my task in this big project is to simply make it function so that when a user types a field in the search query, it searches against a specific "Agency" and "MasterAgency" accounts instead of searching against All the accounts. So this is an Apex, Angular application. I created a RecordHelper class and here is a snippet below:
public static Set<Id> getAgencyRecordTypeIds(){
        Set<Id> recordTypeIds = new Set<Id>();
        recordTypeIds.add(GetRecordTypeIdByDeveloperName('Account','Agency'));
        recordTypeIds.add(GetRecordTypeIdByDeveloperName('Account','MasterAgency'));

        return recordTypeIds;
    }

Then I created another class so that I can use the remoteAction to pass it on Angular, snippet shown below:
@RemoteAction
    public static Set<Id> passRecordsIds() {
        Set<Id> fetchRecordTypeIds = RecordTypeHelper.getAgencyRecordTypeIds();
        return fetchRecordTypeIds;
    }

Then I used a .vfr method to pass this remoteaction results to Angular. Here is the Angular code for it:
var passRecordsIds = vfr.send('S1_PAV_CalendarController.passRecordsIds', $scope.data.SFSendOpts, false);
            passRecordsIds().then(function(result){
                                        $scope.typeRecord = result;
                                        $log.debug($scope.typeRecord);
                                    }
                                    ,function(error){
                                        $log.error('passRecordsIds error');
                                        $log.error(error);
                                        $window.alert(error.message);
        });

So where I am stuck is that in my Angular code, I need to modify the Query statements so that it searches against the Account and MasterAccount only. I think my query after the AND statement is totally wrong. My boss was saying I need to loop through it but I don't know how to tackle this.
var queryString = $scope.ACCOUNT_SELECT_PART + "  FROM Account WHERE" + " (Name Like '%" + searchTerm + "%' OR Safeco_Sub_Stat__c  Like '%" + searchTerm + "%') AND RecordTypeId IN ('Agency', 'MasterAgency')";

I originally had written
var queryString = $scope.ACCOUNT_SELECT_PART + "  FROM Account WHERE" + " (Name Like '%" + searchTerm + "%' OR Safeco_Sub_Stat__c  Like '%" + searchTerm + "%') AND typeRecord IN :passRecordsIds";

But it didn't work and the boss said it was incorrect and that I needed to include the field name RecordTypeId.
I know I have skipped on a lot of code but these are the modifications I have made. Any help would be greatly appreciated.
Thank you
Comment: rewrite your question with an example of the data (fully blown) you want to fetch and the query you use for. because i don't think someone here understand what you are trying to do
Comment: Hi Sam,  Can you please explain what you mean by "example of data(fully blown)"? I myself am not very familiar with all the accounts, I am just trying to work with the partial code my company has provided me.
Comment: i'm not a salesforce guy but take a look at this question http://stackoverflow.com/questions/21059620/salesforce-apex-query-accounts-based-on-activity-history?rq=1
Answer: I think you need a combination of your two attempts.  Try the code below because I believe the id's of the recordtypes you want are int passRecordIds.
var queryString = $scope.ACCOUNT_SELECT_PART + "  FROM Account WHERE" + " (Name Like '%" + searchTerm + "%' OR Safeco_Sub_Stat__c  Like '%" + searchTerm + "%') AND RecordTypeId IN : passRecordsIds";

Looping through Salesforce Accounts


GCM _ java.lang.RuntimeException: An error occured while executing doInBackground()

Question: I am trying to pick up GCM by following the developer.android.com/google/gcm but have end up with the following error:

11-05 08:12:53.147: E/AndroidRuntime(1873): FATAL EXCEPTION: AsyncTask #1
  11-05 08:12:53.147: E/AndroidRuntime(1873): Process: com.example.gcmtest00, PID: 1873
  11-05 08:12:53.147: E/AndroidRuntime(1873): java.lang.RuntimeException: An error occured while executing doInBackground()
  11-05 08:12:53.147: E/AndroidRuntime(1873):     at android.os.AsyncTask$3.done(AsyncTask.java:300)
  11-05 08:12:53.147: E/AndroidRuntime(1873):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
  11-05 08:12:53.147: E/AndroidRuntime(1873):     at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
  11-05 08:12:53.147: E/AndroidRuntime(1873):     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
  11-05 08:12:53.147: E/AndroidRuntime(1873):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
  11-05 08:12:53.147: E/AndroidRuntime(1873):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
  11-05 08:12:53.147: E/AndroidRuntime(1873):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
  11-05 08:12:53.147: E/AndroidRuntime(1873):     at java.lang.Thread.run(Thread.java:841)
  11-05 08:12:53.147: E/AndroidRuntime(1873): Caused by: java.lang.SecurityException: Not allowed to start service Intent { act=com.google.android.c2dm.intent.REGISTER pkg=com.google.android.gms (has extras) } without permission com.google.android.c2dm.permission.RECEIVE
  11-05 08:12:53.147: E/AndroidRuntime(1873):     at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1503)
  11-05 08:12:53.147: E/AndroidRuntime(1873):     at android.app.ContextImpl.startService(ContextImpl.java:1480)
  11-05 08:12:53.147: E/AndroidRuntime(1873):     at android.content.ContextWrapper.startService(ContextWrapper.java:494)
  11-05 08:12:53.147: E/AndroidRuntime(1873):     at com.google.android.gms.gcm.GoogleCloudMessaging.c(Unknown Source)
  11-05 08:12:53.147: E/AndroidRuntime(1873):     at com.google.android.gms.gcm.GoogleCloudMessaging.register(Unknown Source)
  11-05 08:12:53.147: E/AndroidRuntime(1873):     at com.example.gcmtest00.MainActivity$getRegId.doInBackground(MainActivity.java:53)
  11-05 08:12:53.147: E/AndroidRuntime(1873):     at com.example.gcmtest00.MainActivity$getRegId.doInBackground(MainActivity.java:1)
  11-05 08:12:53.147: E/AndroidRuntime(1873):     at android.os.AsyncTask$2.call(AsyncTask.java:288)
  11-05 08:12:53.147: E/AndroidRuntime(1873):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
  11-05 08:12:53.147: E/AndroidRuntime(1873):     ... 4 more

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.gcmtest00"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="16"
    android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
 <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission android:name="com.example.gcmtest00.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />
<uses-permission android:name="com.example.gcmtest00.permission.C2D_MESSAGE" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <meta-data android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version"/>
    <activity
        android:name="com.example.gcmtest00.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <receiver
        android:name="gcm.GcmBroadcastReceiver"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <category android:name="com.example.gcmtest00" />
        </intent-filter>
    </receiver>
    <service android:name=".GcmMessageHandler" />

</application>

MainActivity.java
package com.example.gcmtest00;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity{

    public static final String EXTRA_MESSAGE = "message";
    public static final String PROPERTY_REG_ID = "registration_id";
    private static final String PROPERTY_APP_VERSION = "appVersion";
    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;

    Button btnRegId;
    TextView etRegId;
    GoogleCloudMessaging gcm=null;
    String regid;
    String SENDER_ID = "186386566618";  //project number
    Context context;
    AtomicInteger msgId = new AtomicInteger();
    SharedPreferences prefs;
    static final String TAG = "GCMDemo";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = getApplicationContext();

        btnRegId = (Button) findViewById(R.id.btnGetRegId);
        etRegId = (TextView) findViewById(R.id.etRegId);

        if (checkPlayServices()) {
            gcm = GoogleCloudMessaging.getInstance(this);
            regid = getRegistrationId(context);
            if (regid.isEmpty()) {
                registerInBackground();
            }
        }else {
            Log.i(TAG, "No valid Google Play Services APK found.");
        }
    }

    private String getRegistrationId(Context context) {
        final SharedPreferences prefs = getGCMPreferences(context);
        String registrationId = prefs.getString(PROPERTY_REG_ID, "");
        if (registrationId.isEmpty()) {
            Log.i(TAG, "Registration not found.");
            return "";
        }

        int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
        int currentVersion = getAppVersion(context);
        if (registeredVersion != currentVersion) {
            Log.i(TAG, "App version changed.");
            return "";
        }
        return registrationId;
    }

    private SharedPreferences getGCMPreferences(Context context) {

        return getSharedPreferences(MainActivity.class.getSimpleName(),
                            Context.MODE_PRIVATE);
    }

    private static int getAppVersion(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager()
                            .getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (NameNotFoundException e) {
            throw new RuntimeException("Could not get package name: " + e);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkPlayServices();
    }

    private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                                    PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Log.i(TAG, "This device is not supported.");
                finish();
            }
            return false;
        }
        return true;
    }

    private void registerInBackground() {
            new AsyncTask<Void, Void, String>(){

            @Override
            protected String doInBackground(Void... params) {
                String msg = "";
                try {
                    if (gcm == null) {
                        gcm = GoogleCloudMessaging.getInstance(context);
                    }
                    regid = gcm.register(SENDER_ID);
                    msg = "Device registered, registration ID=" + regid;

                    sendRegistrationIdToBackend();

                    storeRegistrationId(context, regid);
                } catch (IOException ex) {
                    msg = "Error :" + ex.getMessage();

                }
                return msg;
            }
            @Override
            protected void onPostExecute(String msg) {
                etRegId.append(msg + "\n");
            }
        }.execute();
    }
    private void sendRegistrationIdToBackend() {

    }

    private void storeRegistrationId(Context context, String regId) {
        final SharedPreferences prefs = getGCMPreferences(context);
        int appVersion = getAppVersion(context);
        Log.i(TAG, "Saving regId on app version " + appVersion);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(PROPERTY_REG_ID, regId);
        editor.putInt(PROPERTY_APP_VERSION, appVersion);
        editor.commit();
    }
}

Answer: just add:
<action android:name="com.google.android.c2dm.intent.REGISTRATION" /> within the intent-filter tag of the receiver


How to count the number of objects in a constructor javascript

Question: Im working with javascript and would like to know the number of objects inside of a constructor.
I have this:
var EventData = function(ID, Name, StartDate, StartTime, EndDate, EndTime, Location, Notes){
  this.type = "event";
  this.id = ID;
  this.name = Name;
  this.startDate = StartDate;
  this.startTime = StartTime;
  this.endDate = EndDate;
  this.endTime = EndTime;
  this.location = Location;
  this.notes = Notes;
};
EventData.prototype.count = function(){
  return //some code;
};

And i want to call something like this:
var Start = function(){
  var thisEventData = new EventData(1,"Bill", 1,1,1,1, "Home", "N/A");
  console.log(thisEventData.count());
};

Where thisEventData.count() would return 10.
Comment: "Number of objects inside of a constructor" doesn't make a lot of sense. You can count the enumerable properties of an object (regardless of where the properties came from) with `Object.keys(obj).length`.
Comment: Uhm, you mean return 9, right ?
Comment: You don't have to prototype a count function. Is simple as EventData.length
Comment: So it would return `10`, but why would it return `10` ?
Comment: I would need 10 if I was to include prototypes with the count. 8 would give me the number of parameters asked.
Comment: I would guess you wanted `9`, but that's just me ?
Comment: yes, the answer by @dfsq gives 9.
Answer: The most natural way in this case would be to store parameters count in some property (maybe private). I'm not sure why you need this, but, yea, something like this:
var EventData = function (ID, Name, StartDate, StartTime, EndDate, EndTime, Location, Notes) {
    this._paramsCount = arguments.length;
    this.type = "event";
    this.id = ID;
    this.name = Name;
    this.startDate = StartDate;
    this.startTime = StartTime;
    this.endDate = EndDate;
    this.endTime = EndTime;
    this.location = Location;
    this.notes = Notes;
};
EventData.prototype.count = function () {
    return this._paramsCount;
};

UPD. Based on the edited question, look like you want to calculate number of own properties of the instance. In this case you would use convenient Object.keys method which returns an array of property names.
EventData.prototype.count = function () {
    return Object.keys(this).length;
};

Comment: I was just about to save my answer exactly as yours, so i've deleted it and upvoted since its a pretty good approach :)
Comment: @dfsq i think he Op means the properties present, not the arguments passed.  arguments.length will give 3 if we pass only 3 arguments
Comment: @A.B Hm.. originally it was parameters, I guess. Looks like you are right.
Comment: still needs confirmation @dfsq may b this is the scenario, +1 fro edit
Answer: Just get the properties of the EventData object as an array with Object.keys, and then the length of the array?
EventData.prototype.count = function(){
  return Object.keys(this).length;
};

Answer: If you want to know the number of canonical parameters, use the Function.length property, in your case:
EventData.length

or
thisEventData.constructor.length

Note that it won't count additional parameters (variable arguments) since it infers the count from the constructor object.
If you want to know the property count of the constructed object, use Object.keys:
Object.keys(thisEventData).length

This will give you the count of the own properties (excluding the prototype chain).
Or just write your own customizable logic if you need something else, for instance if you want non-falsey objects:
function getPropertyCount(obj, withPrototypeChain) {
    var prop;
    var count = 0;

    for (prop in obj) {
        if ((withPrototypeChain || obj.hasOwnProperty(prop)) && obj[prop])
            ++count;
    }

    return count;
}

Answer: To build a bit on the accepted answer:
export class Person {
      constructor (name, age) {
        if (arguments.length !== 2) {
          throw new Error('invalid Person argument count')
        }
        this.name = name
        this.age = age
      }
    }


Show existence of a continuous function with certain properties

Question: Let $X$ be a compact Hausdorff space and $C(X)$ the commutative algebra of continuous complex-valued functions endowed with the maximum-norm.
Let $J\subset C(X)$ be an ideal and $g\in J$. Let $0<\epsilon <1$. Show there exists a $u\in J $ such that $u = 1$ on the set $\{|g(x)|\geq 1\}$ and $u=0$ on $\{|g(x)|\leq \epsilon \}$ and $0\leq u(x)\leq 1$ for all $x\in X$.
The existence of such continuous $u\in C(X)$ is just an applications of Urysohn's lemma. But to show there exists such $u\in J$ I can't yet figure out.
Since $J$ is an ideal, it would be enough to show that there exists a $f\in C(X)$ such that $fg=u$. This would mean that $f=1/g$ on $\{|g(x)|\geq 1\}$ and $f=0$ on $\{0<|g(x)|\leq \epsilon\}$.
But I don't see why such $f$ would be continuous. Any ideas?
Comment: Because you don't have $u = 0$ on $\{ 0 < \lvert g\rvert < 1\}$. You have $u=0$ on $\{\lvert g(x)\rvert \leqslant\varepsilon\}$. For some $0 < \varepsilon < 1$.
Comment: $f$ would not have to be $0$ on $\{0 < \lvert g\rvert < 1\}$. It would have to be nonzero on a considerable part of that set.
Comment: Why? How can otherwise $f(x)g(x)= u(x)=0$ hold on the set $\{0<|g(x)|<1\}$ if $f(x)\neq 0$? Maybe I am confusing..i mean the set $\{x\in X: 0<|g(x)|<1\}$.
Comment: Ha, yes ofcourse, i was confused indeed.
Answer: You have the desired $u$ by Urysohn's lemma. Now define $U_1 = \{x : \lvert g(x)\rvert > \varepsilon/3\}$ and $U_2 = \{ x : \lvert g(x)\rvert < 2\varepsilon/3\}$. By the continuity of $g$, both $U_1$ and $U_2$ are open, and since $2\varepsilon/3 > \varepsilon/3$, we have $X = U_1 \cup U_2$. Then define
$$f(x) = \begin{cases} \frac{u(x)}{g(x)} &, x\in U_1\\ 0 &, x\in U_2. \end{cases}$$
$f$ is well-defined because on $U_1\cap U_2$, we have $u \equiv 0$.
Evidently $f$ is continuous on $U_2$, and on $U_1$, it is also continuous, as the quotient of two continuous functions, where the denominator doesn't vanish.
Hence $f$ is continuous on all of $X$.
Comment: @ScroogeMcDuck Yes. In general, if you have $X = A \cup B$ and $f\colon X \to Y$, you can't conclude the continuity of $f$ from the continuity of the restrictions $f\lvert_A$ and $f\lvert_B$. If you have (arbitrarily many) $U_\iota$ open with $X = \bigcup U_\iota$, then the continuity of $f$ follows from the continuity of $f\lvert_{U_\iota}$ for all $\iota$. You can also conclude the continuity of $f$ from the continuity of $f\lvert_{F_k}$ for all $k$ when you have $X = \bigcup_{k=1}^n F_k$ as a union of finitely many closed subspaces.
Comment: Great, that's nice. Thanks.
Comment: @Daniel Fischer is there a reason for mentioning explicitly that $U_1$ and $U_2$ are open?


Is it necessary to discharge the capacitors on an AC condensor?

Question: I intend to replace the capacitors on my house air conditioner condenser.  This video claims that discharging the capacitors is not necessary, because the circuitry will discharge through the fan motor if you unplug while it is running.
https://www.youtube.com/watch?v=Jz3DyCSKGB4

Will using this technique really discharge the
capacitor?
Is this a best practice, and is it safe?
What is
the best way to handle capacitor discharge for an AC condenser?
Comment: I agree with Ben's answer. But if you want to make sure with the power off short across the terminals, some use a power resistor , i have used a screwdriver for the last 35 years with only 1 time getting a good arc (the power was still there oops). + Ben
Answer: Most of the motors associated with fans and such, utilize an induced magnetic field, and don't have a permanent magnet. So as the capacitor releases its charge (quickly), a magnetic field would be induced in the motor and cause the motor to turn maybe once or twice, and that should spend most, if not all, of the the stored charge. So the capacitor will release the charge to turn the motor... or more technically, the motor will draw the stored current out of the capacitor (quickly).
With respect to the kind of motor that is turning, for most any AC fan motor, it is highly doubtful that a dynamo-style (using a permanent magnet) motor is being used (except on wind mills). I mention this because the efficiency of the discharging effect could be different compared with a dynamo-style motor... but I also think it should be kind of the same (roughly). The difference being that inertia of the spinning dynamo, will continue to generate electricity, until it nearly stops- at which point it would draw the stored current from the capacitor.
But something else to be aware of is that, typically, large capacitors do not perfectly insulate or isolate or hold charges... they naturally discharge within themselves after a while. Furthermore, large capacitors usually have a bleeder resistor attached to the capacitors terminals. Discharging through motors and other electrical items where a circuit exists is (probably) the primary way, though.

Comment: So this statement is consistent with your answer:  "you can expect the run cap or start cap to already be discharged when you remove the power from the unit."  Is that right?
Comment: @steampowered Kind of... Ed Beal has the right idea though. Always make double sure. If you count on the capacitor (or any other electrical or mechanical thing) to work perfectly, then you may not be able to count your fingers later.
Comment: So expect them to be discharged when the power is disconnected.  But prior to removing the capacitor, test the capacitor to be sure it is discharged using a short or a resistor across the terminals just to be safe.


Image not coming top of another one after giving z index

Question: I am trying to modify the design of a web site . There is an image slider and I would like to show a circle log above of the header section. Now the image is displaying , but it is broken and not displaying in full size , Please check the site here  and see that green rounded button .
I have used the following codes

ROMANTIC GETAWAY

Please help me , I would like to display the green rounded logo full size there .
Answer: you need to add a CSS position:  declaration (relative, absolute etc) in order for z-index to have any effect


Who invented the "swipe to …" gestures

Question: Swipe gestures are now quite common and allow access to one or multiple functionality by swiping a list item to the right or the left.

Even if I know a few apps having such a feature, I wonder which app introduced it. It must not be very old, I reckon 2012 or 2013 but I would be interested to know where you first noticed it.
Answer: The gesture goes back at least to 2009, when it was already being used by Apple and Google, and especially Palm (webOS).
I Googled 'swipe to delete' and restricted the results to pre-2010. I learned that the iPhone had it in Mail, while Gmail's mobile app had 'swipe to archive'. But, as far as I can tell, swipe-to-perform-an-action was used most extensively by Palm webOS, introduced that year at CES.
In webOS 1.0, you could remove cards ( = document-centric windows) by swiping them away:

You could swipe to act upon notifications (this was later improved so that you swiping exposed more possible actions):

You could swipe away e-mails:

I'm not sure where the swipe-to-x gesture started, or who inspired whom, but it does seem like the gesture really started becoming popular around 2009.
Comment: Palm was way ahead of its time.
Answer: I found an article which was published on February 20, 2012 written by Jason Mick (blogger) "Neonode Patented Swipe-to-Unlock 3 Years Before Apple"
Neonode -- a small Swedish phone manufacturer was the first to deploy the technology commercially.  And it also appears to be the first to have patented swipe-to-unlock.
U.S. Patent No. 8,095,879.

The computer readable medium of claim 1, wherein the user interface is characterised in, that an active application, function, service or setting is advanced one step by gliding the object along the touch sensitive area from left to right, and that the active application, function, service or setting is closed or backed one step by gliding the object along the touch sensitive area from right to left.

In the case that the patent was deemed non-novel at some point and redundant with existing drag-and-drop IP, Neonode attempts to strengthen it with a secondary claim.

The computer readable medium of claim 1, wherein the touch sensitive area is 2-3 inches in diagonal dimension.

Neonode's display is resistive (diodes-based) touch design. This does not have any major affect the algorithm.
Neonode patent simply did mention this: If you swipe halfway across the Neonode phone (reaching the middle diode) and stop, you can't just click the endpoint several seconds later. (Neonode's algorithm was less explicit, but it appears to have the same mechanism as Apple's).
U.S. Patent No. 8,095,879.
The present invention relates to a user interface for a mobile handheld computer unit, which computer unit comprises a touch sensitive area, and which touch sensitive area is divided into a menu area and a display area.
The computer unit is adapted to run several applications simultaneously and to present any active application on top of any other application on the display area.
It relates to an enclosure for a handheld computer unit, also relates to a computer readable medium. A computer program product with computer program code is stored within the computer readable medium, which code, when read by a computer, will make it possible for this computer to present a user interface (according to the invention).
Comment: While this is certainly interesting, can you take the relevant elements from the article / patent to include in this answer? Otherwise everyone is going to have to go and read the articles themselves, which is not ideal (especially if the details of the article / patent get taken down for whatever reason).
Answer: They were invented by Apple, here you can see the patent here

Swipe gestures for touch screen keyboards
US 8059101 B2
Abstract
Systems, methods, and devices for interpreting manual swipe gestures as input in connection with touch-sensitive user
  interfaces that include virtual keyboards are disclosed herein. These
  allow for a user entering text using the virtual keyboard to perform
  certain functions using swipes across the key area rather than tapping
  particular keys. For example, leftward, rightward, upward, and
  downward swipes can be assigned to inserting a space, backspacing,
  shifting (as for typing capital letters), and inserting a carriage
  return and/or new line. Various other mappings are also described. The
  described techniques can be used in conjunction with a variety of
  devices, including handheld devices that include touch-screen
  interfaces, such as desktop computers, tablet computers, notebook
  computers, handheld computers, personal digital assistants, media
  players, mobile telephones, and combinations thereof.

They also had the following related patents previous to the specific swipe patent above:

Apple's Granted Patent Incorporates a Great Number of Important
  Patents
Apple's granted patent is related to the following U.S. patents and
  patent applications, each of which is hereby incorporated by reference
  in its entirety: U.S. Pat. No. 6,323,846, titled "Method and Apparatus
  for Integrating Manual Input," issued Nov. 27, 2001; U.S. patent
  application Ser. No. 10/840,862, titled "Multipoint Touchscreen,"
  issued May 6, 2004; U.S. Provisional Patent Application No.
  60/804,361, titled "Touch Screen Liquid Crystal Display," filed Jun.
  9, 2006; U.S. Provisional Patent Application No. 60/883,979, titled
  "Touch Screen Liquid Crystal Display," filed Jan. 8, 2007; U.S. patent
  application Ser. No. 11/367,749, titled "Multi-functional Hand-held
  Device," filed Mar. 3, 2006; U.S. patent application Ser. No.
  11/228,737, titled "Activating Virtual Keys of a Touch-Screen Virtual
  Keyboard," filed Sep. 16, 2005; U.S. patent application Ser. No.
  11/228,700, titled "Operation of a Computer with a Touch Screen
  Interface," filed Sep. 16, 2005; U.S. Pat. No. 6,677,932, titled
  "System and Method for Recognizing Touch Typing Under Limited Tactile
  Feedback Conditions," issued Jan. 13, 2004; and U.S. Pat. No.
  6,570,557, titled "Multi-touch System and Method for Emulating
  Modifier Keys Via Fingertip Chords," issued May 27, 2003.

However, there were companies that used swipe gestures before Apple, even patented then, such as Swedish company Neonode, who patented the swipe to unlock gesture as early as 2002. You can see their patent here
Answer: MyOrigo phone used swiping in 2002. There's a mention and short demonstarion of MyOrigo in the document The Rise and Fall of Nokia. MyOrigo part starts at 40:30 https://youtu.be/PhB7bJ4yfno?t=2432

Who invented the "swipe to …" gestures


svnsync: Revision being currently copied, last merged revision, and destination HEAD are inconsistent

Question: I run the following command:
svnsync synchronize svn://www.example.com/repos
svnsync: Revision being currently copied (19931), last merged revision (19929), and destination HEAD (19931) are inconsistent; have you committed to the destination without using svnsync?

And then I run it again 30 seconds later:
svnsync synchronize svn://www.example.com/repos
svnsync: Revision being currently copied (20012), last merged revision (20010), and destination HEAD (20011) are inconsistent; have you committed to the destination without using svnsync?

I don't understand why, if its "blocked", are the numbers increasing?
I'm doing the above as root, and no jobs or processes are running (and root is the only user account).
Comment: "no jobs or processes are running": so you don't have a parrallel svnsync in the background? Did you try to dump your repo to revision 19931, and resync it?
Comment: I have the same, with creating new fresh copied repo. svn 1.9.5 r1770682 , svnsync with the same svn base version.
Answer: For your process, when you use a svnadmin load the primary repository should be locked. This process checks if the last merged revision are equal for a sync to commence.


How can I fasten a threshold to concrete?

Question: BACKGROUND
A threshold was purchased from HomeDepot:

The item comes with screws and needs to be fixed into concrete slab.  I would like to understand how to properly screw the threshold into the slab.  If it were a wood surface I might drill a pilot hole or use a wood screw, however, given that this is concrete, I get one shot at getting this installed correctly.  If not then, it creates a whole new set of problems.
QUESTIONS

What is the correct procedure to screw the threshold into a concrete floor?
Is it necessary to drill a pilot hole?  The screws are not wide.

UPDATE: screws were misplaced so maybe tapcons may be used
Answer: There are two recommended approaches:

Use plastic plug anchors. Use a hammerdrill or rotary hammer to drill holes sized for the plugs--typicaly in the 5/16" to 3/8" range. Drive the plugs in with a hammer and run the screws into them.
The advantage of this approach is that you can use a variety of screw types, depending on your needs, as long as they're the right size for the plug. Also, the plug can be removed and replaced if necessary. A disadvantage is the larger required hole size.

Use masonry screws. Pilot holes using a hammerdrill or rotary hammer according to the manufacturer's specifications. Drive the screws directly into the concrete.
The advantages of this approach are the smaller hole and greater holding power. Disadvantages include difficulty in driving the screws, the chance that the screw strips the concrete, the non-reusable nature of the system, and the limited head styles.

With both approaches, precise hole placement is critical. There's virtually no adjustment in position once they're drilled.


How to solve "failed: Error during WebSocket handshake: Unexpected response code: 200" in spring websockets?

Question: I am trying to subscribe to a particular channel in spring web sockets but while pointing to a URL using SockJs i getting the following error WebSocket connection to 'ws://localhost:8080/Spring/rest/user/chat/045/jmfz3b3j/websocket' failed: Error during WebSocket handshake: Unexpected response code: 200 Please help me to avoid this.
Here is my client side code for subscription.
Index.jsp

var stompClient =null;
      function subscribe(){
var socket = new SockJS('/Spring/rest/user/chat');
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
     console.log('Connected: ' + frame);
     stompClient.subscribe('/topic/messages', function(test) {
       alert("in call back function");});
 });
 }
Comment: Looks like the endpoint of server mismatches with client. Post the code snippet of server side for reviewing.
Comment: @Kane Please check the following snippet.
Answer: @Kane This is my websocket configuration in spring-servlet.xml
<websocket:message-broker application-destination-prefix="/app" >
    <websocket:stomp-endpoint path="/chat" allowed-origins="*">
        <websocket:sockjs />
    </websocket:stomp-endpoint>
    <websocket:simple-broker prefix="/topic"/>
</websocket:message-broker>

And this is my controller code
@Controller
@RequestMapping("user")
public class OptnCptController{
    @MessageMapping("topic/messages")
    public String getMsg(String s)
    {
        return s;
    }
}


Vent a portable air conditioner with a 6 inch hose through a 3 inch hole in the wall

Question: I bought a new portable air conditioner for my condo. I bought this one: a/c. I want to use it to cool either my living room or my bedroom. My apartment is 1100 sq. ft. so I believe this should be more than enough to cool down either portion of the condo. However my condo is not A/C friendly. It has only narrow casement windows and one roof to ceiling sliding window in the living room. I am also not allowed to install a window mounted A/C. However, it does have these 3 inch holes in the wall in many of the rooms (presumably for ventilation or A/C). I heard some of my neighbors use those holes to vent their A/Cs. I wonder whether this is safe or not (fire, mold). If it is, can I just hook the hose into a 6 to 3 reducer? What material is good for this purpose: PVC, metal, something else?
I know there are ways to install portable A/Cs in casement and tall sliding windows but both seem too complicated. I was hoping I can just use a reducer and be done, but I want to make sure it is safe. BTW the condo exterior walls are concrete.The holes clearly lead to the outside (I can see the street through them)
Comment: You should ask the condo management or owners of other units what these 3" diameter holes are intended for. How are they currently sealed on the inside and the outside? Is this a multi-story building?
Comment: I have only received vague answers, but I will ask again.
This is a multy-story building. I am on the 6th out of 10 stories
Answer: If your air conditioner came with 6 inch hoses it was designed to work with the flow rate available in that size. It is not advisable to be reducing the operational size of the hoses because it will compromise the operational functionality of the AC unit.
Since flow rate (at a given pressure) is related to the cross sectional area of the pipe be aware that a 3 inch pipe has only one quarter of the area that a 6 inch pipe does. If you were going to try using those existing 3" holes you would have use four holes in conjunction with an elaborate manifold to split from the 6 inch. (And do you even have 4 holes to use per 6 inch hose?)
Even though the venting through the window seems complex it is going to be way simpler than the above described manifold system!
Comment: Buy or make up an adapter to go from 6" down to 3". You may have to stack ABS plastic drain adapters to get there, 6" to 5" or 4" , then that to 3". I think that you should try to see if this will work through one hole before you resort to rigging up something in the window.
Comment: Compromise the operational functionality means that it will break sooner? or that it will cause a fire or something awful.
If I am just reducing the expected life of the a/c I guess that is acceptable. It only runs for about 3 or 4 weeks during the summer and that's it Only a few hours a day during those weeks.
Comment: @cloudraven - I cannot say what will happen to your A/C unit if you constrict its ducting down to 3". Clearly the A/C unit was designed to work with 6" hoses and thus the reason I do not recommend that you do what you are suggesting. The A/C unit could overheat inside. Too much overheating could cause any one of a number of failures or critical situations to arise.
Answer: The reduction of the diameter from the 6" of the hose to 3" through the wall may not cause a significant problem. The resistance to fluid flow of a pipe is [inversely] proportional to the square of the diameter and directly proportional to the length of the pipe. So if the length of the 3" diameter hole is short compared to the length of the 6" hose, then the constriction to 3" may work OK. You could ask the mfgr, but you may have to try it. I bet it will work fine.
The key to making it work would be to make a gradual transition from 6" diameter to 3" diameter over say 8 inches to 1 ft of length. This would prevent the creation of turbulence which could restrict flow. Presumably the 3" hole in the wall is lined with a pipe, right?
I wonder if those 3" diameter holes are positioned vertically so that a ductless mini-split a/c could be installed. How high above the floor are these holes? How far are they from the ceiling? Would the building management allow that?
Comment: Another intervention would be an inline booster fan to increase the flow rate of the hot exhaust. This would have to be automatically switched on when the condenser would come on. Does the portable a/c unit have a switched receptacle on it?
Comment: Thanks Jim for all your helpful comments.  The length of the 3" diameter hole is short (9 inches). I will try to contact the manufacturer.
The 3" hole is lined with a pipe. that is correct.
It is horizontally. There is one of those holes in each room. In the lower half of the wall, about 1 foot from the floor.
About a year ago the concierge sent me a picture of that outlet suggesting I should connect the portable A/C to it, but I have no clue how now that I realize it is narrower than the hose. Since they suggested it, I would assume it is allowed.
Comment: The position low on the wall would mean it is not really suitable for a mini-split ductless a/c. The holes for that should be higher on the wall--mid wall to  18" from the ceiling
Comment: I can't see the other end of this fitting but it is described as a 6" to 3" transition: http://www.homedepot.com/p/DURA-6-in-x-3-in-Schedule-40-PVC-Reducer-Bushing-SPGxS-437-530/203225399?cm_mmc=ola|criteo|26P-26-1-60|22037|D26P
Comment: I agree with Jim give it a try. The compressor has tempature safety switches that will prevent a fire, there are also high pressure safetys that will shut down the unit if it gets two hot. It could shorten the life of the unit but that would be the worst I would expect. If it has problems with the 3" size an inline blower or a duct booster could be added many of these are tempature controlled and that would increase the flow through the hole but I would give it a try.
Comment: How did the venting of the a/c out the 3" diameter hole work out?
Answer: I actually tried reducing the exaust pipe on a portable AC unit. It comes out at 6" and we reduced it to 4".  I knew it wasn't right at the time but did it anyways for some reason.
 Anyways the AC worked fine for a few weeks, but then it would click off and just pump out warm air.  However, waiting 10 minutes and restarting it seems to reset the unit as it still works fine.  Tomorrow I am installing an inline fan ~5ft after the reducer and hope that works. Otherwise I will be cutting a larger hole and replacing with 6" this weekend.  At the end of the day, I'm pretty sure that having its exaust capaciry so restricted overheated the unit and it triggers the AC off.  Now whether it does this in advance of and in order to avoid causing damage or as a result of some damage I'm causing, I'm not sure, but the air seems just as cold as before.
Answer: Was researching a similar issue. If you use  an in duct exhaust fan that has a higher cfm than the portable ac, it will negate the constriction caused by downsizing the exhaust from 6" to 3".  And therefore will cause no adverse effects , shorter life, overheating, etc. to your portable ac.


Kendo Grid Inline Editing shows password text instead of plain text

Question: I am currently have challenge with entering plain text in Kendo Grid inline editing mode instead of password mode it shows by default. My other pages are pretty fine. This issue is peculiar to the page in the screenshot.
Answer: I found the solution. The data annotation on the property is [DataType(DataType.Password)]. commenting it out made it work. It's an inherited code though.


Why am I getting these 'already defined' linker errors?

Question: I am a beginner at C++ but I have some experience using Java. I am getting some errors that I don't understand. I attached a pic of the error console and the code below it.
 Error  1   error LNK2005: "public: __thiscall VectorDouble::VectorDouble(void)" (??0VectorDouble@@QAE@XZ) already defined in Main.obj  C:\Users\carrea\Code\Visual Studio\COMP201\Lab8_VectorDoubleClass\VectorDouble.obj  Lab8_VectorDoubleClass

 Error  2   error LNK2005: "public: __thiscall VectorDouble::VectorDouble(int)" (??0VectorDouble@@QAE@H@Z) already defined in Main.obj  C:\Users\carrea\Code\Visual Studio\COMP201\Lab8_VectorDoubleClass\VectorDouble.obj  Lab8_VectorDoubleClass
....

10 more errors like these and
 Error  13  error LNK1169: one or more multiply defined symbols found   C:\Users\carrea\Code\Visual Studio\COMP201\Lab8_VectorDoubleClass\Debug\Lab8_VectorDoubleClass.exe  1   1   Lab8_VectorDoubleClass

Main.cpp

#include "VectorDouble.cpp"
using namespace std;
void printVD(const VectorDouble& v);
int main()
{
    VectorDouble p;
    p.push_back(1);
    p.push_back(4);
    p.push_back(3);
    VectorDouble v(p);
    printVD(v);
    printVD(p);
}
void printVD(const VectorDouble& v)
{
    int n = v.size();
    for(int i = 0; i<n; i++)
    {
        cout << v.getElementAt(n) << " ";
    }
    cout << endl;
}

VectorDouble.h

#pragma once
#include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
#include <iomanip>
#include <vector>
#include <sstream>
using namespace std;
class VectorDouble
{
public:
    VectorDouble(void);
    ~VectorDouble(void);
    VectorDouble(int intSize);
    // Copy constructor
    VectorDouble(const VectorDouble& vd);
    // = override
    void operator =(const VectorDouble& RIGHT_SIDE);
private:
    double *dArray;
    int count, max_count;
public:
    // returns number of occupied cells
    int size(void) const;
    // Returns total number of cells
    int capacity(void) const;
    // Adds an element to array
    void push_back(double num);
    // Resizes the array to be double the original max_count
    void resize(void);
    // Returns element at specified index
    double getElementAt(int i) const;
    // Requests that the capacity of the allocated storage space for the elements of the vector container be at least enough to hold n elements
    void reserve(int n);
private:
    // Sets every element to 0
    void clear(void);
};

VectorDouble.cpp

    #pragma once
#include "VectorDouble.h"

using namespace std;

VectorDouble::VectorDouble(void)
{
    max_count = 100;
    count = 0;
    dArray = new double[max_count];
    clear();
}

VectorDouble::VectorDouble(int intSize)
{
    max_count = intSize;
    dArray = new double[max_count];
    clear();
}

VectorDouble::~VectorDouble(void)
{
    cout << "vector with " << this->count << " is destroyed";
}

// Copy constructor
VectorDouble::VectorDouble(const VectorDouble& vd)
{
    int mcVD = vd.capacity(), i=0;
    max_count = mcVD;
    dArray = new double[max_count];
    clear();
    while(i<max_count)
    {
        dArray[i] = vd.getElementAt(i);
        i++;
    }
}
// = override
void VectorDouble::operator =(const VectorDouble& RIGHT_SIDE)
{
    int rightCount = RIGHT_SIDE.size(), i=0;
    while(rightCount>max_count)
    {
        resize();
    }
    while(i<rightCount)
    {
        dArray[i] = RIGHT_SIDE.getElementAt(i);
        i++;
    }
    count = i;
}
// returns number of occupied cells
int VectorDouble::size(void) const
{
    return count;
}
// Returns total number of cells
int VectorDouble::capacity(void) const
{
    return max_count;
}
// Adds an element to array
void VectorDouble::push_back(double num)
{
    if(count==max_count)
    {
        resize();
    }
    dArray[count] = num;
    count++;
}
// Resizes the array to be double the original max_count
void VectorDouble::resize(void)
{
    double *p = new double[max_count*2];
    for(int i = 0; i < count; i++)
    {
        p[i] = dArray[i];
    }
    dArray = p;
    max_count*=2;
    delete p;
}

// Returns element at specified index
double VectorDouble::getElementAt(int i) const
{
    return dArray[i];
}

// Requests that the capacity of the allocated storage space for the elements of the vector container be at least enough to hold n elements
void VectorDouble::reserve(int n)
{
    while(n<max_count)
        resize();
}

// Sets every element to 0
void VectorDouble::clear(void)
{
    for(int i = 0; i < max_count; i++)
        dArray[i] = 0;
}

Any help would be much appreciated...
Comment: Shouldn't you #include "VectorDouble.h" in main.cpp instead of "VectorDouble.cpp"?
Comment: Also copy assignment isn't correctly implemented (`void operator =(const VectorDouble& RIGHT_SIDE);`). It is supposed to return a reference, in general.
Comment: Your problem is being confused about the distinction between 'declaration' and 'definition', since that distinction does not exist in Java. See my answer.
Answer: You should include "VectorDouble.h" and not "VectorDouble.cpp" in Main.cpp.
The whole concept of include files is rather broken in C++ as compared to many other languages.
First C++ divides things up into 'declarations' and 'definitions'. You may only ever have one definition of something in a program, but as many declarations as you want. In your VectorDouble.cpp file you are defining things, and in VectorDouble.h file you are declaring things.
The #include directive in C++ is dead simple and stupid. When it is encountered the compiler effectively does a simple textual replacement. The #include directive is replaced with the contents of the file you are including.
When you #include a file of definitions, that means you effectively define them all right there where you've done the #include. This is why you shouldn't be including "VectorDouble.cpp". Since you likely also compile that file as a separate file, you then end up with at least two copies of all the definitions right there.
This whole declaration vs. definition dichotomy gets very confusing when talking about certain kinds of things. For example, if a function is declared inline the function body isn't really considered a definition anymore, exactly. This means you can have as many copies of a function body that's been declared inline as you want. All that's required is that all of the definitions be identical.
Similarly, declaring a template function is a declaration, even if you include a function body. This is because the declaration results in no code being generated, only the template instantiation results in code generation. And that's the real litmus test for deciding if something is a declaration or definition. If it results in space being allocated or actual code being produced right then and there, then its a definition, otherwise its a declaration.
Answer: The error you're getting is a linker error telling you that the compiler is finding multiple definitions for certain member functions.  If you look at this chunk of the error message:
public: __thiscall VectorDouble::VectorDouble(void)" (??0VectorDouble@@QAE@XZ) already defined in Main.obj

You can see buried in there the fact that it's talking about the constructor VectorDouble::VectorDouble() already being defined.
I think the particular problem you're running into is in this line in main.cpp:
#include "VectorDouble.cpp"

The problem is that this includes the source file, not the header file.  Consequently, when you compile main.cpp, you'll be compiling all of main, plus all of the definitions in VectorDouble.cpp.  When the linker then tries linking this with the object file generated when it compiled VectorDouble.cpp, it will find two definitions of everything - one from VectorDouble.cpp and one from main.cpp.
To fix this, change this line to read
#include "VectorDouble.h"

That should resolve your issue.  More generally, though, it's extremely rare to actually #include a .cpp file.  You almost always include headers, not sources.
Hope this helps!
Comment: I don't think this is a very good (though not -1 not good) answer because it doesn't explain why there are 'source' files and 'header' files. This is a very odd distinction, and among modern commonly used languages largely only exists in C and C++. It deserves an explanation, especially for someone who's a Java programmer.
Comment: It's not an odd distinction, and is present in some form in all languages designed for large scale programming.  You generally want to keep the interface specified in a separate file from the implementation.
Comment: @James Kanze: It doesn't exist in Java, nor in Python, Ruby, perl, PHP, or lisp, erlang, or OCaml. In fact, in all of the languages I've used for anything serious in the past 10 years, C and C++ have been the only ones that have had the distinction.
Answer: Main.cpp shouldn't be #include-ing VectorDouble.cpp; it should #include VectorDouble.h. If you are linking both .cpp files, the linker is seeing everything in VectorDouble.cpp twice (once on its own, and once when it's #include-d from Main.cpp).
Answer: I got a similar link error when I tried to define a class in a separate file named PresentDataStruct.h and also created a PresentDataStruct.cpp file.
Here are the contents of PresentDataStruct.h:
#pragma once

#include <string>
using namespace System;
ref class CPresentDataStruct
{
public:
    CPresentDataStruct();
    ~CPresentDataStruct();

public:
    void SomeActionOnData();

public:

    System::String^ Name;
    DateTime^ BirthDay;

};

void CPresentDataStruct::SomeActionOnData()
{
    //TO DO here
}

CPresentDataStruct::CPresentDataStruct()
{
}

CPresentDataStruct::~CPresentDataStruct()
{
}

While in PresentDataStruct.cpp it has one line:
include "PresentDataStruct.h"

Then the link error appears when I add include "PresentDataStruct.h"
to the maindialog.h file.
So I moved this to PresentDataStruct.cpp file and the link error disappeared:
void CPresentDataStruct::SomeActionOnData()
{
    //TO DO here
}

CPresentDataStruct::CPresentDataStruct()
{
}

CPresentDataStruct::~CPresentDataStruct()
{
}


Outlook Appointment Timezone display issue

Question: I'm a developer in England and I'm currently on British Summertime.
When adding an appointment via Office 365 API using the .Net Client Library for Office 365 Mail, Calendar and Contact API, the Timezone button on the Appointment when viewed in Outlook (2016) can't be un-clicked and the timezone list is always displaying UTC
See this image for an example

When I hover over the appointment in the Calendar within Outlook, the time in BST is shown (as expected).
See this image for an example

However, when I add an appointment to the calendar manually, the timezone button is not checked/clicked and I can freely check/uncheck the button. Also, when I click the button, the correct timezone is displayed (Dublin, Edinburgh, Lisbon, London).
Note that the appointment shows the correct times when viewing via Office 365 online - https://outlook.office.com/owa/
Why is this happening?
More Information:
After a while of searching on Google, I did come across https://social.technet.microsoft.com/Forums/office/en-US/44093e33-133d-4de7-9f67-9ec591453bd0/calendar-meeting-time-zone-display-issue?forum=outlook
However I do not see that option in https://outlook.office.com/owa/
In my code, I set the following properties on the Microsoft.Office365.OutlookServices.Event:
<code>Private Sub UpdateEvent(ByVal cEvent As [Event], ByVal tCalendar As t_Calendar)
    Dim cLocation As New Location()
    cLocation.DisplayName = tCalendar.sLocation

    Dim cBody As New ItemBody()
    cBody.ContentType = BodyType.HTML
    cBody.Content = tCalendar.sDescription

    cEvent.Subject = tCalendar.sSummary
    cEvent.Location = cLocation

    cEvent.IsAllDay = False
    cEvent.Start = New DateTimeOffset(tCalendar.dtStart)
    cEvent.End = New DateTimeOffset(tCalendar.dtEnd)

    cEvent.Body = cBody
End Sub
</code>
I have followed the guide https://github.com/jasonjoh/office365-azure-guides/blob/master/RegisterAnAppInAzure.md to Register an Office 365 API app in Azure AD.
Comment: Hey Richard Wilson, I am facing the same issue. I'm in IST (UTC+5.30). I'm creating events using the graph API's in UTC. The events show up in the right timezone when viewed in the calendar on the desktop client. On opening the event, the timezone is changed to UTC and cannot be edited. How did you solve this?
Answer: I think we are confusing two different issues here. This problem with Outlook application is not related to Office365 API issue. If you create an event using Outlook application, as you said, you can change the TimeZone, now send the event, and then try to edit that event (in Outlook), you will see that you are Not able to change the timezone. So it is not only happening with Office365 API. It seems like Outlook does not let you change TimeZone once it is set.
Comment: Hi, thanks for replying. I think the issue is with the .Net client library I have been using to add appointments via Office365 API. When I use raw http requests with https://graph.microsoft.com/v1.0/me/calendar/events and specify the "TimeZone" as "GMT Standard Time" then the Time Zone button  on the Outlook appointment can be un-clicked and the time zone displays as (Dublin, Edinburgh, Lisbon, London)


What size extension cord do I need to reach 200' from the house to run 15A tools?

Question: I need to work out in the woods (building a treehouse) with up to 15 Amp tools about 200 feet from the house. Obviously I should be using battery tools, but all of my tools are wired and I'd rather not buy battery versions of all my tools. What size extension cord(s) do I need to purchase?
Comment: At least 12 gauge, but for 200 ft a small(2000w) generator might be almost the same price.
Comment: More expensive to buy the generator on my quick look, for this distance. **Far more expensive** to **fuel** the generator than to pay your electric utility for the power.
Comment: Are you in a 110V or 220V country? Acceptable voltages loses are less in 110V countries
Comment: Modern battery tools store a lot of power, and you can buy more batteries. Depending on how many hours you plan to work at a stretch, batteries might be more cost-effective. You could also use a cheaper extension cord to power, say, a dewalt charger, and switch off.
Comment: @CSM Questioner's profile says Oregon, so 120 VAC, 60 Hz, presumably.
Comment: No you should not use battery tools. They run out of battery at inconvenient times.
Comment: @bmargulies to use a cheaper extension cord, the charger would need to use less power than the tool itself.  That implies it will take longer to charge a battery than to use it up.
Comment: @MarkRansom  most building tools are not running all the time, eg a drop saw spends about 70% of the time not cutting, and that's when it's being used.
Answer: 10 gauge (copper) would be a reasonable size - about 5% voltage drop on 120V at 15A. Be sure you are plugged into a GFCI-protected outlet.
Pricing is off topic, local, goes out of date, yadda, yadda - current 2022 USA cost in the ballpark of slightly over $100 for a 100 foot 10Ga cord, so slightly over $200 for two of them.
Comment: Romex and extension cords are different market segments. Prices were from this morning.
Comment: An outdoor outlet I think should be GFCI protected already to be up to code.  But if it isn't, there's a vast selection of GFCI circuits that can be plugged in inline.  Had never heard of one until I went looking.
Comment: We don't know that the OP has an outdoor outlet, or if their outdoor outlet, if present, has a GFCI. Depending on age of house, neither of things were required, until they were. Not hard to find people still running cords out a window. So, always best to specify. I have one of those 6 foot heavy duty GFCI extensions, and it's a good trick to have in the bag if you find yourself faced with a dubious place to plug in.
Comment: My whole house is wired with 12/2. Would plugging a 10/2 extension cord into a 12/2 fed outlet even work very well? Thinking of electricity like water, wouldn't it be like having a 1/2" water pipe feeding a 1-1/2" pipe? The pressure would drop dramatically.
Comment: Not the way it works. Just minimizing the additional loss (voltage drop) from adding another 200 feet to the run inside your house, which is presumably much shorter if your name isn't Scrooge McDuck, or the modern equivalent (in which case I doubt you'd be DIY-ing it.)

What size extension cord do I need to reach 200’ from the house to run 15A tools?


reversing char array caused access violation

Question: I just wanted to write a code for reversing a char array(or a pointer char . i failed so used char arrays) . like "USAF" gonna be "FAUS" first i did this with pointers so i got access violation  .
CODE :
    #include <iostream>

using namespace std;

int getlength(char *);
void reverse (char * ch );

int main ()
{
    char  *ch ="USAF";
    /*cout<<*ch;*/

    int len = getlength(ch);
    reverse(ch);

    cout<<"Reverse :";

    for(int i =0;i <len; i++)
        cout<<*(ch + i);

    cin.get();

}

int getlength(char * ch)
{
    int len=0;
     char *address = ch;
    for(; *(ch)!='\0' ; ch++)
        len++;

    ch=address;
    return len;
}

void reverse(char *ch )
{
    char tmp;
    int i,j,len=getlength(ch);

    for(i=0;i<(len/2);i++)
        for(j=len-1;j>(len/2);j--){
            tmp=*(ch+i);
            *(ch+i)=*(ch+j); //ACCESS VIOLATED
            *(ch+j)=tmp;

        }

and why that happens? ch+i and + j are in length of the char pointer (array really what should i call it at the moment?) but it throws a c ?
and my current code is almost pointer free but as arrays are somehow pointer and they re called by reference so i guess i did it :
   #include <iostream>

using namespace std;

void reverse (char ch [],int len);

int main ()
{
    char  ch [] ="USAF";
    int len = sizeof(ch);
    reverse(ch,len);

    cout<<"Reverse :";

    for(int i =0;i <len; i++)
        cout<<ch[i];
    cin.get();

}

 void reverse(char ch [],int len)
{

    int i,j;
    char tmp;
    for(i=0;i<len;i++)
        cout<<*(ch+i);

    cout<<*(ch+(3-1));

for(i=0;i<(len/2);i++)
for(j=len-1 ; j>(len/2);j--){

tmp = ch[i];
ch[i]=ch[j];
ch[j]=tmp;

}

but when i compile it shows : "F AUS" its so strange from where that blank character appeared  ? (some cout lines are just leftovers  dont mind em)
PS: This is my first post in stackoverflow(cool name btw :) ) . i really enjoyed pro atmosphere here and found it a good place to ask my own questions + when i get a good deal of knowledge answer others.
Comment: This is more C than C++ TBH. Is there a reason for it?
Comment: `char  *ch ="USAF";` is deprecated in C++ and allowed only for backwards compatibility with C. You should use `const char  *ch ="USAF";` and viola, a bug is revealed!
Comment: @luk32 well my reference used such . btw im interested to learn c . its cool .
Comment: have also a look on the [C++ way of reversing](http://stackoverflow.com/a/10682311/2932052)
Answer: The variable ch points to a string literal, which is an array of constant characters. In other words, attempting to change it will lead to undefined behavior.
Instead when declare it as an array, like
char ch[] = "USAF";

then the compiler creates the string on the stack and it's not constant so you can change the contents of the array.
Comment: **Yes:** UB, but I think it's also bad style to treat string literals as arrays of chars.
Comment: @KNOWN-SOURCE I think you should definitely learn to use `std::string` and all its benefits - be sure you'll love it. Ah, and you should also try `cout << ch` :-)
Comment: @wolf so using c style has no benefits? can i just abandon and go for string class in full?
Answer: http://cpp.sh/3ekd
#include <iostream>

using namespace std;

int getlength(char *);
void reverse(char * ch);

int main()
{
    char  ch[] = "USAF";
    /*cout<<*ch;*/

    int len = getlength(ch);
    reverse(ch);

    cout << "Reverse :";

    for (int i = 0; i < len; i++)
        cout << *(ch + i);

    cin.get();

}

int getlength(char * ch)
{
    int len = 0;
    char *address = ch;
    for (; *(ch) != '\0'; ch++)
        len++;

    ch = address;
    return len;
}

void reverse(char *ch)
{
    int len = getlength(ch);

    for (int i = 0; i < len / 2; i++) {
        char c = ch[i];
        ch[i] = ch[len - i - 1];
        ch[len - i - 1] = c;
    }
}


Awning materials for deck under dirty trees

Question: Our second-story deck is underneath some weeping Cherry trees and Birch trees, which drop cherries, pollen, twigs and junk 3/4 of the year it seems. I want to put an awning over the deck (there is already a frame) to keep the junk off the deck and reduce cleaning. My wife thought of aluminum door/window screen, but I know that will become caked with junk and require scrubbing with a brush. I think that standard canvas will become stained with black cherry juice, which has already stained our newly repainted deck after just 1 season.
What kind of material is available in order to:
-be easy to wash debris off with a hose
-not become stained from cherries
-allow some ambient light (ie white?)
Is there some kind of tyvek-like awning material available?
Answer: You will probably find that the best material to use is Translucent Corrugated Fiberglass Panels. These are available at building supply and some big-box stores, along with accessories and fittings needed to make a sloping roof.

According to product reviews: stay away from PVC because it it too brittle, and avoid polycarbonate because it is too expensive.
Answer: I don't know of a material that will allow "some light in" and resist the stains of cherries. I think translucent panels will stain and because they are translucent, you'll see the stains from below.
The only material that could resist staining might be metal roof panels with a baked-on coating like a fluoropolymer (PVDF) coating, like Kynar Roof Coating...but the sound could drive you nuts in a hail storm or when the cherries are dropping.


Remove specific data from a table which are common based on certain fields

Question: I have a table EMPLOYEE as under:
Enroll Date STS EMP_ID  EMP_Name   DEPT    Rank OST BLOCK
12-Jan-17    Q    123     ABC     ABC123    12  Y   1000
14-Jan-17    Q    123     ABC     DEF123    12  Y   1000
15-Jan-17    R    123     ABC     DEF123    12  Y   100
15-Jan-17    R    123     ABC     DEF123    12  Y   200
15-Jan-17    R    123     ABC     DEF123    12  Y   300
20-Jan-17    R    123     ABC     DEF123    10  Y   300
26-Jan-17    R    456     RST     DEF456    8   N   200
26-Jan-17    R    456     RST     DEF456    8   N   300
2-Feb-17     Q    123     ABC     ABC123    12  Y   300

Now i need to remove the duplicate rows for each emp_id (duplicate if EMP_Name, DEPT, OST and rank is same). If 2 rows have these 4 value same and enroll_date is different then i need not delete that row. And if 2 rows have same enroll date and the 4 fields (OST, EMP_Name, DEPT and rank) are same then i need to keep the row with highest block (1000 followed by 300 followed by 200 and so on)
So after deleting such data my table should have these rows:
Enroll Date STS EMP_ID  EMP_Name    DEPT    Rank    OST BLOCK
12-Jan-17    Q   123       ABC     ABC123    12      Y  1000
14-Jan-17    Q   123       ABC     DEF123    12      Y  1000
15-Jan-17    R   123       ABC     DEF123    12      Y  100
2-Feb-17     Q   123       ABC     ABC123    12      Y  300
20-Jan-17    R   123       ABC     DEF123    10      Y  300
26-Jan-17    R   456       RST     DEF456    8       N  200
26-Jan-17    R   456       RST     DEF456    8       N  300

I tried using below query and will delete rows which have rn >1
SELECT enroll_date, STS, BLOCK, EMP_ID, EMP_NAME, DEPT,RANK, OST, row_number() over ( partition BY emp_id, enroll_date,emp_name, dept, ost, rank ORDER BY enroll_date ASC, block DESC)rn
  FROM employee
But i am getting rn as 1 only everytime.
can someone check the issue here or suggest some other way to do so?
Comment: The three rows with 15-Jan all get rn as 1? Are the rimes for those date values all midnight - what does `to_char(enroll_date, 'SYYYY-MM-DD HH24:MI:SS')` show the time oart as for those (or all) rows? If they are not all midnight, should they be?
Comment: Please explain in more detail: "if **2 rows** have ....  then I need not delete **that row**". When you have TWO ROWS, which one is "THAT ROW"?
Comment: @Mathguy-
"If 2 rows have these 4 value same and enroll_date is different then i need not delete that row"
This means that if any 2 rows in the table have exactly same value (all the 4 column should have same value) for the columns OST, EMP_Name, DEPT and rank, then taht row needs to be deleted. But in same case if the enroll_date is different for any 2 rows which have exact same value for OST, EMP_Name, DEPT and rank, then we need to retain both rows.
Answer: It looks like your enroll_date values have non-midnight times, so partitioning by those also made those combinations unique (even though they don't look it when you only show the date part).
My initial thought was that your analytic row_number() was partitoned by too many columns, and that you shouldn't be including the date value you want to order by - it doesn't really make sense to partition by and order by the same thing, as it will be unique. Reducing the columns you actually want to check against, perhaps to:
row_number() over (partition BY emp_id, emp_name, dept, ost, rank
  ORDER BY enroll_date ASC, block DESC)

would produce different ranks rather than all being 1. But I don't think that's right; that would probably make your secondary block ordering somewhat redundant, as you'll maybe be unlikely to have two rows with exactly the same time for one ID. Unlikely but not impossible, perhaps.
Re-reading your wording again I don't think you want to be ordering by the enroll_date at all, and you do want to be partitioning by the date instead; but, given that it contains non-midnight times that you apparently want to ignore for this exercise, the partitioning would have to be on the truncated date (which strips the time back to midnight, by default:
row_number() over (partition BY trunc(enroll_date), emp_id, emp_name, dept, ost, rank
  ORDER BY block DESC)

With your sample data as a CTE, including slightly different times within each day, and one extra row to get everything the same but the date, this shows your original rn and my two calculated values:
with employee (enroll_date, sts, emp_id, emp_name, dept, rank, ost, block) as (
  select to_date('12-Jan-17 00:00:00', 'DD-Mon-RR HH24:MI:SS'), 'Q', 123, 'ABC', 'ABC123', 12, 'Y', 1000 from dual
  union all select to_date('14-Jan-17 00:00:00', 'DD-Mon-RR HH24:MI:SS'), 'Q', 123, 'ABC', 'DEF123', 12, 'Y', 1000 from dual
  union all select to_date('15-Jan-17 00:00:01', 'DD-Mon-RR HH24:MI:SS'), 'R', 123, 'ABC', 'DEF123', 12, 'Y', 100 from dual
  union all select to_date('15-Jan-17 00:00:02', 'DD-Mon-RR HH24:MI:SS'), 'R', 123, 'ABC', 'DEF123', 12, 'Y', 200 from dual
  union all select to_date('15-Jan-17 00:00:03', 'DD-Mon-RR HH24:MI:SS'), 'R', 123, 'ABC', 'DEF123', 12, 'Y', 300 from dual
  union all select to_date('20-Jan-17 00:00:00', 'DD-Mon-RR HH24:MI:SS'), 'R', 123, 'ABC', 'DEF123', 10, 'Y', 300 from dual
  union all select to_date('26-Jan-17 00:00:00', 'DD-Mon-RR HH24:MI:SS'), 'R', 456, 'RST', 'DEF456', 8, 'N', 200 from dual
  union all select to_date('26-Jan-17 00:00:01', 'DD-Mon-RR HH24:MI:SS'), 'R', 456, 'RST', 'DEF456', 8, 'N', 300 from dual
  union all select to_date('2-Feb-17 00:00:00', 'DD-Mon-RR HH24:MI:SS'), 'Q', 123, 'ABC', 'ABC123', 12, 'Y', 300 from dual
  union all select to_date('3-Feb-17 00:00:00', 'DD-Mon-RR HH24:MI:SS'), 'Q', 123, 'ABC', 'ABC123', 12, 'Y', 300 from dual
)
SELECT to_char(enroll_date, 'DD-Mon-RR') as date_only,
  enroll_date, sts, block, emp_id, emp_name, dept, rank, ost,
  row_number() over ( partition BY emp_id, enroll_date, emp_name, dept, ost, rank
    ORDER BY enroll_date ASC, block DESC) your_rn,
  row_number() over (partition BY emp_id, emp_name, dept, ost, rank
    ORDER BY enroll_date ASC, block DESC) my_rn_1,
  row_number() over (partition BY trunc(enroll_date), emp_id, emp_name, dept, ost, rank
    ORDER BY block DESC) as my_rn_2
FROM employee
ORDER BY enroll_date;

DATE_ONLY ENROLL_DATE         S BLOCK EMP_ID EMP DEPT   RANK O YOUR_RN MY_RN_1 MY_RN_2
--------- ------------------- - ----- ------ --- ------ ---- - ------- ------- -------
12-Jan-17 2017-01-12 00:00:00 Q  1000    123 ABC ABC123   12 Y       1       1       1
14-Jan-17 2017-01-14 00:00:00 Q  1000    123 ABC DEF123   12 Y       1       1       1
15-Jan-17 2017-01-15 00:00:01 R   100    123 ABC DEF123   12 Y       1       2       3
15-Jan-17 2017-01-15 00:00:02 R   200    123 ABC DEF123   12 Y       1       3       2
15-Jan-17 2017-01-15 00:00:03 R   300    123 ABC DEF123   12 Y       1       4       1
20-Jan-17 2017-01-20 00:00:00 R   300    123 ABC DEF123   10 Y       1       1       1
26-Jan-17 2017-01-26 00:00:00 R   200    456 RST DEF456    8 N       1       1       2
26-Jan-17 2017-01-26 00:00:01 R   300    456 RST DEF456    8 N       1       2       1
02-Feb-17 2017-02-02 00:00:00 Q   300    123 ABC ABC123   12 Y       1       2       1
03-Feb-17 2017-02-03 00:00:00 Q   300    123 ABC ABC123   12 Y       1       3       1

To identify the rows to delete you can use a subquery:
SELECT enroll_date, sts, block, emp_id, emp_name, dept, rank, ost
FROM (
  SELECT enroll_date, sts, block, emp_id, emp_name, dept, rank, ost,
    row_number() over (partition BY trunc(enroll_date), emp_id, emp_name, dept, ost, rank
      ORDER BY block DESC) as my_rn_2
  FROM employee
)
WHERE my_rn_2 > 1
ORDER BY enroll_date;

ENROLL_DATE         S BLOCK EMP_ID EMP DEPT   RANK O
------------------- - ----- ------ --- ------ ---- -
2017-01-15 00:00:01 R   100    123 ABC DEF123   12 Y
2017-01-15 00:00:02 R   200    123 ABC DEF123   12 Y
2017-01-26 00:00:00 R   200    456 RST DEF456    8 N

You'll need to decide what actually makes sense for your data and requirements though.
Comment: I think you are correct, edited the query and posting the anwer with that. It working now by changing the enroll_date with trunc function.
Comment: Are you sure you want to use the row with the highest block on a given day, even of there are other rows with later times that day? You are ignoring the times - that may actually be what you do want, but I'd check that is correct before deleting anything. Without knowing what block represents, it just sounds a bit odd.
Answer: I am creating a temporary table which will have all non duplicate values:
 create table employee_temp as
 with duplicates as (
 SELECT enroll_date, STS, BLOCK, EMP_ID, EMP_NAME, DEPT,RANK, OST, row_number()     over ( partition BY emp_id, trunc(enroll_date),emp_name, dept, ost, rank ORDER BY enroll_date ASC, block DESC)rn FROM employee )
 SELECT enroll_date, STS, BLOCK, EMP_ID, EMP_NAME, DEPT,RANK, OST from duplicates where rn =1;


Fetch discounts list using PHP in Prestashop 1.7

Question: The site I'm working on requires me to fetch the available discount for a product and let the customer select the discount from the available options. I tried the below code from How to get the discount amount code of voucher applied in prestashop to fetch the discounts but I'm getting an empty array.
Below being the code on Prestashop controller for fetching discounts.
$context = Context::getContext();
$result = $context->cart->getCartRules(10);
$response = array('status' => true, "message" => $module->l('It works !'), 'result' => $result);

I'm getting an empty array in the result.

I'm not sure what am I doing wrong.
Answer: I figured out a way to do it without the ajax call.
What must be done is just create a discount for a product in the Prestashop admin backend. And then display the discounts in the front end template files using the cart class.
{foreach from=$cart.discounts item=discount}

    <input type="radio" name="trade-in-discount" value="{$discount.code}">{$discount.name}

{/foreach}


Will my tub drain properly if I create a P-trap by running it under a 4 inch floor joist?

Question: Remodeling bathroom in old house. Water always backed up in the tub. I've replaced the waste lines and pitched them properly. The original line from the tub went under a double floor joist and across 3 others. Should I do something different?
Comment: Do you have a problem that you need insight on?
Answer: If the drain is sloped correctly per your local building codes (mine state for  drain pipes under 2 inches the slope be 1/4 inch per foot) and it is connected to a stack of the proper size (usually no smaller than 1 1/4 inch pipe) then your drain and trap should operate trouble-free. Also be sure the distance from the trap to the vent or stack is correct (in my county any run over 40 feet will need a larger diameter vent).  As far as running pipe through framing members and joists you must be selective on the location to drill a hole through. This depends one the size of the joist and if it has existing openings already drilled into it. If you plan to use a non-drilled joist one opening (again, depending on the size of the joist)is safe. Be sure not to deviate from the starting slope.
Comment: It's a bit more complicated than just "one hole is safe" -- there's a good answer on this site that [explains the rules for holes in joists](https://diy.stackexchange.com/a/10661/157).
Comment: The original drain line runs across 3 floor joists that are notched at the top  and then turned 45 degrees down and turned 45 degrees to go under a double joist.  If I make another turn up to the tub/shower drain on the other side of the double joist, will that create a kind if natural  p trap?  I'm kind if worried about the tub/shower  draining properly with that design. This was the original design.
Comment: This is a very good site with great information. My v
Comment: I have seen this. Its great.  Since the natural path of the drain line runs into the double joist. So it turned down and turned 45 degrees again to go under the double joist.  Then up to the tub/shower p trap.  I don't think you can notch that double joist.
Comment: That will depend on the location of the notch or hole in the joist and also the size.


My java code stops and until I hit enter or any key it doesn't work when it just skips that line and goes on to the next one

Question: I am a beginner java programmer. My homework was to create a product inventory.

Write a java program to create product inventory management with basic
details like product name, id, quantity. The program should run
iteratively to get user choice until choose the exit option. The
sample required output has been given below.

I created a class(Products) that has variables like name(String) and id&quantity(int) which could store values. Then I created a main class where I made an array of objects from the Products class where in each of the element of the array I could store details of a product(name, id and quantity). Then using while and switch I tried performing functions like adding new products, showing all products, deleting product and exiting the loop. After that I added 3 products using the add products case This is output of adding products. Then I tried to display all the products that are stored, but it only shows the first 2 products. To better understand look at the picture.This is the image of displaying all the products stored. Look at my java code to see what I tried.
import java.util.*;
class Products{
    String name;
    int id, quantity;
}

public class Task2{
    public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    Products p[] = new Products[100];

        int h = 0;
        while(h!=1){
            System.out.print("23BEC7217@ Enter your choice: ");
            int ch = sc.nextInt();

        switch (ch) {
            case 1: //add products
            for(int i = 0;i < p.length;i++){
                    if(p[i] instanceof Products){
                        ;
                    }else{
                        System.out.println("Enter the product details: ");
                        p[i] = new Products();
                        sc.nextLine();
                        p[i].name = sc.nextLine();
                        p[i].id = sc.nextInt();
                        p[i].quantity = sc.nextInt();
                        break;
                    }
                }

                break;
            case 2 : //show products
            for(int i = 0;i < p.length;i++){
                if(p[i] != null){
                    System.out.println(p[i].name);
                    System.out.println(p[i].id);
                    System.out.println(p[i].quantity);
                    sc.nextLine();
                }
            }break;

            case 3://deleting products
            System.out.println("Enter the product id to delete: ");
            int id = sc.nextInt();
            int i = 0;
            while(i<p.length && p[i] != null){
                if(p[i].id == id){
                    p[i] = null;
                }
                i++;
            };
            break;

            case 4:
            System.out.println("Bye");
            h=1;
            break;

            default:
            System.out.println("Enter a valid number: ");
            break;

        }
    }
    }

    }

This is my complete java code and what I tried. I am very new to java and stack overflow so please ignore my mistakes and help with my problem.
Comment: You are running `sc.nextLine();` inside the `for` loop of showing the products. This means you try to read lines as much as there are already products in the array. When you, let say, have already 10 products in the array, you will be calling `sc.nextLine();` 10 times as well (and waiting for 10 inputs), for no reason.
Comment: @Progman thank u very much it worked but is there any alternative for sc.nextline() because if I remove that and try to replace it with System.out.print() or System.out.println() both give me "Exception in thread "main" java.util.InputMismatchException" error immediately after I give my first input(p[i].name). Again thank u so much for ur help:)
Answer: try this code and tell me
import java.util.*;

class Products {
    String name;
    int id, quantity;
}

public class Task2 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Products p[] = new Products[100];

        int h = 0;
        while (h != 1) {
            System.out.print("23BEC7217@ Enter your choice: ");
            int ch = sc.nextInt();

            switch (ch) {
                case 1: // add products
                    for (int i = 0; i < p.length; i++) {
                        if (p[i] == null) {
                            System.out.println("Enter the product details: ");
                            p[i] = new Products();
                            sc.nextLine();
                            p[i].name = sc.nextLine();
                            p[i].id = sc.nextInt();
                            p[i].quantity = sc.nextInt();
                            break;
                        }
                    }
                    break;
                case 2: // show products
                    for (int i = 0; i < p.length; i++) {
                        if (p[i] != null) {
                            System.out.println("Product Name: " + p[i].name);
                            System.out.println("Product ID: " + p[i].id);
                            System.out.println("Product Quantity: " + p[i].quantity);
                        }
                    }
                    break;

                case 3:// deleting products
                    System.out.println("Enter the product id to delete: ");
                    int id = sc.nextInt();
                    for (int i = 0; i < p.length; i++) {
                        if (p[i] != null && p[i].id == id) {
                            p[i] = null;
                            System.out.println("Product with ID " + id + " deleted successfully.");
                            break;
                        }
                    }
                    break;

                case 4:
                    System.out.println("Bye");
                    h = 1;
                    break;

                default:
                    System.out.println("Enter a valid number: ");
                    break;

            }
        }
    }
}


casting a pointer to struct for qsort's compare

Question: So I'm using qsort() in c and my compare function usually consist of creating a pointer of the correct type and assigning it the value from the arguments. is it possible to just cast the pointer from the arguments without creating a new one?
if so, what am i doing wrong?
struct date_t{
    int time;
    int dob;
};

/* the old working function
int cmpfunc (const void * one, const void * two) {
    struct date_t *itemtwo=two;
    struct date_t *itemone=one;
return itemone->time-itemtwo->time;
}
*/

int cmpfunc (const void * one, const void * two) {
    return (struct date_t*)(one)->time - (struct date_t*)two->time;
}

i'm getting :
main.c:17:30: warning: dereferencing 'void *' pointer
  return (struct date_t*)(one)->time - (struct date_t*)two->time;
                          ^~
main.c:17:30: error: request for member 'time' in something not a structure or union

EDIT:
i got it to compile with
int cmpfunc (struct date_t *one, struct date_t *two) {
    return one->time - two->time;
}

but still, how would i do it with casts?
Comment: Cast it like this: `((struct date_t*)one)->time`. Mind the operator precedence.
Comment: `((struct date_t*)one)->time`
Answer: The type cast operator () has lower precedence than the pointer-to-member operator ->.  So this:
(struct date_t*)(one)->time

Is the same as this:
(struct date_t*)((one)->time)

You need to parenthesize what is casted, then you can dereference the pointer.
int cmpfunc (const void * one, const void * two) {
    return ((const struct date_t*)(one))->time - ((const struct date_t*)two)->time;
}

Also note that the casted pointers are const to be consistent with the original pointers.
Answer: According to the handy precedence table, the cast operation has a lower precedence than the structure member access operator ->. So when doing (struct date_t*)(one)->time, first the member time is accessed (and failed, as one is a void* and has no such a member). And only then the cast is performed on the result. Instead you should force the precedence by using parentheses in appropriate places like:
... ((struct date_t*)one)->time ...


why ajax callback is setting undefined in my local variable?

Question: I found a bug in my site, because of this strange behavior.
The second function alerts "undefined" instead of "one".
function test() {
    var myParam = "one"
    if (false) {
        var myParam = "two";
    }
    alert(myParam);
}
test(); // alert "one"

function testAjax() {
    var myParam = "one";
    $.ajax({
        url:    "http://url-to-get-error",
        error:  function(){
            if (false) {
                var myParam = "two";
            }
            alert(myParam);
        }
    });
}
testAjax(); // alert "undefined"

And if I comment block bellow, alerts "one" correctly.
Someone knows why?
if (false) {
var myParam = "two";
}

See in http://jsfiddle.net/EaW8D/2/.

UPDATE
Guys, I know how to to solve the problem, thanks a lot!
But the question is WHY js is setting undefined in a block
that NEVER run (if (false)).
Comment: Sorry, but in the first post i wrote **And if I comment block bellow, alerts "one" correctly. Someone knows why?**....so, I think that I asked why.
Comment: Be specific about your question inital post asks for ..**The second function alerts "undefined" instead of "one".** ..late in your update you ask for ** WHY ** ?this causes confusion on the anwsers which we provide.
Comment: Fine have just read it at first I went through with your provided JSFiddle..
Answer:
Someone knows why?

You are re-declaring myParam inside the error handler, shadowing the variable with the same name in the outer scope. Variable declarations are "hoisted" to the top of the function, so your code is effectively the same as:
error:  function(){
    var myParam;  // <- declaration
    if (false) {
        myParam = "two"; // <-  initialization
    }
    alert(myParam);
}

and since the if block is never executed, myParam will be undefined (the default value for uninitialized variables).
Here is a simple example to proof this behaviour. If the variable was not hoisted, foo would become a global variable (assuming non-strict mode) and a property of window, but it does not:
(function() {
    if(false) {
        var foo = 'bar';
    }
    foo = 'baz';
    console.log(window.foo); // yields `undefined`
}());

To solve this problem, simply remove var, so that myParam refers to the variable declared in the outer scope, testAjax:
error:  function(){
    if (false) {
        myParam = "two";
    }
    alert(myParam);
}

Answer: Because you're creating myParam as a new var again
function testAjax() {
    var myParam = "one";
    $.ajax({
        url:    "http://url-to-get-error",
        error:  function(){
            if (false) {
                myParam = "two";
            }
            alert(myParam);
        }
    });
}
testAjax(); // alert "undefined"

http://jsfiddle.net/mKdhx/
Comment: Why is the previous definition unset even when the execution never reaches the `var myParam = "two";` line?
Answer: All variable declarations of the form var myParam are hoisted to the top of the function scope.  Even if they are in inaccessible blocks or at the end of the function, a function with a var declaration in it anywhere will treat all instance of that variable name as local.
Consider this handler:
    error:  function(){
        alert(myParam);
        var myParam;
    }

It will also cause a undefined alert, because the var myParam at the bottom means, "Treat all instance of myParam that come both before and after this declaration as local variables in this function."  The same hoisting that applies in this case applies in your inaccessible-logic-block case.
Answer: in second situation your myParam=one and myParam=two are in different blocks - and moreover callback of ajax error is not "under" testAjax in terms of variable visibility - it's asynchroneus. You would need myParam in global scope
Comment: I didn't downvote, but they're in two different *functions* -- JS has function scope, not block scope.  Also, it doesn't actually have to be in *global* scope, it could exist in a non-global shared scope, like a function that wraps all the code.
Comment: agreed about global scope. about block scope - yes I meant function scope - just didn't say correctly


What are my insulation options around a shower?

Question: I'm remodeling my bathroom and shower and I'll be replacing the insulation on the external wall. This wall is the "back" of the shower (opposite from where the water supply lines are). With this in mind, I should be able to just choose some insulation and then plop it in when I have the wall torn down.
The main question and concern I have is about vapor barrier. I will be using cement board with a liquid topical membrane (like Redgard) for waterproofing the shower which means I'm not supposed to put a vapor barrier on the back side of the wall because it is bad to trap moisture. How does this affect insulating? Am I safe to nix the vapor barrier around the shower? What should I do for the rest of the bathroom?
I'm not too concerned with price so if there are other options besides batting insulation (such as foam, etc...) that would solve my problem, I'm willing to hear those ideas as well.
Answer: I'd use unfaced fiberglass, at least if each wall cavity has a place above the shower where the wall can breathe.  Fiberglass is very permeable to air, which is why it only works well in still air.
Answer: I really recommend Hardie boards vs. other good competitors.  They are oblivious to water - don't hold it and break down.  If money is no object, nothing outperforms sprayfoam.  If you want something that works well but cheaper - Roxul.  I have not used a vapor barrier on any of my HB/redguard installs unless inspector needs to see it then I stick fork holes all over it.