text:
Q: Layout elements duplicated on Samsung Galaxy Tab 2 I've been developing a simple android application.
It worked fine on several virtual devices and on HTC One S, but when I started it on Samsung Galaxy Tab 2 with Android 4.0.4 all the elements on the layout was duplicated. Its visible with the virtual keyboard and without it.
Here is the Layout file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">

  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="@string/password_label"
    android:layout_gravity="center_horizontal" />

  <EditText
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:inputType="textPassword"
    android:id="@+id/password_view" />

  <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/ok_label"
    android:id="@+id/password_confirm"
    android:layout_gravity="center_horizontal"
    android:onClick="checkPassword" />
</LinearLayout>

And the Activity source code:
public class PasswordActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);

    setContentView(R.layout.activity_password);

    Button button = (Button) findViewById(R.id.password_confirm);

    if (SharedPreferencesHandler.isPreferenceSet(this, SharedPreferencesHandler.PreferenceKey.PASSWORD_PREFERENCE_KEY)) {
        button.setText(R.string.ok_label);
    } else {
        button.setText(R.string.save_label);
    }

    EditText editText = (EditText) findViewById(R.id.password_view);
    editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            boolean handled = false;
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                checkPassword();
                handled = true;
            }
            return handled;
        }
    });
}
//some utility methods
}

Here is a screenshot of that bug:


text:
Q: How to get the amount of digits after the decimal point How can I easily find the amount of digits after the decimal point?
For example:
0.2 would result 1 (1 digit after the point)
0.09 would result 2 (2 digits after the point)
0.641 would result 3 (3 digits after the point)

I think this is fairly simple, but I just can't get my head around it right now...
Thanks!

A: The answer depends on just how you store your number.
If you are storing it as a rational number or as a fraction $\frac ab$ in lowest terms, or if you have a routine to convert your number to this format, here is how you can do it.
Find the prime factorization of $b$. Let's say it is
$$b=2^r5^sp^t\ldots$$
If $b$ has a prime factor other than $2$ or $5$, the number of decimal places is infinite. Otherwise, the number of decimal places in $\frac ab$ is
$$\max(r,s)$$
Do you need an explanation of why this works?

If your number $x$ is a float or a real number, find the smallest $t$ such that
$$10^t\cdot x=\lfloor 10^t\cdot x \rfloor$$
(The brackets are the greatest integer function.) Then $t$ is the number of decimal places. If no such $t$ exists, the number of decimal places is infinite.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Apache fraction exception: "The fraction to divide by must not be zero" E/AndroidRuntime(878): Caused by: org.apache.commons.math3.exception.MathArithmeticException: the fraction to divide by must not be zero: 0/1

The line the error happens is this one:
flist1.get(x).set(y, flist1.get(x).get(y).divide(z));

But, I have an if statement right before that line saying:
if(!flist1.get(x).get(y).equals(new Fraction(0)))

So I see no possible way for the "fraction to divide" to be zero as the if statement prevents it.

A: You get this error because your z variable must be 0.


text:
Q: Matplotlib - Draw points that satisfy condition I am new to Matplotlib and am trying to display on a graph all the points that satisfy a condition.
For example I want to draw all the points (x,y) where x - 4 <= y - 5.
But I can't find a way to do this, do I need to generate all those points manually, store them in an array and then use scatter (I think) to display them?
Thanks,
Max

A: Yes, you will have to use an array. For the example from "fill_between" it would be:
    x = np.arange(0.0, 2, 0.01)
    y = x + 1
    plt.plot(x, y,color='black')
    plt.fill_between(x, y, y2=y.max(), where=y>= x+1, facecolor='green',interpolate=True)
    plt.show()


text:
Q: Modify values within a column and row (PSQL) I get the following error for this query: [22P02] ERROR: invalid input syntax for type numeric: "."
select
date,
row_number () over () as RN,
case when (row_number() over ()) ='8' then '.' else (success/trials) end as "After_1M"
from trials
groupy by date;

Is there another way to indicate that a certain value in a ROWxCOLUMN combination should be adjusted?

A: Well your description certainly leaves a lot to be desired. But your query only needs slight modification to actually run. First off "groupy by date". I will assume it's just a typo. But a group by without an aggregate function generally doesn't do anything - and this is one of those.  But I believe your attempting to get a row count by date. If so the you need the partition by and order by clauses in the in the row_number function. The other issue is in the expression. Each entry in the expression must return the same data type but in case it doesn't. The THEN condition returns character (.) while the ELSE returns a numeric (success/trials) which must define 2 numeric columns to be valid. So which needs to change? I will assume the later. Given this we wind up with:
select date
    , row_number() over(partition by date order by trl_date) rn
    , case when (row_number() over(partition by date order by trl_date)) = 8
           then '.'
           else (success/trials)::text
      end as  "After_1M"
 from trials;

Note: Date is a very poor date is a very poor column name. It's a reserved word, as well as a data type.


text:
Q: Pandas split on regex I have pandas df with a column containing comma-delimited characteristics like so:
Shot - Wounded/Injured, Shot - Dead (murder, accidental, suicide), Suicide - Attempt, Murder/Suicide, Attempted Murder/Suicide (one variable unsuccessful), Institution/Group/Business, Mass Murder (4+ deceased victims excluding the subject/suspect/perpetrator , one location), Mass Shooting (4+ victims injured or killed excluding the subject/suspect

I would like to split this column into multiple dummy-variable columns, but cannot figure out how to start this process.  I am trying to split on columns like so:
df['incident_characteristics'].str.split(',', expand=True)

This doesn't work, however, because there are commas in the middle of descriptions.  Instead, I need to split based on a regex match of a comma followed by a space and a capital letter.  Can str.split take regex?  If so, how is this done?
I think this Regex will do what I need:
,\s[A-Z]

A: You can try .str.extractall (but I think there are better patterns than mine).
import pandas as pd

txt = 'Shot - Wounded/Injured, Shot - Dead (murder, accidental, suicide), Suicide - Attempt, Murder/Suicide, Attempted Murder/Suicide (one variable unsuccessful), Institution/Group/Business, Mass Murder (4+ deceased victims excluding the subject/suspect/perpetrator , one location), Mass Shooting (4+ victims injured or killed excluding the subject/suspect)'
df = pd.DataFrame({'incident_characteristics': [txt]})
df['incident_characteristics'].str.extractall(r'([\w\+\-\/ ]+(\([\w\+\-\/\, ]+\))?)')[0]

Output:
#    match
# 0  0                                   Shot - Wounded/Injured
#    1                Shot - Dead (murder, accidental, suicide)
#    2                                        Suicide - Attempt
#    3                                           Murder/Suicide
#    4         Attempted Murder/Suicide (one variable unsucc...
#    5                               Institution/Group/Business
#    6         Mass Murder (4+ deceased victims excluding th...
#    7         Mass Shooting (4+ victims injured or killed e...
# Name: 0, dtype: object

If you use .str.split, the first letter will be removed as it is used as a part of delimiter.
df['incident_characteristics'].str.split(r',\s[A-Z]', expand=True)

Output:
#                         0                                         1  \
# 0  Shot - Wounded/Injured  hot - Dead (murder, accidental, suicide)
#                   2              3  \
# 0  uicide - Attempt  urder/Suicide
#                                                    4  \
# 0  ttempted Murder/Suicide (one variable unsucces...
#                            5  \
# 0  nstitution/Group/Business
#                                                    6  \
# 0  ass Murder (4+ deceased victims excluding the ...
#                                                    7
# 0  ass Shooting (4+ victims injured or killed exc...

A: Yes, split supports regex. According to your requirements,

split based on a regex match of a comma followed by a space and a capital letter

you may use
df['incident_characteristics'].str.split(r'\s*,\s*(?=[A-Z])', expand=True)

See the regex demo.
Details

*

*\s*,\s* - a comma enclosed with 0+ whitespaces

*(?=[A-Z]) - only if followed with an uppercase ASCII letter

However, it seems you also don't want to match the comma inside parentheses, add (?![^()]*\)) lookahead that fails the match if, immediately to the right of the current location, there are 0+ chars other than ( and ) and then a ):
r'\s*,\s*(?=[A-Z])(?![^()]*\))'

and it will prevent matching commas before capitalized words inside parentheses (that has no parentheses inside).
See another regex demo.

A: I would first create the data and then feed it into a dataframe, like so
import pandas as pd, re

junk = """Shot - Wounded/Injured, Shot - Dead (murder, accidental, suicide), Suicide - Attempt, Murder/Suicide, Attempted Murder/Suicide (one variable unsuccessful), Institution/Group/Business, Mass Murder (4+ deceased victims excluding the subject/suspect/perpetrator , one location), Mass Shooting (4+ victims injured or killed excluding the subject/suspect"""

rx = re.compile(r'\([^()]+\)|,(\s+)')

data = [x
        for nugget in rx.split(junk) if nugget
        for x in [nugget.strip()] if x]

df = pd.DataFrame({'incident_characteristics': data})
print(df)

This yields
                            incident_characteristics
0                             Shot - Wounded/Injured
1                                        Shot - Dead
2                                  Suicide - Attempt
3                                     Murder/Suicide
4                           Attempted Murder/Suicide
5                         Institution/Group/Business
6                                        Mass Murder
7  Mass Shooting (4+ victims injured or killed ex...

Additionally, this assumes that commas in parentheses should be ignored when splitting.


text:
Q: PowerMock whenNew still going into constructor code I am trying to get Powermock to work by mocking out a constructor. In the method I am testing a constructor of another class is called (and takes in a lot of params, empty constructor not available). I don't want this constructor to be called as I do not have all the params/values it needs.
@RunWith(PowerMockRunner.class)
@PrepareForTest({FeatureManager.class, MyFilter.class})
public class ApplicabilityTest {
@Before
    public void setUp() {
PowerMockito.mock(Filter.class);
        MyFilter myFilterMock = PowerMockito.mock(MyFilter.class);
        try {

  PowerMockito.whenNew(MyFilter.class).withAnyArguments()
.thenReturn(MyFilterMock);
}

@Test
public void testAllApplicableStuff() {
    ApplicabilityComponent applicabilityComponent = new ApplicabilityComponent();
    Map response = ApplicabilityComponent.getAllApplicableExclusions(myInputData);
}

However, when I call the method where the constructor of myFilter is called, it still goes into the constructor code. What am I missing?
This is what the call to the constructor looks like in the actual code:
final MyFilter mFilter = new
MyFilter(
                        getNames(),
                        getPlaces(),
                        null,
                        provider,
                        procedure,
                        null,
                        new ArrayList(),
                        getServiceCategory(),
                        getCategory(),
                        null,
                        null,
                        getEffectiveDate(),
                        null);

A: I am not sure why this work, but this is what I did to fix the problem. I mocked the object with Mockito and not Powermock and the rest then just worked as is:
@Before
    public void setUp() {
        MyFilter myFilterMock = Mockito.mock(MyFilter.class);
    try {

  PowerMockito.whenNew(MyFilter.class).withAnyArguments().thenReturn(MyFilterMock);
}


text:
Q: OpenCV HoughTransformation in Swift I'm about to program a project in which I need to extract the straight lines out of an image.
The first thing that came to my mind is Hough Transformation. So I downloaded the OpenCV framework, added it to my project. Added the Bridging Header as well as the OpenCVWrapper.h and the OpenCVWrapper.mm files. But I can't find any tutorial on how to implement the hough transformation into my swift project. So what sort of files do I need to create to write the function in? And how should that function look like?
I'm happy to hear any helpful suggestion!
Kind regards
Robert

A: I'm also currently working on OpenCV with Swift, it indeed didn't have much tutorial about it.
About the Hound Transformation, here is the link to the documentation, hope it helps.
And this project helps a lot when I want some reference.
Good luck!


text:
Q: L Hopital rule and side limits Today I was in the process of solving a side limit, to be precise this limit:
$$ \lim_{x\rightarrow 0^{+}}\dfrac{\ln(\sin(2x)))}{\ln(\sin(x))} $$
I was supposed to use L'hopital and found that the answer was $1$. However, this function is not differentiable at some interval $(0,a)$ so L'hopital hypothesis is not true here. Based on the fact that I was supposed to use the rule here I assume that it can be used here, but if that was the case then it must be true that:$$\lim_{x\rightarrow 0^{+}}\dfrac{\ln(\sin(2x)))}{\ln(\sin(x))} = \lim_{x\rightarrow 0^{-}}\dfrac{\ln(\sin(2x)))}{\ln(\sin(x))} = \lim_{x\rightarrow 0}\dfrac{\ln(\sin(2x)))}{\ln(\sin(x))} = \dfrac{\dfrac{d}{dx}\ln(\sin(2x)))}{\dfrac{d}{dx}\ln(\sin(x))}$$
Because that is what I believe L'hopital states.
What is happening here? L'hopital should not be used here? Is it real that the rule may be true for JUST one side limit in case it is a limit point of the domain? Or even.. Is $$\lim_{x\rightarrow 0}\dfrac{\ln(\sin(2x)))}{\ln(\sin(x))} = 1$$ ?
I am pretty confused with this fact about side limits and limit points of the domain, and now with L'hopital rule into play it is even more confusing. I hope that I expressed myself the best way possible.
Thanks for your time and sorry if there are grammar mistakes, I do not speak english.

