text:
Q: Calculate the probability that the product of two samples from X is greater than the sum of two samples from Y Suppose there is a distribution $X$ with $P(x) = 1/3, x = 1,2, 3 $ (0 otherwise) and another distribution $Y$ with distribution $P(y) = 1/y, y=2, 3, 6$ (0 otherwise).
Find for two independent samples from $X$ ($X_1, X_2$) and two independent samples from $Y$ ($Y_1, Y_2$) $P(X_1 X_2 > Y_1 + Y_2)$.
I know that this can be done by enumerating cases; is there an algebraic method to do so?

A: There are so few cases that it might easier just to enumerate all cases. In the process, you will find out that there are ways to extrapolate to more general cases with larger data set.
First, find the minimum of $Y_1+Y_2$, which is 4, so $X_1 X_2$ must be greater than 4, giving the only three possibilities: (2,3), (3,2), and (3,3). $X_1 X_2$ equals 6 and 9, respectively, and the probabilities are $P_1=2*(1/3)^2=2/9$ and $P_2=(1/3)^2=1/9$.
In the case of $X_1 X_2=6$, there are the following cases (listed in a general way)

*

*$Y_1=2$ ($P=1/2$), than $Y_2$ must be less than or equal to $3$, and $P(Y_2\le 3)=1/2+1/3=5/6$. Totally $P = 1/2 \times 5/6 = 5/12$.

*$Y_1=3$ ($P=1/3$), than $Y_2$ must be less than or equal to $2$, and $P = 1/2$. In total, $P = 1/3 \times 1/2 = 1/6$.

In the cases where $X_1 X_2 = 9$, we have

*

*$P(Y_1=2) \times P(Y_2 \le 6) = 1/2 \times 1 = 1/2$,

*$P(Y_1=3) \times P(Y_2 \le 5) = 1/3 \times (1/2 + 1/3) = 5/18$,

*$P(Y_1=6) \times P(Y_2 \le 2) = 1/6 \times 1/2 = 1/12$.

Finally, the answer to the question is
$$
P = \frac{2}{9} \times \left( \frac{5}{12} + \frac{1}{6} \right) + \frac{1}{9} \times \left( \frac{1}{2} + \frac{5}{18} + \frac{1}{12} \right) = \frac{73}{324}.
$$

A: Assuming choice without replacement.  Only possibility $X_1X_2=6$ with probability $\frac{1}{3}$ and $Y_1+Y_2=5$ with probability $\frac{7}{12}$.  Since events are independent. Desired $P=\frac{7}{36}$.


text:
Q: In iOS7, chrome & safari, on focus of an input field, the page scrolls. How do I stop that? In iOS7, chrome and safari, on focus of an input field, the page scrolls.
I want the field to be focused if the user taps inside it and I want scrolling to still work, but the default scrolling that happens on input field focus, I want that to stop.
How can I do that?
Here is a sample JS fiddle: http://jsfiddle.net/6HvUh/
Code:
$(window).on('scroll', function(){
    $('input').animate({'top':100});
});

A: iOS safari will always try to center the focused input in the center of the visible screen. That, combined with position: fixed, which is a bit buggy in iOS, can cause strange effects.
My advice is, if possible, not to use position: fixed. You can change your page this way:

*

*wrap your text, or everything scrollable, in a div with class 'scrollable'.

*Change the position of your inputs to absolute (or the position of their container).

*Add some CSS:
div.scrollable
{
    width: 100%;
    height: 100%;
    overflow: auto;
    -webkit-overflow-scrolling: touch;
}
html, body
{
    width: 100%;
    height: 100%;
    overflow: hidden;
}

Be aware that your inputs can never be hidden by the keyboard. If you put inputs near the bottom of the page you'll see scroll anyway.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Gigabyte Geforce GTX 560 Issues I was unable to install Ubuntu via the graphical method. So i used the alternative text-based installation.  I am able to boot into Ubuntu now, but the display is squashed, pixelated and unreadable.
How can i get around this?, would installing the nvidia drivers fix this? and how would i install them with the display in this state?

A: It seems that your answer is in this particular package:
ppa:ubuntu-x-swat/x-updates

I will try this when I get home, since I got the same graphics card
If you dont know how to add packages:
sudo add-apt-repository ppa:ubuntu-x-swat/x-updates && sudo apt-get update
sudo apt-get install nvidia-current && sudo apt-get install nvidia-settings

this should do the trick


text:
Q: How to set min date in DatePickerDialog with a specific date not today (XAMARIN) What I want is to set date before specific date to be disabled (not before today). e.g. :
Today is May 5, 2017
Target Specific Date: May 1 - May 5 only.
All greater than this day is disabled using  this code
        dialog.DatePicker.MaxDate = Java.Lang.JavaSystem.CurrentTimeMillis();

But I can't disable from May 1 and before it.
I have this code for now.
public class DatePickerFragment : DialogFragment,
                              DatePickerDialog.IOnDateSetListener
{
    // TAG can be any string of your choice.
    public static readonly string TAG = "X:" + typeof(DatePickerFragment).Name.ToUpper();

    // Initialize this value to prevent NullReferenceExceptions.
    Action<DateTime> _dateSelectedHandler = delegate { };

    public static DatePickerFragment NewInstance(Action<DateTime> onDateSelected)
    {
        DatePickerFragment frag = new DatePickerFragment();
        frag._dateSelectedHandler = onDateSelected;
        return frag;
    }

    public override Dialog OnCreateDialog(Bundle savedInstanceState)
    {
        DateTime currently = DateTime.Now;
        DatePickerDialog dialog = new DatePickerDialog(Activity,
                                                       this,
                                                       currently.Year,
                                                       currently.Month-1,
                                                       currently.Day);

        //****************this is my problem*****************//
        dialog.DatePicker.MinDate = CurrentUser.lastReplenish.Millisecond;
        dialog.DatePicker.MaxDate = Java.Lang.JavaSystem.CurrentTimeMillis();
        //***************************************************//
        return dialog;
    }

    public void OnDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
    {
        // Note: monthOfYear is a value between 0 and 11, not 1 and 12!
        DateTime selectedDate = new DateTime(year, monthOfYear + 1, dayOfMonth);
        Log.Debug(TAG, selectedDate.ToLongDateString());
        _dateSelectedHandler(selectedDate);
    }
}

I

A: I guess "CurrentUser.lastReplenish" is a .NET DateTime object?!
Android always needs the milliseconds starting from January 1 1970 (epoch), so you need to calculate a bit:
dialog.DatePicker.MinDate = (long)CurrentUser.lastReplenish.ToUniversalTime()
    .Subtract(DateTime.MinValue.AddYears(1969)).TotalMilliseconds;


text:
Q: Copying data files upon build in Java/Eclipse Along with my java source, I have some data files that I would like to copy to the build dir when the source is build. Currently I am not using any build tools (e.g. maven or ant), but develop and run unit tests solely from within Eclipse.
Can I somehow ask Eclipse to copy these data files when it builds my java code?

A: Go with Ant. To be honest this is the best solution for automation of app building process.
I am not using Eclipse often. But I bet there must be a build file (build.xml) where you can add something like the code below to it and have it always executed when building your app.
This is how I am doing it in my build file for one of my projects. I am copying here two folders with all their content to a dist (which in NetBeans serves as a distribution folder where application jar is being created), so then I can easily run my application externally outside the IDE.
Be aware that the target name in Eclipse might differ. But you should find a correct one described in the build file probably.

<!-- to copy data & images folders' contents to dist folder on build. -->
    <target name="-post-jar" description="Copying Images">
        <property name="images.dir" value="${dist.dir}/images" />
        <property name="data.dir" value="${dist.dir}/data" />

        <copy todir="${images.dir}">
            <fileset dir="./images" />
        </copy>
        <echo level="info" message="Images folder content was copied."/>

        <copy todir="${data.dir}">
            <fileset dir="./data" />
        </copy>
        <echo level="info" message="Data folder content was copied."/>
    </target>

All the best, Boro.

A: First Create a new source folder call it something like res, you can use this folder to store your data files. Next open the Java Build Path section of the project properties (from the context menu of the project). Select the Source tab. In this tab you can control the output folders of each of the source folders. By default eclipse copies all the non-java files int the source folder to output directory during the build.

A: Eclipse isn't really meant to copy things around (it may have that feature and I don't know about it). Like you alluded to, that's a job for Maven or Ant. However, for your JUnit tests, you have a couple of options...

*

*Open the data files based on a project relative path.

*Use getResourceAsStream(filename) and add the data files to the build-path


text:
Q: Записать выборку из mysql в массив php Здравствуйте.
Подскажите, как можно вывести значение из базы данных в массив.
У меня имеется база данных с двумя столбцами. id - id отдела и name - наименование.
Я делаю выборку
$todb = $mysqli->query('SELECT * FROM otd');
$mass = array();

while($rws = mysqli_fetch_assoc($todb)){
   $mass[] = $rws['id'];
   $mass[] = $rws['otdel_name'];
}
print_r( $mass );

в данном коде в массив mass записываются в каждую строку свой параметр.
 [0] => 1
 [1] => Руководство
 [2] => 2
 [3] => Бухгалтерия

Я же хочу чтоб массив записался вот таким форматом
 [1] => Руководство
 [2] => Бухгалтерия

Как правильно это сделать?


text:
Q: Umbraco ApiController actions wont map to http-verb I have been working some with the Web API before.. and as far as I can remember..
The actions in (at least the new version) is called Get,Post,Delete,Put etc...
and these actions are triggered depending of the http-verb in the request..
So for instance you might have an ApiController called UserApiController..
and if you do a request to /api/user with the POST http-verb.. then the Post-action in that controller will be triggered/executed..
However....
it seems like Im having some trouble with this using the UmbracoApiController... for some reason it wont execute post or get or any other action mapped to the http-verb..
Any ideas?.. is there any other way to sort of force a method to be executed depending on the http-verb?
My current code is:
public class MyController : UmbracoApiController
{
    [HttpPost]
    public bool Post()
    {
        return true;
    }
}

I have placed a breakpoint with in the action..

A: The reason they won't be accepted is you're using the wrong attribute - HttpPost is part of the System.Web.Mvc namespace, whereas Web API is part of the System.Web.Http namespace.
You have to use AcceptVerbs("POST") instead.


text:
Q: What are the good criteria for committing changes to repository? I'm currently using git for managing several projects, however, one question has been bugging me recently: what is the good tone for committing modifications to the master branch and to secondary branches? Should it be 'commit when it compiles', 'commit when it works', or something else? Thanks.

A: First:  Ignore subversion strategies and strategies stemming from that mentality.  There is a difference between saving a change and publishing a change.
Committing is saving a change.  While I wouldn't suggest committing on a timer, I would suggest you think of it more like saving a file than releasing a version.  Do it when you fear you may need to come back, but are afraid it would otherwise be hard to get back to where you are.
However, rewrite the commits (git rebase -i origin/master # for example) before you publish them.  Find the meaning in the mess you made and create a set of comprehensible and clean commits with good commit messages and ensure each passes whatever quality checks you might have.  Then publish it.

A: It really depends, is this your personal repo or is it a repo that is shared by many developers? How far into the project are you?
Personally I commit to my subversion repositories when I am done with one aspect and everything compiles. It does not have to be complete, just not broken. I prefer to not leave things broken in the first place.
Half written code can get checked in, but only in my personal branches, generally with notes about what I was doing at the time and what still needs to get done. Since I use Subversion and this is my personal repo I use this mainly to be able to leave my desktop and pick back up where I left off on my laptop.
Generally the one bug/issue/feature per commit is nice, but may not suit your development style. If this is a more complete project it may work out since commits mean that you are crossing items off a list somewhere and it means one more item that is now completed.
Other things to consider, what is significant about the changes that it warrants checking in? For example, I checked in code last night that significantly changed an internal API, this meant I had to document the changes in the commit message as well as the documentation. At the same time I also changed a few comments to fix typo's. That gets a small sub-note on the commit message, but is not something I consider a big enough issue to get committed on its own.

A: Some basic things:

*

*Strive to commit per "logical change"; bug fix, refactoring, feature, ...

*Run your unit tests before commiting the code; make sure that you didn't break anything obvious (you do have unit tests, don't you).

