Add custom font for complete android application

Question: In my application I need to use helvetica font for all the textviews and edit-text fields. Is there any way to do this other than using settypeface method for every textview ? Any suggestion would be a great help.
Thanks in advance !
Comment: Visit this one: may be it can be helpful to you:

http://stackoverflow.com/questions/2888508/how-to-change-the-font-on-the-textview/16166184#16166184
Comment: No, there is no way. You have to bundle your font and do as nik says. You can also look at this thread [http://stackoverflow.com/questions/2376250/custom-fonts-and-xml-layouts-android](http://stackoverflow.com/questions/2376250/custom-fonts-and-xml-layouts-android)
Comment: for anyone needing a c#/Xamarin solution which extends textview but also makes it generic i.e. you can pass a specific font path through as an attribute on each textview on the xml, then take a look here https://github.com/Cheesebaron/Cheesebaron.FontSample
Answer: I figured it out by my self. This is the code I used. I create custom TextView which has custom font as default font.
public class MyTextView extends TextView {

    public MyTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

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

    public MyTextView(Context context) {
        super(context);
        init();
    }

    private void init() {
        Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "font/chiller.ttf");
        setTypeface(tf ,1);

    }

}

Comment: @mxg by overriding TextView he's able to use MyTextView in his layout files without having to do anything programmatically in the activity/fragment to realize the custom font.
Comment: @mxg I didn't get what you said
Comment: Here is a good tutorial for this: http://www.barebonescoder.com/2010/05/android-development-using-custom-fonts. If you want to consider different font family types, like bold or italic, you will use different ttf files. The way you can handle that is to ask for this.getTypeface().getStyle() in init method, and use different fonts for the textview. HTH
Comment: all i can see on link above is ads and related links with no content only ads
Answer: In your activities, right after you call

setContentView(R.id.blahblah);

you should run a method to go over the whole hierarchy of widgets and deal with the font substitution, like;
setContentView(R.id.blahblah);
Utils.overrideFonts(this, findViewById(android.R.id.content));

And the mentioned "overrideFonts" method should be something like;
public static void overrideFonts(final Context context, final View v) {
    try {
        if (v instanceof ViewGroup) {
            ViewGroup vg = (ViewGroup) v;
            for (int i = 0; i < vg.getChildCount(); i++) {
                View child = vg.getChildAt(i);
                overrideFonts(context, child);
            }
        } else if (v instanceof TextView) {
            ((TextView)v).setTypeface(FONT_REGULAR);
        }
    } catch (Exception e) {
        e.printStackTrace();
        // ignore
    }
}

In this scheme, FONT_REGULAR should be initialized somewhere safely, you may fancy a singleton or some other way to be sure that it is initialized properly...
private static void initializeFonts(final Context context) {
    FONT_REGULAR = Typeface.createFromAsset(context.getAssets(), "fonts/myfont_medium.otf");
    FONT_BOLD = Typeface.createFromAsset(context.getAssets(), "fonts/myfont_bold.otf");
}

If you use a subclass of Activity like MyAppActivity (extends Activity), then you dont need to change each and every Activity class for such customizations. Instead you may cut into it and override the behavior as such;
public class MyAppActivity extends Activity {
... ...
    @Override
    public void setContentView(final int layoutResID) {
        super.setContentView(layoutResID);
        Utils.overrideFonts(this, findViewById(android.R.id.content));
    }
... ...
}

This way you can use any activity of yours to have common behavior;
public class SettingsUI extends MyAppActivity {
... ...
}

I hope it helps...
Cheers!
Comment: This is a good solution for simple layouts. However, if you have a ListView in your activity, this will not work. Items in the ListView are instantiated after setContent method and therefore, TextView in the list will not be affected by this method
Comment: What about the font of the actionbar?
Comment: you are right, those need to be handled in the ...ItemAdapter class
Comment: TextViews inside fragments won't get their typefaces modified either.
Answer: create a style and use it all text attributes.

Use it:
<TextView style="@style/CustomText" />

Above is to use custom fonts  in all activity for customization you can use....
Typeface font = Typeface.createFromAsset(getAssets(), "CustomFontName.ttf");
txt.setTypeface(font);

TRy this.
Comment: android:typeface field only allow to use inbuilt font names. How can I assign custom font name which is in asset folder ?
Comment: @hanry You cannot use a custom font name in the android:typeface field.  The 2nd part of your answer will work, but the styles portion will not.
Comment: This doesn't answer the question. "Is there any way to do this other than using settypeface method for every textview?".
Answer: To apply custom font across all application, just create following activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FontManager.getInstance().initialize(this, R.xml.fonts);
    setContentView(R.layout.main);
}
@Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
    SimpleFactory factory = new SimpleFactory();
    return factory.onCreateView(name, context, attrs);
}

where FontManager this is class that manage all Fonts that defined in /xml/fonts.xml and SimpleFactory just factory that create views and apply custom font to each view that instance of text view.
/xml/fonts.xml
<?xml version="1.0" encoding="utf-8"?>
<familyset>
    <family>
        <nameset>

            <name>HelveticaNeueLTStd</name>
        </nameset>
        <fileset>

            <file style="normal">fonts/HelveticaNeueLTStd-LtCn.otf</file>
            <file style="bold">fonts/HelveticaNeueLTStd-MdCn.otf</file>
            <file style="italic">fonts/HelveticaNeueLTStd-LtCnO.otf</file>
            <file style="bold_italic">fonts/HelveticaNeueLTStd-MdCnO.otf</file>
        </fileset>
    </family>
    <family>

    </family>
</familyset>

FontFactory - abastract class, just extends it to create your own factory
public abstract class FontFactory implements LayoutInflater.Factory{
    public final String TAG = getClass().getSimpleName();

    static final Class<?>[] mConstructorSignature = new Class[] {Context.class, AttributeSet.class};
    final Object[] mConstructorArgs = new Object[2];
    private static final String[] sClassPrefixList = {
            "android.widget.",
            "android.webkit."
    };