A: Why use L'Hopital's rule?  We have $$\sin 2x = 2\sin x \cos x,$$ and since in a sufficiently small neighborhood of $0$, we have $\cos x > 0$, it follows that $$\log \sin 2x = \log \sin x + \log (2 \cos x).$$  Then $$\lim_{x \to 0^+} \frac{\log \sin 2x}{\log \sin x} = 1 + \lim_{x \to 0^+} \frac{\log (2 \cos x)}{\log \sin x} = 1.$$

A: Hint: Write $\left(\ln(\sin(kx))\right)' = \dfrac{k\cos(kx)}{\sin(kx)}$,and plug in $k =1,2$ into the equation to get the derivatives and take it from there.


text:
Q: Share session between two websites in ASP.NET MVC Currently, Azure Management Portal has two versions:

*

*Old: https://manage.windowsazure.com/

*New: https://ms.portal.azure.com/
They are on two different domains (even different data centers, I guess) but sharing the same login session, i.e. once you logged in one of them, you can enter the other without any authentication.
Can anyone explain how it works on dotNET Stack?

A: Based on your description, I think what you are talking about is Single sign-on (SSO). SSO is a session/user authentication process that permits a user to enter one name and password in order to access multiple applications. The process authenticates the user for all the applications they have been given rights to and eliminates further prompts when they switch applications.

Can anyone explain how it works on dotNET Stack?

To implement SSO, you need to create a shared authentication server or use a exist shared authentication providers(ex Microsoft/Google). Here are some examples of implement SSO using ASP.NET.
Basics of Single Sign on (SSO)
Using OAuth Providers with ASP.NET MVC 4
Introducing Single Sign-on to an existing ASP.NET MVC application


text:
Q: Is there a way to send an email when a build in queue is cancelled? I am trying to find a way to send an email when a queued build is cancelled, and have that email contain the name of the user that cancelled the build. Am I missing a setting somewhere or is there a plugin I need?

A: We use Email Extension plugin.
After installation you will have new step option in Post-build Actions of a job named Editable Email Notification. In the Advanced settings of this step you can add trigger Aborted.


text:
Q: If condition inside click function to concatenate variable I am trying to concatenate an "http://" to the variable 'bar' if it does not already exist, before sending it to ajax where it will be added to the database and will also be displayed back on the page. I can do this in PHP in the processing script and have it added to the db but that does not put it back on the page (without a refresh).
$('#update').click(function() {
    var foo     = "http://";
    var bar     = $('#url').val();

    if (bar != '') {
        if (!preg_match('#^[a-zA-Z]+://#', bar)) {
            var bar = foo.concat(bar);
        }
    }

    $.ajax({
        url         : 'update_this.php',
        method      : 'post',
        data        : {bar:bar},
        success : function(response) {
            $('#id').children('a[data-target=x]').attr('href',bar);

        }
    });
});

A: preg_match doesn't exist in JavaScript but it does offer regular expression functionality. See for example this stackoverflow question and its answer: How can I use preg_match in jQuery?.
So, a possibility would be to use the match(regExp) function that operates on a string.
What's more, '#^[a-zA-Z]+://#' is not a valid regular expression for Javascript. If you want to use a JavaScript regular expression literal you need to change two things:

*

*Don't use ', i.e. don't format the expression as a string.

*# is not a valid delimiter for a regular expression. Use
/ instead. Also keep in mind that you then have to escape the
/ at the end of your expression.

So the resulting expression would then be: /^[a-zA-Z]+:\/\//.
Alternatively, you could use a RegExp object. See here for an introduction:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions.
Last but not least, I want to point out that this regular expression would actually also match wrong formats, e.g. htpts://. If this is a concern, you could use groups to check if the match is either equal to https:// or http:// and replace it if necessary.


text:
Q: Как подключиться к БД из редактора? Весь вопрос в одной картинке по сути:

Что я делаю не правильно? Proxy user и Password ввожу юзера БД и его пароль

A: Вы пытаетесь подключиться к БД через SSH-туннель, т.е. в данном окне нужно вводить имя пользователя и пароль, которые используются для SSH-подключения, а не для подключения к базе данных.


text:
Q: Is there a way to have snipping tool available for windows 7 with .NET Framework 1.1 Is there a way to have snipping tool available for windows 7 with .NET Framework 1.1?
I need help without changing the .NET Framework

A: Snipping Tool come as a default application from Windows 7 onwards. You can open the tool by hitting start and search for 'snipping tool' in the search bar of start.

A: The snipping tool is a feature that the Windows 7 system has by default. If your system does not have this feature for some reason, you can re-download it on the official website.
By the way, I still recommend that you update your Net framework. The new version optimizes the previous drawbacks and provides better features.


text:
Q: std::list sentinel node from standard point of view Code example:

    list<int> mylist{10, 20, 30, 40};
    auto p = mylist.end();
    while (true)
    {
        p++;
        if (p == mylist.end()) // skip sentinel
            continue;
        cout << *p << endl;
    }

I wonder, how much this code is legal from standard (C++17, n4810) point of view?
I looking for bidirectional iterators requirements related to example above, but no luck.
My question is:
Ability to pass through end(), it is implementation details or it is standard requirements?

A: Quoting from the latest draft available online.
[iterator.requirements.general]/7

Just as a regular pointer to an array guarantees that there is a pointer value pointing past the last element of the array, so for any iterator type there is an iterator value that points past the last element of a corresponding sequence. These values are called past-the-end values. Values of an iterator i for which the expression *i is defined are called dereferenceable. The library never assumes that past-the-end values are dereferenceable.

I believe that this applies not just to the end() but what comes after that as well. Note that the standard does not clearly state that end() should never be dereferenced.
And Cpp17Iterator requirements table states that for expression *r, r should be dereferenceable:

past-the-end iterator is considered a non-incrementable iterator and incrementing it (as you are doing at the beginning of the while loop) results in undefined behavior.
Something like what you are trying to do can also happen when using std::advance.
The book "The C++ Standard Library: A Tutorial and Reference" by Nicolai Josuttis has this quote:

Note that advance() does not check whether it crosses the end() of a sequence (it can't check because iterators in general do not know the containers on which they operate). Thus, calling this function might result in undefined behavior because calling operator ++ for the end of a sequence is not defined.

A: You code is illegal. You first initialized p to be the past-the-end iterator.
auto p = mylist.end();

Now you p++. Per Table 76,
the operational semantics of r++ is:

{ X tmp = r;
++r;
return tmp; }

And per [Table 74],
++r

Expects: r is dereferenceable.

And per [iterator.requirements.general]/7,

The library never assumes that past-the-end values are
  dereferenceable.

In other words, incrementing a past-the-end iterator as you did is undefined behavior.


text:
Q: Identifying controls in a Windows Form Can anybody identify what type of Windows Form control(s) the Select signature to edit, Choose default signature, and Edit Signature are in the Microsoft Outlook insert signature modal? I cannot figure out if it's a super-shruken panel, or if it's some other control I'm not finding?

A: They are not controls at all. Most of what you see on that dialog is what I call "pseudo controls", that is painted bits that look and operate as controls, but which do not have system windows. You can see this by using a Spy tool to find the (non-existent) system windows.
You can achieve this yourself with Graphics.DrawText and ControlPaint.DrawXXX, where XXX I'm not sure of. Maybe Border, or 3DBorder?
Here's a cheap and dirty example. I used the WinForms Label control because it was easy.
using System;
using System.Drawing;
using System.Windows.Forms;

public class Form1 : Form
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }

    public Form1()
    {
        ClientSize = new Size(400, 200);
        Controls.Add(new LineLabel { Text = "Edit signature", Location = new Point(10, 10), Anchor = AnchorStyles.Left | AnchorStyles.Right, Width = 380 });
    }
}

public class LineLabel : Label
{
    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        SizeF textSize = e.Graphics.MeasureString(this.Text, this.Font);
        int leftWidth = (int)(textSize.Width + 2);
        Rectangle bounds = new Rectangle(leftWidth, Height / 2 - 4, Bounds.Width - leftWidth, 2);
        ControlPaint.DrawBorder(e.Graphics, bounds, Color.DarkGray, ButtonBorderStyle.Solid);
    }
}

A: They are GroupBoxes, albeit looking a little modified in terms of their borders.
If you would like to customize your own, you could do that for a WinForms groupbox (to some extent) but it will prove a LOT easier to go with a WPF Groupbox and read up on styling in Styling a GroupBox.
A must-read is also MSDN - How To Define a GroupBox Template.


text:
Q: How to draw Feynman diagrams without using LuaLatex in Overleaf? I am new to drawing Feynman diagrams in Latex, however I found some sources and try to implement them. I managed to draw the diagrams using LuaLatex, however it makes changes to other things in the thesis, for example citations should be re-written somehow. So my question is following, is there some way to draw Feynman diagrams (simple ones) without using LuaLatex in Overleaf, but just with pdfLatex?