*If in a multi-developer environment; update from the repo and run the unit tests again to make sure no conflicting changes broke someone's code (yours or theirs).

*Fix as needed and repeat from 3 until nothing is broken.

*Commit immediately and cross your fingers.

*Rely on your continuous integration tests to tell you whether something else broke.

A: If you are using a ticket management system, I would say commit when a task is fixed.

A: I go with 'commit early, commit often', myself.  If you have an automated checkout and build going on, this obviously won't work.

A: Commit only one type of change at a time.
What "type" means is different for each project, but some popular examples include "cosmetic changes" vs "functional changes" and "refactoring" vs "adding new". This makes it easier to follow the changes when looking at the log, and also easier to revert to a revision.

A: To take it one step back, I try to work on issues/bugs/features that can be completed in a short period of time.  If it's going to take more than a day to come to a good stopping point the task is too big.
That said, I think the best practice is to commit your changes when the code compiles and has been adequately tested (ideally with unit or integration tests that get committed with the code change).
If compiles + functions properly + is well tested == 'commit when it works' then that seems like the appropriate rule.

A: Commit when it works. In my case this means to: automate the smoke test, run it and commit.
Note: its just the smoke tests that I automate/run before the commit. Regression tests are left to the continuous integration.

A: Commit any code you don't want to write again :)


text:
Q: How to navigate from one field to another field using Enter Key function in MVC5 Hi I want to know how to navigate from one field to another field by pressing enter Key in MVC5.
My View
    <form>
    <fieldset>

    *
    @Html.Label("Employee Name", new { @class = "control-label" })
    @Html.DropDownList("EmployeeID", null, "Select", new { @class = "form-control required" })

    *
    @Html.LabelFor(model => model.Date, new { @class = "control-label" })
    @Html.TextBoxFor(model => model.Date, new { @class = "form-control required", type = "text", id = "Date" })

   *
    @Html.LabelFor(model => Model.CustomerName, new { @class = "control-label" })
    @Html.TextBoxFor(model => Model.CustomerName, new { @class = "form-control" })
    @Html.HiddenFor(model => Model.CustomerID)

   *
    @Html.Label("Visit Type", new { @class = "control-label" })
    @Html.RadioButtonFor(model => model.VisitType, "true", new { id = "" }) Telephone

    @Html.RadioButtonFor(model => model.VisitType, "false", new { id = "" }) Direct Visit

     <form>
    <fieldset>

My J query
  $("form:not(.filter) :visible:enabled:first").focus();
  $('form > div').keypress(function(e) {
    debugger;
  if (e.keyCode == 13) {
  e.preventDefault();
  if ($(this).next().length > 0) {
  $(this).next().children('div').children(":not(label)").focus();
  } else {
  $("form:not(.filter) :visible:enabled:first").focus();
  }
  }
  });

My Css
div {
margin: 5px 10px;
    }

Now this code is working fine in fiddle. But this code is not working in my View. why because I donno where i have to declare this css in my view. Please any one check my code and tell me suggestion for this problem. Before i have css file in script folder.  so i drag and keep that css file in my view. I donno and dont have any css file for this Key Function. So please any one tell me where i have to declare that css coding in my view. And any one suggest me alter method too. I tried my level best to explain my issue. Any one understand and give me solution
Thanks.

A: 1. css
your view have a layout property like this
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

in the _Layout.cshtml you see in top of file Site.css is included, like so:
@Styles.Render("~/Content/css")
// look at App_Start/BundleConfig.cs to look up which style sheets are included

Put your css in the site.css file.
2. javascript
in the view add section script for your javascript
// view code here ....

@section scripts
{
 // include scripts here
}


text: Q: Check if multivariate confidence elipsoid is within another multivariate confidence elipsoid in If I computed two multivariate confidence regions for two independent samples. How can I check if the confidence region of one sample is completely within the confidence region of the other sample ? I do assume normal distributed data which would resemble (if I am correct) to a hyperelipse.


text:
Q: YouTube videos does not work in full screen in Ubuntu 20.04 Fresh install Ubuntu 20.04 on Matebook X Pro with Intel UHD620. I have display scale set to 175%.
When clicking f or full screen button I get a quarter of the screen as black and see the desktop and other apps outside this quarter screen.
In Chromium I get the video playing on the quarter of the screen.

A: I found that it's caused by turning off "Use system title bar and borders" in Chrome. Enabling this makes it work normally.
I also switched to using Wayland and it works perfect in Wayland! Even with "Use system title bar and borders" disabled.
Scaling settings did not matter.

A: Fractional scaling is a new, and perhaps to an extent still immature feature. The issue you see is most probably related to using fractional scaling. If the current issue is a problem, you may need to move away from fractional scaling until current limitations and issues like this have been fixed.
You may want to revert to 100% scaling. You can then apply a scaling factor to enlarge system fonts. Use Gnome Tweaks (Fonts tab) for that. In all browsers, you also can set a scaling factor for the display of web sites. This way, you likely will be able to achieve a pleasing appearance, avoiding the issue of full screen playback that you experience when using the fractional scaling.
At this time, fractional scaling needs more more computer resources. Thus, sticking to 100% scaling may also make for a smoother experience as it is less taxing on your computer.


text:
Q: where is the Setup Project in Visual-Studio 2013? After a lot of deliberation I finally moved to Visual-studio 2013,
but where is Setup Project in Visual-Studio 2013 ? how to make a package?

A: Apparently you can use Visual Studio Installer Project Extension. You can download it from Here. Also you can find more information in This Question.


text:
Q: How can i expand last row of table to the bottom of table for print format? Please find the attached print format for reference.I am using jinja to create print format.If the content is small,print will have large unwanted space.how can i increase the space of last row in a table dynamially according to page using html and css.

Please find code sample for table without any css.

            Sl.
            Description
            Qty
            Unit Price
            Amount

        {%- for row in doc.items -%}

            {{ row.idx }}
            {{ row.description_for_print or '' }}
            {{ row.qty }}

                {{ row.get_formatted("rate", doc) or ''}}
            {{
                row.get_formatted("amount", doc) or ''}}

        {%- endfor -%}
{%- if doc.discount_amount -%}

Total          :

         {{ doc.get_formatted("total") or '' }}

Discount                    :

         {{ doc.get_formatted("discount_amount") or '' }}

 {%- endif -%}

Net Total                    :  {{ doc.base_in_words or '' }}

         {{ doc.get_formatted("grand_total") or '' }}

50% Down Payment  :  {{ frappe.utils.money_in_words(x) or ''}}

    {{ "{:,.2f}".format(x) or 0.00 }}

50% Upon Delivery    :  {{ frappe.utils.money_in_words(x) or ''}}

     {{ "{:,.2f}".format(x) or 0.00 }}


text:
Q: Why can't i squeeze a pic in python I tried to squeeze an image using this code:
def squeeze_image(im,factor):
    new_n = im.shape[0]/ factor
    new_m = im.shape[1]/factor
    new_mat = np.zeros((new_n,new_m))
    for j in range(new_mat.shape[1]):
        curr_range = range(j*factor,min((j+1)*factor,im.shape[1]))
        new_mat[:,j] = im[:,curr_range].mean(axis=1)
    for i in range(new_mat.shape[0]):
        curr_range1 = range(i*factor,min((i+1)*factor,im.shape[0]))
        new_mat[i,:] = im[curr_range1,:].mean(axis=0)
    return new_mat

when i try it on an image it tells me:
ValueError: could not broadcast input array from shape (512) into shape (256)
for some reason it only works when i use it only for rows or only for columns,
like this:
def squeeze_image(im,factor):
    new_n = im.shape[0]/ factor
    new_m = im.shape[1]/factor
    new_mat = np.zeros((new_n,new_m))
    for j in range(new_mat.shape[1]):
        curr_range = range(j*factor,min((j+1)*factor,im.shape[1]))
        new_mat[:,j] = im[:,curr_range].mean(axis=1)
    return mat

how can i make it work on both rows an columns?

A: Consider the shapes of the arrays.
Suppose im has shape (factor*H, factor*W), so that
new_mat has shape (H, W).
Now consider the line
new_mat[:,j] = im[:,curr_range].mean(axis=1)

On the right-hand side, im[:, curr_range] has shape (factor*H, L) for some L, and im[:,curr_range].mean(axis=1)  has shape (factor*H,).
On the left-hand side, new_mat[:, j] has shape (H,).
So except for when factor = 1, the shape of the left- and right-hand sides of the assignment do not match and can not be broadcasted to agree.
This problem affects both versions of squeeze_image.
To fix the problem, you could use
new_mat[i, j] = im[i*factor:(i+1)*factor, j*factor:(j+1)*factor].mean()

to slice off a 2D rectangular patch of im all at once, and take the mean of that 2D patch.
import numpy as np
import itertools as IT

def squeeze_image(im,factor):
    H, W = im.shape
    H2, W2 = H/factor, W/factor
    new_mat = np.zeros((H2, W2))
    for i, j in IT.product(range(H2), range(W2)):
        new_mat[i, j] = im[i*factor:(i+1)*factor, j*factor:(j+1)*factor].mean()
    return new_mat

im = np.arange(100).reshape((10,10))
print(im)
# [[  0.   1.   2.   3.   4.   5.   6.   7.   8.   9.]
#  [ 10.  11.  12.  13.  14.  15.  16.  17.  18.  19.]
#  [ 20.  21.  22.  23.  24.  25.  26.  27.  28.  29.]
#  [ 30.  31.  32.  33.  34.  35.  36.  37.  38.  39.]
#  [ 40.  41.  42.  43.  44.  45.  46.  47.  48.  49.]
#  [ 50.  51.  52.  53.  54.  55.  56.  57.  58.  59.]
#  [ 60.  61.  62.  63.  64.  65.  66.  67.  68.  69.]
#  [ 70.  71.  72.  73.  74.  75.  76.  77.  78.  79.]
#  [ 80.  81.  82.  83.  84.  85.  86.  87.  88.  89.]
#  [ 90.  91.  92.  93.  94.  95.  96.  97.  98.  99.]]
im2 = squeeze_image(im, 2)
print(im2)

yields
[[  5.5   7.5   9.5  11.5  13.5]
 [ 25.5  27.5  29.5  31.5  33.5]
 [ 45.5  47.5  49.5  51.5  53.5]
 [ 65.5  67.5  69.5  71.5  73.5]
 [ 85.5  87.5  89.5  91.5  93.5]]

A fancier, but far more efficient way to compute this result is to
use reshape/swapaxes to chop the array into blocks of shape (factor,factor),
and then take the mean of each block:
def downsample(im,factor):
    H, W = im.shape
    H2, W2 = H/factor, W/factor
    im = im[:H2*factor, :W2*factor]
    new_mat = (im.reshape(H2, factor, -1, factor)
               .swapaxes(1, 2)).reshape(H2, W2, -1).mean(axis=-1)
    return new_mat