    @Override
    public View onCreateView(String name, Context context, AttributeSet attrs) {
        if("ViewStub".equals(name) || "View".equals(name)){
            return null;
        }
        View view = null;
        Constructor<? extends View> constructor = null;
        Class clazz = null;

        if (view == null) {
            if (-1 == name.indexOf('.')) {
                for (String prefix : sClassPrefixList) {
                    clazz = getClazz(prefix, name);
                    if(clazz != null){
                        break;
                    }
                }
            } else {
                clazz = getClazz("", name);
            }
        }

        if (clazz == null) {
            Log.d(TAG, "View can't be created " + name);
            return null;
        }

        try {
            constructor = clazz.getConstructor(mConstructorSignature);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

        Object[] args = mConstructorArgs;
        args[1] = attrs;

        if(constructor == null){
            return null;
        }

        try {
                view = constructor.newInstance(context, attrs);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        if(view != null){
            onFontApply(context, view);
        }
        return view;
    }

    public abstract void onFontApply(Context context, View view);

    private Class getClazz(String prefix, String name){
        Class clazz = null;
        try {
            clazz = Class.forName(prefix + name);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            return clazz;
        }
    }
}

FontManager - just map font files defined in /xml/fonts.xml to font files placed in /assets directory and return TypeFace by font family name and font style.
public void initialize(Context context, int resId) {
    if(mFonts != null){
        Log.d(TAG,"FontManager have already initialized");
        return;
    }
    XmlResourceParser parser = null;
    try {
        parser = context.getResources().getXml(resId);
        mFonts = new ArrayList();

        String tag;
        String fontStryleAttr = null;
        int eventType = parser.getEventType();

        Font font = null;

        do {
            tag = parser.getName();

            switch (eventType) {
                case XmlPullParser.START_TAG:
                    if (tag.equals(TAG_FAMILY)) {
                        // one of the font-families.
                        font = new Font();
                    } else if (tag.equals(TAG_NAMESET)) {
                        // a list of font-family names supported.
                        font.families = new ArrayList<String>();
                    } else if (tag.equals(TAG_NAME)) {
                        isName = true;
                    } else if (tag.equals(TAG_FILESET)) {
                        // a list of files specifying the different styles.
                        font.styles = new ArrayList<FontStyle>();
                    } else if (tag.equals(TAG_FILE)) {
                        isFile = true;
                        fontStryleAttr = parser.getAttributeValue(null, ATTR_STYLE);
                    }
                    break;

                case XmlPullParser.END_TAG:
                    if (tag.equals(TAG_FAMILY)) {
                        // add it to the list.
                        if (font != null) {
                            mFonts.add(font);
                            font = null;
                        }
                    } else if (tag.equals(TAG_NAME)) {
                        isName = false;
                    } else if (tag.equals(TAG_FILE)) {
                        isFile = false;
                        fontStryleAttr = null;
                    }
                    break;

                case XmlPullParser.TEXT:
                    String text = parser.getText();
                    if (isName) {
                        // value is a name, add it to list of family-names.
                        if (font.families != null)
                            font.families.add(text);
                    } else if (isFile) {
                        // value is a file, add it to the proper kind.
                        FontStyle fontStyle = new FontStyle();
                        fontStyle.font = Typeface.createFromAsset(context.getAssets(), text);
                        String attr = parser.getAttributeValue(null, ATTR_STYLE);
                        if (fontStryleAttr.equals(STYLE_BOLD))
                            fontStyle.style = Typeface.BOLD;
                        else if (fontStryleAttr.equals(STYLE_ITALIC))
                            fontStyle.style = Typeface.ITALIC;
                        else if (fontStryleAttr.equals(STYLE_BOLD_ITALIC))
                            fontStyle.style = Typeface.BOLD_ITALIC;
                        else
                            fontStyle.style = Typeface.NORMAL;
                        font.styles.add(fontStyle);
                    }
            }

            eventType = parser.next();

        } while (eventType != XmlPullParser.END_DOCUMENT);

    } catch (XmlPullParserException e) {
        throw new InflateException("Error inflating font XML", e);
    } catch (IOException e) {
        throw new InflateException("Error inflating font XML", e);
    } finally {
        if (parser != null)
            parser.close();
    }
}

public Typeface get(String family, int style) {
    for (Font font: mFonts) {
        for (String familyName : font.families) {
            if (familyName.equals(family)) {
                // if no style in specified, return normal style.
                if (style == -1)
                    style = Typeface.NORMAL;
                for (FontStyle fontStyle : font.styles) {
                    if (fontStyle.style == style)
                        return fontStyle.font;
                }
            }
        }
    }
    return mDefaultFont;
}

for more code and samples just look here
Answer: Ok you can do it but what you essentially want to make is a font atlas in a kinda map format(it will have to run in unicode order which starts !"#$% '()x+,-./). What the function will do is take in a string and work out where in the atlas each corresponding letter is.
Its not too easy but each character must have the same length and width, you could have different lengths but that will be a lot harder.
Answer: You can use PixlUI at http://bit.ly/1bzjWQn
import their .jar in your project. Use it in XML
 <com.neopixl.pixlui.components.textview.TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world"
    pixlui:typeface="MyFont.ttf" />

Don't forget implement scheme ( xmlns:pixlui="http://schemas.android.com/apk/com.neopixl.pixlui" )
Comment: Why we need add some jar to do what we can purely do with Android itself?
Comment: You can't use custom fonts with Android SDK
Answer:     setContentView(R.layout.activity_main);
    custfont(this, findViewById(android.R.id.content));

private void custfont(final Context context, View v)
{
    try
    {
        if (v instanceof ViewGroup)
        {
            ViewGroup vg = (ViewGroup) v;

            for (int i = 0; i < vg.getChildCount(); i++)
            {
                View child = vg.getChildAt(i);
                overrideFonts(context, child);
            }
        }
        else if (v instanceof TextView )
        {
            ((TextView) v).setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/ostrichblack.ttf"));
        }
    }
    catch (Exception e)
    {
    }
}

Answer: import android.content.Context;
import android.graphics.Typeface;

/**
 * Created by Sanjeev Kumar on 4/18/2017.
 */

public class FontManager {
    public Context mContext;

    public FontManager(Context context) {
        this.mContext = context;
    }

    public Typeface getSquarkiFont() {
        return Typeface.createFromAsset(mContext.getAssets(), "fonts/Squarki.ttf");
    }

    public Typeface getLazySpringDayFont() {
        return Typeface.createFromAsset(mContext.getAssets(), "fonts/LazySpringDay.ttf");
    }
}


Why did the water stop a few hours after my Culligan reverse osmosis filter change?

Question: How do I change the Aqua-Cleer Culligan reverse osmosis filters (the sediment and the carbon ones, the leftmost two of the four)?
Why did the water stop few hours after my change?
Comment: Downvoter, care to comment?
Comment: no clear description of the system ... no clear description of any observations ... no mention of any filter change procedure
Answer: The manual has this under Install Filter Cartridges (I ignored the "lubricate" part as it did not make sense to me),

Twist the cartridge to lock it into the manifold.
  See Figure 2.

I turned the incoming water pipe tap off (from the along-the-pipe position to the across-the-pipe one).
To remove the filters, I twisted them counter-clockwise (looking from the bottom up) and pulled them out.
To put the new ones in, I removed the cellophane from their tops, removed their lids and twisted them in clockwise.
Turned the incoming water pipe tap back on.

The drinking tap in the kitchen had water for few hours after that, then stopped.

Suspecting an issue with incoming water supply, I removed the cover of the filter shelf, removed the steel holder above the incoming tube, pulled out the tube with its plastic cuff, got a bowl ready, turned the incoming tap on for a second and saw the water gushing.
Suspecting a blockage between the filters, I removed the two filters, forced the leftmost (sediment filter) manifold open by rotating it with a screwdriver (taking care not to inflict damage).  Opening the incoming tap for a second pushed water through the manifold.  Closing it off and opening the manifold for the carbon filter showed no water.  (In retrospect I guess this happened because I closed off the sediment socket).
Suspecting an issue with the Automatic Shut-Off (ASO) valve located between the two filters, I removed the top cover, removed the screws, pulled it out, at which moment a few liters of water gushed from the opening (emptying the bladder-pressured tank).

The investigation steps above turned misdirected.  After talking with a local Culligan salesperson, I followed their advice and twisted the filters harder in (clockwise looking from the bottom up).  As soon as I turned the incoming tap on, I heard the water filling the filter system.  The drinking water tap in the kitchen had water couple hours after that.
Comment: On my RO system (iSpring) it requires that after filter change(s) that you flush the system to ensure the carbon dust and sediment is out prior to going into the membrane. You might be ok, but if your water slows down in production you might need to change the RO membrane out as well. My system has a hose I disconnect from the last filter of the pre-RO (filter 3) that I put into a bucket and flush the system until I see no more gray water.
Comment: Usually about 3-5 gallons before it clears, another reason for this flush is to check for leaks on the filter housings and to be sure that water flows though them. I assume at this point your system is back to functioning properly?
Comment: I did not flush the system other than letting the drinking tap run for a minute.  I have no idea if my system has the RO membrane.  It seems reasonable for an RO system to have one...  Thanks for the comments, the system runs OK.
Answer: Sharp Water has it.
Removing the old cartridges:

Turn off inlet feed water valve.
Release each cartridge from manifold by making a counter-clockwise, quarter turn.
Pull down to remove cartridge and dispose.

Installing new cartridges

Mark each cartridge with an install date in the space provided on cartridge label.
Match the inlet and outlet valve on the cartridge to corresponding port within the manifold and insert the cartridge. (Figure 1)

Making a clockwise, quarter turn, twist the cartridge into locked position. (Figure 2)
To replace the polishing filter, the tubing needs to be removed from the old filter. Check both ends of 3/8" tubing for any scratches. If scratches exist, please use a utility knife and make a straight cut to remove any imperfections on tubing. (Figure 3) Connect the tubing to the new polishing filter with the "FLOW" arrow pointed in the direction of the faucet.
Make sure all cartridges are locked in place, and close tank valve, then turn back on the inlet water valve.

Run water for 10 minutes through the faucet in order to flush pre-filters and carbon post-filter.
Check system thoroughly for leaks.

Reinstall the RO membrane, turn on tank valve. Wait for RO tank to refill before product water is available.

http://sharpwater.com/files/support/CulliganAquaCleerMaintenanceDirections.pdf
Answer: A great video by Culligan Water Lloydminster & North Battleford including

how to turn off the filter's water supply,
the tip on pushing in at 1:35,
the reverse osmosis drain change,
how the initial flushing should bypass the accumulating reservoir and kitchen pipes. (It dawned on me that flushing needs to be done step-by-step with adding finer filters so that each addition gets its coarser input flushed before flushing itself).

Culligan How-to Change Aqua-Cleer Filters


How to skip to end of parenthesis in Xcode

Question: After I'm done typing the parameters inside a set of parenthesis, how to skip the cursor to behind the parenthesis so I can just press the semicolon to finish it.
Thanks
Answer: commandright arrow will take you to the end of line.
Comment: Can you change this? I'm used to pressing Tab in Aptana
Comment: Yes. In the Xcode Menu, select Preferences. Then "Key Bindings", then "Text". Look for row that says, "Move to Right End of Line" and then change from default setting (command right-arrow) to anything you like.


How to convert from Arabic numbers to English numbers

Question: When someone puts arabic numbers in my entry , it ends the app .
I'm trying to restrict entry to show only English number or convert arabic number to english
I'm trying it on real device and not working at all unfortunately .
<code> Dictionary<string, string> numberNames;

    // SUM1 لتخزين النتيجة الاولة
    int SUM1 = 0;
    // SUM2 لتخزين النتيجة الثانية
    int SUM2 = 0;
    // DisplayPromptAsync تخزين حالة الاشعار
    string action;
    // لتبديل بين entrys
    int tap = 1;
    // عدد الاعبين
    int playercount = 1;

    int count = 0;
    bool scroll = false;

    public Blootrecord(bool newplay)
    {
        InitializeComponent();

        if (newplay)
        {
            DisplayPrompt(lblname1, "اسم فريقهم");
            DisplayPrompt(lblname2, "اسم فريقنا?");

        }
        else
        {
            // اذا مالنت الثيمة ب False هذا يعني انه يريد الرجوع لاخر لعية
            // هذه اسطر لجلب اخر قيم تم تخزينها
            lblname1.Text = Preferences.Get("lblname1", "");
            lblname2.Text = Preferences.Get("lblname2", "");
            num1.Text = Preferences.Get("num1", "");
            num2.Text = Preferences.Get("num2", "");
            SUM1 = Convert.ToInt32(Preferences.Get("SUM1", "0"));
            SUM2 = Convert.ToInt32(Preferences.Get("SUM2", "0"));
            count = Convert.ToInt32(Preferences.Get("count", "0"));

        }

        numberNames = new Dictionary<string, string>();
        numberNames.Add("0", "۰"); //adding a key/value using the Add() method
        numberNames.Add("1", "۱");
        numberNames.Add("2", "۲");
        numberNames.Add("3", "۳");
        numberNames.Add("4", "٤");
        numberNames.Add("5", "٥");
        numberNames.Add("6", "٦");
        numberNames.Add("7", "٧");
        numberNames.Add("8", "۸");
        numberNames.Add("9", "۹");

        scrollView.HeightRequest = num1.HeightRequest;

    }

    /// <summary>
    /// هذه دالة لعررض الاشعار
    /// </summary>
    /// <param name="label"></param>
    ///         /// <param name="label2"></param>

    /// <param name="str"></param>
    async void DisplayPrompt(Label label, string str)
    {
        var s = await DisplayPromptAsync("Alert", str);
        if (string.IsNullOrEmpty(s))
            label.Text = "فريق" + playercount++;
        else
            label.Text = s;
    }

    /// <summary>
    /// زر سجل
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    ///

    private async void btnRegister_Clicked(object sender, EventArgs e)
    {

        try
        {

            Entnum1 = ARCH(Entnum1);
            Entnum2 = ARCH(Entnum2);

            scrollView.HeightRequest = num1.HeightRequest;

            scroll = false;

            // اضافة سط في Editors مع القيمه المدخله
            num1.Text += "\n" + Entnum1.Text;
            num2.Text += "\n" + Entnum2.Text;
            //اذا كان الentry فارغ يبدل القيمه ب صفر
            if (string.IsNullOrEmpty(Entnum1.Text))
            {
                num1.Text += "0";
            }
            if (string.IsNullOrEmpty(Entnum2.Text))
            {
                num2.Text += "0";
            }
            //تحويل القيمه الي عدد صحيح وجمعها ع اخر قميه
            SUM1 += int.Parse(num1.Text.Substring(num1.Text.LastIndexOf("\n") + 1));
            SUM2 += int.Parse(num2.Text.Substring(num2.Text.LastIndexOf("\n") + 1));
            // اذا كانت القيمه اقل من 152 يتم اضافة سطر ثم خط ثم قيمه الجمع في كل Editor
            if (SUM1 < 152 && SUM2 < 152)
            {
                num1.Text += "\n" + "------";
                num2.Text += "\n" + "------";
                num1.Text += "\n" + SUM1;
                num2.Text += "\n" + SUM2;
            }
            else
            {
                // يتم عرض  اكير قيمه مع اكبر فائز
                if (SUM1 > SUM2)
                {
                    action = await DisplayActionSheet(" هاردلك الفوز لهم " + SUM1 + " ", "اغلاق", "لعبة جديدة");

                }
                else if (SUM1 < SUM2)
                {

                    action = await DisplayActionSheet(" مبروك الفوز لنا" + SUM2 + "", "اغلاق", "لعبة جديدة");
                }
                else

                {

                    action = await DisplayActionSheet("تعادل", "اغلاق", "لعبة جديدة");
                }
                // اذا قمت بأختيار لعبة جديدة
                if (action == "لعبة جديدة")
                {
                    // يحذف جميع القيم ولاكن يبقي اسم العبين
                    num1.Text = num2.Text = "0";
                    Entnum1.Text = Entnum2.Text = null;
                    SUM1 = SUM2 = 0;
                    await scrollView.ScrollToAsync(num1, ScrollToPosition.Start, true);
                    count = 0;
                    scroll = true;
                }
            }

            Entnum1.Text = Entnum2.Text = null;
            // store data
            // تخزين البيانات في كل مره
            Preferences.Set("lblname1", lblname1.Text);
            Preferences.Set("lblname2", lblname2.Text);
            Preferences.Set("num1", num1.Text);
            Preferences.Set("num2", num2.Text);
            Preferences.Set("SUM1", SUM1.ToString());
            Preferences.Set("SUM2", SUM2.ToString());

            count++;
            if (count >= 5 && count <= 7 && !scroll)
            {
                await scrollView.ScrollToAsync(num1, ScrollToPosition.Center, true);
            }
            else if (count > 7 && !scroll)
            {
                await scrollView.ScrollToAsync(num1, ScrollToPosition.End, true);

            }
        }
        catch (Exception ex)
        {
            // في حالة وجود خطأ غير متوقع
            await DisplayAlert("Opps!", ex.Message, "Ok");
            await Navigation.PopAsync();
        }
    }

    void btnBack_Clicked(System.Object sender, System.EventArgs e)
    {

        try
        {

            if (num1.Text != "0" && num2.Text != "0")
            {
                // يتم اذالة ثلاث اسطر وطرح قيمة السطر الثالث من المجموع الكلي ثم ازالة السطر الثالث
                // editor number one
                num1.Text = num1.Text.Remove(num1.Text.LastIndexOf("\n"));
                num1.Text = num1.Text.Remove(num1.Text.LastIndexOf("\n"));
                SUM1 -= int.Parse(num1.Text.Substring(num1.Text.LastIndexOf("\n") + 1));
                num1.Text = num1.Text.Remove(num1.Text.LastIndexOf("\n"));
                // editor number two
                num2.Text = num2.Text.Remove(num2.Text.LastIndexOf("\n"));
                num2.Text = num2.Text.Remove(num2.Text.LastIndexOf("\n"));
                SUM2 -= int.Parse(num2.Text.Substring(num2.Text.LastIndexOf("\n") + 1));
                num2.Text = num2.Text.Remove(num2.Text.LastIndexOf("\n"));
            }
        }
        catch (Exception ex)
        {

            DisplayAlert("Opps!", ex.Message, "Ok");
        }
    }

    private void Entnum1_Focused(object sender, FocusEventArgs e)
    {
        tap = 1;
    }

    private void Entnum2_Focused(object sender, FocusEventArgs e)
    {
        tap = 2;
    }

    private void Entnum2_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        // في حالة اختيار Closr

        if (action == "اغلاق")
        {
            // حزف جميع القيم المخزنه
            Preferences.Clear();
            // الرجوع الي الصفحة الاولة
            Navigation.PopAsync();
        }
    }

    Entry ARCH(Entry entry)
    {
        for (var i = 0; i < 10; i++)
        {
            entry.Text = entry.Text.Replace(numberNames[i.ToString()], i.ToString());
        }

        return entry;
    }

}
}
</code>
Comment: Does this answer your question? [How to convert Arabic number to int?](https://stackoverflow.com/questions/5879437/how-to-convert-arabic-number-to-int)
Comment: https://stackoverflow.com/questions/5879437/how-to-convert-arabic-number-to-int
Comment: https://stackoverflow.com/questions/64413727/c-sharp-int-and-non-english-numbers
Comment: This may help you. It's for Persian numeric digits, but they are identical to the Arabic digits.
Answer: You could try this method to convert it:
<code> private string convertArabic(string arabicNum)
    {
        var chArr = arabicNum.ToCharArray();
        var sb = new Java.Lang.StringBuilder();
        foreach (var ch in chArr)
        {
            if (Character.IsDigit(ch))
            {
                sb.Append(Character.GetNumericValue(ch));
            }
            else if (ch == '٫')
            {
                sb.Append(".");
            }

            else
            {
                sb.Append(ch);
            }
        }
        return sb.ToString();
    }
</code>


K-medoids: k = total dataset

Question: I have a project about K-medoids, how to perform K-medoids if I set K = total dataset.
ex: Dataset[0,1,2,3]
K = 4
this means, we dont have non-medoids for iteration. so what should I do?
Answer: Setting k = N means that every point is a cluster.
You don't need to run the algorithm at all then, but you are already done.
In general, if a cluster has only 1 object, you cannot improve by swapping.

K-medoids: k = total dataset


Find if there is any holidays between two dates in a large dataset?

Question: I am working on a dataset that has some 26 million rows and 13 columns including two datetime columns arr_date and dep_date. I am trying to create a new boolean column to check if there is any US holidays between these dates.
I am using apply function to the entire dataframe but the execution time is too slow. The code has been running for more than 48 hours now on Goolge Cloud Platform (24GB ram, 4 core). Is there a faster way to do this?
The dataset looks like this:
Sample data
The code I am using is -
import pandas as pd
import numpy as np
from pandas.tseries.holiday import USFederalHolidayCalendar as calendar

df = pd.read_pickle('dataGT70.pkl')
cal = calendar()
def mark_holiday(df):
    df.apply(lambda x: True if (len(cal.holidays(start=x['dep_date'], end=x['arr_date']))>0 and x['num_days']<20) else False, axis=1)
    return df

df = mark_holiday(df)

Comment: Maybe we can do parallel computing speed up the process
Comment: Sample data would be nice.  You also have a filter in your apply: `x['num_days']<20`.  Can you please elaborate?
Comment: @Alexander That's a good observation but that would just eliminate 1.5% of the data in my case.
Answer: This took me about two minutes to run on a sample dataframe of 30m rows with two columns, start_date and end_date.
The idea is to get a sorted list of all holidays occurring on or after the minimum start date, and then to use bisect_left from the bisect module to determine the next holiday occurring on or after each start date.  This holiday is then compared to the end date.  If it is less than or equal to the end date, then there must be at least one holiday in the date range between the start and end dates (both inclusive).
from bisect import bisect_left
import pandas as pd
from pandas.tseries.holiday import USFederalHolidayCalendar as calendar

# Create sample dataframe of 10k rows with an interval of 1-19 days.
np.random.seed(0)
n = 10000  # Sample size, e.g. 10k rows.
years = np.random.randint(2010, 2019, n)
months = np.random.randint(1, 13, n)
days = np.random.randint(1, 29, n)
df = pd.DataFrame({'start_date': [pd.Timestamp(*x) for x in zip(years, months, days)],
                   'interval': np.random.randint(1, 20, n)})
df['end_date'] = df['start_date'] + pd.TimedeltaIndex(df['interval'], unit='d')
df = df.drop('interval', axis=1)

# Get a sorted list of holidays since the fist start date.
hols = calendar().holidays(df['start_date'].min())

# Determine if there is a holiday between the start and end dates (both inclusive).
df['holiday_in_range'] = df['end_date'].ge(
    df['start_date'].apply(lambda x: bisect_left(hols, x)).map(lambda x: hols[x]))

>>> df.head(6)
  start_date   end_date  holiday_in_range
0 2015-07-14 2015-07-31             False
1 2010-12-18 2010-12-30              True  # 2010-12-24
2 2013-04-06 2013-04-16             False
3 2013-09-12 2013-09-24             False
4 2017-10-28 2017-10-31             False
5 2013-12-14 2013-12-29              True  # 2013-12-25

So, for a given start_date timestamp (e.g. 2013-12-14), bisect_right(hols, '2013-12-14') would yield 39, and hols[39] results in 2013-12-25, the next holiday falling on or after the 2013-12-14 start date. The next holiday calculated as df['start_date'].apply(lambda x: bisect_left(hols, x)).map(lambda x: hols[x]). This holiday is then compared to the end_date, and holiday_in_range is thus True if the end_date is greater than or equal to this holiday value, otherwise the holiday must fall after this end_date.
Comment: Thanks @Alexander. It worked and takes around 16 mins. Preety fast!! Accepted your answer.
Answer: Have you already considered using pandas.merge_asof for this?
I could imagine that map and apply with lambda functions cannot be executed that efficiently.
UPDATE: Ah sorry, I just read, that you only need a boolean if there are any holidays inbetween, this makes it much easier. If thats enough you just need to perform steps 1-5 then group the DataFrame that is the result of step5 by start/end date and use count as the aggregate function to have the number of holidays in the ranges. This result you can join to your original dataset similar to step 8 described below. Then fill the rest of the values with fillna(0). Do something like joined_df['includes_holiday']= joined_df['joined_count_column']>0. After that, you can delete the joined_count_column again from your DataFrame, if you like.
If you use pandas_merge_asof you could work through these steps (step 6 and 7 are only necessary if you need to have all the holidays inbetween start and end in your result DataFrame as well, not just the booleans):

Load your holiday records in a DataFrame and index it on the date. The holidays should be one date per line (storing ranges like for christmas from 24th-26th in one row, would make it much more complex).
Create a copy of your dataframe with just the start, end date columns. UPDATE: every start, end date should only occur once in it. E.g. by using groupby.
Use merge_asof with a reasonable tolerance value (if you join over the start of the period, use direction='forward', if you use the end date, use direction='backward' and how='inner'.
As a result you have a merged DataFrame with your start, end columns and the date column from your holiday dataframe. You get only records, for which a holiday was found with the given tolerance, but later you can merge this data back with your original DataFrame. You will probably now have duplicates of your original records.
Then check the joined holiday for your records with indexers by comparing them with the start and end column and remove the holidays, which are not inbetween.
Sort the dataframe you obtained form step 5 (use something like df.sort_values(['start', 'end', 'holiday'], inplace=True). Now you should insert a number column that numbers the holidays between your periods (the ones you obtained after step 5) form 1 to ... (for each period starting from 1). This is necesary to use unstack in the next step to get the holidays in columns.
Add an index on your dataframe based on period start date, period end date and the count column you inserted in step 6. Use df.unstack(level=-1) on the DataFrame you prepared in steps 1-7. What you now have, is a condensed DataFrame with your original periods with the holidays arranged columnwise.
Now you only have to merge this DataFrame back to your original data using original_df.merge(df_from_step7, left_on=['start', 'end'], right_index=True, how='left')

The result of this is a file with your original data containing the date ranges and for each date range the holidays that lie inbetween the period are stored in a separte columns each behind the data. Loosely speaking the numbering in step 6 assigns the holidays to the columns and has the effect, that the holidays are always assigned from right to left to the columns (you wouldn't have a holiday in column 3 if column 1 is empty).
Step 6. is probably also a bit tricky, but you can do that for example by adding a series filled with a range and then fixing it, so the numbering starts by 0 or 1 in each group by using shift or grouping by start, end with aggregate({'idcol':'min') and joining the result back to subtract it from the value assigned by the range-sequence.
In all, I think it sounds more complicated, than it is and it should be performed quite efficient. Especially if your periods are not that large, because then after step 5, your result set should be much smaller than your original dataframe, but even if that is not the case, it should still be quite efficient, since it can use compiled code.


Is there any way I can fix my corrupted Hard Drive?

Question: Here is the output of badblocks -sv /dev/sda
Checking blocks 0 to 488386583
Checking for bad blocks (read-only test): 190698244one, 31:24 elapsed. (0/0/0 errors)
190698245one, 31:29 elapsed. (1/0/0 errors)
190698246one, 31:33 elapsed. (2/0/0 errors)
190698247one, 31:37 elapsed. (3/0/0 errors)
done
Pass completed, 4 bad blocks found. (4/0/0 errors)

What should I do ?
Comment: There is no way to repair bad blocks.
Comment: http://www.howtogeek.com/173463/bad-sectors-explained-why-hard-drives-get-bad-sectors-and-what-you-can-do-about-it/
Comment: Four blocks bad out of 488386583 blocks is nothing. Also, you cannot repair bad blocks.  What makes you think your drive is 'corrupted'?  Only four bad blocks is nothing.
Comment: @bodhi.zazen, that's not actually true.  Even if they are physically bad, drives will remap the logical sector to another one from their spare pool if you write to them, and often times, they aren't physically bad, just corrupt for some reason, such as power failure during write.
Answer: You should also check the SMART attributes of the drive either with the Disks utility, or with smartctl on the command line.  Since badblocks has identified the bad blocks it found, you can now attempt to repair them by writing zeros to them:
sudo dd if=/dev/sda of=/dev/null bs=1024 count=1 skip=190698244

If that returns an error, then you got the numbers right, and confirmed the sector can not be read.  Now try to write zeros to it and the drive will try to repair it:
sudo dd if=/dev/zero of=/dev/sda bs=1024 count=1 seek=190698244

Notice the difference between the two commands, especially seek instead of skip.  Make sure you type it correctly or bad things will happen.  After doing this, repeat the first command to read-test the sector again and this time it should not fail.  Also check the SMART stats on the drive.  The important numbers to look at are the counts of pending, reallocated, and offline sectors.  If there was nothing physically wrong with the disk, the count of pending sectors should go down, and there should still be zero reallocated or offline sectors.  If the count of reallocated sectors goes up, then the drive switched to using a spare sector for that block instead of the damaged area.  If there are more than a handful of these, or any offline sectors, you should replace the drive.


Do I need to add a ground wire from house panel to a workshop sub-panel?

Question: I read that if a workshop was wired before 2007 from the service panel in the house to a sub-panel in a workshop that 3 wires were ok. My workshop only has 3 wires from the main panel. Is this ok or do I need to use 4 wires, instead of 3?
Comment: Are the 3 wires **in metallic conduit the whole way?** What was the code in effect in your area at the time that it was built or wired?
Comment: Does your workshop have a sub-panel? Is the breaker feeding it a two-pole breaker, or a single-width breaker? We tend to assume a full 240V subpanel, but one possibility for a smaller workshop is that you have only a 120V feed with Hot, Neutral and Ground wires.
Answer: For reasons of safety, (which is why code was changed) a ground is good to have. That can be a 4th wire, or it can be a complete metallic conduit enclosing the 3 wires you may already have, and not recognize as a ground (it is a code-legal ground conductor.)
For legalistic quibbling about "do you need to retrofit a ground" you need to know at what date the shop was either built, or connected to electricity, and what code was adopted by your Local Area Having Jurisdiction on that date. Some LAHJs adopt new code revisions very quickly. Others are still using the 2008 code in 2023. Many LAHJs adopt the code, but with local changes. For instance, many places that have adopted NEC2020 have changed the AFCI/GFCI requirements somewhat because supplies of two-pole GFCIs/AFCIs newly called for in the 2020 code were or are somewhat inadequate as yet.


What is the fastest way to complete "The Art of Conversation" achievement?

Question: I know from reading this question how to finish up the follower conversations, however to get "The Art of Conversation" I need to complete almost all conversations in the game (I believe there are a handful that don't count).  I've beat the game at this point, so I believe all conversations should be unlocked, but I see that I can't simply proceed to the last mission in each Act to get all conversations from the other NPCs.  I am genuinely interested in hearing all of the conversation, but I'd like to perform a "speed run" in which I make the minimum number of stops to get them all.  Actual speed is not an issue, I just want to maximize efficiency.
The ideal answer will specify the minimum stops in terms of events/quests/acts to gather all conversations.
Comment: [Talk fast?](http://www.youtube.com/watch?v=TzbUPfoveok)
Comment: Can we change the question to make it more general (more like this http://gaming.stackexchange.com/questions/72159/how-to-collect-all-diablo-3-conversation-achievements) and make it into a wiki?
Comment: @Anders This question is targeted at the exact info I want.  I edited it last night to be more clear, after Bridge conversation with MarkTrapp and others.  I also personally believe that anyone doing this achievement, like me, just wants the most efficient way.  I'm not sure why it needs to be moved to a community wiki.  I researched the existing convo questions at the time I wrote this one, linked to one of them, and phrased in such a way that a Googler would find it.  I think that entitles me to the +15 rep I got for it.
Comment: Since it would be a way too big thread to have a complete answer to  your question it is better for the answer to just link to the places where you can get the individual character achievements. Making it community wiki is just better for the community and it will make it easier for people to edit. You will still keep your 15 rep.
Comment: @Anders I think skovacs1 has shown that the question can be answered concisely.  Given this, I don't think the links to other questions are as good of an answer, since they involve traversing 10 other questions, and they make it very hard to get all convos in one pass.  Not that I don't appreciate that answer too, I just think the concise list is an improvement - and what I had always intended as a best answer.
Answer: Based on a rough timeline of the data I collected, there are 23 points during the game that have to be hit to complete all the conversation achievements and, because of dependencies, they need to be hit in order. When talking to someone, you are expected to complete all their available conversations before moving on to talk to someone else, but I only count the conversations that count towards achievements despite there being additional extra conversations available. I will try to group conversations to cut down travel time, making this pretty close to the fewest stops with the least travel, but there is probably some room for optimization once all dependencies are mapped out. Don't worry about avoiding people with asterisks because you will get those conversations later and this way involves less running around. I'll go through and confirm specifics and nuances later to determine if there are inconsistencies to timing and number of conversations based on current objective and dependencies.
Act I

The Fallen Star - Rumford at the Gates: Takes you right to town. Talk to Haedrig and then Leah for 1 conversation each.
The Legacy of Cain - Begin Quest: Talk to Leah to begin the quest. Talk to Haedrig and then Leah for 1 conversation each.
A Shattered Crown - Begin Quest: Talk to Haedrig for 1 conversation. Talk to Deckard Cain to begin the quest and then talk to Leah for 2 conversations, Deckard Cain for 4 conversations and then Covetous Shen for 4 conversations.
Reign of the Black King - The Royal Crypts: Talk to Haedrig for 2 conversations and then Covetous Shen for 1 conversation. Deckard Cain has a conversation that you get by completing the quest, but you should have this one already since you beat the game - if you want to re-listen to it, you can get it at the next point.
Sword of the Stranger - Khazra Den: Talk to The Stranger for 1 conversation, then Deckard Cain for 2 conversations, and then Covetous Shen for 1 conversation.
The Broken Blade - Talk to Alaric: Talk to The Stranger for 1 conversation. You will need to run through the act a bit to get Leah's 2 conversations as she follows you, 1 while collecting beacons and 1 at the drowned temple.
The Doom in Wortham - Begin Quest: Talk to Deckard Cain for his last 4 conversations, and Haedrig and Covetous Shen for 1 conversation each. Talk to The Stranger to begin the quest. Talk to The Stranger again and then Covetous Shen for 1 conversation each.
Trailing the Coven - Khazra Barricade: Talk to Leah and then Covetous Shen for 1 conversation each.
The Imprisoned Angel - The Cursed Hold: Talk to Covetous Shen for 1 conversation.
Return to New Tristram - Begin Quest: Talk to Tyrael twice, Haedrig, and then Covetous Shen for 1 conversation each.

Act II

A Royal Audience - Begin Quest: Talk to Eirena for 3 conversations, Haedrig for 3 conversations and then Covetous Shen for 6 conversations.
Blood and Sand - Begin Quest: Talk to Leah for 3 conversations, Adria for 9 conversations, Tyrael for 8 conversations, and Covetous Shen for 1 conversation.
The Black Soulstone - Realm of Shadow: Waypoint to The Archives of Zoltun Kulle and talk to Leah for 1 conversation.
The Scouring of Caldeum - Begin Quest: Talk to Adria, Haedrig and Covetous Shen for 3 conversations each.

Act III

The Siege of Bastion's Keep - Light the Beacons: Talk to Tyrael for 2 conversations. Town Portal. Talk to Haedrig for 3 conversations.
Turning the Tide - Begin Quest: Talk to Tyrael to begin the quest. Talk to Tyrael for 4 conversations and Haedrig for 1 conversation. Enter the Armory and talk to Adria for 2 conversations and Leah for 3 conversations.
The Breached Keep - Find the Breach: Talk to Tyrael for 3 conversations and Kormac for 11 conversations.
Tremors in the Stone - Begin Quest: Talk to Lieutenant Lavail to begin the quest. Talk to Haedrig for 1 conversation and Covetous Shen for 7 conversations.
Machines of War - Destroy Ballistae: Talk to Haedrig and Covetous Shen for 1 conversation each. Enter the Armory and talk to Adria for 1 conversation.
Heart of Sin - The Second Heart: Talk to Haedrig for 1 conversation and Covetous Shen for 2 conversations.

Act IV

Fall of the High Heavens - Begin Quest: Talk to Tyrael several times for 3 conversations. Use the nearby waypoint to Bastion's Keep Stronghold. Talk to Kormac for 4 conversations, Lyndon for 14 conversations, Eirena for 8 conversations, and Covetous Shen for 3 conversations.
Beneath the Spire - Begin Quest: Talk to Haedrig for 2 conversations and Covetous Shen for 3 conversations.
Prime Evil - Enter the Crystal Arch: Talk to Lyndon for 1 conversation, Eirena for 2 conversations and Covetous Shen for 1 conversation. Use the Waypoint to go to The Pinnacle of Heaven and talk to Tyrael for 5 conversations.
Comment: FYI, this list doesn't quite cover RoS yet. Some of Myriam's conversations are missed in this path.
Comment: There is a google doc though: https://docs.google.com/spreadsheet/ccc?key=0Ant9_ousoqFcdDlQMzhPOWFfWHBuNUluWDFyY0JVQ2c&usp=sharing#gid=0
Comment: I needed the 4th from last conversation in Act 3 with Haedrig, which was "The Final Goal"; this conversation can be found in bullet point #4 in Act III as listed above, despite it being the 3rd from last in the list. Somewhere in steps 4-6 there might be an extra Haedrig convo.
Answer: Followers
Templar "For the order"
Scoundrel "To catch a thief"
Enchantress "Secret of ages"

Blacksmith "Hassling Haedring"
Jeweler "Everybody loves Shen"
Merchants "Sales and tales"

Main characters
Deckard Cain "Stay a while and listen"
Leah "More than stories"
Tyrael "It's just us"
Adria "Bewitched"
Comment: +1 , nice compilation. Hopefully this is the final word on this topic, hehe
Comment: I edited in the Templar one. I don't believe the merchants one has been discussed here... someone call @skovacs1! ;)
Comment: I could not find the Templar or the Merchants thred. If anyone find  them please tell so I can link =)
Comment: Sure hope @skovacs1 does make the merchants thread soon so that these will finally be done with :p.
Comment: *Sales and Tales* isn't needed for *The Art of Conversation*.
Answer: The comments on each of the achievements at d3db.com has an extensive list of all the points where you can get each conversation. It took me an hour or so to work through them all.
Comment: Thanks for the resource.  To prevent link rot, and for a concise answer I'd like to see it written out.  If no one else wants to take the time I'll probably distill it myself.
Comment: @EBongo: Concise isn't a word I'd use to describe such a list, which is the main reason I didn't copy it all over myself. Considering that d3db is backed by Zam, I don't see it disappearing any time soon, however I may take the time to copy it all across.
Comment: @EBongo I know this is all speculative, but I think in the case of the ZAM network (as opposed to some blogging site), as long as games like Diablo III still exist and people are still playing it, it will continue to exist.
Comment: @JamesJiao: While I agree, there's also an argument to be made for combining all the information provided by the link above into what is truly "the fastest way to finish all the conversation achievements". My contention is simply that I didn't want to take that effort at the drop of a hat and hence posted the link to the information so there'd be a reasonable answer to help out EBongo as soon as possible.


Why does apt say an enormous 16.7 GB additional disk space is needed?

Question: On Ubuntu 14.04 LTS running in a Proxmox 4.4 container:
<code>$ apt update
$ apt dist-upgrade
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
The following packages will be upgraded:

  bind9 bind9-host bind9utils libbind9-90 libdns100 libisc95 libisccc90
  libisccfg90 liblwres90 linux-libc-dev webmin-virtual-server

11 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
Need to get 4.500 kB of archives.

After this operation, **16,7 GB of additional disk space** will be used.
Do you want to continue? [Y/n] n
Abort.
</code>
How is it possible?
I try on several Proxmox Container 14.04: same 16.7 GB!
I never see an error in the disk space need.
It's bigger than the Proxmox container (6 GB). I haven't yet done this dist-upgrade.
Comment: This can't be right, as it will download only 4.5Mb. The space needed for the unzipped files can be several times larger than the downloaded data, but not 3500 times larger. It must be a bug ( and a fun one to report as well).
Answer: I got the same message on 14.04 (not sure which container) though I tried to apt-get upgrade, not dist-upgrade.
It showed me exactly the same 16.7 GB. Anyway I proceeded with the upgrade and everything went well. Only some 30 MB of additional space were used instead of 16.7 GB. So it's definitely a bug.
EDIT: A month has passed and here's what I got today on 16.04.2
<code>apt-get uprgade
...
2 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
Need to get 3,008 kB of archives.
After this operation, 16.7 GB disk space will be freed.
Do you want to continue? [Y/n]
</code>
The same 16.7 GB but now it will be freed.
Comment: Same problem with 22.04. apt claimed 353 GB additional disk space is needed but only 575 MB is downloaded. After apt upgrade I still had the same 22 GB free as before.


Clean division of numbers

Question: public class Evendiff
{

  public static void main(String[] args)
  {
    int x = Integer.parseInt(System.console().readLine());
    int y = Integer.parseInt(System.console().readLine());

      if(x/y == 1)
      {
        System.out.print ( " true " ) ;
         }
      else {
        System.out.print (" False ");
      }

  }
}

I just want it to take in two numbers as input , divide them and see if they divide up into each other cleanly (Like 5/5= 1 etc)
So, what am I doing wrong here?
Also, I get the error java.lang.NullPointerException
    at Evendiff.main(Evendiff.java:6)
Never seen it before so I don't know anything about it.
Comment: You have to use `x % y == 0`
Comment: What´s your `IDE`? `System#console` returns null for `eclipse` for example and hence would produce an error.
Comment: I ran this code using command-prompt and it's working perfectly fine. I think it's an `IDE` problem.
Comment: What's the problem? What result are you expecting? What result are you getting?
Comment: And the error it also pops up is this: java.lang.NullPointerException
 at Evendiff.main(Evendiff.java:6)
>
Comment: Please edit your question with those details.
Comment: "Never seen it before so I don't know anything about it."
It's like there were no 1000s questions about NullPointerException before.
Answer:
see if they divide up into each other cleanly

If by that you mean that the first number is divisible by the second number, you should be using the modulus operator %, not the division operator / (i.e. you should be checking whether the remainder x % y is 0).
x/y would return 1 if x >= y and x < 2 * y. I don't think that's what you are looking for.
Comment: @Josef `System.console()` will return null depending on the IDE you use, DrJava being an example. Best to use `Scanner` instead.
Comment: Thanks man!! that really did help.
But if I can also ask you, java.lang.NullPointerException
 at Evendiff.main(Evendiff.java:6)
why would the IDE poop out that error?

Clean division of numbers


How can we use laravel dusk with browserkit?

Question: We started using Dusk but have existing test suites that use Browserkit. Because Browserkit testing is faster than using Dusk, we do not want to convert our existing test suites.
However, when using both Dusk and Browserkit testcases in the same run, the Dusk tests fail with an error:

Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1
  no such table: users (SQL: select * from "users" where "users"."id" =
  1 and "users"."deleted_at" is null limit 1)

When we run them alone, Dusk test cases work.
I realize it's related to the setup of the tests but have not succeeded in either reusing the DB setup/connection or resetting properly in the BaseTestCase, and I haven't seen traces of people doing it. I'm pretty sure it can be done but how not to "break" laravel phpunit testing?
Thx
Answer: You could use
trait DatabaseMigration
Comment: Bit of explanation is always good in answers. With your rep you should know.


Tcl script to do Indentation

Question: I want to write a tcl script to align my tcl script with proper indentation. For Example if i have a code  like :
proc calc { } {
set a 5
set b 10
if {a < b} {
puts "b Greater"
}
}

I need to change like:
proc calc { } {
    set a 5
    set b 10
    if {a < b} {
        puts "b Greater"
    }
}

Could u guys help on this.
Comment: You might want to check out `frink`, it's outdated but it may be OK for you: http://wiki.tcl.tk/2611
Comment: besides `frink` and `naglfar` what does this?  Nobody uses pretty-print of their tcl code?  They just write it pretty all the time??
Answer: Writing an indenter that handles your example is trivial. A full indenter that can handle most Tcl scripts is going to be very big and quite complicated. An indenter that can handle any Tcl script will have to incorporate a full Tcl interpreter.
This is because Tcl source code is very dynamic: for one thing you can't always just look at the code and know which parts are executing code and which parts are data. Another thing is user-defined control structures, which might change how the code is to be viewed. The example below works by counting braces, but it makes no attempt to distinguish between quoting braces that should increase indentation and quoted braces that should not.
This example is a very simple indenter. It is severely limited and should not be used for serious implementations.
proc indent code {
    set res {}
    set ind 0
    foreach line [split [string trim $code] \n] {
        set line [string trim $line]
        # find out if the line starts with a closing brace
        set clb [string match \}* $line]
        # indent the line, with one less level if it starts with a closing brace
        append res [string repeat {    } [expr {$ind - $clb}]]$line\n
        # look through the line to find out the indentation level of the next line
        foreach c [split $line {}] {
            if {$c eq "\{"} {incr ind}
            if {$c eq "\}"} {incr ind -1}
        }
    }
    return $res
}

This will convert your first code example to your second one. Add even a single brace as data somewhere in the code to be indented, though, and the indentation will be off.
Documentation: append, expr, foreach, if, incr, proc, return, set, split, string

Tcl script to do Indentation


is there any realtion between linearity and the axioms of vector spaces?

Question: Is there any relation between linearity (aditivity and homogeneity)
Additivity: $f(x + y) = f(x) + f(y)$.
Homogeneity: $f(αx) = αf(x)$ for all α.
And the axioms for a vector space?
Does one motivate the other? are vector spaces linear because linearity can be constructed from those axioms?
Comment: The definitions are set up to be compatible with each other: vector spaces are the structures for which homomorphisms (structure-preserving maps) are linear maps.
Comment: I'm unsure what you mean by calling a vector space "linear." Linearity isn't a property of a vector space, it is a property of certain transformations. Could you elaborate?
Answer: A linear function will be an Homomorphism of vector spaces.
Hence you can say the notion of linearity arises from the axioms of a vector space since it conserves them.
Answer:
Does one motivate the other?

Linear transformations are essentially homomorphisms between the additive groups of two vector spaces. Homogeneity, in your sense, is only preserved if the transformation is between two vector spaces over the same field. This follows because the distributive laws must be obeyed in both.

[A]re vector spaces linear because linearity can be constructed from those axioms?

Vector space and linear space are two terms for the same thing. Although I am not entirely sure regarding the etymology of the term, it is suggestive that linear spaces are 'linear' in the sense that every automorphism acts linearly on linear combinations in the space. The same follows for any homomorphism between two linear spaces over the same field.
Comment: It seems i'm lacking some abstract algebra to interpret this. I will have to get back to this answer after some field theory or something.


Sequence which converges weakly but not strongly in $L^1$

Question: I was reading the book "Functional Analysis" by Brezis and I was searching for an example for a sequence in $L^1(\Omega)$ such that it converges in the weak topology but not in the strong one (the one given by the norm) where $(\Omega, \mathscr{E})$ is a measure space without atoms.
In particular I know that open sets in the weak topology are (strickly) included in the strong one when $L^1$ has infinite dimension. But there are simple examples of a sequence which converges weakly but not strongly in $L^1$ with a general $\Omega$? And in the case $\Omega=\mathbb{R}$?
Answer: There is  a simple example for $\Omega =\mathbb R$ but a simple example in general may not be possible. Riemann Lebesgue Lemma shows that $\int f(x) g(x) e^{inx} dx \to 0$ as $ n \to \infty$ for all $g \in L^{\infty} (\mathbb R)$ if $f$ is integrable. So $f(x)e^{inx}$ tends to $0$ weakly in $L^{1}$ and it does not tend to $0$ in the norm if $f \neq 0$.
Comment: Do you intend complex valued integration when writing the exponent $inx$ inside the integral?
Comment: If you want to avoid complex valued functions note that $f(x)(\frac 1  2-\sin ^{2}(nx)) \to 0$ weakly and  $f(x)(\frac 1  2-\cos ^{2}(nx)) \to 0$ but at least one of these does not tend to $0$ in the norm if $f \neq 0$. @FilippoGiovagnini


What's the real reason for 20 psi differential for water well pressure switch setting?

Question: Another forum (https://terrylove.com/forums/index.php?threads/why-is-pressure-switch-differential-always-20psi.95365/) had this advice:
"Any more than a 20 PSI differential will stretch the bladder/diaphragm too far. Anything less than 20 PSI and you don't get the 15 gallons of draw down you normally get from a 50 gallon size tank. Even an 80 gallon tank only holds 20 gallons of water."
I don't think it's correct. I think the "stretch" has to do with the max pressure (not the differential).
Compare these two examples - I say the diaphragm has the same "max excursion" (stretch).

Differential 30 psi - setting 30/60
Differential 20 psi - setting 40/60 (a typical setting)

If I'm wrong, has anyone quantified the decreased life expectancy due to increased differential?
I was researching this topic because I wanted to increase the differential from the typical setting to gain some perceived increased pressure (and increased for a longer time period) at house fixtures with only slight increase in risk of "premature" failure of any system components. I was thinking of going to 42/67. (FWIW, I have a brand new WX-255. I also have an Express Water Heavy Metal triple 4.5" x 20" set up.) I'm too used to (consistent) city water pressure.
Comment: Running longer is actually better for the pump than starting more frequently (to run less time.) However, it's quite possible to get into a situation where the pump can't pump anymore. I lowered my system from 40/60 to 30/50 because when the well was full, 60 was fine, but when the well gets drawn down near the pump (water 200 feet lower) the pump would max out at 57 PSI to the pressure switch until the well slowly refilled. That sort of thing depends on details of your particular well and pump curve, which is a whole other education for those coming from city water.
Comment: The larger differential will allow the water pressure to drop lower before the pump comes back on.  Causing the pump to work longer to bring the pressure back up.
Comment: How much water a given pressure tank holds is variable with setpoint pressures. Tank charts from the manufacturer will typically show you 20/40, 30/50 and 40/60 (& rarely 60-80) drawdown (tidal volume) for a properly precharged (2-3 PSI less than the lower setpoint) tank. They are similar but not identical between manufacturers for reasons having to do with how the tanks are built.
Comment: @Ecnerwal - assuming it was your house with fixtures, when you reset you set point to 30/50 from 40/60, did you perceive a drop in pressure at a fixture (e.g., washing machine filling, toilet refilling, kitchen sink, etc.)? Did you ever consider using 30/55?
Comment: For most modern fixtures, it's practically imperceptible since the fixture itself is the major chokepoint with typical water conservation features. Does it bother me in any way - no. Does it bother me when the pump turns on and the pressure goes from 30 to 50 - also no. It barely affects flow out of the faucet, the toilet gets full at either pressure, etc. Then again, I grew up with wells, so I don't have whatever bias you appear to have towards pressure that does not change at all.
Comment: I have a Well X Trol 351 (62 gallon) and have had it set at 30/60. It is 15 years old now so I think that shows that it is not stretching the bladder too much.
Answer: Incorrect. If properly set:
A 30/60 set tank would have an air precharge of 27-28 PSI.
A 40/60 set tank would have an air precharge of 37-38 PSI.
So, the 30/60 set tank, starting from 0, will start accepting water into the tank at 27-28 PSI, while the 40/60 set tank won't accept water until 37-38 PSI. Thus, the diaphragm or bladder will stretch more on the wider setting. Whether that's bad for the diaphragm/bladder depends on the details of tank manufacture. Most are happy to be set at 20/40, and that should be the "same stretch" as 30/60, 40/80 or 50/100. 20/100 would be "more stretch" and might well break something. The max pressure has to do with the outer containment vessel, not whether you've broken the internal bladder/diaphragm/membrane.
All of which is irrelevant to solving your perceived problem with modern technology.
You want city-like constant pressure.
You can purchase variable-speed pump controllers (variable frequency drives) that will give you city-like constant pressure, or a lower-tech and (generally, at present) somewhat less expensive pressure-regulation-valve thing (which I refuse to shill the most widespread version of by name, but I believe they have bought a shill-space on the forum you looked at, so you'll have no trouble finding them) that will get you near-constant pressure after one drop to the lower setpoint to turn the pump on, so long as you are using water at a sufficient rate, followed by one excursion to the higher setpoint (slowly) after you turn the water off.
Both of those will work with no increase in your present pressure tank size, and they will work with a much smaller pressure tank if/when you need to replace your pressure tank or are building a new system.
You could also go older tech and run a bunch of pressure tanks from 60-80 (or perhaps 60/120, but that might be impractical from the pump and pressure on the down-well pipe point of view) into a pressure regulator set at 50-60 output, but that would be much more costly in terms of money and space required.
Comment: See also: https://diy.stackexchange.com/a/62696/18078


Write a short C++ program that outputs all possible strings formed by using each of the characters 'a', 'b', 'c', 'd', 'e', and 'f' exactly once

Question: I came across this question and I am not able to solve it. All I could code was for small strings like ab,ac,ad,ae,af and such. But not for the longer strings like abc,abcd,etc. It would be really nice if someone could direct me towards some kind of solution. I would prefer without recursion but if not then recursion is also fine.
Here is my code:
#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

vector<string> make_string(vector<char>vec, char ch)
{
    int i=0;
    vec.erase(remove(vec.begin(), vec.end(), ch), vec.end());
    int size = vec.size();
    vector<string>all_strings;
    string answer="";

    for(i=0;i<size;i++) //here is the "meat". I could add a few more for loops for longer strings
                        // But I think that would just get messy.
    {
        answer= answer+ch+vec[i];
        all_strings.push_back(answer);
        answer="";
    }
    return all_strings;
}

void print_vector(vector<string>vec)
{
    int i=0;
    int size = vec.size();
    for(i=0;i<size;i++)
    {
        cout<<vec[i]<<endl;
    }
    cout<<"--------------------------";
    cout<<endl;
}

int main()
{
    vector<char>vec;
    vec.push_back('a');
    vec.push_back('b');
    vec.push_back('c');
    vec.push_back('d');
    vec.push_back('e');
    vec.push_back('f');
    int i=0;
    vector<string>my_strings;

    int size=vec.size();

    for(i=0;i<size;i++)
    {
        my_strings=make_string(vec,vec[i]);
        print_vector(my_strings);
        my_strings.clear();
    }

    return 0;

}

Comment: For "each character exactly once" you can use std::next_permutation in the algorithm header. For "atmost once", you will have to try something else.
Answer: You are looking for a permutation algorithm. Please take a look at this post on wordaligned.org, which describes an iterative solution to the problem:
Next permutation
The author's code is very simple and makes use of the standard library:
#include <algorithm>
#include <cstdio>

int main()
{
    char xs[] = "abcdef"; // <-- modified to fit the question.
    do
    {
        std::puts(xs);
    }
    while (std::next_permutation(xs, xs + sizeof(xs) - 1));
    return 0;
}

If you read further, there is a discussion on the implementation of next_permutation and a breakdown of how it works.

Write a short C++ program that outputs all possible strings formed by using each of the characters ’a’, ’b’, ’c’, ’d’, ’e’, and ’f’ exactly once


Mounting a pull up bar that doesn't align with studs

Question: I bought this pull-up bar ( https://trugrit-fitness.com/products/tru-grit-pull-up-bar-lite ) since it was on sale, but now I'm stumped on whether I am mounting it safely. Here is how I planned to install it, first my walls are plaster so using a stud finder or magnets was giving me inconsistent reading, so I ended up buying an endoscope camera to locate the studs which explains the holes in the walls which I will patch up later. The red outlines show the studs which I found out are 2x4 and are laying on the 4-inch side, so it only gives me 2 inches of depth to screw the lag screws.

I plan on using a 2x4 (which is outlined in black) that will span across 3 studs at the very top and use 3/8 lag screws to mount the 2x4 to the 3 studs.
one more 2x4 that will span across 2 studs below the first one,
Then another 2x4 that will span across 2 studs 23 inches below the previous 2x4.
I will then have a 2x4 right above the left side of the door frame to fill in the gap between the wall and the pull-up bar bracket.

The final image has the pull-up bar bracket color-coded in pink which is how I plan to mount it. Should I be worried about it not being secured? are there modifications that I can make or should I ditch the plan entirely?
Comment: I would be a little worried about hanging that bar from that wall. The bar comes out really far relative to the height of the mounting plates, meaning that you'll be putting a lot of torque on a fairly small thickness of wood. You probably won't break the studs outright, but you might bend them enough to crack the drywall or screw with the door.
Comment: If truly the wall is constructed with studs laid sideways and a plaster coating on both sides of them, and you don't know how the studs were fixed to the floor or ceiling, you should not mount a chin up bar on that wall at all.  The whole wall could come down.  OTOH the door looks like a traditional early 20th century one.  Isn't it framed as it should be?   Can you show us pictures of the door frame thickness, and how it interfaces with the supposedly very thin wall?   Also, cheese goes on crackers, Nutella goes on a lightly toasted white pita. :)
Comment: Both sides of the pull up bar would be supported by 2x4 studs, directly or indirectly.  Why do you think there is not enough support?
Comment: @Yehuda_NYC Mainly because I wasn't able to mount it directly to the studs in the walls and questioning whether the 2-inch depth (1 1/2 inch to be exact ) of the studs in the walls was enough length for the lag screw to grip and carry the weight of the bar and myself (190 lb). Also because I've never mounted something this heavy on my walls.
Comment: What is behind the flat-laying studs?  The wall must be more than two inches thick.  The door framing must be also, which I assume is why the left bracket relies on just one stud?  Also what is on the other side of the wall?
Comment: @jay613 the walls are 1 inch thick, I measured them when I drilled a hole for the endoscope camera. Behind the stud is another wall, the door leads to a closet, so the wall in the picture is just a divider between the room and the closet.
Answer: Don't
Based on your comments so far the wall was designed and built as a divider for a closet with sideways-mounted studs. You should not mount a chin up bar to this wall.   It's strong enough to support the plaster on both sides of it, nothing more.   The wall could flex under the force of a chin-up, and the plaster would all crack and crumble.  Worst case if the studs were attached to the building with a "just enough" mindset, they could detach from the ceiling or floor and fall over.
Hopefully there is more to the wall than that and you'll tell us in the comments. But if that's the whole story, you should find a better location for the bar, on a stronger wall.
Comment: Thank you for the input, once I saw the studs mounted sideways, I started questioning its integrity with the pull-up bar mounted using those very studs. I plan on drilling holes on the adjacent wall to see how the studs are laid out. The adjacent wall is the wall that aligns with the side of my building though mounting it on that wall would mean me moving furniture around but I think I can make it work.
Answer: Yes your plan to bridge across the missing studs is sound.
to protect the glass install a door stopper on the angle bracket and another on the floor.
Answer: Canonical solution: mount wood or metal to studs to bridge the space where you want to hang the object, mount object to that bridge. A chunk of plywood might be good since it will distribute the torque forces over a larger area and give you room to run a few more screws into the studs.
Run it all the way down to the floor and it will also ensure you never kick a hole in your plaster. ;-)


How to find which installed packages are important?

Question: I installed many additional packages on my PC. dpkg --get-selections command displays all the installed packages. From the installed packages how do I know which are important for system booting (if we remove any one package from the important packages list, system won't boot or system doesn't appear like normal).
If I know that, I'm aware of it and I won't remove these kind of important packages. So how do I know that these packages are important and these packages are not important from the output of dpkg --get-selections?
Answer: If the installed package has priority  important or required then this kind of packages are considered as most important packages.
apt-cache show <package-name>

The above command  shows the priority of the corresponding package.
avinash@avinash-Lenovo-IdeaPad-Z500:~$ apt-cache show hostname
Package: hostname
Essential: yes
Priority: required

So run the below command to find all the packages which has the priority important or required.
dpkg --get-selections | xargs apt-cache show {} | awk -F' *: *' '$1=="Package"{p=$2;next} $1=="Priority"&&$2~/(important|required)/ {print p}'

Essential packages has the an extra record "Essential: yes" in the output of apt-cache show <package-name> command.These essential packages also has the priority important or required.To get the list of only essential packages then run the below command.
dpkg --get-selections | xargs apt-cache show {} | awk -F' *: *' '$1=="Package"{p=$2;next} $1=="Essential"&&$2=="yes" {print p}'

Save the above commands output to a text file for future use.
Answer: I don't know if Ubuntu has this set up, but should follow the Debian standard. There are packages flagged as important and required, you need for that aptitude:
sudo apt-get install aptitude

Now you can look at what packages are required:
aptitude search '~prequired'

or important:
aptitude search '~pimportant'

You could also do more and see which packages that you have installed are not important nor required:
aptitude search '?and(~i, !~pimportant, !~prequired)'

(the above search means: search for installed package that are not important nor required)
Be aware that no GUI package is important or required. Both section are the bare minimum to have a bootable system (think about a server without services) and download more programs, if you remove any of this packages is probable that you will be left with an unbootable system, if you remove everything but these is definitive that you won't have any GUI.
Reference:

https://unix.stackexchange.com/a/90533/41104


Build C library with CMakeLists.txt while packaging python library

Question: I use Cython to wrap C library and extend its functionality. C library is developed by separate team and is provided with CMakeLists.txt. For now I use source .c and .h files to build this library. This is how my build.py file for poetry (setup.py analog) looks like:
...
# source_files_paths - list of full paths to .c files
c_library = ('c_library', {'sources': source_files_paths})
...
def build(setup_kwargs):
    setup_kwargs.update({
        ...,
        'libraries': [c_library],  # Here c library is built with build_clib command
        ...
    })

Is it possible to use CMakeLists.txt to build c_library in build function (or in setuptools.setup function)?
UPD: It is also ok for me to define variable that is used in .c files. I tried to add define_macros:
c_library = ('c_library', {'sources': source_files_paths,
                           'define_macros': [('MY_MACRO': True)]})

Still no luck with it.
UPD2: I finally found the solution to my problem though it is not the answer to my initial question. To add macros you should add it in this way:
c_library = ('c_library', {'sources': source_files_paths,
                           'macros': [('MY_MACRO': True)]})

According to build_libraries function from http://svn.python.org/projects/python/branches/pep-0384/Lib/distutils/command/build_clib.py you can also specify 'include_dirs', 'obj_deps' and 'cflags' arguments.
Comment: At work I wrote up some scripts to build my cmake project using python. I was able to do this using the subprocess module in python. Which allowed me to build my cmake project easily from python. Is this what you want?
Answer: The scikit-build package can replace setuptools and it is able to use CMakeLists.txt. (See Basic Usage guide for scikit-build). It can do CMake with Cython.
Comment: I tried this out but could not find the way to build underlying C-library with it. As I could understand it can only build Cython package cmakefile, not the chain of cmake files. Could you please provide me an example if I am wrong?
Comment: Moreover, could not find how to use it with poetry
Comment: What happens when you add the CMakeLists instructions for the C library directly into the CMakeLists.txt used to build the Cython code? Try including this text manually, or use the instruciton [_include_](https://stackoverflow.com/questions/17228677/how-to-include-an-additional-cmakelists-txt).


Closest div as container for bootstrap datepicker in rails and coffee script and simple_form

Question: I am trying to set up bootstrap datepicker in my rails application.
It is working fine but the css is all messed up unless i assign a container div that can hold the pop up.
I would like to make a generic method that checks the closest div for the popup instead of appending it to the body.
Here is my code
Coffee
jQuery ->
jQuery('input.date_picker').datepicker
    dateFormat: 'mm/dd/yyyy'
    todayHighlight: true
    container: jQuery(this).closest('div').attr(class)
    autoclose: true
    todayBtn: true

Erb
    <%= simple_form_for @qc_assay_parameter, :url => qc_assay_parameter_path(@qc_assay_parameter) do |f| %>
     <%= f.error_messages %>
     <%= f.input :reference_number, label: 'Reference #', error: 'Reference Number is mandatory' %>
     <%= f.input :qc_assay_product_name_with_revision, label: 'Analyte , Rev#', url: '/qc_revisions', as: :autocomplete, placeholder: 'Type in Analyte Name', :input_html => {:class =>"span2", :rows => 6, :type => :text}%>
     <%= f.input :assay_date, as: :date_picker, placeholder: 'mm/dd/yyyy' %>
    <%= f.button :submit %>
   <%end%>

Plain Html
 <form id="edit_qc_assay_parameter_176094" class="simple_form edit_qc_assay_parameter" novalidate="novalidate" method="post" action="/qc_assay_parameter.176094" accept-charset="UTF-8">

Analyte , Rev#

<input id="qc_assay_parameter_qc_assay_product_name_with_revision" class="autocomplete optional span2 ui-autocomplete-input" type="text" value="LAP revision 0" size="30" rows="6" placeholder="Type in Analyte Name" name="qc_assay_parameter[qc_assay_product_name_with_revision]" data-autocomplete="/qc_revisions" autocomplete="off">

Assay date
<input id="qc_assay_parameter_assay_date" class="string date_picker optional datepicker" type="date_picker" value="Sun, 03 Apr 2016 00:00:00 -0500" size="30" placeholder="mm/dd/yyyy" name="qc_assay_parameter[assay_date]">

<input class="btn" type="submit" value="Update Qc assay parameter" name="commit">
</form>

I would like to do something like
jQuery ->
jQuery('input.date_picker').datepicker
    dateFormat: 'mm/dd/yyyy'
    todayHighlight: true
    container: jQuery(this).closest('div').attr(class)
    autoclose: true
    todayBtn: true

container: jQuery(this).closest('div')
Answer: If the date_picker class is always set on the input then you can do this:
var nearestDivClassName = '.' + $('.date_picker').closest('div').attr('class')

jQuery('input.date_picker').datepicker
    dateFormat: 'mm/dd/yyyy'
    todayHighlight: true
    container: nearestDivClassName
    autoclose: true
    todayBtn: true

Note that the container option needs to be an element selector so we prepend a . to the string returned by .attr('class')
Update
As you need it to be generic enough to account for more than one .date_picker, you can use jQuery's .each() method to iterate through them and then you can use this as you expect/need:
$('input.date_picker').each(function(){
    $(this).datepicker({
        dateFormat: 'mm/dd/yyyy',
        todayHighlight: true,
        autoclose: true,
        todayBtn: true,
        container: closestDivClassName($(this))
    });
});

function closestDivClassName($el){
      return '.' + $el.closest('div').attr('class');
}

Comment: But in case there are multiple inputs with class 'date_picker' this wont work right ?


Cannot delete project

Question: I am unable to delete a project from the Nest Device Access Console. When I click the delete icon and click delete, it processes and comes back with a pop-up that says "Could not delete project" with no other information. If I try to delete the OAuth Client ID, it processes and comes back with a pop-up that says "Could not update project data" with no other info.
Any advise would be helpful.
Answer: Resolved: this seemed to be just a temporary issue with the website.

Cannot delete project


find the sum of the mass of this container ($d_{water} = 1 g/cm^3$)

Question: The mass of container is $50$g when it is empty. When we complete this container with water, its mass is becoming $130$g. If we unload half of this water and put a liquid which its density is $2 g/cm^3$ instead of this water, find the sum of the mass of this container ($d_{water} = 1 g/cm^3$)
I currently don't have any idea about this question. Can you assist?
Comment: I assume the answer should be $170g$. This is because the water has a mass of $130 - 50 = 80g$ and half of this ($40 g$) is replaced with a liquid twice as dense. This liquid has a mass of $80g$ so the total mass is $50 + 40+80 = 170 g$. Did I understand the question correctly, Enzo?
Comment: @MohammadZuhairKhan Exactly, you did understand it correctly. However, I didn't get your hint.
Comment: Unfortunately I might have given the entire answer. I am sorry.
Comment: @MohammadZuhairKhan Can you explain this $130 - 50 = 80g$?
Comment: This is to find the mass of the water. $130g$ is the mass of container _and_ water so the subtraction to find the mass of water only.
Answer: Hint:
So, the container requires $80$g water to be full, hence its volume is $80$ cm$^3$
Now, $40$ cm$^3$ of water (i.e., $40$g of water) is replaced by $40$ cm$^3$ of another liquid whose mass will be $40\cdot2$g$=80$g .
Answer: This container can contain 80 grams of water. The density of water is $1g/cm^3$. So, this container has a capacity of $80cm^3$. The mass of the container is:
$$ m_1 = 50g $$
The half of the container is filled with water. The weight of the water is:
$$ m_2 = 80cm^3 / 2 \times 1g/cm^3 = 40g $$
The other half of the container is filled with a liquid with density $2g/cm^3$. The weight of this liquid is:
$$ m_3 = 40cm^3 \times 2g/cm^3 = 80g $$
The total mass of the filled container is:
$$ m = m_1 + m_2 + m_3 = 50g + 40g + 80g = 170g $$
Comment: The answer is not $210$g.
Answer: Take $m_{c},V_{c},d_{w},m_{total}$ as mass and volume of the container, density of water and mass of the filled up container respectively. We know that $m_{c}+V_{c}d_{w}=m_{total}$ where $m_{c}=50g$, $m_{total}=130g$ and $d_{w}=1g/cm3$. Here we calculate $V_{c}=80cm3$. The new mass after filling the container by half water and half the other liquid which has two times more density than if water, we calculate $m_{new}=m_{c}+ {V_{c}\over 2}d_{w}+{V_{c}\over 2}2d_{w}=m_{total}+{V_{c}\over 2}d_{w}=130g+40*1g=170g$


How can I set the clock to 24 hour mode?

Question: How can I set the clock to global (24h time) in Maverick instead of am/pm? Including the login screen?
I mean there's no option to do that in rclick clock > preferences or in system > admin > time & date.
Answer: The normal way :

Go to System -> Administration -> Language Support
On the Text Tab, choose your prefered language to display numbers, dates, ...

The advanced way for your Desktop Applet :

Press Alt+F2
Type: gconf-editor & Hit return
Navigate to "Apps > Panel > Applets > Clock_Screen0 > Prefs"
Double-click on the 'Format' value. Change it to '24-hour'

Login Screen
There was an option in Ubuntu previous versions in the GDM setup GUI (System > Admin > Login Window) but not in maverick, bug is reported on Launchpad
Comment: You might wanna add the bug report(s): [Launchpad](https://bugs.launchpad.net/ubuntu/+source/gdm/+bug/445674) and [GNOME Bugzilla](https://bugzilla.gnome.org/show_bug.cgi?id=626896).


Split a string using string.gmatch() in Lua

Question: There are some discussions here, and utility functions, for splitting strings, but I need an ad-hoc one-liner for a very simple task.
I have the following string:
local s = "one;two;;four"

And I want to split it on ";". I want, eventually, go get { "one", "two", "", "four" } in return.
So I tried to do:
local s = "one;two;;four"

local words = {}
for w in s:gmatch("([^;]*)") do table.insert(words, w) end

But the result (the words table) is { "one", "", "two", "", "", "four", "" }. That's certainly not what I want.
Now, as I remarked, there are some discussions here on splitting strings, but they have "lengthy" functions in them and I need something succinct. I need this code for a program where I show the merit of Lua, and if I add a lengthy function to do something so trivial it would go against me.
Comment: `[^;]*` is perfectly happy matching zero semicolons. So lua matches zero semicolons each time it gets to a delimiter. You can use "[^;]+" instead for a slightly better result but there are reasons the http://lua-users.org/wiki/SplitJoin page of the lua-users wiki runs as long as it does when talking about splitting strings.
Answer: local s = "one;two;;four"
local words = {}
for w in (s .. ";"):gmatch("([^;]*);") do
    table.insert(words, w)
end

By adding one extra ; at the end of the string, the string now becomes "one;two;;four;", everything you want to capture can use the pattern "([^;]*);" to match: anything not ; followed by a ;(greedy).
Test:
for n, w in ipairs(words) do
    print(n .. ": " .. w)
end

Output:
1: one
2: two
3:
4: four

Comment: @NiccoloM. Remember that `*` matches zero or more, the empty string where I marked `$` in the string `one$;two$;$;four$` is also a match.
Comment: @NiccoloM. Because `*` is greedy, it will try to match as long as possible, the non-greedy version to match zero or more is `-`.
Comment: It's worth noting that LUA Patterns are not actually Regular Expressions, you will notice many differences between 'standard' regexp implementations and how LUA patterns operate.
Comment: Wow, thanks. Your solution works perfectly! (I won't close this question yet: if somebody could explain to me why my original code returns spurious empty strings I'd be grateful.)
Comment: But what about `one$;$two$;$;$fo$ur$`? Why is the zero match only before `;` ? Why isn't it also after the `;`, and between every two letters?
Comment: After thinking very long about this, I now understand. I see that regexps in Ruby (and probably in other languages as well) behave in exactly the same way. Thanks.
Answer: Just changing * to + works.
local s = "one;two;;four"
local words = {}
for w in s:gmatch("([^;]+)") do
    table.insert(words, w)
    print(w)
end

The magic character * represents 0 or more occurrene, so when it meet ',', lua regarded it as a empty string that [^;] does not exist.
Sorry for my carelessness, the words[3] should be a empty string, but when I run the original code in lua5.4 interpreter, everything works.
code here
running result here
(I have to put links because of lack of reputation)
Comment: This does not give the OP's desired output, they want an empty string at index 3. `{ "one", "two", "", "four" }`
Comment: @Nifim sry,I dont read the question carefully.But when I use lua5.4 interpreter, the original code suddenly works!?
Answer: function split(str,sep)
    local array = {}
    local reg = string.format("([^%s]+)",sep)
    for mem in string.gmatch(str,reg) do
        table.insert(array, mem)
    end
    return array
end
local s = "one;two;;four"
local array = split(s,";")

for n, w in ipairs(array) do
    print(n .. ": " .. w)
end

result:
1:one
2:two
3:four
Comment: This doesn't work as OP expected, because the empty string between `;;` isn't captured.
Comment: Your answer should contain an explanation of your code and a description how it solves the problem.
Comment: I see. Now I understand what you mean.


question about javascript string's replace method

Question: I know that I can pass a string as the second parameter to the JavaScript string object's replace method. In this case I can use $` and $' to reference the left/right part text of a successful match. Now my question is, If I pass a callback function as the second parameter, how can I get the same information? I want to use this infomation in the callback function. Great thanks.
Comment: ...whoa, you can use a callback? Neat!
Answer: See Mozilla's documentation; you won't get that data for free.
The good news is, you will get the offset of the match as your second-to-last argument, and the total string as the last. So you can run your own substring functions.
var str = 'abc';
str = str.replace('b', function (match, offset, full) {
    var before = full.substr(0, offset),
        after = full.substr(offset + 1, full.length - offset);
    return 'foo'; // or, ya know, something actually using before and after
});

Answer: var str = 'abc';
str = str.replace('b', function (match) {
    // (!) List of actual arguments depends from template of RegEx >>>
    var offset = arguments.length - 1, full = arguments[offset];
    offset = arguments[offset - 1];
    // (!) But the first argument is match
    var before = full.substr(0, offset),
        after = full.substr(offset + 1, full.length - offset);
    return 'foo'; // or, ya know, something actually using before and after
});


Has anyone heard of kickproof.com?

Question: I am wanting to reinforce our front and back door. I have researched the net and found kickproof.com, they manufacture the rebar door reinforcers that are kick in proof. Has anyone ever heard this company or had experience with their products?
Answer: They sell an expensive version of a common product sold under a dozen different names, many of which can be found substantially cheaper at big box home improvement stores or even online.
Comment: It's also worth noting that in many areas, kick-ins are a vanishingly small percentage of total breakins, that simply having a properly-installed 1" deadbolt us enough to stop most kick-ins (don't forget to use a solidly made door and secure the strike properly to the framing), and generally that all most of us need is to be obviously one step more secure than our neighbors. Get local advice before assuming you need this.
Comment: Not to mention that a decent screen door is likely much more effective if locked. If you have to kick through something that is set in the jamb from the outside, you likely aren't going to get that far.  Oh look, is that a window?
Comment: I just fixed a kick-in last week. Solid core door that shattered at the lock. This product would not have availed me. Nor does any thing prevent someone with a crowbar from doing *anything*.

Has anyone heard of kickproof.com?


Showing $\sum A_i$ for $i\in I$ is an order if $I$ is and each $A_i$ is

Question: I'm currently working through Vaught's 'Set Theory: An Introduction' and was stuck on Chapter 5 q1.1:
'Show $$ \sum_{i=\underline{I}}^n \underline{A_i } $$ is an order if $\underline{I}$ is and $\underline{A_i }$ is.'
From my understanding, $\underline{A_i }$ is an algebraic structure s.t. $\underline{A_i } = (A, R, •)$, where R is the binary relation over $A$ where $R \subseteq A \times A$ and • is the binary operation over $A$.
As per Vaught, an order would be $\underline{A_i }$ = (A, $\leq$) and $\underline{I}$ = (I, $\leq$) s.t. the summation known as the ordered sum is defined by $\cup_{i\in I}A_i$
I'm honestly not entirely sure a) what an order is and b) how to approach this problem.
Thanks in advance for the help!
Comment: What is "an order" in this context? And how to do you define the summation in this case?
Comment: In this context, an order would be $\underline{A_i }$ = (A, $\leq$) and $\underline{I}$ = (I, $\leq$) s.t. the summation known as the ordered sum is defined by $\cup_{i\in I}A_i$
Comment: Is $\leq$ going to satisfy any axioms (e.g. partial order? linear order? well-order?)
Comment: It is a partial order and connected
Comment: What do you mean by "connected"? (and please [edit] all this in so that people don't have to read the comments...)
Answer: What Vaught calls an order is usually called a linear order or a total order. A partial order $\le$ on $A$ is a binary relation on $A$ that is reflexive, transitive, and antisymmetric. (These terms are defined at the beginning of the section.) It is a linear order — what he calls an order — if it is also connected, meaning that for all $x,y\in A$, either $x<y$, $x=y$, or $y<x$. I will use the term linear order rather than his order.
Each $\underline{A_i}$ is a linear order $\langle A_i,\le_i\rangle$: $A_i$ is some set, and $\le_i$ is a relation on $A_i$ that is a linear order on $A_i$. $\underline{I}$ is a linear order $\langle I,\le_I\rangle$. And what you're asked to compute, at least according to what I can see in the Amazon Look Inside for the second edition of the book, is
$$\sum_{i\in\underline{I}}\underline{A_i}\,.$$
The underlying set, $A$, of this ordered sum is the disjoint union of the sets $A_i$:
$$A=\bigcup_{i\in I}\big(\{i\}\times A_i\big)\,.$$
The order relation, $\le$, on $A$ is defined as follows. Each element of $A$ is an ordered pair $\langle i,a\rangle$, where $i\in I$ and $a\in A_i$. If $\langle i,a\rangle,\langle j,a'\rangle\in A$, then $\langle i,a\rangle\le\langle j,a'\rangle$ if and only if either $i<_Ij$, or $i=j$ and $a\le_ia'$. What you're to prove is that this relation $\le$ really is a linear order on the set $A$: that it's reflexive, transitive, antisymmetric, and connected.
For instance, for antisymmetry we must prove that if $\langle i,a\rangle\le\langle j,a'\rangle$ and $\langle j,a'\rangle\le\langle i,a\rangle$, then $\langle i,a\rangle=\langle j,a'\rangle$. From the definition of $\le$ we know that if $\langle i,a\rangle\le\langle j,a'\rangle$, then $i\le_Ij$, and if $\langle j,a'\rangle\le\langle i,a\rangle$, then $j\le_Ii$, and we're told that $\underline{I}$ is a linear order. By definition, then, $\le_I$ is antisymmetric, so $i=j$. But then $\langle i,a\rangle\le\langle i,a'\rangle$, which by definition means that $a\le_ia'$, and also $\langle i,a'\rangle\le_i\langle i,a\rangle$, meaning that $a'\le_ia$. And $\le_i$ is a linear order, hence antisymmetric, so $a=a'$, and therefore $\langle i,a\rangle=\langle j,a'\rangle$, as desired.
The other three properties are proved similarly.
Comment: Thank you so much, this is really helpful!
Comment: @logicgirl: You're very welcome!
Comment: As a follow-up question: in order to prove the other three properties, are we trying to prove the same statement? E.g. for reflexivity, is that the same relationship we're trying to show between i and j, a and a'? My apologies if my question sounds nonsensical!
Comment: @logicgirl: It sounds as if you may need to check the definitions of these properties. A binary relation $R$ on a set $X$ is reflexive if $x\,R\,x$ (i.e., $\langle x,x\rangle\in R$) for all $x\in X$. Thus, in the present instance you need to show that for each $\langle i,a\rangle\in A$, $\langle i,a\rangle\le\langle i,a\rangle$.