A: You can draw Feynman diagrams without using LuaLatex in Overleaf, but will have a lot of warnings, but You still can compile Your document and view .pdf file, see more https://en.wikipedia.org/wiki/LuaTeX


text:
Q: Override a method when creating an object in Arduino/C++ I am working on a C++ Arduino sketch that creates a GUI on an OLED display. I want to have buttons buttons that all do different things when you press them. In Java, I can simply override the method when creating an anonymous class like this:
    class Example {
        public void method() {
        }
    }
    Example e = new Example() {
        @Override
        public void method() {
            //do something
        }
    };

So my question is: Can I do this in an C++?

A: As arduino sketch are in fact C/C++, you could do the same as in Java.
class Button {
   virtual void push() = 0;
}

class PowerButton : public Button {
   virtual void push() {
      shutdown();
   }
}

Notice the virtual keyword, it's used to declare a method overidable, the "= 0" means pure virtual (the address of the method is 0). It simply says that this method is not implemented in this class, the class became abstract as in Java.
Also, the virtual keyword is not mandatory, but if you don't put it, C++ will just call the method of the given type and not from the real type.
Take a look there
But, the difference with Java is that you can't create an anonymous class directly in the code. Instead, maybe take a look for lambda.
For example, the class Button would became :
class Button {
   public:
      Button(const std::function<void()> &pushCallback) :
         mPushCallback(pushCallback) {}

      void push() { mPushCallback(); }
   private:
      const std::function<void()> mPushCallback;

And then the usage:
Button powerButton([]() {
   powerOff();
});

*

*Brackets are use to "capture" a variable, for example this, &str { myMethodInMyClass(str); }

*Parenthesis are used to pass parameters

*The std::function class take the function type as type parameter, a function that take a string as const ref and an int and that return an int will look like this : std::function<int(const std::string &, int)>


text:
Q: What is the correct way to copy data from a postgresql database in one app to a postgresql database in another app on heroku? I have been following the documentation Heroku docs on the subject
and have gone through this and tried variations on what it says to do to for

Direct database-to-database copies

I am convinced the docs are wrong or I have some setting or somthing wrong (do have admin access). I have also read some scattered things on SO that the command in the heroku CLI for how to do this has changed.
When I run this command (using the credentials for my heroku DB)
heroku pg:copy sushi::ORANGE GREEN --app sushi-staging

After I confirm the message:

WARNING: Destructive action
   ▸    This command will remove all data from

and confirm. Then I get an error that says:

Heroku PostgreSQL database must be source or target

What is the corrrect way to copy data from a postgresql database in one app to a postgresql database in another app on heroku?

A: The proper way to do this is:
heroku pg:copy [app name to copy from]::[app DB name] [DB to copy to] --app [app name to copy to]

So if you want to copy from database 'Orange' on app 'sushi' to database 'Green' on app 'sushi-staging', the command would be what you had:
heroku pg:copy sushi::Orange Green --app sushi-staging

Most of the time, you will only have one database on an app and the name won't be a color. It will be named 'DATABASE_URL'. You can find your database names in the config vars of the app. I had only one DB, so I had to do:
heroku pg:copy sushi::DATABASE_URL DATABASE_URL --app sushi-staging

Hope that helps

A: This was seriously not clear from the docs. And sombody at with heroku should make this clear.
heroku pg:copy ::DATABASE_URL -a ...

You actually write the database as the string representation for the to-database-url but you use the environment variable name DATABASE_URL

A: This worked for me:
heroku pg:copy [origin databasee URI] DATABASE_URL --app [app-name]

A: I had same issue, resolved by using HEROKU_POSTGRESQL_TEAL_URL instead of the DATABASE_URL:
heroku pg:copy postgresql-rugged-XXXX postgresql-closed-XXX -a app-name

Note: The two databases are attached here to the same app (app-name, in my case).

Now, how do you find the HEROKU_POSTGRESQL_TEAL_URL? You can find it here:

A: The actual FULL command that worked for me, DATABASE_URL not being replacement for anything, was:
heroku pg:copy project1::DATABASE_URL project2::DATABASE_URL

heroku automatically fills in the environmental variables.

A: Unfortunately copy didn't work for me so I did a backup/restore operation
heroku pg:backups:capture --app [source-app]

If you run the command below, it will show the available backups from the source-app and its IDs
heroku pg:backups --app=[source-app]

Get your destination database URL using
heroku config:get DATABASE_URL --app [destination-app]

Then you create an env var named DATABASE_URL and add the information from the command above
export DATABASE_URL='postgres://…'

And finally the restore command. (just write DATABASE_URL as this will get the value from the env variable we've created before)
heroku pg:backups:restore [source-app]::[backup-id] DATABASE_URL --app [destination-app]

Update:
Exporting the database_urls for both SOURCE and DESTINATION you can use the below to copy between apps
heroku pg:copy [source-app]::SOURCE DESTINATION --app [destination-app]

A: It's a different scenario if you're looking at transferring an app from one heroku account to another. You'd probably want to "transfer ownership". This is possible like so:

*

*You must ensure that the account receiving the new ownership has a credit-card detail (i.e if the original account has an accrued cost)

*Ensure you've added the new account receiving ownership as "a collaborator" in the original owners heroku-account. This can be done by clicking on the app (in your dashboard), click on the "Access" tab. Then add a collaborator, by inputting the email address of the heroku-account receiving ownership.
you can follow this guide as well: https://devcenter.heroku.com/articles/transferring-apps


text:
Q: change checkbox color in angular material I'm using angular material(6.4.7). I was using select and I want to change the color of select checkbox. I have tried /deep/ and ::ng-deep but no success. I think, I am using it in wrong way for these checkbox.
Here is the stackblitz link

A: adding this to the select-multiple-example.css works in the stack-blitz link
::ng-deep .mat-primary .mat-pseudo-checkbox-checked {
    background: red;
}

A: I know it was a bit late for my answer but this works for me the best
// for color when checkbox is checked
::ng-deep .mat-checkbox-checked.mat-accent .mat-checkbox-background
  background-color: orange;
}

::ng-deep .mat-checkbox-indeterminate.mat-accent .mat-checkbox-background {
  background-color: orange;
}

//to change the border color
::ng-deep .mat-checkbox-frame{
  border-color: rgb(75, 75, 75, 0.7);
}


text:
Q: $a$ is a prime and $R$ is an integral domain $\implies a$ is irreducible I noticed the following statement in a proof of a theorem on Euclidean rings.
$a$ is a prime and $R$ is an integral domain $\implies a$ is irreducible
It seems like this part of the statement is superfluous - $R$ is an integral domain.
Aren't primes always irreducible?

A: No, if the ring is not an integral domain, primes need not be irreducible. Consider $R = \mathbb{Z}/(6)$.
The elements $\overline{2}$ and $\overline{3}$ are prime, but you have $\overline{2} = \overline{2}\cdot \overline{4}$ and $\overline{3} = \overline{3}^2$, so they are not irreducible.

A: The most common definition is that a nonzero element $p$ is prime if it not invertible and, for all $a,b\in R$, $p\mid ab$ implies $p\mid a$ or $p\mid b$.
Every prime in an integral domain is irreducible: if $p$ is prime and $p=ab$, then either $p\mid a$ or $p\mid b$. If $p\mid b$, we have $b=px$ and so $p=apx$, so $ax=1$ and $a$ is invertible.
Note that the hypothesis that $R$ is an integral domain has been used when canceling  $p$ from $p=apx$. If you add in the definition that $p$ is not a zero divisor, then the reasoning can go on in the same fashion.

A: No, a prime element need not be irreducible.
Recall that an element $x$ in a ring $R$ is prime if $\langle x\rangle$ is a prime ideal, ie if $R/\langle x\rangle$ is an integral domain.
For an example of a non-reducible prime, take the element $x = (1,0)$ in $R = \mathbb{F}_2\times \mathbb{F}_2$, which is not irreducible, since $x = x^2$ is a non-trivial factorization. But the quotient $R/\langle x\rangle$ is isomorphic to $\mathbb{F}_2$ and hence an integral domain.


text:
Q: Problemas con funcion Click en jquery y llamada a funcion $get.JSON Hola no se como explicar bien mi duda pero voy a hacer mi mejor esfuerzo.
Resulta que tengo creada una API en node.js y quiero interactuar con ella a través de jquery. Es un caso sencillo donde tengo que hacer una búsqueda.
Si implemento directamente la búsqueda en el input como por ejemplo:
$("input").on("change input textInput", ()=>{.....})

funciona perfecto, pero lo que deseo es dar click en un boton y funcione igual y lo que pasa es que no muestra ninguna info ni los console.log().
A continuación les pongo el código que no funciona. Reitero que el problema esta en el jquery porque la api responde bien.

<meta charset="UTF-8">
<title>Search Animals</title>

Find Animals

SPECIES: <input  name="species">

<input id="button" type="submit" value="Enviar">

//-----En el servidor Node.js
  app.use('/findAnimals', (req, res) =>{
  var query = {};
  if(req.query.species)
    query.species = req.query.species;
  if(Object.keys(query).length != 0){
    Animal.find(query, (err, animals)=>{
        if(!err){
            res.json(animals);
        }else{
            console.log(err);
            res.json({});
        }
    });
   }else res.json({});
   });


text:
Q: Android Spinner get selected value OnSelectedItemListener(); I'm having a problem to get value selected for spinner. here is my code and adapter.
Spinner event listener
category = (Spinner) findViewById(R.id.Spinner);
category.setPrompt("Select Category..");
ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("Category", "Choose a Category");
list.add(map);

map = new HashMap<String, Object>();
map.put("Icon", R.drawable.icon1);
map.put("Category", "Category1");
list.add(map);

map = new HashMap<String, Object>();
map.put("Icon", R.drawable.icon2);
map.put("Category", "Category2");
list.add(map);

map = new HashMap<String,Object>();
map.put("Icon", R.drawable.icon3);
map.put("Category", "Category3");
list.add(map);
CategoryAdapter adapter = new CategoryAdapter(v.getContext(), list,R.layout.list_layout, new String[] { "Category", "Icon" }, new int[] { R.id.category, R.id.icon });
category.setAdapter(adapter);

category.setOnItemSelectedListener(new OnItemSelectedListener(){

@Override
public void onItemSelected(AdapterView<?> arg0,View v, int arg2,long arg3) {
    // TODO Auto-generated method stub
    String selected = category.getSelectedItem().toString();
    //String selected = category.getTag().toString();
    try{
        //String selected = category.getSelectedItem().toString();
        //Object selected = arg0.getTag();
        //Toast.makeText(getApplicationContext(), String.valueOf(selected), Toast.LENGTH_SHORT).show();
        if(selected.toString().equals("Category1")){
            String msg1 = "Category1 type selected";
            Toast.makeText(getApplicationContext(), msg1 + " " + selected, Toast.LENGTH_SHORT).show();
        }else if(selected.toString().equals("Category2")){
            String msg2 = "Category2 type selected";
            Toast.makeText(getApplicationContext(), msg2 +  " " + selected, Toast.LENGTH_SHORT).show();
        }else if(selected.toString().equals("Category3")){
            String msg3 = "Category3 type selected";
            Toast.makeText(getApplicationContext(), msg3 + " " + selected, Toast.LENGTH_SHORT).show();
        }
    }catch(Exception e){
        Toast.makeText(getApplicationContext(),"Error occured " + e.getName().getClass(), Toast.LENGTH_SHORT).show();
    }
}

@Override
public void onNothingSelected(
        AdapterView<?> arg0) {
    // TODO Auto-generated method stub
    Toast.makeText(getApplicationContext(), "nothing selected", Toast.LENGTH_SHORT).show();
}

});

CategoryAdapter
public class ReminderCategoryAdapter extends SimpleAdapter{