This is about 17x faster for the small array im.
In [91]: %timeit squeeze_image(im, 2)
1000 loops, best of 3: 319 µs per loop

In [97]: %timeit downsample(im, 2)
100000 loops, best of 3: 17.2 µs per loop

The speed advantage increases with the number of iterations in the for-loop in squeeze_image, which equals H2*W2.

Note that scipy.ndimage.zoom can squeeze or zoom an image too. It uses spline interpolation instead of taking means. The result, even with spline order=1, is a bit different, however:
import scipy.ndimage as ndimage
print(ndimage.zoom(im, 0.5, order=1))

yields
[[  0.     2.25   4.5    6.75   9.  ]
 [ 22.5   24.75  27.    29.25  31.5 ]
 [ 45.    47.25  49.5   51.75  54.  ]
 [ 67.5   69.75  72.    74.25  76.5 ]
 [ 90.    92.25  94.5   96.75  99.  ]]


text:
Q: jupyter_notebook_config.py: which argument sets the location of the 'download as' file for jupyter notebook? I want to set the 'Download as' location for export files from Jupyter Notebook as os.getcwd(), the directory of the ipython notebook. Presently on my mac it defaults to the downloads folder, which is my browser default. Does anyone know which argument sets this location in the jupyter_notebook_config.py file? Or whether this can be set at all?
This is a link to the documents: Read the Docs - Config File

A: Browsers (and the browser user) control the destination for downloaded files.  The server can't specify it; it would be a security risk if it could.


text:
Q: Getting bash completion error is a directory everytime I open the terminal I just switched over to Linux (Ubuntu 20.04) a few days ago after using Windows for the last 13 years and I am loving it so far.
Of course I started messing around with everything, because that's how I usually learn something new and now I ran into a problem.
I installed Alacritty terminal and everything went smoothly but for one small problem.
I followed those instructions in order to install the bash completions:

mkdir -p ~/.bash_completion
cp extra/completions/alacritty.bash ~/.bash_completion/alacritty
echo "source ~/.bash_completion/alacritty" >> ~/.bashrc

Now everytime I open the terminal I get the following error:
bash: .: /home/myname/.bash_completion: is a directory
I thought I was referencing the folder and not the file, so I opened the .bashrc file in the nano editor but I find no reference to /home/myname/.bash_completion , just source ~/.bash_completion/alacritty
I tried to search for this problem, but I didn't find anyone who had the same problem.
Here is my bashrc file: https://pastebin.pl/view/83ce4d25

A: So the issue is the following lines in your .bashrc
if ! shopt -oq posix; then
  if [ -f /usr/share/bash-completion/bash_completion ]; then
    . /usr/share/bash-completion/bash_completion
  elif [ -f /etc/bash_completion ]; then
          . /etc/bash_completion
  fi
fi

I'm not sure why you got that specific error, but the lines here are trying to find the path to the bash_completion tool and execute it.
Since the completion works after removing the lines, it is already specified somewhere else.

A: TLDR: Create ~/.bash_completion.d directory instead and reference it wherever it's relevant.
Following up as I stumbled upon the exact same scenario and wanted to figure out how to process this properly.
For information, I'm running Linux Mint (Debian based).
In .bash_profile, there is this line:
[ -f /etc/bash_completion ] && source /etc/bash_completion

The sourced file contains:
. /usr/share/bash-completion/bash_completion

So far, we got pretty much the same behavior. It's just not handled the same way.
Now, since this is default, it's better not to touch anything to avoid extra issues. Most Linux distributions assume that ~/.bash_completion is a file with user-defined completions, not a directory.
And there is this (kind of?) convention for creating directory suffixed with .d in their name to make things explicit and prevent conflicts (such as our).
The solution would then to be:
mkdir -p ~/.bash_completion.d
mv ~/.bash_completion/* ~/.bash_completion.d
rm ~/.bash_completion
vim ~/.bashrc

Once the editor is open, update the path from:
source ~/.bash_completion/alacritty

to:
source ~/.bash_completion.d/alacritty

Reload and you should be good to go no matter the distribution you're working on :)


text:
Q: Convert given URL to a base URL How can I convert a given url to a base url?
That means if I have "http://test.com/folder/it.html?gsa=5", the script should return "http://test.com/folder/".
I tried:
preg_match('~.*/~', $cur_url, $match);
$base=($match[0]=='http://') ? $cur_url : $match;

Doesn't work good.

A: Try parse_url
Sample from php.net
<?php $url = 'http://username:password@hostname/path?arg=value#anchor';

print_r(parse_url($url));

echo parse_url($url, PHP_URL_PATH); ?>

returns
Array
(
    [scheme] => http
    [host] => hostname
    [user] => username
    [pass] => password
    [path] => /path
    [query] => arg=value
    [fragment] => anchor
)
/path

A: Use a regex string that keeps everything from the .com forward. Just set it up so any of your possible site endings can be used. Will update shortly with sample string.
--EDIT--
This php regex string works to get the base address from any url(ive tested).
![a-zA-Z]+(.com/|.ca/|.gov/)!

Note: this string is set to only work with .com, .ca, and .gov domains, but you can add others in the brackets separating them with |.
--EDIT--
Rereading your post, I have designed another string for if you want everything in the url except the file at the end.
!([a-zA-Z]*+(.com/|.ca/|.gov/))+([a-zA-Z/]*[/])!

Note: If you use this with urls that don't have a file on the end, the directory must have the slash still or the last directory will be cut as well.

A: Well if you want to remove the $_GET vars from the url
?hello=somethin&something=somethingelse
The the following might work:
$fullurl = $_SERVER['REQUEST_URI'];
$urlarray = explode($fullurl, "?");
$urlnoget = $urlarray[0];

that will explode the url into bits for every ? and there are no ? in an actual file/fooledr name so it will clear out the $_GET urls.
Have you considered using JavaScript?
Sorry if there are easier ways but this is what I know.