    Context c;

    public ReminderCategoryAdapter(Context context, List<? extends Map<String, ?>> data,
            int resource, String[] from, int[] to) {
        super(context, data, resource, from, to);
        c = context;

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            LayoutInflater li = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = li.inflate(R.layout.list_layout,null);
        }

        HashMap<String, Object> data = (HashMap<String, Object>) getItem(position);

        ((TextView) convertView.findViewById(R.id.category)).setText((String) data.get("Category"));
        ((TextView) convertView.findViewById(R.id.category)).setTag((Object) data.get("Category"));

        return convertView;
    }
}

for my Spinner, in the adapter, I inflate Image + Text, my spinner is working find, herewith I illustrate my spinner
============================
|Icon1 Text1               |
|Icon2 Text2               |
|Icon3 Text3               |
but once i try to use onitemselectedlistener and use the getSelectedItem().toString() method and toast it, the value return on the toast is the combination of icon and the text, I don't want the value of icon will be return but I just want the string or text only. I've try using setTag(Object value) method using ((TextView) convertView.findViewById(R.id.category)).setTag((Object) data.get("Category")); in the adapter, and when use getTag() method in the listener nullpointer exception was thrown. Instead of using getItemPosition(position) or getSelectedItem() method is there any other solution to get and manipulate string value for selected Item?
Please help.

A: One solution you can easily use is by using the Spinner#getSelectedItemPosition() method. This method will return the position of the selected item, and you can retrieve the item itself from the list you are passing to the adapter.
So basically, replace the following line in your onItemSelected method:
String selected = category.getSelectedItem().toString();

with:
String selected = list.get(category.getSelectedItemItemPosition()).get("Category");


text:
Q: How do I create a bot to play games for me in python? For the specific game I want to make a bot for (Fnaf: Ultimate Custom Night) I want to have certain keys pressed when something pops up on the screen. For this i need to recognize the object on the screen, and then use something like pyautogui to click the button. I know how to do the second part, but I can't seem to figure out how to do the real time object recognition part on the screen. The only tutorials I can find online are object detection with webcams, or stuff like that but I can't find any with real time detection on your screen.
Thank you for your help.

A: import pyautogui

locateOnScreen should work with you by saving screenshots of the desired elements to click and run it in an infinite loop
example:
image = pyautogui.locateOnScreen('image2.png')
if image != None:
     pyautogui.click(image)
else:
    pass

A: The answer above works, but if the object is slightly covered up, it won't work as it has to be an exact match. I would recommend installing OpenCV as it lets you:
import pyautogui
image = pyautogui.locateOnScreen('image2.png', confidence = 0.9)
if image != None:
     pyautogui.click(image)
else:
    pass

Notice that the 'confidence' argument is given as a decimal


text:
Q: How to pass state from parent Component to child component in route (react-route-dom) reactjs I am new to React.js and created a small react application using react-router-dom. In which I have two components:

*

*Dashboard(dashboard.js)

*Information(information.js)

and one main Component App, App.js, in which I am using the react-router-dom.
<Route exact path="/dashboard" render={props => <Dashboard someProp="2" {...props} />} />
<Route exact path="/information" render={props => <Information someProp="2" {...props} />} />

I am able to send props from App component to dashboard and information but I want to send state. Can somebody help me, How can I send state from Parent component to child component?

A: In parent component you can send props like this
<child prop1 = {this.state.stateName} />

A: Using above answer I am posting full code so that further users can understand this.
App.js file
class App extends React.Component {
constructor(props) {
    super(props);
    this.state = {open: false};
    this.state = {message: "StackOverflow"};
  }

return (
        <Router>

          <AppBar title="App" onLeftIconButtonTouchTap={this.handleToggle} />

            <Drawer containerStyle={{height: 'calc(100% - 64px)', top: 64}} docked={true} width={200} open={this.state.open} zDepth={2}>
              <Link to="/dashboard" style={{ textDecoration: 'none' }}><MenuItem>Dashboard</MenuItem></Link>
              <Link to="/information" style={{ textDecoration: 'none' }}><MenuItem>Information</MenuItem></Link>
            </Drawer>

            <Route exact path="/dashboard" render={props => <Dashboard someProp={this.state.message} {...props} />} />
            <Route exact path="/information" render={props => <Information someProp={this.state.message} {...props} />} />

        </Router>
    );
}

Dashboard.js
import React from 'react';

class Dashboard extends React.Component {

  constructor(props) {
    super(props);
  }

  render() {
    console.log(this.props);
    const {styleFromProps} = this.props;
    const contentStyle = {  ...styleFromProps, transition: 'margin-left 450ms cubic-bezier(0.23, 1, 0.32, 1)' };

    return (

 Hello {this.props.someProp}

    );
  }
}

export default Dashboard;


text:
Q: Big Sur: PDF Service shell script cannot call python I recently upgraded from Mohave to Big Sur, and the shell script I use as a PDF Service has stopped working. The script calls a Python script to process the PDF, and this gives the error "operation not permitted". Thinking that this has to do with the new security restrictions, I tried dragging everything that seemed relevant to Full Disk Access in the Privacy pane of the Security & Privacy settings, but that didn't help. Here is the script with some debugging lines inserted:
#!/bin/sh

export PATH=/Library/TeX/texbin:/usr/local/bin:$PATH

########################################
# Log stdout and stderr (from https://stackoverflow.com/a/20564208).
LOG_FILE=/tmp/pdfbooklog.txt
# Close STDOUT file descriptor
exec 1<&-
# Close STDERR FD
exec 2<&-
# Open STDOUT as $LOG_FILE file for read and write.
exec 1<>$LOG_FILE
# Redirect STDERR to STDOUT
exec 2>&1

########################################
# Get name of file printed and print options (unused).

# name or title of file printed, e.g., document.odt
TITLE="${1:-}"
# space separated options from the print dialog: k1=v1 k2='v2' …
PRINT_OPTIONS="$2"
# Make first (usually only) filename $1.
shift
shift

# Some programs called write files to the current directory, so make sure
# we're somewhere where that will work.
cd /tmp

########################################
# Apparently it's possible to be called with multiple filenames.
# Use a loop to make sure we handle all files listed on the command line.

for f in "$@"
do
    echo "Processing '$f'"
    echo "PATH: $PATH"
    /usr/local/bin/python3 -c 'print("Python works")'
    pdfbook2 --inner-margin=80 "$f"
    open "${f%.pdf}-book.pdf"
done

When I invoke it from the print dialog, this is what is written to the log file:
Processing '/var/folders/2j/w5jh3df55p7f4n05nh_m45jr0000gn/T/printing.11142.10/test.odt.pdf'
PATH: /Library/TeX/texbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
/Users/me/Library/PDF Services/Make PDF booklet.sh: line 40: /usr/local/bin/python3: Operation not permitted
/Users/me/Library/PDF Services/Make PDF booklet.sh: /Library/TeX/texbin/pdfbook2: /usr/bin/env: bad interpreter: Operation not permitted
The file /var/folders/2j/w5jh3df55p7f4n05nh_m45jr0000gn/T/printing.11142.10/test.odt-book.pdf does not exist.
test.odt-book.pdf does not exist.
Done

pdfbook2 is included with MacTeX: it is a Python script that invokes python3 with /usr/bin/env. python3 is in /usr/local/bin (installed with Homebrew), and as the test line shows, I cannot even invoke it directly. What do I have to do to permit Big Sur to run this script?
Update:

*

*In case it wasn't clear, the script works when invoked from the Terminal. It only fails when it is invoked from the print dialog.

*Since Big Sur still has /usr/bin/python3, the script above can be modified to use it. When the PDF Service is invoked from the print dialog, /usr/bin/python3 -c 'print("Python works")' will print "Python works". /usr/bin/python3 /Library/TeX/texbin/pdfbook2 --inner-margin=80 "$f" will begin executing, but pdfbook2 will then throw a PermissionError of "Operation not permitted" when it tries to run pdfcrop, which is also in /Library/TeX/texbin.

*The first line of pdfbook2 is #!/usr/bin/env python3. The first line of pdfcrop is #!/usr/bin/env perl, which should find /usr/bin/perl, since there is no Perl in my /usr/local/bin.

*So apparently SIP is preventing PDF Services from execing anything that is not in a protected directory, and from using /usr/bin/env as an interpreter (which could circumvent that restriction). Is there any way to give a script permission to do this? Giving the script Full Disk Access doesn't work.

A: I have discovered that Big Sur will graciously allow a script to execute in a PDF Service, if the script is put inside an Automator workflow.
Use the 'Run Shell Script' Automator action, and place the script in there.
PDF Service scripts normally take a different set of incoming arguments (title, print options, filepath); whereas the Automator workflow only passes the filepath to the PDF, so you need to modify your script accordingly.
These problems seem to be unique to Big Sur, and are fixed in Monterey, which will allow PDF Services scripts a bit more latitude.


text:
Q: C# run time consuming method on button click without keeping the button pressed I do have experience with software developping in Python (GUI platform PyQt) and I am learing software development in C#. I wanted to know how can I run a thread/task in C# that uses UI objects but keeping the UI "alive" and not keeping the button pressed. I did used "Invoke" method to share UI objects with thread/task and did not call any join method, but still button remain pressed during thread execution. Is there any way to run this method in background, but keeping the GUI responsive?
Thanks in advance!

private async void Button_Click(object sender, RoutedEventArgs e)
{
    await Task.Run(new Action(this.Iterate_balance));

}

private async void Iterate_balance()
{
    this.Dispatcher.Invoke(() =>
    {
        // the rest of code
    }
}

A: use async/await pattern properly and you won't need Dispatcher at all:
private async void Button_Click(object sender, RoutedEventArgs e)
{
    await Iterate_balance();
}

private async Task Iterate_balance()
{
    button.Content = "Click to stop";

    // some long async operation
    await Task.Delay(TimeSpan.FromSeconds(4));

    button.Content = "Click to run";
}

A: TRY THIS:
1.Add following using:    using System.ComponentModel;
2.Declare background worker:
private readonly BackgroundWorker worker = new BackgroundWorker();

3.Register events:
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;

4.Implement two methods:
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
   // run all background tasks here
}

private void worker_RunWorkerCompleted(object sender,
                                       RunWorkerCompletedEventArgs e)
{
  //update ui once worker complete his work
}

5.Run worker async whenever your need.
worker.RunWorkerAsync();

Also if you want to report process progress you should subscribe to ProgressChanged event and use  ReportProgress(Int32) in DoWork method to raise an event. Also set following: worker.WorkerReportsProgress = true;
Hope this help.


text:
Q: How to change keyboard shortcut of "Show location of pointer"? I am running Ubuntu GNOME 15.10 with GNOME 3.18 and in the gnome-tweak-tool there is an option called Show location of pointer, which upon clicking CTRL makes a little circle thing come off like a ripple from the mouse pointer in order to show its location. Now this is all very useful and that, but I would find it more useful if I could reassign this useful feature to another keyboard shortcut, can this be done?

A: Unfortunately, you'll have to compile your own version of the Gnome settings deamon to accomplish this: the key value is hard-coded in gsd-locate-pointer.c.
Alternatively, you could map an unused key or key combination to xdotool key 'Control_R'.

A: 2021 UPDATE:
Base on the 2 years old discussion here. Starting from GNOME 3.36 (I think) the key binding of locate-pointer can be remapped. It lies under /org/gnome/mutter/locate-pointer-key key.
To change it (for example remapping it to Right Shift instead):
gsettings set org.gnome.mutter locate-pointer-key Shift_R

Don't forget to enable it before using.
gsettings set org.gnome.desktop.interface locate-pointer true

Tested on Ubuntu 21.04.


text:
Q: ubuntu Server asus chromebox won't boot unless I have a hdmi display plugged in So I installed Ubuntu Server on my Asus Chromebox, all works great except I have a strange issue.
Ubuntu won't boot unless I have a hdmi display plugged in
I've tested this over and over. If I plug in the HDMI Display it boots and runs as expected, but since I wanted to run this as a server and SSH into the box, not if wont boot.
Is there a check I need to uncheck for the HDMI Display?
NOTE: I have command line access only, no gui
EDIT: Here is the installation process I'm following

*

*https://plus.google.com/115693545287597955633/posts/QsEE96RLJvV

A: I had the same issue.  There is no software solution that I can find.  What I did end up doing was buying the Fit PC Headless HDMI dongle.  It's about $15, and mimics an attached HDMI display.
http://www.fit-pc.com/web/products/fit-headless/

A: I was able to determine that either an HDMI or a USB keyboard (or in my case a spare Logitech unifying receiver) allow the system to boot.
When unplugged, the system is hard shut down instantly, no acpi suspend or anything like that. A little bizarre.

A: For future readers:
I had the same issue (different hardware, though). This is what worked for me:

*

*Edit the grub config file:

sudo nano /etc/default/grub

*Uncomment (remove the # at the beginning of) the following line:

#GRUB_TERMINAL=console

Be sure to save the file using Ctrl-O then Enter.

*Update grub:

sudo update-grub

*Reboot.

Source: https://www.reddit.com/r/Ubuntu/comments/v0ff1r/ubuntu_2204_server_wont_boot_without_hdmi_plugged


text:
Q: Fail to curl to secure HTTP from local minikube cluster So, I have minikube 0.16.0 installed
Also istio 1.7.3
So I do envoy sidecars on each deployment I do, as per with command kubectl label namespace default istio-injection=enabled
Now, coming to the question, I'm not able to do any curl from inside any pod whatsoever, even from sleep-diag, I always get request timed out message, but it does work for non secure http
For example while installing jenkins, I try to curl against this url with no success:
bash-5.0# curl -v https://updates.jenkins.io/current/update-center.json
*   Trying 92.242.132.16:443...
* TCP_NODELAY set
* connect to 92.242.132.16 port 443 failed: Operation timed out
* Failed to connect to updates.jenkins.io port 443: Operation timed out
* Closing connection 0
curl: (28) Failed to connect to updates.jenkins.io port 443: Operation timed out

But even if I try let's say:
bash-5.0# curl -v https://www.google.com
*   Trying 92.242.132.16:443...
* TCP_NODELAY set
* connect to 92.242.132.16 port 443 failed: Operation timed out
* Failed to connect to www.google.com port 443: Operation timed out
* Closing connection 0
curl: (28) Failed to connect to www.google.com port 443: Operation timed out

While I'm able to outside of any pod in my local cluster, any ideas on this?
For example, tried installing jenkins like this, with helm:
helm install --set Master.ServiceType=ClusterIP jenkins/jenkins --generate-name

Obviously it will fail because I cannot access any https from my local cluster, even specifying NodePort I have the same issue:
helm install --set Master.ServiceType=NodePort jenkins/jenkins --generate-name

Any ideas?


text:
Q: Multi jobs failing SonarQube analysis and MsBuild in Azure DevOps build pipeline in an Azure DevOps build pipeline, I would like to run a MsBuild task in an Azure hosted agent and a sonar analysis task in a self-hosted agent.
I understand that I need to pass artifacts from a job to another. I try to use Publish and Download pipeline artifact tasks for this purpose.

*

*First, I prepare SonarQube analysis on a self-hosted agent

*then I publish the .sonarqube folder

*On a Microsoft hosted agent I download the previously published SonarQube metadata to the job

*I run MsBuild and test tasks

*I publish test results

*Back on the self-hosted agent I download SonarQube metadata and test results

*I run SonarQube analysis

The following error message shows during the SonarQube analysis task execution.
##[error][SQ] The 'Prepare Analysis Configuration' task was not executed prior to this task

Here is how I proceed
On Self-hosted agent job "PrepareSonarqube"

*

*Prepare Sonarqube analysis

*

*Publish pipeline artifact $(Pipeline.Workspace)/.sonarqube folder

On Microsoft hosted agent job "Build"

*

*Msbuild and test tasks

*

*Publish pipeline artifact "TestResults" folder

On self-hosted agent job "SonarQube Analysis"

*

*Download pipeline artifact ".sonarqube" folder

*

*Download pipeline artifact "TestResults"


text:
Q: C++ sockets: communication between PCs over internet I'm writing a program on Windows using winsocks that can send messages to another computer. The client connects with the server in the other computer and begin exchanging data.
It works fine on my local network using local addresses(192.168.1.*), but I can't communicate with public addresses (216.185.45.129); not even my own. I can successfully connect to a website on port 80, but not to my laptop at home using its public IP address, regardless of what ports I use (unreserved ports).
So I did research online and the only solution that seems to work is port forwarding.
-But is there absolutely no other way to achieve this?
-How do other programs like Teamviewer connect to other computers on the network then?
-Is there an already open but typically unused port that I can use?
-At the very least, can I forward the ports on my router but not have the client do anything? Or maybe have my program forward the ports automatically.

A: The main problem is, that every router is using NAT to distinguish different computer in your lokal network against the WAN. He need to do this, because you got only one IP in the internet, but several devices in your home. To archive this, he uses groups of ports. That means, if you use to send maybe from port 2048 to a webserver in internet with two devices, the router gives one device another port (like 2049). The response has the Port of the requester, so the router can map it back. Unfortunately most router always map ports so you never now which port you have from the internet side.
There are two common ways to work around and archive your goal.

*

*Port Fowarding
You can force most router not to map special ports but bind them to unique MAC addresses. You can use UPNP to config most router to do that, but I do not recommend that for security reasons and also it does not work in many enviroments where Router do not allow UPNP manipulation.
Most router have port forwarding abilities for gaming reasons (mostly it is used in P2P networks)
It works with TCP and UDP.

*NAT Traversal
The common way is NAT traversal, also known as NAT hole punching. I will describe it in short for UDP. You can find a wiki explanation here for TCP and for UDP here. Unfortunately you need a server in the internet both clients can reach. Here the steps:

*

*Both clients contact the server. The server now know IP and PORT of both clients.

*Server send back the information to the clients.

*Both(!) clients send now packages to each other on the known address.

It is necessary that both client send a UDP package and have to accept that the first package get lost. The reason is the router. Most router only accept packages from a source on a mapped PORT if a client has send a package to that source before.
UPDATE
Regarding to a comment of Remy Lebau I changed the Firewall piercing part to NAT Traversal as it was partly wrong.


text:
Q: scrollIntoView ain't working on my react component I'm working on a chatbot.
Below is my React component.I am tring to scroll the MessageListWrapper to the bottom every time messageList gets updated. But it doesn't seem to work, in the sense the div doesn't scroll to the bottom. I looked around and did a bit of research but unable to figure out why this doesn't work. :/
const MessageListContainer =  styled.div`
    display: flex;
    flex-direction: column;
    flex: 1 1;
    height: 85%;
`;

 const MessageListWrapper =  styled.div`
    padding: 10px;
    overflow-x: hidden;
    overflow-y: auto;
    max-height: 100%;
 `;

const MessageList = ({messageList}) => {

    const messagesEndRef = useRef();

    const scrollToBottom = () => {
        const {current} = messagesEndRef;
        current.scrollIntoView();
    }

    useEffect(() => {
        scrollToBottom()
    }, [messageList]);

    return (
        <>
            <MessageListContainer>
                <MessageListWrapper ref={messagesEndRef} >
                    {
                        (messageList && messageList.length) ? (messageList.map(..<snipped for brevity>..)) :
                        <></>
                    }
                </MessageListWrapper>
            </MessageListContainer>
        </>
    )
};

A: To anyone landing on this post with the same issue, I resolved the issue by using
    const scrollToBottom = () => {
        const {current} = messagesEndRef;
        current.scrollTo(0,current.scrollHeight);
    }


text:
Q: Discord.py - bot deletes message after it sends I've recently been trying to make it so that when someone types a specific command the bot deletes their message. Everything I tried before didn't work so I have absolutely no idea how to do this. I'm new to discord.py so my knowledge is quite limited.
#making sure the command only works in the specific channel
async def is_channel(ctx):
    return ctx.channel.id == 873501773971726346

#the actual code
@client.command(case_sensitive=True)
@commands.check(is_channel)
async def resus(ctx,*, saymsg=None):
    if saymsg==None:
        return await ctx.send("To reserve a username type - !resus (your discord tag) (the username you want) (if you want verification) You can also add some extra information if you would like. Any spam/troll reservations will result in a warning and or mute.")

    sayEmbed = discord.Embed(title=f"{ctx.author.name} Said", color = discord.Color.blue(), description=f"{saymsg}")
    sayEmbed.timestamp = ctx.message.created_at
    channelf = client.get_channel(873564203535958047)
    await channelf.send(embed = sayEmbed)

A: right above the if statement you want to put await ctx.message.delete() which will delete their message and then run the rest of your code.

A: This is what i usually do but when waiting for input but you can use it on a normal message
  title = "Something...",
  description = "||This request will timeout in 60s||"
  )
  await ctx.send(embed=embed)
  try:
    amount_of_codes = await client.wait_for('message', check=lambda m: m.author == ctx.author and m.channel == ctx.channel, timeout=60.0)
  except asyncio.TimeoutError:
    await ctx.channel.send("Request timed out")