text:
Q: Setting up RefTeX Tab completion in emacs I am trying to make Tab completion work with RefTeX. When typing C-c [ and selecting the type of reference I have then a prompt in the minibuffer. When I know the beginning of the bib key I want to enter, say for instance Campbell2006, I would like to type Camp Tab and get Campbell2006 [sole completion].
I have managed to set it up for some documents but I do not understand exactly why it works for them and not for others. I have noticed that for the documents that have proper Tab> completion, the following line is added to the file name_of_tex_file.el created in a auto subfolder:
(TeX-add-style-hook "name_of_tex_file"
(lambda ()
(LaTeX-add-bibliographies
"absolute_path_to_bib")))

I think I obtained this results by adding %%% reftex-default-bibliography: absolute_path_to_bib at the end of my files but this is kind of a nuisance, especially when editing the same file on several computers.
Note that RefTeX is working because when I type C-c [ Camp Ret, I get a list (sometime a bit odd) with the Campbell2006 entry.
I have tried to set the %BIBINPUTS% environment variables with no success.
Adding (setq reftex-bibpath-environment-variables '("c:/path_to_bib_file/")) seemed necessary for the C-c [ Camp Ret method to work.
It has somehow the same defects as adding a %%% reftex-default-bibliography: to the end of the file and did not provided the Tab completion.
I have tried various combinations of /, //, \\ and \ as file separators when specifying files but I do not know exact which I should use (I'm using emacs in a windows environment). The issue might be as simple as that but as there are lots of parameters to try I fail do determine where is the problem.
What is the step-by-step method to make RefTeX work smoothly with bibliography, including the Tab completion?
EDIT:
Completion is possible according to the Reftex manual entry about the command reftex-citation:

The regular expression uses an expanded syntax: &&' is interpreted as and. Thus,aaaa&&bbb' matches entries which contain both aaaa' andbbb'. While entering the regexp, completion on knows [sic] citation keys is possible. `=' is a good regular expression to match all entries in all files.

it does not provide precise guidance on how to make it work though.
Kindahero suggests setting a list of the bib entries and use the completing-read command. This sounds sensible, however I would like to generate this list automatically and it seems feasible because it works with some of my documents.

A: The documentation of reftex-citation is a bit confusing. It promises completion on known citation keys but I believe "known" refers to keys that have been used previously in this session rather than all keys in the appropriate bibliography. You can use the LaTeX-add-all-bibitems-from-bibtex command defined below to load all keys in your bibliography:
(defun get-bibtex-keys (file)
  (with-current-buffer (find-file-noselect file)
    (mapcar 'car (bibtex-parse-keys))))

(defun LaTeX-add-all-bibitems-from-bibtex ()
  (interactive)
  (mapc 'LaTeX-add-bibitems
        (apply 'append
               (mapcar 'get-bibtex-keys (reftex-get-bibfile-list)))))

Suggestions on appropriate hooks to make this happen automatically are welcome.


text:
Q: Segmentation Fault - how to solve it? CS50 PSET 4 - Recover I am trying to run this code for the pset4 where we have to recover jpegs from a file. I keep getting segmentation fault and did the debugging and found the problem is here:
else
            {
                    fwrite(&buffer, 512, 1, jpg);

            }

Why would the program run into a segmentation fault here? Is it because I have not assigned enough memory for the jpeg file? Down is my code for reference.
Thanks!!

#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <string.h>
#include <stdint.h>

int main(int argc, char *argv[])
{

// Detects if a file is a JPEG

typedef uint8_t BYTE;

    // Check usage
    if (argc != 2)
    {
        fprintf(stderr, "Usage: ./recover image \n");
        return 1;
    }

    // Open memory card
    FILE *file = fopen(argv[1], "r");

    if (!file)
    {
        printf("Could not open %s.\n", argv[1]);
        return 2;
    }

    // Repeat until end of card

    int jpegcounter=0;
    BYTE buffer[1000];
    char *name = malloc(jpegcounter);
    // Read 512 bytes into a buffer
    FILE *jpg=NULL;

    size_t bytes_read = fread(buffer, 512, 1, file);

do{

    fread(&buffer,512, 1, file);

    {
        // Check first four bytes for the header of a new JPEG to see if it's a new JPEG
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)

            {
                if(jpegcounter == 0)

                {

                    sprintf(name, "%03i.jpg", jpegcounter);
                    jpg = fopen(name, "w");
                    if (jpg == NULL)
                         {
                        fprintf(stderr, "%s.\n", name);
                        return 3;
                         }
                    fwrite(&buffer, 512, 1, jpg);

                }

                else

                {
                    fclose(jpg);
                    sprintf(name, "%03i.jpg", jpegcounter);
                    jpg = fopen(name, "w");
                    if (jpg == NULL)
                         {
                        fprintf(stderr, "%s.\n", name);
                        return 3;
                         }
                    fwrite(&buffer, 512, 1, jpg);
                }
                jpegcounter++;
                printf("%i\n",jpegcounter);

            }

        else
            {
                    fwrite(&buffer, 512, 1, jpg);

            }

        fclose(jpg);

    }
}
while (bytes_read == 512) ;

        fclose(jpg);
        free(buffer);
        fclose(file);
        return 0;

}

A: There is not enough memory assigned for name here char *name = malloc(jpegcounter);. jpegcounter is 0, so 0 bytes are allocated. It needs enough bytes to accommodate the full file name plus the null terminator (since it is a string created by sprintf).


text:
Q: Converting ü to ü I am working with asp.net project and i am using datagridview.. so i am filling datagridview and when i read grid view, then some character is changing from "ü" to "ü"
i am filling datagridview like below :
DataTable dt = new DataTable();
....
..
.

datagridview.DataSource = dt;
datagridview.Databind();

when i bind to datagridview..
datagridview.rows[1][4] is being "Türkiye"
but when i read this value for setting to some textbox.

txtXXX.Text = datagridview.rows[1][4].Text;

i am getting this value = "Türkiye" ....
soo my question is : how to i convert "ü" to "ü" ?

A: Hope this helps :
System.Net.WebUtility.HtmlDecode(datagridview.rows[1][4].Text);


text:
Q: How to implement a session I want to implement a session in my server to be able to store some temporary data to handle user's requests properly. I would like to get advice how to do it in the right way.
What I need is:

*

*Each user in my website has his own session.

*The session is alive as long as the user is surfing my website, and it gets deleted once he leaves the website.

*The session is thread-safe, which means it is shared over multiple threads, if one performs changes to it, the others gets these changes.

*The session is meant to store a few small data.

What I tried to do:

*

*As I'm using flask to implement my back-end, I used flask-session which was totally perfect for my use case until I encountered problems with the third point, as flask-sessions isn't thread-safe, is there an analogous package in python like flask-session that is thread-safe? because I find flask-session so easy and straightforward.

*I tried using global dictionary as a session, as it gets deleted from storage as a user leaves the website, but again I encountered the same problem and even worse as for flask-session, global variables in python isn't thread-safe and furthermore it's not process-safe.
Finally I thought of two solutions and I would like to get advice about the implementation:

*

*Implement the session as a global dictionary in python but using packages for handling multi-proccesses/multi-threads to ensure that all threads share the same dictionary/session (as I don't have enough experience in multi-threads packages I don't know which to use and how to do that but it seems easy to learn, maybe using multiprocessing, threading packages in python).

*Implement the session as a database, here there are two things I find it hard to determine:

*

*How to identify each user uniquely? I thought of generating a unique key once a user requests the website for the first time in the server-side and send it to him, and in each request he sends me this id back so I can load his session and manipulate it.

*How can I empty sessions of users that are no longer on my website? I can't find a way to know that the user left my website in the server-side, and I can't keep the session in the database as it will get larger with time.


text:
Q: Issue when using Xcode 11 running Canvas on macOS Catalina I have Catalina macOS version (10.15) installed and still the canvas is not showing up.
The error message I get from Xcode is

Select a scheme that builds a target which contains the current file,
  or add this file to a target that is built by the current scheme

A: I filled a Radar FB6123260 please do that also. For me resetting the nvram worked and deleting derived data.
Resetting Nvram
Deleting derived data:
rm -rf ~/Library/Developer/Xcode/DerivedData

A: Add your new files to the compiled bundles as part of the build phases?
Not only does the target need to be set for the file- but it also has to be included in the compiled bundles..
Project -> Target -> Build Phases -> search for the file your are trying to work on


text:
Q: Inline JavaScript transition from negative position overridden by CSS style I have a fiddle that has two small boxes inside a larger box.
When either of the buttons "Run B" or "Run C" is clicked, the corresponding box is run through a CSS transition, effected via JavaScript. The code is reproduced here with comments:
  // Get the specified box
  var element = document.getElementById(id);

  // Save initial style for resetting
  var initial = element.style.cssText;

  // Initialise transition
  element.style.position = 'relative';
  element.style.transition = 'top 800ms ease';

  // Set start position
  element.style.top = '-50px';

  // Effect the transition in the next cycle
  // by setting the end position
  setTimeout(function(){

    element.style.top = '15px';

  }, 25);

// Reset the style on completion
setTimeout(function(){

    element.style.cssText = initial;
}, 800);

You should be able to observe that each transition is quite different. However, the only difference between the two boxes is the CSS property top: 0 set in the stylesheet.
Can someone please explain why the transitions are different?
Since the style for the element is set inline, I would have expected that to override the CSS style, but that is not happening. Why does the top: 0 have any impact at all?

A: I'll do my best to explain:
You are setting the top to -50px and then you have a setTimeout which sets it to 15px;
Since #b have a starting position of 0px, it will start animating to -50px but after 25 mllis it will get a new position of 15px and it will animate there instead (you can see that if you give the first setTimeout a longer time like 100). Since 25 millis is very short, it looks like it immediately starts to go down.
Since #c does not have a starting position, when you set it to -50 you actually give it a starting position and then it animates from -50 to 15px;
I hope I've managed to clarify it :)


text:
Q: Heroku API: capture output of a command run on a one-off dyno How do I capture the output of a command being run on a one-off dyno via the API?
For example:
heroku = PlatformAPI.connect("...")

heroku.dyno.create(
  app_name,
  attach: false,
  command: "ls"
)

This just returns the dyno creation response. It does not include the output of the command.

A: If you set the attach argument to true, it will stream the output. To actually get the stream, you should look at the response to dyno create and find the value of attach_url. You should be able to pass this to a rendezvous client (like the rendezvous gem) to read info, more details on that here: https://github.com/heroku/rendezvous.rb


text:
Q: Blob would be exported before changes are made to the files I wrote a google script to generate resume and cover letter faster. It does the following

*

*use ui.prompt to input content

*create a folder and copy docs to the folder

*replace keyword to content

*convert docs to pdf in the folder

However, somehow the docs would be converted to PDFs before the keywords were replaced.
I have tried below but to no avail:

*

*async awaits to wait for the main function before starting exporting PDFs

*use utilities.sleep() to delay the exports

I have the main function and export function below for your information.

function jobHuntAutomation() {

  //UI prompts for documents
  var ui = DocumentApp.getUi();
  var companyName = ui.prompt('Cover Letter', 'Enter Company Name: \n', ui.ButtonSet.OK);
  var positionName = ui.prompt('Cover Letter', 'Enter Position Name: \n', ui.ButtonSet.OK);
  var hiringManagerName = ui.prompt('Cover Letter', 'Enter Hiring Manager Name: \n', ui.ButtonSet.OK);

  //Create some file name strings
  var folderName = `${companyName.getResponseText()}_${positionName.getResponseText()}`
  var coverLetterName = `${companyName.getResponseText()}_${positionName.getResponseText()}_Coverletter`
  var resumeName = `${companyName.getResponseText()}_${positionName.getResponseText()}_Resume`

  //Get new folder object and Id
  var newFolder = DriveApp.getFolderById(mainFolderId).createFolder(folderName);
  var newFolderId = newFolder.getId();
  var newFolderUrl = newFolder.getUrl()

  //Make a copy
  console.log('Making Copies')
  DocumentApp.getUi().showModalDialog(modalMessage('Making Copies...'), 'Status');
  var coverLetterId = DriveApp.getFileById(coverLetterTemplateId).makeCopy(coverLetterName, newFolder).getId();
  var resumeId = DriveApp.getFileById(resumeTemplateId).makeCopy(resumeName, newFolder).getId();

  //Status
  DocumentApp.getUi().showModalDialog(modalMessage('Updating Content...'), 'Status');

  //Get the coverLetter document body as a variable
  var coverLetterBody = DocumentApp.openById(coverLetterId).getBody();

  //Get the resume document body as a variable
  var resumeBody = DocumentApp.openById(resumeId).getBody();

  //Update Content
  doc.replaceText(keyword, input.getResponseText())
    .
    .
    .
  //you get the idea

  //export PDFs
  convertToPdf(resumeId, newFolder)
  convertToPdf(coverLetterId, newFolder)

  DocumentApp.getUi().showModalDialog(folderLink(newFolderUrl), 'Link');
}

function convertToPdf(fileId, dest) {
  doc = DriveApp.getFileById(fileId);
  docblob = doc.getAs('application/pdf');
  console.log(`Converting ${doc.getName()}...`)

  /* Add the PDF extension */
  docblob.setName(doc.getName() + ".pdf");

  // add file to the dest Folder
  dest.createFile(docblob);

}

It would be much appreciated if someone knows a solution to export PDFs AFTER the keywords are replaced. TIA

A: I figured it out. the docs need to be saveAndClose() before exporting so the changes would be flushed


text:
Q: H2 database migration from 1.4.192 to 2.1.210 I have migrated my h2db.mv.db from 1.4.192 to 2.1.210. All works well application started with the new version of h2(smoothly) but suddenly what I see in my application that h2 database have dropped some tables on its own(runtime). I am not sure why it is happening, but below are some tables which were there before the migration and dropped randomly. Not sure why it is happening
create table if not exists alerting_criteria_violations(id identity, timestamp bigint not null, meta " + H2Schema.BINARY_COLUMN_64K, alerting_incident_id bigint not null, foreign key(alerting_incident_id) references alerting_incidents(id) on delete cascade);

create table if not exists config(data " + H2Schema.BINARY_COLUMN_64K + ");

create table if not exists user_alert_messengers(id bigint, user_id bigint, data " + H2Schema.BINARY_COLUMN_64K + ",foreign key (user_id) references users(id) on delete cascade);

create table if not exists user_alert_services(id bigint, user_id bigint, data " + H2Schema.BINARY_COLUMN_64K + ", foreign key (user_id) references users(id) on delete cascade);

create table if not exists user_permissions(user_id bigint, group_id bigint, server_id bigint, permissions smallint,
foreign key (user_id) references users(id) on delete cascade,
foreign key (group_id) references informix_server_groups(id) on delete cascade, foreign key (server_id) references informix_servers(id) on delete cascade);

H2Schema.BINARY_COLUMN_64K = binary(65536)

Earlier my jdbc URL have trace level 4 but now I have changed it to 3 to see the debug logs.
Trace logs for h2db as below
2022-06-23 08:43:23 database: disconnecting session #3
2022-06-23 08:43:23 database: closing /Volumes/Macintosh HD - Data/Projects/informixhq-server/server/h2db
2022-06-23 08:43:23 lock: 2 shared read unlock SYS
2022-06-23 08:43:23 lock: 1 shared read unlock SYS
2022-06-23 08:43:23 database: closed
2022-06-23 08:43:23 database: disconnected session #3
2022-06-23 08:43:23 database: opening /Volumes/Macintosh HD - Data/Projects/informixhq-server/server/h2db (build 210)
2022-06-23 08:43:23 lock: 1 exclusive requesting for SYS
2022-06-23 08:43:23 lock: 1 exclusive added for SYS
2022-06-23 08:43:23 lock: 1 exclusive requesting for INFORMIX_SERVER_GROUPS
2022-06-23 08:43:23 lock: 1 exclusive added for INFORMIX_SERVER_GROUPS
2022-06-23 08:43:23 lock: 1 exclusive requesting for SYSTEM_REPORTS
2022-06-23 08:43:23 lock: 1 exclusive added for SYSTEM_REPORTS
2022-06-23 08:43:23 lock: 1 exclusive requesting for ALERTING_INCIDENTS
2022-06-23 08:43:23 lock: 1 exclusive added for ALERTING_INCIDENTS
2022-06-23 08:43:23 lock: 1 exclusive requesting for USERS
2022-06-23 08:43:23 lock: 1 exclusive added for USERS
2022-06-23 08:43:23 lock: 1 exclusive requesting for SENSOR_TYPES
2022-06-23 08:43:23 lock: 1 exclusive added for SENSOR_TYPES
2022-06-23 08:43:23 lock: 1 exclusive requesting for ALERTING_CRITERIA_VIOLATIONS
2022-06-23 08:43:23 lock: 1 exclusive added for ALERTING_CRITERIA_VIOLATIONS
2022-06-23 08:43:23 lock: 1 exclusive requesting for USER_PERMISSIONS
2022-06-23 08:43:23 lock: 1 exclusive added for USER_PERMISSIONS
2022-06-23 08:43:23 lock: 1 exclusive requesting for USER_ALERT_MESSENGERS
2022-06-23 08:43:23 lock: 1 exclusive added for USER_ALERT_MESSENGERS
2022-06-23 08:43:23 lock: 1 exclusive requesting for DASHBOARDS
2022-06-23 08:43:23 lock: 1 exclusive added for DASHBOARDS
2022-06-23 08:43:23 lock: 1 exclusive requesting for USER_ALERT_SERVICES
2022-06-23 08:43:23 lock: 1 exclusive added for USER_ALERT_SERVICES
2022-06-23 08:43:23 lock: 1 exclusive requesting for INFORMIX_SERVERS
2022-06-23 08:43:23 lock: 1 exclusive added for INFORMIX_SERVERS
2022-06-23 08:43:23 lock: 1 exclusive unlock SYS
2022-06-23 08:43:23 lock: 1 exclusive unlock INFORMIX_SERVER_GROUPS
2022-06-23 08:43:23 lock: 1 exclusive unlock SYSTEM_REPORTS
2022-06-23 08:43:23 lock: 1 exclusive unlock ALERTING_INCIDENTS
2022-06-23 08:43:23 lock: 1 exclusive unlock USERS
2022-06-23 08:43:23 lock: 1 exclusive unlock SENSOR_TYPES
2022-06-23 08:43:23 lock: 1 exclusive unlock ALERTING_CRITERIA_VIOLATIONS
2022-06-23 08:43:23 lock: 1 exclusive unlock USER_PERMISSIONS
**2022-06-23 08:43:23 lock: 1 exclusive unlock USER_ALERT_MESSENGERS**
2022-06-23 08:43:23 lock: 1 exclusive unlock DASHBOARDS
2022-06-23 08:43:23 lock: 1 exclusive unlock USER_ALERT_SERVICES
2022-06-23 08:43:23 lock: 1 exclusive unlock INFORMIX_SERVERS
2022-06-23 08:43:23 database: opened /Volumes/Macintosh HD - Data/Projects/informixhq-server/server/h2db
2022-06-23 08:43:23 database: connecting session #3 to /Volumes/Macintosh HD - Data/Projects/informixhq-server/server/h2db
2022-06-23 08:43:23 jdbc[3]:
/*SQL */SET TRACE_LEVEL_FILE 3;
2022-06-23 08:43:23 jdbc[3]:
/**/Connection conn2679 = DriverManager.getConnection("jdbc:h2:file:./h2db;TRACE_LEVEL_FILE=3", "", "");
2022-06-23 08:43:23 jdbc[3]:
/**/PreparedStatement prep947 = conn2679.prepareStatement("update informix_servers set alias = ?, hostname = ?, service_name = ?, port = ?, monitor_user = ?, monitor_password = ?, admin_user = ?, admin_password = ?, group_id = ?, profile = ?, alerts = ?, properties = ?, agent_config = ?, password_secret_Key = ?, server_type = ? where id = 11");
2022-06-23 08:43:23 jdbc[3]: Table      :     potential plan item cost 10,390 index PUBLIC.INFORMIX_SERVERS.tableScan
2022-06-23 08:43:23 jdbc[3]: Table      :     potential plan item cost 230 index PUBLIC.PRIMARY_KEY_3
2022-06-23 08:43:23 jdbc[3]:
/**/prep947.setString(1, "FUN1");
2022-06-23 08:43:23 jdbc[3]:
/**/prep947.setString(2, "localhost");
2022-06-23 08:43:23 jdbc[3]:
/**/prep947.setString(3, null);
2022-06-23 08:43:23 jdbc[3]:
/**/prep947.setObject(4, x);
2022-06-23 08:43:23 jdbc[3]:
/**/prep947.setString(5, "informix");
2022-06-23 08:43:23 jdbc[3]:
/**/prep947.setString(6, "47E8rRcSCgt12fTZ3b60sZrLVx911PoDS7YrFYHU43QiR3t/1A==");
2022-06-23 08:43:23 jdbc[3]:
/**/prep947.setString(7, "informix");
2022-06-23 08:43:23 jdbc[3]:
/**/prep947.setString(8, "z+owAPTcqQE7qx1sX5Ij2qDXiQl2QdNeEXTQJ0Pz61iPvb61FQ==");
2022-06-23 08:43:23 jdbc[3]:
/**/prep947.setLong(9, 0L);
2022-06-23 08:43:23 jdbc[3]:
/**/prep947.setBytes(10, org.h2.util.StringUtils.convertHexToBytes("ae0200000473656e736f727300a0020000033000610000000274797065001700000068615f7472616e73616374696f6e5f6c6174656e6379001272756e496e74657276616c000f000000000000001064617461526574656e74696f6e496e74657276616c001e0000000864697361626c6564000100033100550000000274797065000b00000068615f6c616774696d65001272756e496e74657276616c003c000000000000001064617461526574656e74696f6e496e74657276616c001e0000000864697361626c65640001000332005e0000000274797065001400000068615f6c6f676963616c5f6c6f675f72617465001272756e496e74657276616c000f000000000000001064617461526574656e74696f6e496e74657276616c001e0000000864697361626c65640001000333005f0000000274797065001500000068615f636f6e6e656374696f6e5f737461747573001272756e496e74657276616c003c000000000000001064617461526574656e74696f6e496e74657276616c001e0000000864697361626c6564000100033400650000000274797065001b00000068615f617070726f78696d6174655f6c6f675f6261636b6c6f67001272756e496e74657276616c000f000000000000001064617461526574656e74696f6e496e74657276616c001e0000000864697361626c6564000100033500580000000274797065000e00000068615f6170706c795f72617465001272756e496e74657276616c0005000000000000001064617461526574656e74696f6e496e74657276616c001e0000000864697361626c6564000000033600560000000274797065000c00000068615f776f726b6c6f6164001272756e496e74657276616c003c000000000000001064617461526574656e74696f6e496e74657276616c001e0000000864697361626c65640001000000"));
2022-06-23 08:43:23 jdbc[3]:
/**/prep947.setBytes(11, org.h2.util.StringUtils.convertHexToBytes("2100000004616c657274730005000000000464697361626c656400050000000000"));
2022-06-23 08:43:23 jdbc[3]:
/**/prep947.setBytes(12, org.h2.util.StringUtils.convertHexToBytes("0500000000"));
2022-06-23 08:43:23 jdbc[3]:
/**/prep947.setBytes(13, org.h2.util.StringUtils.convertHexToBytes("50000000127265706f7369746f72795365727665724964000100000000000000026461746162617365000600000068716d6f6e000a6167656e74436f6e6e656374696f6e50726f706572746965730000"));
2022-06-23 08:43:23 jdbc[3]:
/**/prep947.setObject(14, x);
2022-06-23 08:43:23 jdbc[3]:
/**/prep947.setObject(15, x);
2022-06-23 08:43:23 jdbc[3]:
/**/prep947.executeUpdate();
2022-06-23 08:43:23 lock: 3 shared write requesting for INFORMIX_SERVERS
2022-06-23 08:43:23 lock: 3 shared write ok INFORMIX_SERVERS
2022-06-23 08:43:23 jdbc[3]:
/*SQL l:284 #:1 t:1*/update informix_servers set alias = ?, hostname = ?, service_name = ?, port = ?, monitor_user = ?, monitor_password = ?, admin_user = ?, admin_password = ?, group_id = ?, profile = ?, alerts = ?, properties = ?, agent_config = ?, password_secret_Key = ?, server_type = ? where id = 11 {1: 'FUN1', 2: 'localhost', 3: NULL, 4: 6090, 5: 'informix', 6: '47E8rRcSCgt12fTZ3b60sZrLVx911PoDS7YrFYHU43QiR3t/1A==', 7: 'informix', 8: 'z+owAPTcqQE7qx1sX5Ij2qDXiQl2QdNeEXTQJ0Pz61iPvb61FQ==', 9: CAST(0 AS BIGINT), 10: X'ae0200000473656e736f727300a0020000033000610000000274797065001700000068615f7472616e73616374696f6e5f6c6174656e6379001272756e496e74657276616c000f000000000000001064617461526574656e74696f6e496e74657276616c001e0000000864697361626c6564000100033100550000000274797065000b00000068615f6c616774696d65001272756e496e74657276616c003c000000000000001064617461526574656e74696f6e496e74657276616c001e0000000864697361626c65640001000332005e0000000274797065001400000068615f6c6f676963616c5f6c6f675f72617465001272756e496e74657276616c000f000000000000001064617461526574656e74696f6e496e74657276616c001e0000000864697361626c65640001000333005f0000000274797065001500000068615f636f6e6e656374696f6e5f737461747573001272756e496e74657276616c003c000000000000001064617461526574656e74696f6e496e74657276616c001e0000000864697361626c6564000100033400650000000274797065001b00000068615f617070726f78696d6174655f6c6f675f6261636b6c6f67001272756e496e74657276616c000f000000000000001064617461526574656e74696f6e496e74657276616c001e0000000864697361626c6564000100033500580000000274797065000e00000068615f6170706c795f72617465001272756e496e74657276616c0005000000000000001064617461526574656e74696f6e496e74657276616c001e0000000864697361626c6564000000033600560000000274797065000c00000068615f776f726b6c6f6164001272756e496e74657276616c003c000000000000001064617461526574656e74696f6e496e74657276616c001e0000000864697361626c65640001000000', 11: X'2100000004616c657274730005000000000464697361626c656400050000000000', 12: X'0500000000', 13: X'50000000127265706f7369746f72795365727665724964000100000000000000026461746162617365000600000068716d6f6e000a6167656e74436f6e6e656374696f6e50726f706572746965730000', 14: CAST(X'aced00057372001f6a617661782e63727970746f2e737065632e5365637265744b6579537065635b470b66e230614d0200024c0009616c676f726974686d7400124c6a6176612f6c616e672f537472696e673b5b00036b65797400025b427870740003414553757200025b42acf317f8060854e0020000787000000010150d49c6152ac53bf23ea2daff16dbda' AS JAVA_OBJECT), 15: X'2b000000027365727665725479706500090000005374616e6461726400086973526561644f6e6c79000000'};
2022-06-23 08:43:23 lock: 3 shared write unlock INFORMIX_SERVERS
2022-06-23 08:43:23 jdbc[3]:
/**/prep947.close();
2022-06-23 08:43:23 jdbc[3]:
/**/conn2679.close();
2022-06-23 08:43:23 lock: 3 shared read unlock SYS
2022-06-23 08:43:23 database: disconnecting session #3
2022-06-23 08:43:23 database: closing /Volumes/Macintosh HD - Data/Projects/informixhq-server/server/h2db
2022-06-23 08:43:23 lock: 2 shared read unlock SYS
2022-06-23 08:43:23 lock: 1 shared read unlock SYS
2022-06-23 08:43:24 database: closed
2022-06-23 08:43:24 database: disconnected session #3
2022-06-23 08:43:29 database: opening /Volumes/Macintosh HD - Data/Projects/informixhq-server/server/h2db (build 210)
2022-06-23 08:43:29 lock: 1 exclusive requesting for SYS
2022-06-23 08:43:29 lock: 1 exclusive added for SYS
2022-06-23 08:43:29 lock: 1 exclusive requesting for INFORMIX_SERVER_GROUPS
2022-06-23 08:43:29 lock: 1 exclusive added for INFORMIX_SERVER_GROUPS
2022-06-23 08:43:29 lock: 1 exclusive requesting for INFORMIX_SERVERS
2022-06-23 08:43:29 lock: 1 exclusive added for INFORMIX_SERVERS
2022-06-23 08:43:29 lock: 1 exclusive requesting for SYSTEM_REPORTS
2022-06-23 08:43:29 lock: 1 exclusive added for SYSTEM_REPORTS
2022-06-23 08:43:29 lock: 1 exclusive requesting for ALERTING_INCIDENTS
2022-06-23 08:43:29 lock: 1 exclusive added for ALERTING_INCIDENTS
2022-06-23 08:43:29 lock: 1 exclusive requesting for USERS
2022-06-23 08:43:29 lock: 1 exclusive added for USERS
2022-06-23 08:43:29 lock: 1 exclusive requesting for SENSOR_TYPES
2022-06-23 08:43:29 lock: 1 exclusive added for SENSOR_TYPES
2022-06-23 08:43:29 lock: 1 exclusive unlock SYS
2022-06-23 08:43:29 lock: 1 exclusive unlock INFORMIX_SERVER_GROUPS
2022-06-23 08:43:29 lock: 1 exclusive unlock INFORMIX_SERVERS
2022-06-23 08:43:29 lock: 1 exclusive unlock SYSTEM_REPORTS
2022-06-23 08:43:29 lock: 1 exclusive unlock ALERTING_INCIDENTS
2022-06-23 08:43:29 lock: 1 exclusive unlock USERS
2022-06-23 08:43:29 lock: 1 exclusive unlock SENSOR_TYPES
2022-06-23 08:43:29 database: opened /Volumes/Macintosh HD - Data/Projects/informixhq-server/server/h2db
2022-06-23 08:43:29 database: connecting session #3 to /Volumes/Macintosh HD - Data/Projects/informixhq-server/server/h2db
2022-06-23 08:43:29 jdbc[3]:
/*SQL */SET TRACE_LEVEL_FILE 3;
2022-06-23 08:43:29 jdbc[3]:
/**/Connection conn2680 = DriverManager.getConnection("jdbc:h2:file:./h2db;TRACE_LEVEL_FILE=3", "", "");
2022-06-23 08:43:29 jdbc[3]:
/**/Statement stat1734 = conn2680.createStatement();
2022-06-23 08:43:29 jdbc[3]:
/**/ResultSet rs1747 = stat1734.executeQuery("select a.id, a.when_created, a.state, b.meta, a.informix_server_id, c.alias from alerting_incidents a join alerting_criteria_violations b on a.id = b.alerting_incident_id, informix_servers c where a.informix_server_id = c.id and a.informix_server_id = 11 order by a.when_created desc ");
2022-06-23 08:43:29 jdbc[3]: exception
org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "ALERTING_CRITERIA_VIOLATIONS" not found; SQL statement:
select a.id, a.when_created, a.state, b.meta, a.informix_server_id, c.alias from alerting_incidents a join alerting_criteria_violations b on a.id = b.alerting_incident_id, informix_servers c where a.informix_server_id = c.id and a.informix_server_id = 11 order by a.when_created desc  [42102-210]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:521)
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:496)
    at org.h2.message.DbException.get(DbException.java:227)
    at org.h2.message.DbException.get(DbException.java:203)
    at org.h2.command.Parser.getTableOrViewNotFoundDbException(Parser.java:8410)
    at org.h2.command.Parser.getTableOrViewNotFoundDbException(Parser.java:8381)
    at org.h2.command.Parser.readTableOrView(Parser.java:8370)
    at org.h2.command.Parser.readTablePrimary(Parser.java:1866)
    at org.h2.command.Parser.readTableReference(Parser.java:2342)
    at org.h2.command.Parser.readTableReference(Parser.java:2377)
    at org.h2.command.Parser.parseSelectFromPart(Parser.java:2793)
    at org.h2.command.Parser.parseSelect(Parser.java:2900)
    at org.h2.command.Parser.parseQueryPrimary(Parser.java:2783)
    at org.h2.command.Parser.parseQueryTerm(Parser.java:2650)
    at org.h2.command.Parser.parseQueryExpressionBody(Parser.java:2629)
    at org.h2.command.Parser.parseQueryExpressionBodyAndEndOfQuery(Parser.java:2622)
    at org.h2.command.Parser.parseQueryExpression(Parser.java:2615)
    at org.h2.command.Parser.parseQuery(Parser.java:2576)
    at org.h2.command.Parser.parsePrepared(Parser.java:707)
    at org.h2.command.Parser.parse(Parser.java:674)
    at org.h2.command.Parser.parse(Parser.java:644)
    at org.h2.command.Parser.prepareCommand(Parser.java:551)
    at org.h2.engine.SessionLocal.prepareLocal(SessionLocal.java:615)
    at org.h2.engine.SessionLocal.prepareCommand(SessionLocal.java:553)
    at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1116)
    at org.h2.jdbc.JdbcStatement.executeQuery(JdbcStatement.java:92)
    at com.informix.hq.server.rest.api.alert.AlertingIncidentsResource.getIncidents(AlertingIncidentsResource.java:108)
    at sun.reflect.GeneratedMethodAccessor15.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161)
    at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:205)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
    at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:326)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
    at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)
    at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
    at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473)
    at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:799)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:550)
    at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:233)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1435)
    at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:188)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:501)
    at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:186)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1350)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
    at org.eclipse.jetty.server.handler.HandlerList.handle(HandlerList.java:59)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:127)
    at org.eclipse.jetty.server.Server.handle(Server.java:516)
    at org.eclipse.jetty.server.HttpChannel.lambda$handle$1(HttpChannel.java:388)
    at org.eclipse.jetty.server.HttpChannel.dispatch(HttpChannel.java:633)
    at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:380)
    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:277)
    at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:311)
    at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:105)
    at org.eclipse.jetty.io.ChannelEndPoint$1.run(ChannelEndPoint.java:104)
    at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.runTask(EatWhatYouKill.java:336)
    at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.doProduce(EatWhatYouKill.java:313)
    at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.tryProduce(EatWhatYouKill.java:171)
    at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.run(EatWhatYouKill.java:129)
    at org.eclipse.jetty.util.thread.ReservedThreadExecutor$ReservedThread.run(ReservedThreadExecutor.java:383)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:882)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$Runner.run(QueuedThreadPool.java:1036)
    at java.lang.Thread.run(Thread.java:748)
2022-06-23 08:43:29 jdbc[3]:
/**/stat1734.close();
2022-06-23 08:43:29 jdbc[3]:
/**/conn2680.close();

As you can see there is no table with name "USER_ALERT_MESSENGERS"


text:
Q: NSFetchedResultsController with indexed UITableViewController and UILocalizedIndexedCollation I have a table that uses an NSFetchedResultsController.  This gets me an index with the headers that are present
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [[_fetchedResultsController sections] count];
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [[[_fetchedResultsController sections] objectAtIndex:section] name];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger numberOfRows = 0;
    NSArray *sections = _fetchedResultsController.sections;
    if(sections.count > 0)
    {
        id <NSFetchedResultsSectionInfo> sectionInfo = [sections objectAtIndex:section];
        numberOfRows = [sectionInfo numberOfObjects];
    }
    return numberOfRows;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return [_fetchedResultsController sectionIndexTitles];
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    return [_fetchedResultsController sectionForSectionIndexTitle:title atIndex:index];
}

but I want to use UILocalizedIndexCollation to get the complete alphabet.
How do I wire up these methods to the NSFetchedResultsController?
I think I need to get the index titles from the current Collation
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
}

but I am lost on how to write this method
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    //How do I translate index here to be the index of the _fetchedResultsController?
    return [_fetchedResultsController sectionForSectionIndexTitle:title atIndex:index];
}

A: I think you have to traverse the fetched results controller sections and find a matching section for the given title, for example:
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    NSInteger section = 0;
    for (id <NSFetchedResultsSectionInfo> sectionInfo in [_fetchedResultsController sections]) {
        if ([sectionInfo.indexTitle compare:title] >= 0)
            break;
        section++;
    }
    return section;
}

For section index titles that to not have a matching section, you have to decide if you want to jump to a "lower" or "higher" section. The above method jumps to the next higher section.

A: The solution I went with, after inspiration from Martin.
    - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    NSInteger localizedIndex = [[UILocalizedIndexedCollation currentCollation] sectionForSectionIndexTitleAtIndex:index];
    NSArray *localizedIndexTitles = [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
    for(int currentLocalizedIndex = localizedIndex; currentLocalizedIndex > 0; currentLocalizedIndex--) {
        for(int frcIndex = 0; frcIndex < [[_fetchedResultsController sections] count]; frcIndex++) {
            id<NSFetchedResultsSectionInfo> sectionInfo = [[_fetchedResultsController sections] objectAtIndex:frcIndex];
            NSString *indexTitle = sectionInfo.indexTitle;
            if([indexTitle isEqualToString:[localizedIndexTitles objectAtIndex:currentLocalizedIndex]]) {
                return frcIndex;
            }
        }
    }
    return 0;
}


text:
Q: std::ofstream: can open file but not append My program opens and writes to several files incrementally but at some seemingly arbitrary point appending text to an already existing file fails. Here's the offending piece of code:
bool append_to_file(std::string const &Path, std::string const &What) {
  std::ofstream FStream(Path, std::ios::out | std::ios::app);
  if (!FStream) {
    std::cerr << "OPEN FAILED" << std::endl;
    return false;
  }

  FStream << What;

  if (!FStream) {
    std::cerr << "WRITE FAILED" << std::endl;
    return false;
  }

  return true;
}

When this function fails, the first check succeeds but the second doesn't and prints:
WRITE FAILED. The file in question definitely does exist in the filesystem both before and after the function is called and has read and write permissions set. I can't make sense of this, why would opening the file succeed but appending fail in this scenario?
EDIT: this is not reproducible given the information I've provided and should be closed.

A: This works for me:
#include <string>
#include <fstream>
#include <iostream>
int append_to_file(std::string const& Path, std::string const& What) {
    std::fstream FStream(Path,std::ios_base::app);
    if (!FStream) {
        std::cerr << "OPEN FAILED" << std::endl;
        return 1;
    }

    FStream << What;

    if (!FStream) {
        std::cerr << "WRITE FAILED" << std::endl;
        return 2;
    }

    return 0;
}
int main() {
    int res = append_to_file("Tester.txt", "HIIII");
    std::cout << res;
}

In the example you provided, had you #included <iostream>, <string> and <fstream>? Also, when opening with std::ios_base::app, you don't have to have to open with std::ios_base::out. Also, I changed the return true; and return false; so that it returns a number depending on where it failed. This makes it easier to trace the error. Finally, I changed std::ofstream to std::fstream, because we are opening customly. After that, it worked perfectly.


text:
Q: How to decode a mime part of a message and get a **unicode** string in Python 2.7? Here is a method which tries to get the html part of an email message:
from __future__ import absolute_import, division, unicode_literals, print_function

import email

html_mail_quoted_printable=b'''Subject: =?ISO-8859-1?Q?WG=3A_Wasenstra=DFe_84_in_32052_Hold_Stau?=
MIME-Version: 1.0
Content-type: multipart/mixed;
 Boundary="0__=4EBBF4C4DFD012538f9e8a93df938690918c4EBBF4C4DFD01253"

--0__=4EBBF4C4DFD012538f9e8a93df938690918c4EBBF4C4DFD01253
Content-type: multipart/alternative;
 Boundary="1__=4EBBF4C4DFD012538f9e8a93df938690918c4EBBF4C4DFD01253"

--1__=4EBBF4C4DFD012538f9e8a93df938690918c4EBBF4C4DFD01253
Content-type: text/plain; charset=ISO-8859-1
Content-transfer-encoding: quoted-printable

Freundliche Gr=FC=DFe

--1__=4EBBF4C4DFD012538f9e8a93df938690918c4EBBF4C4DFD01253
Content-type: text/html; charset=ISO-8859-1
Content-Disposition: inline
Content-transfer-encoding: quoted-printable

Freundliche Gr=FC=DFe

--1__=4EBBF4C4DFD012538f9e8a93df938690918c4EBBF4C4DFD01253--

--0__=4EBBF4C4DFD012538f9e8a93df938690918c4EBBF4C4DFD01253--

'''
def get_html_part(msg):
    for part in msg.walk():
        if part.get_content_type() == 'text/html':
            return part.get_payload(decode=True)

msg=email.message_from_string(html_mail_quoted_printable)
html=get_html_part(msg)
print(type(html))
print(html)

Output:
<type 'str'>

Freundliche Gr��e

Unfortunately I get a byte string. I would like to have unicode string.
According to this answer msg.get_payload(decode=True) should do the magic. But it does not in this case.
How to decode a mime part of a message and get a unicode string in Python 2.7?

A:
Unfortunately I get a byte string. I would like to have unicode string.

The decode=True parameter to get_payload only decodes the Content-Transfer-Encoding wrapper, the =-encoding in this message. To get from there to characters is one of the many things the email package makes you do yourself:
bytes = part.get_payload(decode=True)
charset = part.get_content_charset('iso-8859-1')
chars = bytes.decode(charset, 'replace')

(iso-8859-1 being the fallback in case the message specifies no encoding.)


text:
Q: How do I combine the upper.tri of one matrix with the lower.tri of another in R? I have two symmetrical matrices of the same lengths (one contains correlation coefficients and the other contains p-values).
I'm trying to make a matrix such that the upper.tri contains correlation coefficients and the lower.tri contains the relevant p-values.

A: Assuming your matrices are correl and pval
# create a new matrix that is the pvalues
new <- pval
# not sure what you want the diagonal to be, lets make it NA
diag(new) <- NA
# replace the upper triangle of this new matrix with the
# upper triangle of the correlation matrix
new[upper.tri(new)] <- correl[upper.tri(correl)]


text:
Q: YouTubeStandalonePlayerActivity crashes as soon as it launches In my Activity, I try to launch a particular video:
Intent intent = YouTubeStandalonePlayer.createVideoIntent(this, key, videoId);
startActivity(intent);

The video id is LT5YThKAsic, but right after the standalone player activity shows up (I can just briefly see my video there), I get a Force Close with the following stack trace which I don't think is all that helpful.
FATAL EXCEPTION: main
java.lang.IllegalArgumentException
    at com.google.android.youtube.core.utils.s.a(SourceFile:112)
    at com.google.android.youtube.core.async.GDataRequestFactory.a(SourceFile:395)
    at com.google.android.youtube.api.ab.a(SourceFile:141)
    at com.google.android.youtube.core.async.a.d.a(SourceFile:101)
    at com.google.android.youtube.core.async.a.d.a(SourceFile:73)
    at com.google.android.youtube.core.player.Director.v(SourceFile:530)
    at com.google.android.youtube.core.player.Director.a(SourceFile:398)
    at com.google.android.youtube.core.player.Director.a(SourceFile:412)
    at com.google.android.youtube.core.player.Director.a(SourceFile:425)
    at com.google.android.youtube.api.ApiPlayer.a(SourceFile:195)
    at com.google.android.youtube.api.service.a.d.run(SourceFile:167)
    at android.os.Handler.handleCallback(Handler.java:587)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:132)
    at android.app.ActivityThread.main(ActivityThread.java:4134)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:491)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
    at dalvik.system.NativeStart.main(Native Method)
Force finishing activity com.google.android.youtube/.api.StandalonePlayerActivity

Any idea why it's crashing?


text:
Q: Understand BINDER_VM_SIZE in Android source code In file framework/native/libs/binder/ProcessState.cpp
Why is BINDER_VM_SIZE set to 1M-8k?
#define BINDER_VM_SIZE ((1*1024*1024) - (4096 *2))

A: It's not this value initially, you can find that(from git commit log) it's first value is
#define BINDER_VM_SIZE (1*1024*1024)

Then someone change this value to
#define BINDER_VM_SIZE ((1*1024*1024) - (4096 *2))

with the following commit message:

Modify the binder to request 1M - 2 pages instead of 1M.  The backing
  store in the kernel requires a guard page, so 1M allocations fragment
  memory very badly.  Subtracting a couple of pages so that they fit in
  a power of two allows the kernel to make more efficient use of its
  virtual address space.

I myself don't fully understand this message,so I just paste it here hope it may help your understanding!


text:
Q: Can I download my iOS App Store Icon from my iTunesConnect account? Can I download the 1024x1024 App Store Icon from my iTunesConnect account portal?
The icon in the portal says "This icon will be used on the App Store. For apps built with Xcode 9 or later, add this icon in the build. For apps built with earlier versions of Xcode, add the icon here."
I'm using XCode 9 now but I lost the original file. I can't find a way to download my icon from the portal.

A: No direct way to download the app icon, but possible with the developer tools of any browser.

*

*Log into https://itunesconnect.apple.com and choose your app.

*Right click on the app icon under "General App Information" > App Store Icon and Inspect / View source with the developer tools of Chrome/Safari/Firefox

*Find the <img> tag.

*

*Get the URL (both srcor ng-src work. URL should look something like this:

https://is1-ssl.mzstatic.com/image/thumb/Purple111/v4/eb/d7/18/ebd71843-0f6e-b78c-aa66-8b6c9b4e79e9/mzl.lhnaxkoi.png/150x150bb.jpg

*Remove the last part: 150x150bb and replace it by 1024x1024

https://is1-ssl.mzstatic.com/image/thumb/Purple111/v4/eb/d7/18/ebd71843-0f6e-b78c-aa66-8b6c9b4e79e9/mzl.lhnaxkoi.png/1024x1024.jpg

Voila, you got the icon.

A: Just use developer tool on your browser and get jpg and png format like the picture.


text:
Q: probem with wordpress replica sync I have a wordpress site with admin.example.com address. I created 3 replicas that sync with primary wordpress website (admin.example.com). the addresses of 3 replicas are example.com. I get all files and a dump from admin.example.com database. I put the files in a right path of 3 replicas and change addresses in database in following way:
sed -i 's/admin.example.com/example.com/g' admin.example.com_database.sql

but I have a problem: some breadcrumbs not shown in replicas.
anyone has an idea?


text:
Q: what to do when "import folium" fails but "conda list" shows it I have already installed folium, but import folium fails .
Also "conda list" for "base" env also lists folium
Giving example of pandas as well to show that pandas is getting imported which is also installed in the same location
folium                    0.12.1.post1       pyhd8ed1ab_1    conda-forge

(base) user1@user1-mac site-packages % conda list | grep -i pandas
pandas                    1.3.4            py38h743cdd8_0

If you see the site-packages directory...
(base) user1@user1-mac site-packages % pwd
/Users/user1/opt/anaconda3/lib/python3.8/site-packages

(base) user1@user1-mac site-packages % ls -ld pandas*
drwxr-xr-x  21 user1  staff  672 Jan  3 12:23 pandas
drwxr-xr-x  10 user1  staff  320 Jan  3 12:23 pandas-1.3.4-py3.8.egg-info

(base) user1@user1-mac site-packages % ls -ld folium*
drwxr-xr-x  14 user1  staff  448 Jan  3 15:00 folium
drwxr-xr-x  10 user1  staff  320 Jan  3 15:00 folium-0.12.1.post1.dist-info

from  Jupyter notebook ->
$ import os
$ os.environ['PATH']
'/Users/user1/opt/anaconda3/bin:/Users/user1/opt/anaconda3/condabin:/Library/Frameworks/Python.framework/Versions/3.10/bin:/Library/Frameworks/Python.framework/Versions/3.9/bin:/Applications/apache-maven-3.6.3/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Frameworks/Python.framework/Versions/3.10/bin'

I tried adding the path into $PATH variable
os.environ['PATH'] = os.environ['PATH'] + ':/Users/user1/Desktop/anaconda3/lib/python3.8'

But it did not solve the problem either . What else needs to be done ?

A: If you fail to import a module with error ModuleNotFoundError, then this module must not be in your Python interpreter's searching path. You can check this path by:
>>> import sys
>>> sys.path
['', '/Users/xxx/.pyenv/versions/3.9.9/lib/python39.zip', '/Users/xxx/.pyenv/versions/3.9.9/lib/python3.9', '/Users/xxx/.pyenv/versions/3.9.9/lib/python3.9/lib-dynload', '/Users/xxx/.pyenv/versions/3.9.9/lib/python3.9/site-packages']

You can adjust this variable via Python code, or via the environment variable PYTHONPATH. The variable PATH is where your shell searches when entering a command. They are different things.


text:
Q: Why can't we use Ansible only instead of Chef inspect? Referring to : http://scienceofficersblog.blogspot.com/2016/02/testing-ansible-with-inspec.html
There are so many posts mentioning use of Chef inspec for Ansible testing. But they usually give example like:
Ansible:
- hosts: all
  user: root
  tasks:
  - debug: msg="debug {{inventory_hostname}}"
  - apt: name=apache2 state=present

Chef Inspec:
impact 0.7
title "Test some simple resources"
describe package('apache2') do
    it { should be_installed }
end

So, if I execute the same Ansible block it will give me surety that the apache2 package is installed. Similarly there are so many examples like port 80 should be open, for that also if we execute the same playbook in chech mode (dry run) then also I will get to know whether port 80 is listening or not.
So, why can't we use Ansible itself? and what is the exact necessity of Chef inspec when we can do almost everything by using Ansible ?

A: Mostly that's because the examples are very very very simple.
For the same ansible block, I assume you expect apache to be installed, running and listening to port 80, a better inspec example would be:
impact 0.7
title "Test some simple resources"
describe package('apache2') do
    it { should be_installed }
end
describe service('apache2') do
    it { should be_installed }
    it { should be_enabled }
    it { should be_running }
end
describe port(80) do
  it { should be_listening }
  its('processes') {should include 'apache2'}
end

But the main point is that coding the configuration desired and the test to ensure what was planned separately allows for a TDD approach.
Inspec has also another interesting point in the formater side, where it can return audit information in various format.
At the end of the day, there's nothing requiring Inspec to test Ansible, that's a practice to get separated "tests" and "actions" so an error in ansible code making apache listen to port 800 wouldn't be catch by ansible as it would be what you asked it to set (and that's just normal), having them separated ensure the test are not derived by the action code.

A: I'm not sure why people seem to think Chef Inpec is necessary for this. Ansible has an assert module that allows to ensure things evaluate to true so effectively you register the output of a task and assert things about it are as you expect.
https://docs.ansible.com/ansible/latest/modules/assert_module.html
In fact, this is how almost all the Ansible integration tests are written upstream https://github.com/ansible/ansible/tree/devel/test/integration/targets


text:
Q: Random imperfections simulating traditional print Is there an easy way to accomplish something like this:

I am aware this is scanned, what I want is the random ink distribution and character placement.


text:
Q: Why do font size commands like \large have to be wrapped in blocks as opposed to e.g. \textbf? This is probably a beginner question, but it's always been throwing me off about LaTeX, especially because when I'm showing new people the basics, I can't explain why that is.
So the question is: Why does \large have to be wrapped inside {} to not make everything after it become large as well? When I type \large{Some text} it doesn't mean at all what one might expect ({Some text} isn't an argument apparently). For commands like \textbf it works the way I'm used to for most commands: Without braces, it just affects the next token, with curlies, it affects that whole argument inside the curlies and nothing beyond that.
Is there a term for these kinds of commands? I don't recall having seen very many others that behave like this.


text:
Q: Encoding 32bit hex numbers using OneHotEncoding in sklearn I have some categorical features hashed into 32bit hex numbers, for example, in one category ,the three different classes are hashed into:
'05db9164'  '68fd1e64' '8cf07265'

One Hot Encoding map these into a binary array, and only one bit is 1, the other is 0. So if I want to encoding the above features. Only need three bits.
001 correspond to 05db9164,  010 correspond to 68fd1e64, 100 correspond to 8cf07265
But when I use OneHotEncoder in sklearn, which tell me that the number is too large. this confused me. because we don't care the numerical property of the number. we only care about they are the same or not.
On the other hand, if i encoding 0,1,2:
enc = OneHotEncoder()
enc.fit([[0],[1],[2]])

print enc.transform([[0]]).toarray()
print enc.transform([[1]]).toarray()
print enc.transform([[2]]).toarray()

I have got the expected answer. And I think these 32bit hex number is used to indicate the class in the category. so it it the same as 0 , 1 ,2. and [0,0,1], [0,1,0],[1,0,0] is enough to encoding it. Could you please help me .thanks very much.

A: If your array is not extremely long, you can rename the features using np.unique. That way you can also determine the maximal number of different features, which in return you can feed to the OneHotEncoder, so that it know how many columns to allocate. Note that the renaming is not per se necessary, but it has the nice side effect of generating integers which use less space (if you use np.int32).
import numpy as np
rng = np.random.RandomState(42)
# generate some data
data = np.array(['05db9164', '68fd1e64', '8cf07265'])[rng.randint(0, 3, 100)]

uniques, new_labels = np.unique(data, return_inverse=True)
n_values = len(uniques)

from sklearn.preprocessing import OneHotEncoder
encoder = OneHotEncoder(n_values=n_values)
encoded = encoder.fit_transform(new_labels[:, np.newaxis])

print repr(encoded)


text:
Q: How can I set it so that when a number is pressed it leads to corresponding theorem (or formula)? Literally, given a Theorem and a number, is there any way to make it move to that theorem when the number is pressed? Can anyone provide example or Templates?
For example, let's see the next image :

Notice the underlined pinked numbers. How can we make it possible so that

*

*If we press the number (23) or (24), then it leads to the formula (23), (24)

*If we press the Construction 4.9.1., then it leads to the corresponding constructoin 4.9.1

?
Can anyone help ?

A: An example:
\documentclass{report}
\newtheorem{construction}{Construction}[section]
\counterwithout{equation}{chapter}
\usepackage{lipsum}
\usepackage{xcolor}
\usepackage[colorlinks,linkcolor=magenta]{hyperref}
\begin{document}
\setcounter{equation}{22}
\setcounter{chapter}{3}
\chapter{One}
\setcounter{section}{8}
\section{One}
\begin{construction}[title name]\label{cons:4.9.1}
\lipsum[1]
\begin{equation}\label{eqn:23}
    E=m\cdot c^2
\end{equation}
and
\begin{equation}\label{eqn:24}
    c=\sqrt{\frac{E}{m}}
\end{equation}
\end{construction}
\clearpage

Refer to the construction \ref{cons:4.9.1}.

Refer to the equation (\ref{eqn:23}) and (\ref{eqn:24}).
\end{document}


text:
Q: Foundation - Icon Bar:  inside  validation issue I'm trying to build the Icon Bar with the Foundation framework. The suggested, official way is:

  Home

I want to use Font Awesome icons and did this:

  Home

When checking this code in the Validator I get the error message: The element label must not appear as a descendant of the a element.
What can I do to fix this while keeping the functionality? Thanks!

A: It looks like foundation is using HTML structure that is not 100 valid. You can use

  Home

and update the css to make sure it looks like the label
or leave it as is and tell foundation to fix it..

A: [Probably] Complete set of .label styles in .scss file would be:
.icon-bar {
  .label {
    display: block;
    color: $icon-bar-font-color;
    font-size: $form-label-font-size;
    background: $icon-bar-bg;

    &:hover {
      color: $icon-bar-font-color-hover;
    }
  }
  .active .label {
    background: $icon-bar-hover-color;
  }
}

This solution assumes that you have all Foundation variables available in this .scss file.
For above styles using:

  Home

Will give desired effect.


text: Q: Issue In AWS WAF Classic Rule while deleting IP addresses range I have rule for ip address which block specific ip ranges. I remove one range of ip address from the AWS WAF rule and AWS console shows Success-full message: CIDRs deleted successfully. But after some time its show the ip range which I have already removed. How the ip range is added automatically which I removed?


text:
Q: jQuery Validate plugin is validating a field which has become "disabled" I have a field gender? which enables is Pregnant? if gender is set to FEMALE,
then if is Pregnant? field is unanswered, it's flagged as invalid.
If you go back and set gender? to MALE  The validation still flags is Pregnant? as invalid, even though it has been disabled.
jQuery says disabled fields are ignored.  I even tried:
jquery.validate validating disabled field
ignore: ":hidden"

What am I missing?

A: this is a valid problem, with this markup
<form>

    Male:
    <input type="radio" name="gender" value="male" />
    Female:
    <input type="radio" name="gender" value="female" />

    Pregnant:
    <input type="radio" name="pregnant" value="yes" />
    Not Pregnant:
    <input type="radio" name="pregnant" value="no" />

<input type="submit" />
</form>

and this script
$('[name=gender]').click(function () {
    var disabled = $(this).val() === 'male';
    $('[name=pregnant]').attr('disabled', disabled);

    // UNCOMMENT THIS TO FIX
    // if ($('[name=pregnant]').hasClass('error')) {
    //    $('form').validate().form();
    // }
});

$('input').addClass('required');

$('form').validate({
    ignore: ":disabled",
    errorPlacement: function (error, element) {
        error.appendTo(element.parent("div"));
    },
    submitHandler: function () {
        alert('form is ok');
    }
});

to reproduce the problem:

*

*click female

*click submit

*error message shows - this is correct

*click male - error message still shows

*click submit - form is valid

so as @ioan says you need to try and get rid of this error message as it is confusing, even though the form is valid the error message is still there

*

*problem -  http://jsfiddle.net/YzCHJ/4/

*a possible solution -  http://jsfiddle.net/YzCHJ/5/

A: The .validate() ignore: option works as follows:

ignore, Default: ":hidden"
  Elements to ignore when validating, simply filtering them out. jQuery's not-method is
  used, therefore everything that is accepted by not() can be passed as this option.

http://docs.jquery.com/Plugins/Validation/validate#toptions
Working Demo: http://jsfiddle.net/us9aE/
HTML:
<form id="myform">
     <input type="text" name="field" disabled="disabled" />

</form>

jQuery:
$(document).ready(function() {
    $('#myform').validate({
        ignore: ":disabled"
    });
});

If you'd like more specific help, please show your relevant HTML, your jQuery, and optionally create a jsFiddle demo.

A: The disabled fields are ignored during the validation phase BUT if the validation phase comes into action before the field has been disabled, the error message will still be there.
You can try to simply remove the validation message by cleaning the validation errors and re-validate the form.


text:
Q: Unable to create AWR report When I try to generate an AWR Report in Oracle, I keep getting this error:
[Error] Execution (37: 21): ORA-00904:
"SYS"."DBMS_WORKLOAD_REPOSITORY"."AWR_REPORT_HTML": invalid identifier

The command I run in Oracle SQL Developer:
SELECT *
FROM TABLE(SYS.DBMS_WORKLOAD_REPOSITORY.AWR_REPORT_HTML(550758650, 1, 3385, 3386));

I also tried with the GUI in Oracle Developer (View -> DBA) from the menu, I got the same error.  Does anyone know what I need to do to fix this?

A: Most likely, you do not have the rights to create an AWR report. Try to create it through the root user

A: Do as follow.
conn / as sysdba
SQL> @$ORACLE_HOME/rdbms/admin/awrrpt.sql
Specify the Report Type
AWR reports can be generated in the following formats. Please enter the
name of the format at the prompt. Default value is 'html'.

'html' HTML format (default)
'text' Text format
'active-html' Includes Performance Hub active report

Enter value for report_type:
old 1: select 'Type Specified: ',lower(nvl('&&report_type','html')) report_type from dual
new 1: select 'Type Specified: ',lower(nvl('','html')) report_type from dual

Type Specified: html

old 1: select '&&report_type' report_type_def from dual
new 1: select 'html' report_type_def from dual

old 1: select '&&view_loc' view_loc_def from dual
new 1: select 'AWR_PDB' view_loc_def from dual

Current Instance


text:
Q: Regex to capture part of string that switches between alpha characters and digits at least twice My goal is to create a regex to capture a line where some string switches between alpha characters and digits at least twice (but ignoring the filename/extension).
I am trying to find my "weird dynamically generated files".
My current regex captures digit/alpha character changes but also single changes.
I want to only capture a line if there has been multiple number/alpha character changes, since single changes tend to be on purpose (e.g. the name End2EndTest is OK).
How can I improve this regex to capture a pattern only when it's switching, let's say, three times for a string?
Here is my current regex:
(:[A-Za-z][A-Za-z\d-_]*\d[A-Za-z\d-_].*?\\|[\d][A-Za-z\d-_]*[A-Za-z][A-Za-z\d-_].*?\\)

Data set to match:
\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\123xyz123xyz\42abc43abc\App_global.asax.a1b23cd.dll
\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\123xyz123xyz\ab12cd45\App_global.asax.a2cd123.dll
\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\1b6123f0\ab12cd34\App_global.asax.kkp9w6zm.dll
\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\42abc43abc\539445c9\App_global.asax.-1bnvx3f.dll
\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\ab12cd34\eb88e642\App_global.asax.fswscrcw.dll
\scope\ScopeWorkingDir\script_7D16668D9F697A13\__ScopeCodeGenEngine__.dll
\scope\ScopeWorkingDir\script_7D16668D9F697A13\__ScopeCodeGen__.dll
\scope\ScopeWorkingDir\script_7D16668D9F697A13\__ScopeCodeGenEngine__.dll
\scope\ScopeWorkingDir\script_7D16668D9F697A13\__ScopeCodeGen__.dll

Data set to NOT match:
\\bt\\RANDOM\\repo\\out\\retail-amd64\\End2EndTest\\End2EndTest.exe
\\bt\\RANDOM\\repo\\out\\retail-amd64\\HighFive3\\DiskVfy512.exe

A: You can an alternation | to match either requirement, starting either with a digit, or with a char A-Za-z
If you want to allow more characters in between, you can extend the character class with the allowed chars like [A-Za-z\d-_]
Note to put the - at the end or escape it \-
\d[A-Za-z]+\d+[A-Za-z]|[A-Za-z]\d+[A-Za-z]+\d

Regex demo
If you want to match the whole line:
^.*(?:\d[A-Za-z]+\d+[A-Za-z]|[A-Za-z]\d+[A-Za-z]+\d).*

Regex demo