text:
Q: Syntax error near unexpected token '(' after implementing python program I initally ran RepeatMasker on a Mac, and I am attempting to analyze the file on a Linux OS.
When I try to run my program Unique_Repeat_Code.py:
RM_output=open('genomic.fna.out')
contents=RM_output.read'()'
unique_repeats_DNA=open('genomic_unique_repeats.txt','w')
for _ in contents:
    bit_score=column[0]
    percent_div=column[1]
    percent_del=column[2]
    percent_ins=column[3]
    query_seq=column[4]
    position_query_begin=column[5]
    position_query_end=column[6]
    left=column[7]
    sense=column[8]
    matching_repeat=column[9]
    repeat_class=column[10]
    position_in_repeat_begin=column[11]
    position_in_repeat_end=column[12]
    left2=column[13]
    ID=column[14]
    while matching_repeat:
        unique_repeats=set(matching_repeat)
        unique_repeats_DNA.write(unique_repeats)
unique_repeats_DNA.close()

in terminal I get the following error:
./Unique_Code.py: line 6: syntax error near unexpected token '('
./Unique_Code.py: line 6: 'RM_output=open('genomic.fna.out')'

Any help in fixing this problem would be appreciated. Thank you in advance!

A: You are running your script as a bash script when you use the "./" syntax. You need to use the python interpreter to run your script:
python Unique_Code.py


text:
Q: jQuery fadeIn() not working in IE $(document).ready(function() {

 //Default Action
 $(".tab_content").hide(); //Hide all content
 $("ul.tabs li:first").addClass("active").show(); //Activate first tab
 $(".tab_content:first").show(); //Show first tab content

 //On Click Event
 $("ul.tabs li").click(function() {
  $("ul.tabs li").removeClass("active"); //Remove any "active" class
  $(this).addClass("active"); //Add "active" class to selected tab
  $(".tab_content").hide(); //Hide all tab content
  var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
  $(activeTab).fadeIn("slow"); //Fade in the active content
  return false;
 });

});

Works in everything but IE?

A: You can do this to get consistent behavior:
var activeTab = $(this).find("a").get(0).hash;

IE likes to return not "#id" but instead it thinks you want:  "http://site.com/currentPage.html#id", which won't work for a selector :)  I you grab the .hash off the DOM element, you get just he #id portion consistently.
You can find a bit more discussion on why this happens in this question

A: $(this).find("a").attr("href") gets you the HREF of the target, not the target. Assuming you're putting the name of a DIV in the href in there that may be correct (I don't know what's in there).
Try alert($(this).find("a").href()) to see if you've got the right element, or just try .show() and see what happens.


text:
Q: Neovim: Relative config file(init.vim) location I'm moving from vim to neovim, and my problem is that I need to carry it on portable USB sticks.
So I need to read config files from relative path. I used $VIM/_vimrc for this purpose on original vim, since $VIM always points to vim files in my USB.
But Neovim stores config files in ~/.config on Linux or Appdata on Windows, which both points to local computer's directory I was using.
Is their any relative directory Neovim uses to read config files? I don't want to manually source config file every single time...

A: From :help startup:

    The Nvim config file is named "init.vim", located at:
            Unix            ~/.config/nvim/init.vim
            Windows         ~/AppData/Local/nvim/init.vim
    Or if $XDG_CONFIG_HOME is defined:
                            $XDG_CONFIG_HOME/nvim/init.vim

So you can use $XDG_CONFIG_HOME in a way similar to how you used $VIM before.
Instead of setting $XDG_CONFIG_HOME, you can make a bash alias, or an equivalent wrapper script:
alias vim="vim -u /path/to/vimrc"


text:
Q: NServiceBus 4 Could not forward failed message, queue not found I am having issues after migrating to NService 4 (4.0.4). When a message handling fails, it looks like whole NServiceBus is stopping and not doing any work (messages from MSMQ are not consumed any more).
After looking into logs, I found the following errors:
NServiceBus.log:

2013-10-02 17:49:31.5786 | FATAL | 110 | Fault manager failed to process the failed message with id aa32dce1-f408-4f6d-b448-a24b0118ec27 System.InvalidOperationException: Could not forward failed message to error queue 'administration.worker@localhost.Retries@localhost' as it could not be found. ---> NServiceBus.Unicast.Queuing.QueueNotFoundException: Failed to send message to address: [administration.worker@localhost.Retries@localhost] ---> System.Messaging.MessageQueueException: The queue does not exist or you do not have sufficient permissions to perform the operation.
     at System.Messaging.MessageQueue.MQCacheableInfo.get_WriteHandle()
     at System.Messaging.MessageQueue.StaleSafeSendMessage(MQPROPS properties, ITransaction transaction)
     at System.Messaging.MessageQueue.StaleSafeSendMessage(MQPROPS properties, IntPtr transaction)
     at System.Messaging.MessageQueue.SendInternal(Object obj, MessageQueueTransaction internalTransaction, MessageQueueTransactionType transactionType)
     at NServiceBus.Transports.Msmq.MsmqMessageSender.Send(TransportMessage message, Address address) in c:\BuildAgent\work\d4de8921a0aabf04\src\NServiceBus.Core\Transports\Msmq\MsmqMessageSender.cs:line 60
     --- End of inner exception stack trace ---
     at NServiceBus.Transports.Msmq.MsmqMessageSender.Send(TransportMessage message, Address address) in c:\BuildAgent\work\d4de8921a0aabf04\src\NServiceBus.Core\Transports\Msmq\MsmqMessageSender.cs:line 76
     at NServiceBus.Faults.Forwarder.FaultManager.SendFailureMessage(TransportMessage message, Exception e, Boolean serializationException) in c:\BuildAgent\work\d4de8921a0aabf04\src\NServiceBus.Core\Faults\Forwarder\FaultManager.cs:line 48
     --- End of inner exception stack trace ---
     at NServiceBus.Faults.Forwarder.FaultManager.SendFailureMessage(TransportMessage message, Exception e, Boolean serializationException) in c:\BuildAgent\work\d4de8921a0aabf04\src\NServiceBus.Core\Faults\Forwarder\FaultManager.cs:line 78
     at NServiceBus.Unicast.Transport.FirstLevelRetries.TryInvokeFaultManager(TransportMessage message, Exception exception) in c:\BuildAgent\work\d4de8921a0aabf04\src\NServiceBus.Core\Unicast\Transport\FirstLevelRetries.cs:line 71InnerExceptionNServiceBus.Unicast.Queuing.QueueNotFoundException: Failed to send message to address: [administration.worker@localhost.Retries@localhost] ---> System.Messaging.MessageQueueException: The queue does not exist or you do not have sufficient permissions to perform the operation.
     at System.Messaging.MessageQueue.MQCacheableInfo.get_WriteHandle()
     at System.Messaging.MessageQueue.StaleSafeSendMessage(MQPROPS properties, ITransaction transaction)
     at System.Messaging.MessageQueue.StaleSafeSendMessage(MQPROPS properties, IntPtr transaction)
     at System.Messaging.MessageQueue.SendInternal(Object obj, MessageQueueTransaction internalTransaction, MessageQueueTransactionType transactionType)
     at NServiceBus.Transports.Msmq.MsmqMessageSender.Send(TransportMessage message, Address address) in c:\BuildAgent\work\d4de8921a0aabf04\src\NServiceBus.Core\Transports\Msmq\MsmqMessageSender.cs:line 60
     --- End of inner exception stack trace ---
     at NServiceBus.Transports.Msmq.MsmqMessageSender.Send(TransportMessage message, Address address) in c:\BuildAgent\work\d4de8921a0aabf04\src\NServiceBus.Core\Transports\Msmq\MsmqMessageSender.cs:line 76
     at NServiceBus.Faults.Forwarder.FaultManager.SendFailureMessage(TransportMessage message, Exception e, Boolean serializationException) in c:\BuildAgent\work\d4de8921a0aabf04\src\NServiceBus.Core\Faults\Forwarder\FaultManager.cs:line 48InnerExceptionSystem.Messaging.MessageQueueException (0x80004005): The queue does not exist or you do not have sufficient permissions to perform the operation.
     at System.Messaging.MessageQueue.MQCacheableInfo.get_WriteHandle()
     at System.Messaging.MessageQueue.StaleSafeSendMessage(MQPROPS properties, ITransaction transaction)
     at System.Messaging.MessageQueue.StaleSafeSendMessage(MQPROPS properties, IntPtr transaction)
     at System.Messaging.MessageQueue.SendInternal(Object obj, MessageQueueTransaction internalTransaction, MessageQueueTransactionType transactionType)
     at NServiceBus.Transports.Msmq.MsmqMessageSender.Send(TransportMessage message, Address address) in c:\BuildAgent\work\d4de8921a0aabf04\src\NServiceBus.Core\Transports\Msmq\MsmqMessageSender.cs:line 60

MsmqDequeueStrategy.log has lots of:

2013-10-02 17:49:32.5579 | ERROR | 57 | Error processing message. System.ObjectDisposedException: The semaphore has been disposed.
     at System.Threading.SemaphoreSlim.Release(Int32 releaseCount)
     at NServiceBus.Transports.Msmq.MsmqDequeueStrategy.Action() in c:\BuildAgent\work\d4de8921a0aabf04\src\NServiceBus.Core\Transports\Msmq\MsmqDequeueStrategy.cs:line 227
     at System.Threading.Tasks.Task.Execute()

FaultManager.log:

2013-10-02 17:49:31.5746 | FATAL | 110 | Could not forward failed message to error queue 'administration.worker@localhost.Retries@localhost' as it could not be found.

I init NSB as follows:
Configure.Serialization.Xml();
Configure.Features.Enable<TimeoutManager>();
Configure.Features.Enable<Sagas>();

var conf = Configure.With(assemblies)
.CustomConfigurationSource(new BusConfigSource(assemblies))
.DefineEndpointName(ConfigurationManager.AppSettings["InputQueue"])
.CastleWindsorBuilder(container)
.MessageForwardingInCaseOfFault()
.UseInMemoryTimeoutPersister()
.UseTransport<Msmq>()
.PurgeOnStartup(false)
.FileShareDataBus(WebConfigurationManager.AppSettings["NServiceBusFileShare"])
.UnicastBus()
.LoadMessageHandlers()
.MsmqSubscriptionStorage()
.CreateBus()
    .Start(() => Configure.Instance.ForInstallationOn<Windows>().Install());

EDIT: more info.
I host NSB in IIS. I Publish, Send and handle messages in it.
Web.config looks like this:

A: The problem is in your Init code...
.DefineEndpointName(ConfigurationManager.AppSettings["InputQueue"])

I don't see that in the screenshot of your Web.config you provided, but based on the error, I'm guessing you have that defined as "administration.worker@localhost". This should be only "administration".
Endpoint name and input queue are not the same thing. Starting from your endpoint name, NServiceBus infers the names of all the queues from there. So input queue is {EndpointName}@localhost. If you're running a master node with an attached worker, the worker's input queue is {EndpointName}.Worker@localhost. The Timeout queue is {EndpointName}.Timeouts@localhost, etc.
Of course you don't usually have to define the endpoint name in an NServiceBus.Host endpoint, but it looks like you are self-hosting in a web application.
Here's more information on the NServiceBus Input Queue / Endpoint Name from the docs.

A: This is a funny looking address: administration.worker@localhost.Retries@localhost
you may need to add in your config file:
<section name="MessageForwardingInCaseOfFaultConfig" type="NServiceBus.Config.MessageForwardingInCaseOfFaultConfig, NServiceBus.Core" />

and set
<MessageForwardingInCaseOfFaultConfig ErrorQueue="error"/>

Take a look at the Error handling sample (if you installed NServiceBus it will be in %ProgramFiles%\Particular Software\NServiceBus\v4.0\NServiceBus\Samples\ErrorHandling)
or in Github https://github.com/Particular/NServiceBus/tree/develop/Samples/ErrorHandling
Hope this helps


text:
Q: Altering displayed item name in JComboBox I filled a combo box with items from an entity class with the following code :
private void fillPositionComboBox(){
    EntityManager em = JPAUtilities.getEntityManagerFactory().createEntityManager();
    positionComboBox.removeAllItems();
    try{
        List<Position> list = em.createQuery("select p from Position p order by p.positionCode").getResultList();
        for(int i=0; i<list.size();i++){
            positionComboBox.addItem(list.get(i));
        }
    }
    catch(Throwable t){
        JOptionPane.showMessageDialog(this, t.toString());
    }
    finally{
        em.close();
    }
}

But when i ran the program and clicked the combo box, it displayed weird text on it's drop-down list. I want to replace those weird text with particular String say, like, string from the entity position.getPositionName();. Is it possible ? If so, pleaaase show the code on how to do it and give explanation of the code. Thank you so much for all of your help!

A: I don't know if I understood your question, but if you want that your JCombobox display a text different than what it stores, so you should create a class that have an internal text and a method toString() that return a different text like this :
class MyData{
  private String data;
  MyData(String text){
    data = text;
  }
  public String toString(){
    if(condition) return data;
    else return "Something else";
  }
}

Then you have to create a JCombobox that uses this class :
JComboBox<MyData> combo = new JComboxBox<>()

And put every result in a MyData object before adding it to the JCombobox.


text:
Q: Excel get max between two cells (NOT RANGE) The MAX function gives me the maximum number in a range but what if my cells are not in a range?
If we have in A1 the number 10m and in D11 the number 8m how can we find the MAX number between these two cells?

A: You can specify a set of cells instead of a range:
max(A1;A4;A10;A12)

In your case:
max(A1;D11)


text:
Q: Open a XML with ASP I am trying to read a XML File with ASP (absolute beginner in ASP).
The XML to open:
<?xml version="1.0" encoding="UTF-8"?>
<Reisen>
  <Reise Reise-Nummer="5608" Status="Released">
    <Pfad>Reisen/Europa/DE/Bayerischer_Wald/5608</Pfad>
    <Informationen>
<Anforderung>1-2</Anforderung>
    </Informationen>
    <Reisedaten>
<Titel>Eine Reise durch den Bayrischen Wald</Titel>
    </Reisedaten>
  </Reise>
</Reisen>

The ASP code:
(file_name contains the file name of the xml)
Set objXMLDoc = Server.CreateObject("MSXML2.DOMDocument.3.0")
objXMLDoc.async = False
objXMLDoc.setProperty "ServerHTTPRequest", true
objXMLDoc.load Server.MapPath("/xml/single/" & file_name)

Dim xmlProduct
For Each xmlProduct In objXMLDoc.documentElement.selectNodes("Reisen")
     Dim reise : reise = xmlProduct.selectSingleNode("Reise").Attributes.GetNamedItem("Reise-Nummer").Text
     Response.Write Server.HTMLEncode(reise)
Next

If I call this script, I always get an error 500. The error is placed in the foreach-loop...
Can someone show me how to fix it?

A: My understanding is Reisen is the root node with multiple child Reise nodes inside. In that case you shouldn't use selectNodes for Reisen. I tested the following and seems to be working fine:
Set objXMLDoc = Server.CreateObject("MSXML2.DOMDocument.3.0")
objXMLDoc.async = False
objXMLDoc.setProperty "ServerHTTPRequest", true
objXMLDoc.load Server.MapPath("/xml/single/" & file_name)

Set root = objXMLDoc.documentElement.selectSingleNode("/Reisen")

Dim xmlProduct
For Each xmlProduct In root.selectNodes("./Reise")
     Dim reise : reise = xmlProduct.Attributes.GetNamedItem("Reise-Nummer").Text
     Response.Write Server.HTMLEncode(reise)
Next

I tried with multiple Reisen elements with no root and I got HTTP 500 so it might be the case that your XML is not valid after all which is causing the error.


text:
Q: WebPacker not loading module (metisMenu) I'm facing an issue with loading the plugin metisMenu in Webpacker/Rails 6
I keep getting the error: Uncaught TypeError: $(...).metisMenu is not a function
These are the contents from application.js:
require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")

import '../stylesheets/application'
import 'assets/images'

import 'bootstrap'

document.addEventListener('turbolinks:load', () => {
  $('[data-toggle="tooltip"]').tooltip()
  $('[data-toggle="popover"]').popover()
})

import 'metismenu'

import 'assets/javascripts/vendor.js'
import 'assets/javascripts/app.js'
import 'assets/stylesheets/icons.css'
import 'assets/stylesheets/app-creative.css'

config/webpack/environment.js:
const { environment } = require('@rails/webpacker')
const webpack = require('webpack')

environment.plugins.append('Provide', new webpack.ProvidePlugin({
  $: 'jquery/src/jquery',
  'window.jQuery': 'jquery/src/jquery',
  jQuery: 'jquery/src/jquery',
  jquery: 'jquery/src/jquery',
  Popper: ['popper.js', 'default']
}))

module.exports = environment

A: All I can say is that this code works before metisMenu is fully loaded. A solution cannot be produced without seeing your configuration.


text:
Q: Aggregate a bunch of different data in a single groupby with multiple columns I have large dataframe of data in Pandas (let's say of courses at a university) looking like:
ID          name        credits     enrolled    ugrad/grad  year        semester
1           Math        4           62          ugrad       2016        Fall
2           History     3           15          ugrad       2016        Spring
3           Adv Math    3           8           grad        2017        Fall
...

and I want to group it by year and semester, and then get a bunch of different aggregate data on it, but all at one time if I can. For example, I want a total count of courses, count of only undergraduate courses, and sum of enrollment for a given semester. I can do each of these individually using value_counts, but I'd like to get an output such as:
year        semester    count       count_ugrad total_enroll
2016        Fall        #           #           #
            Spring      #           #           #
2017        Fall        #           #           #
            Spring      #           #           #
...

Is this possible?

A: Here I added a new subject for Python and provided as a dict to load into dataframe.
Solution is a combination of the agg() method on a groupby, where the aggregations are provided in a dictionary, and then the use of a custom aggregation function for your ugrad requirement:
def my_custom_ugrad_aggregator(arr):
    return sum(arr == 'ugrad')

dict = {'name': {0: 'Math', 1: 'History', 2: 'Adv Math', 3: 'Python'}, 'year': {0: 2016, 1: 2016, 2: 2017, 3: 2017}, 'credits': {0: 4, 1: 3, 2: 3, 3: 4}, 'semester': {0: 'Fall', 1: 'Spring', 2: 'Fall', 3: 'Spring'}, 'ugrad/grad': {0: 'ugrad', 1: 'ugrad', 2: 'grad', 3: 'ugrad'}, 'enrolled': {0: 62, 1: 15, 2: 8, 3: 8}, 'ID': {0: 1, 1: 2, 2: 3, 3: 4}}
df  =pd.DataFrame(dict)

   ID  credits  enrolled      name semester ugrad/grad  year
0   1        4        62      Math     Fall      ugrad  2016
1   2        3        15   History   Spring      ugrad  2016
2   3        3         8  Adv Math     Fall       grad  2017
3   4        4         8   Python   Spring       ugrad  2017

print df.groupby(['year','semester']).agg({'name':['count'],'enrolled':['sum'],'ugrad/grad':my_custom_ugrad_aggregator})

gives:
               name                 ugrad/grad enrolled
              count my_custom_ugrad_aggregator      sum
year semester
2016 Fall         1                          1       62
     Spring       1                          1       15
2017 Fall         1                          0        8
     Spring       1                          1        8

A: Use agg with dictionary on how to rollup/aggregate each column:
df_out = df.groupby(['year','semester'])[['enrolled','ugrad/grad']]\
           .agg({'ugrad/grad':lambda x: (x=='ugrad').sum(),'enrolled':['sum','size']})\
           .set_axis(['Ugrad Count','Total Enrolled','Count Courses'], inplace=False, axis=1)

df_out

Output:
               Ugrad Count  Total Enrolled  Count Courses
year semester
2016 Fall                1              62              1
     Spring              1              15              1
2017 Fall                0               8              1


text:
Q: Translation file in Symfony doesn't exist I'm using Symfony 3 and I want to make a translation of somethings in my app to Spanish.
I enabled the translator by this way:
framework:
#esi:             ~
#translator:      { fallbacks: ["%locale%"] }
translator:      { fallbacks: en }
secret:          "%secret%"
router:
    resource: "%kernel.root_dir%/config/routing.yml"
    strict_requirements: ~
form:            ~
csrf_protection: ~
validation:      { enable_annotations: true }
#serializer:      { enable_annotations: true }
templating:
    engines: ['twig']
#default_locale:  "%locale%"
default_locale:  es
trusted_hosts:   ~
trusted_proxies: ~
session:

A file called by default "messages.fr.xlf" is supposed to appear in /app/resources/translation or /src/BundleName/resources/translation, but after search in all the folder structure, there is no "messages.fr.xlf" file and there is no "translation" folder, so I decided to create it by myself, and I tried it in all the folders in which this file is supposed to exist.
So my "messages" file contains the following code:
<?xml version="1.0"?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
    <file source-language="en" datatype="plaintext" original="file.ext">
        <body>
            <trans-unit id="1">
                <source>Next</source>
                <target>Siguiente</target>
            </trans-unit>
            <trans-unit id="2">
                <source>Previous</source>
                <target>Anterior</target>
            </trans-unit>
            <trans-unit id="3">
                <source>client</source>
                <target>Cliente</target>
            </trans-unit>
            <trans-unit id="4">
                <source>user</source>
                <target>Usuario</target>
            </trans-unit>
        </body>
    </file>
</xliff>

But it doesn't work, it seems that symfony can't find the translation file because I get this error:

"These messages are not available for the given locale and cannot be found in the fallback locales. Add them to the translation catalogue to avoid Symfony outputting untranslated contents."

A: Message files need to exist in the app/Resources/translations folder. The files should be named [bundle].[language_code].[format] . Assuming you are using the default bundle "AppBundle", the Spanish language code of "es", and the "xlf" format, your file would be named "AppBundle.es.xlf".
To test your translations create an action in a controller to do something like this:
/**
 * @Route("/controller/test/{_locale}", name="cont_test")
 */
public function testAction(Request $request, $_locale="en")
{
    return $this->render('sometemplate.html.twig'));
}

Then you'd just go to http://domain.com/controller/test/es to test your translation (see twig template below first).
The next thing I noticed about your example is that your trans-unit id's are incorrect. You are using id's that are kind of like auto-generated mysql id's. The Symfony manual suggests using a keyword method for id's. So for example if you have a "name" field on a form you might use the keyword "form.name". So your message file would look something like this:
<trans-unit id="form.name">
    <source>name</source>
    <target>Nombre</target>

Unless you are coding for a large company who may potentially hire translators, the XLF format isn't as desirable as using the YAML version which is much more abbreviated and has many advantages of using that I wont go into here. The YAML version might look like this:
form:
    name: 'Nombre'
    price: 'Precio'

In your twig template you can translate the id something like this:
{% trans_default_domain 'AppBundle' %}
Please provide your {{'form.name'|trans}}

Note the first line in the template is telling the translator to default to looking in your bundle for the translations first before falling back.
Another thing to mention about using translations is that you will need to make sure to have a message translation file created for the language that you default to (for most it is English (en) ). Otherwise when choosing a different language your id's will get translated fine but when coming back to your default language, they will not. So if your default language is english, my example template would translate my sentence something like this:
Please provide your form.name

Hope this helps.


text:
Q: In this phrase should I use `have noticed` or `had noticed`? In this phrase, should I use 'have noticed' or 'had noticed'?

On a road trip, if you see a beautiful tree or a beautiful mountain,
but you don't know whether your children have noticed it or not...

A: Use the present perfect form.  We use the past perfect to refer to an action that happened before another time in the past.
Example. I asked the kids if they had noticed the beautiful scenery. That gives you two reference points - did they notice before I asked?
Since there's a connection from the past to the present with the question of the experience of having noticed, use the present perfect (have noticed).


text:
Q: Bad Access Parent is Null - Wht is this Happening? I understand what the error is, but in this case not what is causing it.  In general use it occurs maybe 1% of the time (probably less) but I have found an extreme way to cause it which I will describe below.  First, I am using an in-app purchase process I found on Ray Wenderlich's site.  Below are the specific pieces of concern here:
.h:
typedef void (^RequestProductsCompletionHandler)(BOOL success, NSArray * products);
@interface IAPHelper : NSObject

- (void)requestProductsWithCompletionHandler:RequestProductsCompletionHandler)completionHandler;

@end

.m
@implementation IAPHelper
{
    SKProductsRequest * _productsRequest;
    RequestProductsCompletionHandler _completionHandler;
}

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {

    NSLog(@"Loaded list of products...");
    _productsRequest = nil;

    NSArray * skProducts = response.products;
    for (SKProduct * skProduct in skProducts) {
        NSLog(@"Found product: %@ %@ %0.2f",
              skProduct.productIdentifier,
              skProduct.localizedTitle,
              skProduct.price.floatValue);
    }

    _completionHandler(YES, skProducts); // here is where bad access occurs
    _completionHandler = nil;
}

Again, 99%+ of the time this works just fine.  Given how infrequent the bad access happens in regular use and it has been difficult to diagnose.  However, I found an extreme way to cause the issue.  The setup is "Tab 1" is a table view controller and "Tab 2" is a table view controller that uses the code from above.  If I quickly switch back and forth between the two tabs I can usually cause the problem to occur anywhere from a few seconds into it to 20-30 seconds.  Doesn't happen every time in this scenario but it does the vast majority.  As marked above the following line gets a bad access error with Parent is Null.

_completionHandler(YES, skProducts);

To solve the issue I simple do the following:
if (_completionHandler)
{
    _completionHandler(YES, skProducts);
    _completionHandler = nil;
}

While that fix does work and does solve the problem I am still bothered by why this is occurring.  Any thoughts as to the cause of this?
Update:
Apologies to all as I did forget to include the following in what I pasted above.
- (void)requestProductsWithCompletionHandler:(RequestProductsCompletionHandler)completionHandler {

    // 1
    _completionHandler = [completionHandler copy];

    // 2
    _productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:_productIdentifiers];
    _productsRequest.delegate = self;
    [_productsRequest start];

}

A: You need to treat your completion block as any other object when you are storing it. So if you are storing your block as a variable and then using it within a different scope from where you assign it, you need to increment the reference count by either copying it or retaining it. The simple solution is to create a strong property to store your block.

A: Depending on unseen bits of code, your completion handler block might not be being assigned correctly. You need to copy a block if you intend to use it outside of the scope in which it was created.
In your interface, declare your completion handler's storage attribute as "copy".
@property (nonatomic, readwrite, copy) void (^completionHandler)(BOOL, NSArray *);

If you want to control the local variable, you can synthesize the property manually in your implementation:
@synthesize completionHandler = _completionHandler;


text:
Q: Deducing type for overloaded functions - currying Given a callable object ( a function ) a, and an argument b ( or a series of arguments ), I would like to deduce the type returned from f considering that f is overloaded with multiple signatures.
one of my many attempts is
#include <iostream>
#include <cstdint>
#include <string>
#include <functional>
#include <utility>
#include <typeinfo>

int foo(uint32_t a) { return ((a + 0) * 2); }

bool foo(std::string a) { return (a.empty()); }

/*template <typename A, typename B> auto bar(A a, B b) -> decltype(a(b)) {
  return (a(b));
}*/

/*template <typename A, typename B> decltype(std::declval<a(b)>()) bar(A a, B b)
{
  return (a(b));
}*/

template <typename A, typename B> void bar(std::function<A(B)> a, B b) {
  std::cout << a(b) << "\n";
}

int main() {

  // the following 2 lines are trivial and they are working as expected
  std::cout << foo(33) << "\n";
  std::cout << typeid(decltype(foo(std::string("nothing")))).name() << "\n";

  std::cout << bar(foo, 33) << "\n";
  //std::cout << bar(foo, std::string("Heinz")) << "\n";

  return (0);
}

and 2 templates options are commented out and included in the previous code.
I'm using declval result_of auto decltype without any luck.
How does the overloading resolution process works at compile time ?
If anyone wants to know why I'm trying to get creative with this, is that I'm trying to implement some Currying in C++11 in a workable/neat way.

A: The problem is that you can't easily create a function object from an overload set: when you state foo or &foo (the function decays into a function pointer in most case, I think) you don't get an object but you get an overload set. You can tell the compiler which overload you want by either calling it or providing its signature. As far as I can tell, you don't want either.
The only approach I'm aware of is to turn your function into an actual function object which makes the problem go away:
struct foo_object
{
    template <typename... Args>
    auto operator()(Args&&... args) -> decltype(foo(std::forward<Args>(args)...)) {
        return foo(std::forward<Args>(args)...);
    }
};

With that wrapper which is unfortunately needed for each name, you can trivially deduce the return type, e.g.:
template <typename Func, typename... Args>
auto bar(Func func, Args&&... args) -> decltype(func(std::forward<Args>(args)...)) {
    // do something interesting
    return func(std::forward<Args>(args)...);
}

int main() {
    bar(foo_object(), 17);
    bar(foo_object(), "hello");
}

It doesn't quite solve the problem of dealing with overload sets but it gets reasonably close. I experimented with this idea, essentially also for the purpose of currying in the context of an improved system of standard library algorithms and I'm leaning towards the algorithms actually being function objects rather than functions (this is desirable for various other reasons, too; e.g., you don't need to faff about when you want to customize on algorithm with another one).

A: If foo is overloaded, you need to use the following:
#include <type_traits>

int foo(int);
float foo(float);

int main() {
    static_assert(std::is_same<decltype(foo(std::declval<int>())), int>::value, "Nope.");
    static_assert(std::is_same<decltype(foo(std::declval<float>())), float>::value, "Nope2.");
}

If it's not, then this will suffice:
#include <type_traits>
bool bar(int);

int main() {
    static_assert(std::is_same<std::result_of<decltype(bar)&(int)>::type, bool>::value, "Nope3.");
}

Yes, it is verbose because you're trying to explicitly extract what implicit ad-hoc overloading does for you.

A: This is actually already implemented for you std::result_of. Here is a possible implementation
template<class>
struct result_of;

// C++11 implementation, does not satisfy C++14 requirements
template<class F, class... ArgTypes>
struct result_of<F(ArgTypes...)>
{
    typedef decltype(
                     std::declval<F>()(std::declval<ArgTypes>()...)
                    ) type;
};


text:
Q: What can you do the System.IO namespace and its classes (fileinfo, directory etc.)? (simple terms) I'm taking a C# course on Udemy. In this course, there is a section where they discuss "working with files". He teaches us how to use the .IO namespace and its classes, however I don't know what it does, how it can be used, and when it should be used (examples of real world applications).
Can someone please explain to me what the .IO namespace and it's classes (like fileinfo) are used for, and when we can apply it (in simple terms(I'm only a beginner)). Thank you!

A: The System.IO namespace contains types for working with I/O. So, whenever you want to input something or output something, you will almost certainly use it.
And since pretty much everything will at some point either need some input or provide some output, if only for debugging purposes, the real-world applications of System.IO is "pretty much every .NET code ever written".
For example, almost every programmer will, at some point in their life, have written the following program:
class HelloWorld
{
    static void Main()
    {
        System.Console.WriteLine("Hello World");
    }
}

Well, System.Console.WriteLine simply delegates to System.IO.TextWriter.WriteLine, so whenever you have written a Hello World program, you have used System.IO.


text:
Q: Exchange setup on existing domain I am working on a project where a new MS Exchange 2016 will be installed on a new server for a company. The company has already a working AD with 700 users and decided to buy and setup an Exchange server. Because I do not want to mess-up with the existing servers, I prefer to setup a new machine, join in to the AD, deploy Exchange etc....
I have read a few tutorials on this, I tested it in a virtual lab but I would like to know whether this setup is going to harm/modify something on the working AD. Has anyone deployed an Exchange server by joining the machine in an existing AD? Additionally, is there a better design concept instead of mine, when creating an Exchange for an existing AD? (e.g. create a new domain only for mail purposes_.
Thank you very much for your time.

A: To answer your questions (but if I were you, I wouldn't do these tasks without an MS Exchange architect in your project team).
1st point: If you join an MS Exchange server to an existing ActiveDirectory where no MS Exchange server was installed in, you need to run a process called "Schema Update". This will adjust the whole AD schema and will add additional fields which are required in order to run an Exchange server. If they already have an Exchange Server (e.g. 2010) and you wish to install Exchange 2016, you need to upgrade the schema via the Exchange 2016 installation.
By the way, if the AD schema is also very old because they are using Windows NT (which I really hope not, but such stuff happen sometimes), you need at first upgrade the normal AD schema before you can prepare that for Exchange. Exchange 2016 required that the functional level of your forest is at least Windows Server 2008, and that the schema master is running Windows Server 2008 or later as written here.
Also make  sure you have an AD backup if something breaks during that process!
2nd point: You might setup a different/own domain only for the Exchange server and then build some trusts between the domains. But this setup would take some additional work and also require somebody to administer the 2nd domain!