text:
Q: Why does stat_compare_means only show pairwise comparisons in one facet? I'm trying to do a pairwise comparison of grouped data. I've used stat_compare_means to do this successfully before, but for some reason this time it is only showing the comparison bars in one of the facet panels. I've tried, but can't seem to make it work. I've provided a simplified worked example below with just two conditions below. The real data has the same number of sets, but more conditions. Any help much appreciated!
data <- data.frame(sample = seq(1:83),
condition = c("KO", "KO", "KO", "KO", "KO", "KO", "KO", "KO", "KO", "KO",
"KO", "KO", "KO", "KO", "KO", "KO", "KO", "WT", "WT", "WT", "WT",
"WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT",
"WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT",
"WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT",
"WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT",
"WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT",
"WT", "WT", "WT", "WT", "WT", "WT", "WT"),
set = c("di", "tet", "mono", "di", "tet", "di", "tet", "mono", "di",
"tet", "mono", "di", "tet", "mono", "di", "tet", "mono", "di",
"tet", "mono", "di", "tet", "mono", "di", "tet", "mono", "di",
"tet", "mono", "di", "tet", "mono", "di", "tet", "mono", "di",
"tet", "mono", "di", "tet", "mono", "di", "tet", "mono", "di",
"tet", "mono", "di", "tet", "mono", "di", "tet", "mono", "di",
"tet", "mono", "di", "tet", "mono", "di", "tet", "mono", "di",
"tet", "mono", "di", "tet", "mono", "di", "tet", "mono", "di",
"tet", "mono", "di", "tet", "mono", "di", "tet", "mono", "di",
"tet", "mono"),
score = c(0, 0, 0, -5.95940584704586, 10.0932562947815, -3.16676604569923,
4.46133814098881, -1.9888611720281, -7.08194974795108, 3.17097628218171,
-1.83986980857496, -0.843268716519414, 1.40178526106758, -0.340339302553342,
-3.76913603338144, 4.28943971347741, -3.20197704274428, -3.54168755452774,
15.414510676737, -5.85333426479177, -1.87949902971026, 14.1424002410594,
-2.14726619139082, -5.01378228438499, 11.1131227496058, 0.097013584879446,
-6.55527134311774, 12.2234175105232, -2.55259067519978, -6.68392512983342,
15.8358484731832, -2.27825891764331, -5.40451835097939, 11.2240240941934,
-1.53075128507785, -4.80008896082703, 15.3667539728667, -4.81370852797055,
-2.69976280917806, 21.9926791189896, 0.61798090190648, -8.68663007652496,
13.8852585926079, -0.80329005076484, -16.8459570277756, 13.3500356549569,
-5.59531483186873, -3.33602772657725, 11.338954967882, -2.12614700145763,
-3.37418493461362, 11.5903340330526, -2.87224785160433, -14.7792521265679,
7.7542705233175, -2.06876649679246, -1.31032740187699, 17.6666627835987,
-0.824420163207606, -4.82659116096503, -0.0626028094479509, -1.90431942338018,
-20.3180652520285, 6.83632028067972, -1.58570945276274, -2.77261532150261,
2.98168865160908, -1.89922364414076, -5.80584721371712, 7.13599592922731,
-1.23964885854847, -5.1236580504364, 14.5532078112838, -3.82017971494402,
-4.39741499313133, 11.7342969461195, -2.5852194454582, -3.18458897513284,
12.7762556862722, 1.1245622869403, -2.98430760077172, 13.981837061262,
-1.19532384849617))

ggplot(data aes(x=condition, y=score, fill=set)) +
  stat_summary(fun=mean, geom="bar", colour="black", alpha=1) +
  stat_summary(fun.data = mean_se, geom = "errorbar", width=0.25) +
  geom_point(color="black", shape=21, show.legend=TRUE, size=3, stroke=1) +
  facet_wrap(~set, scales="free") +
  stat_compare_means(method = "t.test", comparisons=list(c("KO", "WT")), hide.ns=F) +
  theme_bw() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  scale_y_continuous(expand = expansion(mult = c(0.2, 0.2)))

A: I think you should add group = condition to the aes in ggplot.
ggplot(temp, aes(x=condition, y=score, color = set,  fill=set, group = condition)) +
  stat_summary(fun=mean, geom="bar", colour="black", alpha=1) +
  stat_summary(fun.data = mean_se, geom = "errorbar", width=0.25) +
  geom_point(color="black", shape=21, show.legend=TRUE, size=3, stroke=1) +
  facet_wrap(~set, scales="free") +
  stat_compare_means(method = "t.test", comparisons=list(c("KO", "WT")), hide.ns=F) +
  theme_bw() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  scale_y_continuous(expand = expansion(mult = c(0.2, 0.2)))

A: You can also calculate the p-values manually and then place them on the plot using the ggsignif package. It's more work, but you can adjust the p-values for multiple comparisons and/or specify what symbols you want to use, so it might come in handy for more complicated plots e.g.
library(tidyverse)
library(ggsignif)
temp <- data.frame(sample = seq(1:83),
                   condition = c("KO", "KO", "KO", "KO", "KO", "KO", "KO", "KO", "KO", "KO",
                                 "KO", "KO", "KO", "KO", "KO", "KO", "KO", "WT", "WT", "WT", "WT",
                                 "WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT",
                                 "WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT",
                                 "WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT",
                                 "WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT",
                                 "WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT", "WT",
                                 "WT", "WT", "WT", "WT", "WT", "WT", "WT"),
                   set = c("di", "tet", "mono", "di", "tet", "di", "tet", "mono", "di",
                           "tet", "mono", "di", "tet", "mono", "di", "tet", "mono", "di",
                           "tet", "mono", "di", "tet", "mono", "di", "tet", "mono", "di",
                           "tet", "mono", "di", "tet", "mono", "di", "tet", "mono", "di",
                           "tet", "mono", "di", "tet", "mono", "di", "tet", "mono", "di",
                           "tet", "mono", "di", "tet", "mono", "di", "tet", "mono", "di",
                           "tet", "mono", "di", "tet", "mono", "di", "tet", "mono", "di",
                           "tet", "mono", "di", "tet", "mono", "di", "tet", "mono", "di",
                           "tet", "mono", "di", "tet", "mono", "di", "tet", "mono", "di",
                           "tet", "mono"),
                   score = c(0, 0, 0, -5.95940584704586, 10.0932562947815, -3.16676604569923,
                             4.46133814098881, -1.9888611720281, -7.08194974795108, 3.17097628218171,
                             -1.83986980857496, -0.843268716519414, 1.40178526106758, -0.340339302553342,
                             -3.76913603338144, 4.28943971347741, -3.20197704274428, -3.54168755452774,
                             15.414510676737, -5.85333426479177, -1.87949902971026, 14.1424002410594,
                             -2.14726619139082, -5.01378228438499, 11.1131227496058, 0.097013584879446,
                             -6.55527134311774, 12.2234175105232, -2.55259067519978, -6.68392512983342,
                             15.8358484731832, -2.27825891764331, -5.40451835097939, 11.2240240941934,
                             -1.53075128507785, -4.80008896082703, 15.3667539728667, -4.81370852797055,
                             -2.69976280917806, 21.9926791189896, 0.61798090190648, -8.68663007652496,
                             13.8852585926079, -0.80329005076484, -16.8459570277756, 13.3500356549569,
                             -5.59531483186873, -3.33602772657725, 11.338954967882, -2.12614700145763,
                             -3.37418493461362, 11.5903340330526, -2.87224785160433, -14.7792521265679,
                             7.7542705233175, -2.06876649679246, -1.31032740187699, 17.6666627835987,
                             -0.824420163207606, -4.82659116096503, -0.0626028094479509, -1.90431942338018,
                             -20.3180652520285, 6.83632028067972, -1.58570945276274, -2.77261532150261,
                             2.98168865160908, -1.89922364414076, -5.80584721371712, 7.13599592922731,
                             -1.23964885854847, -5.1236580504364, 14.5532078112838, -3.82017971494402,
                             -4.39741499313133, 11.7342969461195, -2.5852194454582, -3.18458897513284,
                             12.7762556862722, 1.1245622869403, -2.98430760077172, 13.981837061262,
                             -1.19532384849617))

anno_df = compare_means(score ~ condition, group.by = "set", data = temp) %>%
  mutate(y_pos = c(3, 24, 2.5))

ggplot(temp, aes(x=condition, y=score, fill=set)) +
  stat_summary(fun=mean, geom="bar", colour="black", alpha=1) +
  stat_summary(fun.data = mean_se, geom = "errorbar", width=0.25) +
  geom_point(color="black", shape=21, show.legend=TRUE, size=3, stroke=1) +
  facet_wrap(~set, scales="free") +
  geom_signif(data = anno_df, aes(xmin=group1,
                                  xmax=group2,
                                  annotations=p.signif,
                                  y_position = y_pos),
              manual = TRUE) +
  theme_bw() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  scale_y_continuous(expand = expansion(mult = c(0.2, 0.2)))

@ricoderks answer is clearly the easier/better option though!


text:
Q: Probability with Independent Normal Variables Let X and Y be independent standard normal variables. Find:
a) P(3X + 2Y > 5)

A: Here are some hints that should go a long way towards answers.
(a) In your course, you may have learned that if $X$ and $Y$ are independent normal with means $p$, $q$ and variances $s^2$, $t^2$, then $aX+bY$ is normal mean $ap+bq$, variance $a^2s^2+b^2t^2$.  So $3X+2Y$ has mean $0$, variance $13$.
(b)  Our probability is $1$ minus the probability that they are both $\ge 1$. What is the probability that $X \ge 1$?
(c)  The probability that the absolute value of $\min(X,Y)$ is less than $1$ is the probability that $(X < 1) \cup (Y<1)$ minus the probability that  $(X \le -1) \cup (Y \le -1)$.
(d) This is the probability that $|X-Y|<1$.  Let $W=X-Y$ and look at the remark for part (a).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Excel, Trying Index, Match, to lookup values with VBA I am trying to look-up values at cell locations using VBA, I have searched google and all over stackoverflow before asking this because I can't seem to get it to work.
The following is the code I am trying to use, note that budgetcode references a cell containing one of the codes in the first column and mo references a cell that contains a number (1-12) or contains a short code (ytd, 1qtr, 2qtr, 3qtr). Example is that I want to pull CAD-NS for February (2), and I should get 5666.40.
Function eBudgetl(budgetcode As String, mo As String)
eBudgetl = Application.WorksheetFunction.Index(Range("Budget!G1:X5000"), _
   Application.WorksheetFunction.Match(budgetcode, Range("Budget!B1:B5000"), 0), _
   Application.WorksheetFunction.Match(mo, Range("Budget!G1:X1"), 0))
End Function

Here is part of the data I wish to lookup:
                                       1    2          3       4
CAD-NS      I   Net Sales           5264.0  5666.4  5614.9  5966.6
COSMAT      E   Material            6207.5  3660.0  3661.9  3560.9
COSDL       E   Direct Labor         610.4  105.3   167.1   123.6
CAD-MOIL    E   Indirect Labor       671.2  163.4   181.6   161.7
CAD-MOSAL   E   Salary Overhead      601.0  106.0   101.0   101.0

Here is the code in the cell that works, but I need to do in VBA. (The reason I need to do in vba is sometimes the budgetcode will contain 2+ references separated by a comma and I am going to use vba to separate them and look each up independently.)
=INDEX(Budget!$G$1:$X$5000,MATCH($F12,Budget!$B$1:$B$5000,0),MATCH(AN$1,Budget!$G$1:$X$1,0))

I appreciate any help very much, I have been at this for 3 days now.
Thanks,
Enoch

A: The issue is the Function parameter types.
When you call your Function with mo = cell AN1, containing the number 1, the Function type casts it to the String "1", which doen't exisit in the range Budget!$G$1:$X$1, since these are also numbers.
The solution is to use Variant as the function paramters type.
To make debugging this type of error easier, try not to do too much in a single line of code.  Splitting the line into 2 x Match functions and an Index, would allow you to see the second match return an error.
Couple of other points:

*

*If your are calling this function as a UDF (ie called from a worksheet cell), it is better not to hard code the ranges.  As written, the calls to eBudgetl would not automatically recalculate when any of their data changes.

*the Application object has a version of Index and Match so the WorksheetFunction calls are not required

Refactored version to demonstrate:
Function eBudgetl(rData As Range, rBudCode As Range, rMo As Range, budgetcode As Variant, mo As Variant)
    Dim rw As Variant
    Dim col As Variant

    With Application
        col = .Match(budgetcode, rBudCode, 0)
        rw = .Match(mo, rMo, 0)
        eBudgetl = .Index(rData, col, rw)
    End With
End Function

Called as
=eBudgetl(Budget!$G$1:$X$5000,Budget!$B$1:$B$5000,Budget!$G$1:$X$1,$F12,AN$1)


text:
Q: Does Site.createPortalUser work in a sandbox? I have a problem in production where, when users activate their account via Site.createPortalUser, instead of the User being linked to the existing Contact a new Contact is created. (Any advice on that problem very welcome too.) The logic for this is in a managed package.
I can't reproduce the problem in my managed package development org. So to debug this and test a solution, I've created a developer sandbox from production. But the activation always fails with:

Your request cannot be processed at this time. The site administrator
  has been alerted.

and I note that the "Used Licenses" is zero in the sandbox (but not in production). So I am wondering if Site.createPortalUser does not function in a sandbox by design. Any insight appreciated.

A: Yes, this method works in sandbox, production and every other org where Sites/Communities are enabled.
There are 3 steps required to make Site.createPortalUser works correctly:

*

*Login and Self registration is enabled for your portal/community

*Account record is created that holds all contacts of external users (in your code you should reference to this account)

*A role is assigned to the Account owner

If some error occurs during self registration you as System Administrator should receive the email from Salesforce with some details about the error.  (If you don't receive any email please check "Deliverability" option in sandbox and set it to "All emails")


text:
Q: Unable to re-load a youtube video on ActivityResult from second class Hello fellow programmers,
I'm experiencing some issues regarding my Android App, i'm currently
 working on. For this purpose, I only need to mention that I have two
 Activities (One is called MainActivity.class and the second is called
 FilterActivity.class).
The purpose of my MainActiviy class is to display a movie (Genres,
 year, rating etc) + a trailer of the specifik video.
In the OnCreate method for MainActiviy, im initializing the
 YouTubePlayerView (since I want a random movie to pop up as soon as
 you open the application).
The purpose of my FilterActivity class is to choose some specfik
 search criterias for a movie.
I'm opening FilterActivity from MainActivity like this:
public void openFilter(){
         Intent askIntent = new Intent(this, FilterActivity.class);
         startActivityForResult(askIntent, 1); }

And in my FilterActivity im sending the information from a newly
 created movie like this:
movieIntent.putExtra("url", a.getUrl());
             movieIntent.putExtra("title", a.getTitle());
             movieIntent.putExtra("rating", (String.valueOf(a.getRating())));
             movieIntent.putExtra("plot", a.getDesc());
             movieIntent.putExtra("year", (String.valueOf(a.getYear())));
             movieIntent.putExtra("genre", a.getGenres());
             setResult(RESULT_OK, movieIntent);
             finish();

And this is how I fetch data from MainActivity:
protected void onActivityResult(int requestCode, int resultCode, final Intent data){
    if(resultCode == RESULT_OK){
        titleView.setText(data.getStringExtra("title"));
        ratingView.setText(data.getStringExtra("rating"));
        plotView.setText(data.getStringExtra("plot"));
        yearView.setText(data.getStringExtra("year"));
        genreView.setText(data.getStringExtra("genre"));
        url = data.getStringExtra("url");     }

This is basically what I need to show. (This is all works by the way):
 I'm getting a newly created movie and the criterias match.
However, in the OnActivityResult, I can't get my YoutubePlayerView to
 re-load the video with the specific URL. The old video is still there,
 and playable. I have checked and I am indeed getting a new URL from
 the FilterActivity.
The only way I'm coming around this issue is by basically reloading
 the activity, and then (since im creating a random movie in my
 OnCreate method), the criteria don't match.
Any suggestions would be appreciated!
Sincerely

A: In onActivityResult, release current player and re-initialize YoutubePlayerView :
@Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
    if (resultCode == RESULT_OK) {
        mVideoId = getVideoId(data.getStringExtra("url"));
        mPlayer.release();
        mYoutubeplayerView.initialize(mApiKey, this);
    }
}

A complete example of MainActivity is :
public class MainActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {

    String mVideoId = "5xVh-7ywKpE";

    String mApiKey = "YOUR_API_KEY";

    YouTubePlayerView mYoutubeplayerView;

    YouTubePlayer mPlayer;

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

        mYoutubeplayerView = (YouTubePlayerView) findViewById(R.id.player);

        mYoutubeplayerView.initialize(mApiKey, this);

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

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openFilter();
            }
        });

    }

    @Override
    public void onInitializationSuccess(YouTubePlayer.Provider provider,
                                        YouTubePlayer youTubePlayer, boolean b) {
        mPlayer = youTubePlayer;
        mPlayer.loadVideo(mVideoId);
    }

    @Override
    public void onInitializationFailure(YouTubePlayer.Provider provider,
                                        YouTubeInitializationResult youTubeInitializationResult) {
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        if (resultCode == RESULT_OK) {
            mVideoId = getVideoId(data.getStringExtra("url"));
            mPlayer.release();
            mYoutubeplayerView.initialize(mApiKey, this);
        }
    }

    private String getVideoId(String url) {
        String pattern = "(?<=watch\\?v=|/videos/|embed\\/)[^#\\&\\?]*";

        Pattern compiledPattern = Pattern.compile(pattern);
        Matcher matcher = compiledPattern.matcher(url);

        if (matcher.find()) {
            return matcher.group();
        }
        return "";
    }

    public void openFilter() {
        Intent askIntent = new Intent(this, FilterActivity.class);
        startActivityForResult(askIntent, 1);
    }
}

Note that I've used this post to extract Youtube videoId from url path


text:
Q: Change in actionbar on opening in Android I have changed actionbar color and other things to open in required color and text but when I open the app: The app opens with default theme and immediately changes to given theme.
This happens in phones like Galaxy Nexus, Nexus 4 but not on Nexus 5. I am not sure why this is happening?
I have set the actionbar before setContentView in my APP
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    getActionBar().setDisplayHomeAsUpEnabled(true);
    getActionBar().setDisplayShowHomeEnabled(true);
    getActionBar().setIcon(android.R.color.transparent);
    getActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.actionBarColor)));

    setContentView(R.layout.activity_main);
 }

I got the theme using: http://jgilfelt.github.io/android-actionbarstylegenerator/
My style which I got from the above looks like this:
<style name="Theme.link" parent="@android:style/Theme.Holo">
    <item name="android:actionOverflowButtonStyle">@style/ThemeFor.OverFlow</item>
    <item name="android:actionBarItemBackground">@drawable/selectable_background_link</item>
    <item name="android:popupMenuStyle">@style/PopupMenu.link</item>
    <item name="android:dropDownListViewStyle">@style/DropDownListView.link</item>
    <item name="android:actionBarTabStyle">@style/ActionBarTabStyle.link</item>
    <item name="android:actionDropDownStyle">@style/DropDownNav.link</item>
    <item name="android:actionBarStyle">@style/ActionBar.Solid.link</item>
    <item name="android:actionModeBackground">@drawable/cab_background_top_link</item>
    <item name="android:actionModeSplitBackground">@drawable/cab_background_bottom_link</item>
    <item name="android:actionModeCloseButtonStyle">@style/ActionButton.CloseMode.link</item>
</style>

<style name="ActionBar.Solid.link" parent="@android:style/Widget.Holo.ActionBar.Solid">
    <item name="android:background">@drawable/ab_background_textured</item>
    <item name="android:backgroundStacked">@drawable/ab_stacked_solid_link</item>
    <item name="android:backgroundSplit">@drawable/ab_background_textured_link</item>
    <item name="android:progressBarStyle">@style/ProgressBar.link</item>
</style>

<style name="ActionBar.Transparent.link" parent="@android:style/Widget.Holo.ActionBar">
    <item name="android:background">@drawable/ab_transparent_link</item>
    <item name="android:progressBarStyle">@style/ProgressBar.link</item>
</style>

<style name="PopupMenu.link" parent="@android:style/Widget.Holo.ListPopupWindow">
    <item name="android:popupBackground">@drawable/menu_dropdown_panel_link</item>
</style>

<style name="DropDownListView.link" parent="@android:style/Widget.Holo.ListView.DropDown">
    <item name="android:listSelector">@drawable/selectable_background_link</item>
</style>

<style name="ActionBarTabStyle.link" parent="@android:style/Widget.Holo.ActionBar.TabView">
    <item name="android:background">@drawable/tab_indicator_ab_link</item>
</style>

<style name="DropDownNav.link" parent="@android:style/Widget.Holo.Spinner">
    <item name="android:background">@drawable/spinner_background_ab_link</item>
    <item name="android:popupBackground">@drawable/menu_dropdown_panel_link</item>
    <item name="android:dropDownSelector">@drawable/selectable_background_link</item>
</style>

<style name="ProgressBar.link" parent="@android:style/Widget.Holo.ProgressBar.Horizontal">
    <item name="android:progressDrawable">@drawable/progress_horizontal_link</item>
</style>

<style name="ActionButton.CloseMode.link" parent="@android:style/Widget.Holo.ActionButton.CloseMode">
    <item name="android:background">@drawable/btn_cab_done_link</item>
</style>

<!-- this style is only referenced in a Light.DarkActionBar based theme -->
<style name="Theme.link.Widget" parent="@android:style/Theme.Holo">
    <item name="android:popupMenuStyle">@style/PopupMenu.link</item>
    <item name="android:dropDownListViewStyle">@style/DropDownListView.link</item>
</style>

And I am calling the theme in Manifest:
   <application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/Theme.link" >
    <activity
        android:name=".Link_Main"
        android:label="@string/app_name"
        android:screenOrientation="portrait" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".Link_Support"
        android:label="@string/action_support"
        android:screenOrientation="portrait" >
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.ylg.linking.Link_Main" />
    </activity>
</application>

Can somebody help me fix this?
Thanks!

A: Try to add <item name="android:actionBarStyle">@style/Theme.link</item> to your base Activity style in AndroidManifest.xml.

A: I think you should change a value for android:background in ActionBar.Solid.link to @color/actionBarColor.

A: This is happening because when the application run, it gets style from styles.xml so your default style would be visible to you and after that you are changing actiob bar in onCreate() so theme changes immediately. To solve this set the icon and background color of action bar using styles.xml only using below code.
Try it. Hope it works.
<style name="AppBaseTheme" parent="@android:style/Theme.Holo.Light">
      .....

     <item name="android:actionBarStyle">@style/MyActionBar</item>
</style>

<style name="MyActionBar"  arent="@android:style/Widget.Holo.Light.ActionBar.Solid.Inverse">
    <item name="android:background">@color/actionBarColor</item>
    <item name="android:text">""</item>
    <item name="android:icon">@android:color/transparent</item>
</style>

And remove below code.
getActionBar().setIcon(android.R.color.transparent);
getActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.actionBarColor)));


text:
Q: c# AutoMapper Conditional Mapping Condition i just want to get Communities count as well as if its community delete flag its true then count will be minus. i had wrote below code, its return all count. any suggestion fot that -
Code -
Mapper.CreateMap< VPS_Entity.Brand, ZillowBrandViewEntity >()
              .ForMember(e => e.CommunityCount, ex => ex.MapFrom(s => s.Communities.Count))
                .ForSourceMember(e => e.Builder, ex => ex.Ignore());
class file -
Brand data model class file have -
  public virtual ICollection<Community> Communities { get; set; },
 in between Community class file have - "public bool Deleted { get; set; }"
thanks.


text:
Q: Laravel- Auto Change Currency based on Country I have an ecommerce website, using Laravel and mysql. I need to auto change the currency based on the client country.
I already have the selection based currency change. I need to auto change the currency to the one of the user's country when visiting the website.

A: We have a laravel package called Torann/laravel-geoip for this purpose.
Add below snippet after finished installing this lib;
$geoData = geoip(request()->ip());
$currency = $geoData['currency'];

For more details, see this link; https://lyften.com/projects/laravel-geoip/doc/


text:
Q: Split a file into 8 files depending on the number of records I have a file with 10K records and I need to divide it into 8 files.
I used split  -n l/8 -d file1 file2. This will split the file into 8 files, but I need to divide the file into 8 depending on the data/records in it.
For example,
       case $1
       in
        "P"|"D") no_lines=$(wc -l $NAS_LAND/$infile | cut -d ' ' -f1 )

                #no of lines in the each file after split
                split_count=`expr $no_lines / 10`

               if [ $split_count -ge 1 ]
                then
                    #Input file has more than or equal to 8 lines
                    echo "lines_per_instance=$split_count"
                    split  -n l/8 -d $NAS_LAND/$infile $MY_WORK/CCN_split_files/$infile
                else
                    cp $NAS_LAND/$infile $MY_WORK/CCN_split_files/ccn.email.list.file00
            fi
      esac

In the above code I am trying to count total number of records from In-file and doing a division split_count=expr $no_lines / 10 if it is greater than 1, split the file else do not split.
Now if my In-file contains 1000 records then file split into 8 files with 125 records each.
if I change split_count=expr $no_lines / 10 to split_count=expr $no_lines / 100, it will split into 8 files with the same 125 records in each file.
I am expecting when I changed the number to 100 (say1000/10=100) i am expecting 100 records in each of 8 files.
where did I went wrong.
The In-file must divide into 8 files, but records in the 8 files must vary by Dividor.


text:
Q: rClone to mount Onedrive Business Whenever I try to mount my onedrive on my pc, I face an issue. Right now my Org has more than 1 onedrive. (business plan 2)
and whenever I try to connect my onedrive, I get connected to other onedrive.
So when I fill the client id, secret code created by me. it shows other user drive. what is the issue?
I tried doing alot but always failed. In rClone it shows only 1 onedrive and that is other user onedrive.
Thank you

A: What do you mean by another OneDrive?  Another user's OneDrive?  A OneDrive with the same account but different contents?  Are you presented with different directories to choose from once you are authenticated?  If you're an admin in your org, or they haven't disabled the functionality for users to do so, go to https://aad.portal.azure.com , click on Users on the left, search for your account and click on it (don't check it) and then click on Sign-in logs on the left hand side.  Just to verify that your sign-in is actually being tracked in the tenant and you are connecting to what you think you are connecting to.


text:
Q: Using BufferedReader to count rows in a multi-dimensional array I'm using BufferedReader to read a .csv file.  I have no problem reading the file and extracting the data.  However, the problem that I do have is that I have to hard-code my array declaration.  For example:
        String[][] numbers=new String[5258][16];

The .csv file I was using had  5258 rows and 16 columns.  I'd like to be able to do something like this though:
        String[][] numbers=new String[rowsInFile][16];

In other words, I want the variable 'rowsInFile' to be equivalent to the amount of rows in the file (I don't want to count the columns, because every .csv file I will be running through this program has 16 columns).
Here's the code I have so far:
        int row = 0;
        int col = 0;

        String fileInput = JOptionPane.showInputDialog(null,
                "Please enter the path of the CSV file to read:");

        File file = new File(fileInput);

        BufferedReader bufRdr;
        bufRdr = new BufferedReader(new FileReader(file));
        String line = null;

        //get rows in the file
        int rowsInFile = 0;
        while(bufRdr.readLine() != null) {
            rowsInFile++;
            row++;
        }
        String[][] numbers=new String[rowsInFile][16];

        //read each line of text file
        row = 0;
        while((line = bufRdr.readLine()) != null) {
            StringTokenizer st = new StringTokenizer(line,",");
            col=0;

            while (st.hasMoreTokens()) {
                //get next token and store it in the array
                numbers[row][col] = st.nextToken();
                col++;
            }
            row++;
        }

However, I'm getting a null pointer exception.  Any ideas of what I should do?
P.S.  Yes, this code is surrounded by a try/catch statement.

A: The problem is, once you go through the BufferedReader once, you can't go back through it again. In other words, you have to use a new BufferedReader.
bufRdr = new BufferedReader(new FileReader(file));
row = 0;
while((line = bufRdr.readLine()) != null) {

Alternatively, you could use a dynamic array structure like an ArrayList<String[]> or a LinkedList<String[]> to store the rows.
LinkedList<String[]> numbers = new LinkedList<String[]>();

while( (line = bufRdr.readLine()) != null ) {
    numbers.add(line.split(","));
}

Then instead of doing numbers[i][j], you use numbers.get(i)[j].

A: Instead of an array use something dynamic like a List.   For example:
List<String[]> data = new ArrayList<String[]>();

Also using String's split() method will simplify the loading of the row.

A: Your problem is that BufferedReaders work by reading until the end of a file, and then they get stuck there. Your code requires reading through the file twice, but because you already reached an EOF, the BufferedReader is stuck returning null. I tend to solve this by stuffing the lines into an ArrayList, and using the size() method to get the number of lines. The source code looks something like this:
    int rowsInFile=0;
    ArrayList<String> lines = new ArrayList<String>();
    String tmp = "";
    while(tmp=bugRdr.readLine())
    {
        lines.add(tmp);
    }

    rowsInFile = lines.size();
    String[][] numbers = new String[rowsInFile][16];

    int row = 0;
    for(String line : lines)
    {
        StringTokenizer st = new StringTokenizer(line,",");
        col=0;

        while (st.hasMoreTokens()) {
        //get next token and store it in the array
            numbers[row][col] = st.nextToken();
            col++;
        }
        row++;
    }


text:
Q: Does Windows 7 64 bit make use of dual core CPU? Does Windows 64 bit make use of dual or more cores if they exist? Regardless if software is written for more cores.

A: Windows 7 (along with Vista, XP and even earlier operating systems) will make use of multiple cores. Microsoft has a per processor licensing model:

On October 19, 2004, Microsoft announced that its server software that is currently licensed on a per-processor model will continue to be licensed on a per-processor, and not on a per-core, model. This policy enables customers to recognize more performance and power from Microsoft software on a multicore processor system without incurring additional software licensing fees.

They have load balancing algorithms that ensure that if you run multiple applications they don't all get executed by just one core.


text:
Q: How to install a specific version of a package with pip I want to install Pyquery 1.2.4 version, but when I try
 pip install pyquery==1.2.4

I face with
  Compile failed: command 'gcc' failed with exit status 1
    creating tmp
    cc -I/usr/include/libxml2 -c /tmp/xmlXPathInitXZJM6c.c -o tmp/xmlXPathInitXZJM6c.o
    /tmp/xmlXPathInitXZJM6c.c:1:26: error: libxml/xpath.h: No such file or directory
    *********************************************************************************
    Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?
    *********************************************************************************
    error: command 'gcc' failed with exit status 1

    ----------------------------------------
Command "/usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip-build-cmQUrb/lxml/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-YFpKDF-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-cmQUrb/lxml

    No matching distribution found for python-pyquery

I know it because my Python version (2.6), and I can't update it to 2.7 because of  yum
How can I resolve this problem?

A: You may possibly be missing XML dependencies which your GCC compiler is spitting out at you, which can be installed with the following:
yum install libxslt-devel libxml2-devel libxml2 libxslt
After installing each the development and release dependencies, try:
pip install pyquery==1.2.4
Which should successfully execute. You should be also able to update Python with the following method: here. (Probably depends on your OS version.)
The above method explains:

yum install -y centos-release-SCL
yum install -y python27

Okay for centos 6.4 also On apu.0xdata.loc, after this install was done
$ which python
/usr/local/bin/python

$ python -V
Python 2.7.3

$ ls -ltr /usr/local/bin/pyth*
lrwxrwxrwx 1 root root      24 Jan 30  2013 /usr/local/bin/python -> /usr/local/bin/python2.7
-rwxr-xr-x 1 root root 6162289 Sep  3 00:59 /usr/local/bin/python2.7
-rwxr-xr-x 1 root root    1624 Sep  3 01:00 /usr/local/bin/python2.7-config

So yum will use '/usr/bin/python' which is 2.6
$ /usr/bin/python -V
Python 2.6.6

"python" will give you python 2.7.
"python2.7" will give you python 2.7.
"easy_install" and "easy_install-2.7" will easy install for python 2.7. While separate files, they both seem to install into /usr/local/lib/python2.7/site-packages/

A: You are missing some OS related dependencies.
Try this:
apt-get install libxml2-dev libxslt1-dev python-dev

A: Or try this:
sudo apt install libxml2-dev libxslt1-dev python-dev

Or so:
sudo apt install python-pyquery


text:
Q: Punctuation in centred equations Consider the following sentence
The function is given by
$$f(t)=t,$$
for $t\geq 0$.
Do we need to include the comma after the centred equation, provided the expression "for $t\geq 0$" afterwards? Personally, I prefer to omit all punctuation in a centred equation, but I was told to include it in a report I am doing. For example, I was told that if the follow-up sentence was "where t (...)", then I should include the comma. Any tips?

A: I think $f$ & "for" should be on the same line , because that is the Complete Definition of $f$.
In Case we consider other Intervals, then we will have multiple "for" clauses , each aligning with the value in that Interval.
The "Comma" is necessary , though alternatives are Possible , Eg "SPACING" (Alignment Only) or "semicolon".
The "for" too has alternatives like "if" or "where" or "when" or even "" Nothing !
We use the "run-on" for the Complete Definition & the following Sentences for the Elaboration like "where $t$ is the time" or "where $t$ is the temperature" Etc.
Examples taken from Wiki :
COMMA & If :

https://en.wikipedia.org/wiki/Absolute_value
SPACING & If :

https://en.wikipedia.org/wiki/Sign_function
SEMICOLON & "" (Alignment Only) :

https://en.wikipedia.org/wiki/Inverse_trigonometric_functions
SPACING & If :

https://en.wikipedia.org/wiki/Chebyshev_polynomials
SPACING & for :

https://en.wikipedia.org/wiki/Chebyshev_polynomials


text:
Q: Prove $f$ has inverse $f^{-1}$ in a neighborhood of the point $(1,1)$ Let $$f(u,v)=(u^2+u^2v+10v,u+v^3).$$
a) Prove $f$ has inverse $f^{-1}$ in a neighborhood of the point $(1,1)$;
b) Find an aproximate value of $f^{-1}(11.8,2.2)$.
My work:
Note $$f'(u,v)=\begin{pmatrix}
2u+2uv &1\\
u^2+10 &3v^2
\end{pmatrix},$$
then $$\det(f'(u,v))=(2u+uv)(3v^2)-(u^2+10)=6uv^2+3uv^3-u^2-10=0\\\iff6uv^2+3uv^3-u^2=10\\\iff3u(2v^2+v^3-u)=10\\\iff 2v^2+v^3-u=10.$$
Suppose $2v^2+v^3-u\not = 10$, then $$\det(f'(u,v))\not =0,$$ whis implies $f'(u,v)$ is invertible.
Moreover, note $f$ is of class $C^1$ then by inverse theorem function we have: there exists an open set $U=B((1,1),r)$ with $r=1-ε$ such that $f|_U$ is injective and have local inverse.
I don't know how to make the part b). Can someone help me?


text:
Q: How to prevent HTML5 looped video from downloading infinitely when cache is disabled I'm having bandwidth issues.
I have an HTML5 video playing on loop. It automatically starts playing when the visitor lands on the website. It is normally served one time to the user, but what is to prevent anyone from completely disabling cache and the video being served to them again every time it ends and tries to loop?
The reason I ask is because I had google developer console settings open and checked "disable cache when DevTools is open". I walked away from the page for a long time and 10gb of bandwidth was used!  If I could sabotage my bandwidth then I am assuming anyone could.
How can I go about addressing this issue? Here is the HTML5 video code. If you're wondering, the data attributes are for skrollr.js functionality.
            <video id="videoOne" autoplay poster="" style="width: 1920px; height: auto; visibility: visible; z-index: 0;" class="landscape desktop"  loop data-anchor-target="#fixTest" data-top="display: block; opacity:1; transform:translateY(0px);" data--70p-top="display: none; opacity:0; transform:translateY(-50px);">
                <source src="img/landVid3.mp4" type="video/mp4">
            </video>

A: If you use a little bit of JavaScript, you could load the video via an XMLHttpRequest. Something like:
var xhr = new XMLHttpRequest();
xhr.open("GET", "img/landVid3.mp4", true);
xhr.responseType = "blob";
xhr.onload = function () {
    var video = document.getElementById("videoOne");
    video.src = window.URL.createObjectURL(xhr.response);
    video.play();
};
xhr.send();

Code adapted from this question. Of course, as the answers on the question state, it's much better to set the source of the video to the actual path of the file, but in your situation, you've already done that and decided it's a bad idea.


text:
Q: react native fetch request to localhost server, even after change to IPV4 I'm trying to make http request in my react native app(in android in real device) with the localhost url.
after it failed in localhost url with the error

Network request Failed

I changed it to my ipv4 but it still not works.
but when I'm using in POSTMAN to check with my ipv4 it looks it works fine.
 try {
            let response = await fetch("http://myIPV4address:3008", {
                method: method,
                headers: headers,
                body: body != null ? JSON.stringify(body) : null,
            })
            console.log('response:',response)
            const endTime = (new Date()).getTime();
            if( response.status == 401 ) {
                return Promise.reject(response);
            }
            if( response.status == 400 ) {
                return Promise.reject(response);
            }
            if( response.status == 404 ) {
                return Promise.reject(response);
            }
            if( response.status == 500 ) {
                return Promise.reject(response);
            }
            if( response.status == 502 ) {
                return Promise.reject(response);
            }
            let responseJson = response.headers.map['content-type'][0].includes('application/json') ? await response.json() : response.statusText;
            return responseJson;
        } catch(error) {
            console.error(error);
        }

maybe it is settings in react native app I need to change?

A: Solution:
I connected to the wifi where the pc is connect because before it doesn't know what is localhost is

A: look for dns server the solution is to configure your emulator


text:
Q: Hard problem to show almost sure boundedness Let us assume that $X_i = \theta t_i + e_i, \ \ i=1,2,...,n$ where $\theta \in \Theta$ which is unknown and $\Theta$ is a closed subset of $\mathbb{R}$. Suppose $e_i$'s are i.i.d. on the interval $[-\tau,\tau]$ with unknown $\tau >0$ and $E(e_i)=0$. Given $t_i$'s are fixed constants let
$$T_n= S_n(\tilde{\theta})=\min_{\gamma \in \Theta} S_n(\gamma)$$ where
$$S_n(\gamma) = 2 \max_{i \le n} \frac{|X_i - \gamma t_i|}{\sqrt{1+\gamma^2}}.$$
If we assume that $\sup_{i} |t_i| < \infty$ and $\sup_i t_i - \inf_i t_i > 2\tau$ show that $\{\tilde{\theta_n}, n =1,2,...\}$ is bounded almost surely.
I have really no clue how to tackle this one as there is too much detail. Judging by the expression of $S_n(\gamma)$, it looks like the perpendicular distance of a straight line from a point and it feels that out of $t_1,...,t_n$, I need to find that $t_i$ which is the most distance from the straight line $X_i = \gamma t_i$. Can anyone have a crack at this?
Another follow-up question :
Under the same assumptions mentioned, can we show that $T_n$ is a strongly consistent estimator of $\nu = \min_{\gamma \in \Theta} S(\gamma)$, where $S(\gamma)=\lim_{n \rightarrow \infty} S_n(\gamma)$ almost surely?
By strong consistency of an estimator, you can think of almost sure convergence of the estimator to the parameter of interest.
Again, I could show that for any sequence $\theta_n \rightarrow \theta$, $S_n(\theta_n)-S_n(\theta)=O(|\theta_n-\theta|)$ almost surely. But how can I use this fact to show the almost sure convergence of $T_n$ to $\nu$?

A: First observe that
$$
S_n(\theta)=2\max_{i\le n} \frac{|e_i|}{\sqrt{1+\theta^2}}\le 2\tau.
$$
By assumption there must exist $i$ such that $|t_i|>\tau$. Now for any $n\ge i$ and $\gamma$, for sure we have the lower bound
$$
S_n(\gamma)\ge \frac{2|(\theta-\gamma)t_i+e_i|}{\sqrt{1+\gamma^2}}\underset{\gamma\to\pm\infty}{\longrightarrow} 2|t_i|.
$$
Thus, for $\gamma$ large enough (uniformly in $n$), we have $S_n(\gamma)>S_n(\theta)$, which immediately implies that $(\tilde{\theta_n})$ must be bounded almost surely.


text:
Q: Selenium ChromeDriver: unable to set user-data-dir I'm setting the user director to be my default User data directory as such (so I don't have to worry about entering passwords to sites and logging in each time):
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument("--user-data-dir=~/Library/Application\ Support/Google/Chrome/Default/")
browser = webdriver.Chrome(options=options, executable_path=r"chromedriver")
browser.get('https://mail.google.com/mail/u/0/')
print browser.desired_capabilities

Now I would expect my Gmail to come up but it asks me to sign in.
Further, when I print the desired capabilities it appears that the user data directory has NOT been set at all:

{u'takesScreenshot': True, u'acceptSslCerts': True,
  u'networkConnectionEnabled': False, u'mobileEmulationEnabled': False,
  u'unexpectedAlertBehaviour': u'', u'applicationCacheEnabled': False,
  u'locationContextEnabled': True, u'rotatable': False, u'chrome':
  {u'chromedriverVersion': u'2.29.461585
  (0be2cd95f834e9ee7c46bcc7cf405b483f5ae83b)', u'userDataDir':
  u'/var/folders/2r/twg_2d4j5cnf2d6k1m_mnx4c0000gn/T/.org.chromium.Chromium.ihUqp7'},
  u'hasTouchScreen': False, u'platform': u'Mac OS X', u'version':
  u'70.0.3538.110', u'nativeEvents': True, u'handlesAlerts': True,
  u'takesHeapSnapshot': True, u'javascriptEnabled': True,
  u'databaseEnabled': False, u'browserName': u'chrome',
  u'webStorageEnabled': True, u'browserConnectionEnabled': False,
  u'cssSelectorsEnabled': True, u'pageLoadStrategy': u'normal'}

I am on the latest version of Selenium (3.141) and ChromeDriver (2.29.461585)

A: you need to remove /Default/ because its not valid directory for --user-data-dir it is for --profile-directory
options.add_argument('--profile-directory=Default')
# or
options.add_argument('--profile-directory=other_profile')


text:
Q: Showing that $f:\{0, 1\}^{\mathbb{N}}\to \mathbb{R}, f(x) = 2\sum_{j=1}^\infty 3^{-j}x_j$ is an embedding Let the function $f:\{0, 1\}^{\mathbb{N}}\to \mathbb{R}$ be defined as $f(x) = 2\sum_{j=1}^\infty 3^{-j}x_j$, where $x = (x_1, x_2,\dots)$ is some binary string. I am looking to understand a proof why this mapping is an embedding. Suppose that it is already argued that i.)  $f$ is an injection, ii.) $\forall x, y\in \{0, 1\}^{\mathbb{N}}: x \neq y: |f(x) - f(y)| \geq 3^{-l}$, where $l$ is the first index where strings $x$ and $y$ differ, iii.) $f$ is continuous. Moreover, assume that is has already been proven that if $f:X\to Y$ is a mapping, then $f$ being continuous is equivalent to the fact that if $Y$ has a basis or subbasis, then the pre-image of each of the element of the basis (or subbasis) is open.
Then my reading material claims:

Write $\{0, 1\}^{\mathbb{N}} = X$. Define $U_j = \{x \in X\mid x_j = 0\}, V_j = \{x \in X\mid x_j = 1\}$. These sets form a subbasis for the space $X$. Let $x \in U_j, y \in V_j$ and $l$ be the first index at which $x_l \neq y_l$. Note that $l \leq j$. Then $|f(x) - f(y)| \geq 3^{-l} \geq 3^{-j}$. Hence $(f(x) - 3^{-j}, f(x) + 3^{-j}) \cap f[X] \subset f[U_j]$. Thus $f[U_j]$ is an open subset of $f[X]$.

What I'm unsure about is why is the set $f[X]$ open? Is there some result stating that if $f:X\to Y$ is an injection and continuous, then then elements of the subbasis of $X$ are elements for the subbasis for $Y$, which would then (I guess) yield that $f[X]$ is open? Or is the argument that the set $f[U_j]$ is open in the relative topology of $f[X]$ in the real line $\mathbb{R}$?

A: The last statement is "Thus $f[U_j]$ is an open subset of $f[X]$" which should be understood as "open in $f[X]$ with subspace topology on $f[X]\subseteq\mathbb{R}$".
The author doesn't claim  that $f[X]$ itself is open in $\mathbb{R}$. And in fact no continuous image of $\{0,1\}^\mathbb{N}$ is open in $\mathbb{R}$ because $\{0,1\}^\mathbb{N}$ is compact while $\mathbb{R}$ connected (but not compact).


text:
Q: How to set the background color of a pygtk window I am trying to set the background color for a pyGtk window which has a single DrawingArea widget.
With this code I always get a random color everytime I launch the script:
widget = gtk.DrawingArea()
widget.show()
window = gtk.Window()
window.add(widget)
col = gtk.gdk.Color('#010')
window.present()
widget.window.set_background(col)
window.connect('delete-event', gtk.main_quit)
gtk.main()

I also tried using widget.modify_bg(gtk.STATE_NORMAL, col) instead of the set_background line, and I always get a black background.
What am I missing?

A: Ok, it seems like I was struggling too much with other things, and I didn't realize that I set the test color to #010, which is, obviously, almost black.
Using modify_bg works, just remember to set a reasonable color ;)
This is the working code:
widget = gtk.DrawingArea()
widget.show()
window = gtk.Window()
window.add(widget)
col = gtk.gdk.Color('#0f0')
window.present()
widget.modify_bg(gtk.STATE_NORMAL, col)
window.connect('delete-event', gtk.main_quit)
gtk.main()

By the way, does anybody know why widget.window.set_background() sets a random color?


text:
Q: REST-Apache CXF-Schema validation I am using RESTful Webservice using Apache CXF (blended with spring).
I am exposing two services in my WADL.
For every request to my Webservice,I need to validate request to a particular schema.One of my exposed service use a specific schema and other service complies to other specific schema.
Can you help me?

A: There is a couple of ways to do what you need. One way is using jaxrs:schemaLocations element:
<beans>
    <jaxrs:server address="/" serviceClass="com.something.ServiceClass">
        <jaxrs:schemaLocations>
            <jaxrs:schemaLocation>classpath:/schemas/a.xsd</jaxrs:schemaLocation>
            <jaxrs:schemaLocation>classpath:/schemas/b.xsd</jaxrs:schemaLocation>
        </jaxrs:schemaLocations>
    </jaxrs:server>
</beans>

For more information and examples please see this link.


text:
Q: Why I am getting different outputs with these 2 assignments, one in a function and other in main of a pointer? "I was trying to assign NULL to a pointer root in a function. But it doesn't really get assigned by NULL using function. But when I tried to assign root = NULL in main it get assigned. I am not getting why it happens so?
#include<bits/stdc++.h>
using namespace std;
struct node{
    int key;
};
void deletion(struct node* root){
    root=NULL;
}
void print(struct node* temp){
    if(!temp)
    return;
    cout<<temp->key;
}
int main(){
    struct node* root = new struct node;
    root->key=10;
    cout<<"Initially : ";
    print(root);

    deletion(root);
    cout<<"\nAfter deletion() : ";
    print(root);

    root=NULL;
    cout<<"\nAfter assigning in main() : ";
    print(root);
}

The output I am getting is :
Initially : 10

After deletion() : 10

After assigning in main() :

A: You're passing the pointer by value and modifying that value. To modify the value of a variable being passed, you can either pass it by reference (C++-style) or pass it by pointer(C-style). With C-style, remember to dereference the pointer to change its value for the caller.
C++-style:
void foo(const struct node*& n);

C-style:
 void foo(const struct node** n);


text:
Q: Nested ui-sref in angular-google-map info window I'm trying to pass the id of the object via ui-sref directive to no avail.
My markup:

{{::name}}

Everything is working via data binding. When clicking the window area the route changes but the id parameter is always empty in $stateParams.
How do I fix this?


text:
Q: How to push to an array using index.of and if statement I'm trying to figure out how to push an additional value to an array if my index.Of is equal or greater than 0. However the below code doesn't seem to work, I don't get any errors and I've checked the index.0f and it always equals 0.
var groups = ['a,b,c,']

function myfunction () {

    if (groups.indexOf('a,b,c,') >= 0) {
       groups.push('d')
    }
}

console.log(groups);

A: Just call your myFunction(). Also, you can use incldes method, and declare your array as a const:
const groups = ['a,b,c,'];

function myfunction() {
    if (groups.includes('a,b,c,')) {
       groups.push('d')
    }
}

myfunction();
console.log(groups);


text:
Q: Invalid URI: The format of the URI could not be determined Exception In my asp.net c# web application, I m unable to find where exactly in the code, this exception (Invalid URI: The format of the URI could not be determined.)is raised. The URL where the exception is coming is of format as below
http://somedomain.com/sepsisvte/sepsis.aspx?4040431page=2
If the problem is related to the structure of the URL then there are URL like below where I m not getting any exception at all
http://somedomain.com/sepsisvte/sepsis.aspx?4020894page=2
http://somedomain.com/sepsisvte/sepsis.aspx?4020894page=3
Its a quite large application and Its really difficult to find the origin of error. Any ideas?
The stacktrace is as below

[UriFormatException: Invalid URI: The format of the URI could not be
  determined.]    System.Uri.CreateThis(String uri, Boolean dontEscape,
  UriKind uriKind) +5462488    System.Uri..ctor(String uriString) +20
  umbraco.presentation.requestModule.rewrite404Url(String url, String
  querystring, Boolean returnQuery) +265
  umbraco.presentation.requestModule.Application_BeginRequest(Object
  sender, EventArgs e) +237
  System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
  +68    System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75

A: That's because your url contains this "?404". Umbraco searches each url for this text, and if it exists, it rewrite the url. Check the source code here: https://searchcode.com/codesearch/view/28576630/, search for this method: rewrite404Url.
One of the solutions is to try to prefix your query string key with underscore.


text:
Q: Uniformly distributing hash of given properties I am trying to distribute a set of items across number of buckets. I am looking for following properties:

*

*Bucket assignment needs to be deterministic. In different runs same
input should end up in the same bucket.

*Distribution of data between buckets should be uniform.

*This should work for fairly small number of inputs (e.g. if I want
to distribute 50 inputs across 25 buckets ideally each bucket will
have 2 items).

First try was to generate md5 from input data and form bucket from first bytes of md5. I am not too satisfied with uniformity. It works well when input is large but not so well for small input. E.g. distributing 100 items across 64 buckets:
List<string> l = new List<string>();

for (int i = 0; i < 100; i++)
{
    l.Add(string.Format("data{0}.txt", i));
}

int[] buckets = new int[64];

var md5 = MD5.Create();
foreach (string str in l)
{
    {
        byte[] hash = md5.ComputeHash(Encoding.Default.GetBytes(str));
        uint bucket = BitConverter.ToUInt32(hash, 0) % 64;
        buckets[bucket % 64]++;
    }
}

Any suggestions what could I do to achieve higher uniformity? Thanks.

A: Leaving aside the efficiency of using MD5 for this purpose (see the discussion here and in the marked duplicate of that question), basically the answer is that what you have is what a uniform distribution really looks like.
That might seem counter-intuitive, but it's easily demonstrable either mathematically or by experiment.
As a kind of motivating example, consider the task of choosing exactly 64 numbers in the range 0-63. The odds that you will get one per bucket are very close to 0. There are 6464 possible sequences, of which 64! contain all 64 numbers. The odds of getting one of these sequence is about one in 3.1×1026. In fact, the odds of getting a sequence in which no element appears three times is less than one in a thousand (it's about .000658). So it's almost certain that a random uniform sample of 64 numbers in the range 0-63 will have some triplets, and it's pretty likely that there will be some quadruplet. If the sample is 100 numbers, those probabilities just get even bigger.
But the maths are not so easy to compute in general, so here I chose to illustrate by experiment :-), using random.org, which is a pretty reliable source of random numbers. I asked it for 100 numbers in the range 0-63, and counted them (using bash, so my "graph" is not as pretty as yours). Here are two runs:
First run:
Random numbers:
44  17  50  11  16   4  24  29  12  36
27  32  12  63   4  30  19  60  28  39
22  40  19  16  23   2  46  31  52  41
13   2  42  17  29  39  43   9  20  50
45  40  38  33  17  45  28   6  48  12
56  26  34  33  35  40  28  44  22  10
50  55  49  43  63  62  22  50  15  52
48  54  53  26   4  53  13  56  42  60
49  30  14  55  29  62  15  13  35  40
22  38  37  36  10  36   5  41  43  53

Counts:
                      X                 X         X
    X       XX   X    X     XX      X   X  X      X  X
  X X     X XX XXX X  X   X XXX  X XX XXXXXXXX  XXX XX XX   X XX
  X XXX  XXXXXXXXX XX XXX XXXXXXXXXXXXXXXXXXXXX XXX XXXXX   X XX
----------------------------------------------------------------
          1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 6 6
0 2 4 6 8 0 2 4 6 8 0 2 4 6 8 0 2 4 6 8 0 2 4 6 8 0 2 4 6 8 0 2

Second run:
Random numbers:
41  31  16  40   1  51  17  41  27  46
24  14  21  33  25  43   4  36   1  14
40  22  11  22  30  19  23  63  39  61
 8  55  40   6  21  13  55  13   3  52
17  52  53  53   7  21  47  13  45  57
25  27  30  48  38  55  55  22  61  11
11  28  45  63  43   0  41  51  15   2
33   2  46  14  35  41   5   2  11  37
28  56  15   7  18  12  57  36  59  51
42   5  46  32  10   8   0  46  12   9

Counts:
           X                             X    X        X
  X        X XX      XX                 XX    X    X   X
XXX  X XX  XXXXX X   XX  X XX X  X  X   XX X XX    XXX X X   X X
XXXXXXXXXXXXXXXXXXXX XXXXX XX XXXX XXXXXXXXX XXXX  XXX XXX X X X
----------------------------------------------------------------
          1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 6 6
0 2 4 6 8 0 2 4 6 8 0 2 4 6 8 0 2 4 6 8 0 2 4 6 8 0 2 4 6 8 0 2

You could try this with your favourite random number generator, playing around with the size of the distribution. You'll get the same sort of shape.


text:
Q: how to calculate cross tabs between all variables with chi square calculation using R My data example
cross=structure(list(a = c(2L, 2L, 1L, 2L, 2L, 1L, 2L, 2L, 1L, 2L,
2L, 1L, 2L, 1L, 2L, 2L, 2L, 1L), b = c(1L, 1L, 1L, 2L, 2L, 2L,
1L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 1L), c = c(1L, 1L,
1L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L
), d = c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, NA, 2L, 2L,
2L, 2L, 2L, 2L, 2L), e = c(1L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 2L,
1L, NA, 2L, 2L, 2L, 2L, 1L, 2L, 1L), f = c(2L, 2L, 2L, 2L, 1L,
1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 1L, 2L, 1L), g = c(NA,
1L, 2L, NA, 2L, 2L, 1L, 2L, 1L, NA, NA, NA, NA, NA, 1L, NA, NA,
NA), h = c(2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L), i = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L,
1L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L), j = c(2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), k = c(2L,
1L, 1L, 2L, 2L, 1L, 1L, 1L, 2L, 1L, NA, 1L, 2L, 1L, 1L, 1L, 1L,
1L), l = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, NA, 2L, NA,
1L, 1L, 1L, 1L, 2L), m = c(1L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 2L,
1L, 1L, 1L, 2L, NA, 2L, 2L, 2L, 1L), n = c(1L, 2L, 2L, 2L, 1L,
2L, 2L, 2L, 2L, NA, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L), xxx = c(2L,
1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L,
2L)), class = "data.frame", row.names = c(NA, -18L))

I need  perform cross tab between all categorical variables
I.E.
a vs b
a vs c
...
d vs c
m vs n

and so on
i tried use table command ,but it provided not result that i need,cause i need also calculation of the chi-square test . That why ideally desired result for  me would be like this
b       total
        1   2
a   1   42  54  96
    2   40  35  75
total   82  89  171

and p-value for chi-square
Value(empirical)    df       p-value
chi-square  1,549   1   0,213

How to do   crosstab between combinations of variables at once and get similar output results? Namely, the table  and the chi-square statistics for it.
Grateful for any help.

A: To get all combinations of column names (there will be 105 combinations of 2 columns if you are starting with 15 columns) you can use the combn function:
cmb <- combn(names(cross), 2)

You can use this to get a contingency table for each column pair using apply:
tabs <- apply(cmb, 2, function(x) table(cross[[x[1]]], cross[[x[2]]]))

This then allows you to calculate your p values using sapply. With the data you provided, Chi square tests throw an error due to the small numbers involved, which invalidate the assumptions of the test. We can use the Fisher Exact test instead in this situation, though if your own data is much larger you may wish to stick to Chi Square.
pvals <- sapply(tabs, function(x) {
  if(all(dim(x) == c(2, 2))) fisher.test(x)$p.val else NA
  })

Finally, we can create a results data frame with the two columns compared, and the p value for the ratio of proportions between each two columns. Note that depending on your use case, your threshold for significance should be lowered to account for multiple hypothesis testing, as one would expect to have around 5 'significant' p values of < 0.05 purely by chance.
data.frame(col1 = cmb[1,], col2 = cmb[2,], pval = pvals)
#>     col1 col2         pval
#> 1      a    b 1.0000000000
#> 2      a    c 1.0000000000
#> 3      a    d           NA
#> 4      a    e 1.0000000000
#> 5      a    f 0.2682072829
#> 6      a    g 1.0000000000
#> 7      a    h 0.5294117647
#> 8      a    i 0.6148459384
#> 9      a    j           NA
#> 10     a    k 0.6000323206
#> 11     a    l 0.6043956044
#> 12     a    m 0.5927601810
#> 13     a    n 1.0000000000
#> 14     a  xxx 1.0000000000
#> 15     b    c 0.0114379085
#> 16     b    d           NA
#> 17     b    e 1.0000000000
#> 18     b    f 0.3259803922
#> 19     b    g 1.0000000000
#> 20     b    h 0.4967320261
#> 21     b    i 1.0000000000
#> 22     b    j           NA
#> 23     b    k 0.2800581771
#> 24     b    l 0.2335164835
#> 25     b    m 0.6220691074
#> 26     b    n 1.0000000000
#> 27     b  xxx 1.0000000000
#> 28     c    d           NA
#> 29     c    e 1.0000000000
#> 30     c    f 1.0000000000
#> 31     c    g 0.4285714286
#> 32     c    h 1.0000000000
#> 33     c    i 1.0000000000
#> 34     c    j           NA
#> 35     c    k 0.5378151261
#> 36     c    l 0.5164835165
#> 37     c    m 0.1029411765
#> 38     c    n 0.2605042017
#> 39     c  xxx 0.2450980392
#> 40     d    e           NA
#> 41     d    f           NA
#> 42     d    g           NA
#> 43     d    h           NA
#> 44     d    i           NA
#> 45     d    j           NA
#> 46     d    k           NA
#> 47     d    l           NA
#> 48     d    m           NA
#> 49     d    n           NA
#> 50     d  xxx           NA
#> 51     e    f 0.2800581771
#> 52     e    g 0.4285714286
#> 53     e    h 0.5147058824
#> 54     e    i 0.5840336134
#> 55     e    j           NA
#> 56     e    k 1.0000000000
#> 57     e    l 0.6043956044
#> 58     e    m 0.0076173826
#> 59     e    n 0.0631868132
#> 60     e  xxx 0.0276341306
#> 61     f    g 0.4285714286
#> 62     f    h 1.0000000000
#> 63     f    i 0.5827497666
#> 64     f    j           NA
#> 65     f    k 1.0000000000
#> 66     f    l 1.0000000000
#> 67     f    m 1.0000000000
#> 68     f    n 0.6000323206
#> 69     f  xxx 1.0000000000
#> 70     g    h 1.0000000000
#> 71     g    i 1.0000000000
#> 72     g    j           NA
#> 73     g    k 1.0000000000
#> 74     g    l 1.0000000000
#> 75     g    m 0.4285714286
#> 76     g    n 1.0000000000
#> 77     g  xxx 1.0000000000
#> 78     h    i 0.4901960784
#> 79     h    j           NA
#> 80     h    k 1.0000000000
#> 81     h    l 0.4500000000
#> 82     h    m 0.4852941176
#> 83     h    n 1.0000000000
#> 84     h  xxx 0.5294117647
#> 85     i    j           NA
#> 86     i    k 0.2605042017
#> 87     i    l 0.2445054945
#> 88     i    m 1.0000000000
#> 89     i    n 0.6000323206
#> 90     i  xxx 1.0000000000
#> 91     j    k           NA
#> 92     j    l           NA
#> 93     j    m           NA
#> 94     j    n           NA
#> 95     j  xxx           NA
#> 96     k    l 0.5164835165
#> 97     k    m 1.0000000000
#> 98     k    n 0.5467032967
#> 99     k  xxx 0.6000323206
#> 100    l    m 0.2351648352
#> 101    l    n 0.1538461538
#> 102    l  xxx 0.0631868132
#> 103    m    n 0.0013736264
#> 104    m  xxx 0.0005656109
#> 105    n  xxx 0.0001616031

Created on 2022-06-27 by the reprex package (v2.0.1)


text:
Q: running Keras on macOs through the terminal with python installed? When I type the command, 'from tensorflow import keras' into the terminal on macOS, I get
"from: can't read /var/mail/tensorflow"

A: You can't just write Python code into the CLI directly. That only accepts shell commands to some extent.
You can either:

*

*fire up a Python interpreter from your CLI and use that directly, e.g.

$ python3
Python 3.9.4 (default, Apr  5 2021, 01:50:46)
[Clang 12.0.0 (clang-1200.0.32.29)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from tensorflow import keras

*or write all of your code into a text file and name it something like my_first_script.py, e.g.

#!/usr/bin/env python3

import tensorflow as tf
from tensorflow import keras

# the rest of your code

Then you run that with python, e.g.
$ python my_first_script.py

Check out this tutorial here.


text:
Q: Query to return data where Id Column is unique but display number is the same? I have data in a table like below:
CustomerId   OrderId  NoToDisplay
123           176        1
123           177        1
124           125        1
124           126        2
124           127        3
125           182        6
125           183        6

I am trying to write a query that returns unique order numbers that have got the same NoToDisplay Value.  So from the dataset snippet above the output would be:
CustomerId   OrderId  NoToDisplay
123           176        1
123           177        1
125           182        6
125           183        6

This is the query I have tried but it isn't returning what I expected:
SELECT DISTINCT c.CustomerID, o.OrderID, o.NoToDisplay
FROM Customer c
LEFT OUTER JOIN Order o ON o.CustomerID = c.CustomerID
WHERE o.OrderID IN (SELECT DISTINCT o.NoToDisplay
FROM Customer c
LEFT OUTER JOIN Order o ON o.CustomerID = c.CustomerID
GROUP BY o.NoToDisplay HAVING COUNT(*) > 1)

A: You seem to want customers where the NoToDisplay values are all the same.  To get the customers:
select customerid
from t
group by customerid
having min(NoToDisplay) = max(NoToDisplay);

You can easily extend this to get the original rows:
select t.*
from t join
     (select customerid
      from t
      group by customerid
      having min(NoToDisplay) = max(NoToDisplay)
     ) tc
     on t.customerid = tc.customerid;

A: Try this:
select * from Customer
where customerid not in
(select customerid
 from Customer
 group by customerid
 having count(distinct notodisplay) >1)

A: You can try below:
declare @Customer  table
(CustomerId int,   OrderId int,  NoToDisplay int)
insert into @Customer
select 123 ,          176  ,      1 union all
select 123 ,          177  ,      1 union all
select 124 ,          125  ,      1 union all
select 124 ,          126  ,      2 union all
select 124 ,          127  ,      3 union all
select 125 ,          182  ,      6 union all
select 125 ,          183  ,      6

select CustomerID, OrderId, NoToDisplay
from
(select CustomerID, OrderId, NoToDisplay, count(*) OVER (PARTITION BY CustomerID, NoToDisplay) [check]
from @Customer
group by CustomerID, OrderID, NoToDisplay) x
where [check] > 1
order by CustomerID


text:
Q: WinForms Combobox: Fill with String and Object I already have seen that there are many Topics about this,but I am not able to make them work.
I have an Combobox which shall be filled with an List of String.
  this.elementBox.DataSource = this.elementList;
  this.elementBox.SelectedIndexChanged += new EventHandler(this.elementBox_SelectedIndexChanged);

If I put this into the Code my GUI does not appear, I suppose the assignment of the data is wrong. I already tried Bindingsource.
Then I want to fill an Combobox with an List of Objects and this does not work either. itemData is an Dictionary with an String as key and the Objectlist as value.
        box1.DataSource = itemData["ele1"];
        box1.DisplayMember = "Name";

        box2.DataSource = itemData["ele2"];
        box2.DisplayMember = "Id";

I tried to play around with DisplayMember and Value but I am not able to get it to work.
The Type of the List is MyItem:
   class myItem{ int Id; Internal data;}
   class Internal {String name;}

Obviously I want to show the myItem.data.name in the Combobox, but I do not know how to get it. Furthermore what is the difference of DisplayMember and Value?

A: DisplayMember expects a public property not a private field
Change the classes:
class myItem
{
   public int Id {get; set}
   public Internal data {get;set;}
}

class Internal
{
   public string Name {get; set;}
}

Note also that the property names are case sensitive. So 'name' and 'Name' are considered to be different entities.
Further, if you are adding an object of 'myItem` class, you cannot get the combo box to access the a member of a member. You will have to do the fetching yourself:
class myItem
{
   public int Id {get; set}
   public Internal data {get;set;}

   public string Name { get { return data.Name; }}
}

Now by setting DisplayMember to "Name" it will reference the Name property of myItem which in turn accesses the data.Name property.
If the list comes to you from somewhere else (you don't own the list class and thus cannot modify it's code), you will have to wrap the objects inside another class and replace the list with a list of the wrapped objects:
class myItemWrapper
{
     private myItem _myItem;

     public myItemWrapper(myItem item)
     {
         _myItem = item;
     }

     public override string ToString()
     {
         return _myItem.data.Name;
     }

     public myItem Item { get { return _myItem;}}
}

then you can get rid of the DisplayMember assignment
box1.DisplayMember = "Name";

as the ToString() will be called instead.
but you have to replace the
box1.DataSource = itemData["ele1"];

with a bit more code:
var  wrapper = new List<myItemWrapper>();

foreach(var item in itemData["ele1"]);
   wrapper.Add(new myItemWrapper(item));

box1.DataSource = wrapper;

And don't forget that, when you are handling the selected item in the listbox that you are no longer dealing with myItem objects, but myItemWrapper objects instead. So to access the actual myItem object you will have to use the Item property of the myItemWrapper class instead.


text:
Q: How do you install packetfence? Was anyone able to install packetfence on Ubuntu 10.10? I tried a tutorial, but didn't have any luck. Some of the services installed and are working apache with php, snort, pfdetect, and pfdhcplistener. I can even get info from it, but for the life of me I can't get it to work with apache2.
When I run pfcmd service pf start I also get an error uninitialized value $_[7] in join at /usr/local/pf/lib/pf/class.pm line 170

A: Disclaimer: I work on the PacketFence project
It's complicated because of the interaction between PacketFence and the system components (apache, snmptrapd, named, dhcpd). As soon as the configuration files are not located in the same locations (/etc/httpd/ vs /etc/apache2/) we run into problems. It is not only a packaging issue, the code will have to be patched.
However, good timing for you, it's something we want to tackle soon. Here's a ticket where you can track our progress:
http://www.packetfence.org/bugs/view.php?id=1067
There will also be pointers to what is working and what is not. Feel free to chip in and help.

A: It looks like packetfence and it's related modules, needs to be packages for Debian. This isn't a hard job, since a lot of the modules are available with standard perl installers. But it would require each module to be built.
Once you've got a nice package of packetfence made up, you can apply the patch suggested in the tutorial which enables apache2 configuration.
I think that the web interface for packetfence needs upgrading to work with apache2 if it doesn't already work. This probably requires the attention of a developer.
Don't be shy asking for (or paying for) developers and packagers to help you get this installable for everyone. It's obviously something that needs doing:
http://www.debian-administration.org/articles/78


text:
Q: find out indices where numeric condition is met when data is str I have this array
x = np.array([['1', 'Nb v'],
              ['2', '2'],
              ['3', 'Nb v'],
              ['4','3']])

I want to find out the indices where the second column is greater than 2 .
That is the 3rd index (last line).
Because data are string, I can't just convert from string to int because I have problem with Nb v.
So, I thought to find out the indices where I don't have the word Nb v.
idx, = np.where(x[:, 1] != 'Nb v')

gives :
array([1, 3])

and then find the indices where  value is greater than 2:
new_idx, = np.where(x[idx, 1].astype(int) > 2)

gives :
array([1])

but that gives the index of idx where this happens, not the index of x.
I want to find out the index/indices of x where the second column is > 2.

A: A pure NumPy method, you can use np.char.isnumeric and np.where twice:
x_slice = x[:, 1]
x_int = np.where(np.char.isnumeric(x_slice), x_slice, 0).astype(int)
idx = np.where(x_int > 2.0)[0]

array([3], dtype=int64)

Or use np.where following by indexing:
x_numeric = np.where(np.char.isnumeric(x[:, 1]))[0]
idx = x_numeric[x[x_numeric, 1].astype(int) > 2]

A: You don't need the np.where the second time, you can slice directly idx:
idx, = np.where(x[:, 1] != 'Nb v')
print (idx[x[idx, 1].astype(int) > 2])
# array([3], dtype=int64)

A: Try if the string can be converted to an integer or not.
import numpy as np
x = np.array([['1', 'Nb v'],['2', '2'],['3', 'Nb v'],['4','3']])

for i,j in enumerate(x):
    try:
        a=int(j[1])
        if a>2:
            print(i)
    except:
        pass


text:
Q: How to interpret lock_time in the Aurora slow_query_logs? I have an Aurora Serverless instance running MySql 5.6, with an isolation level of READ-REPEATABLE and storage engine of InnoDB.
My understanding is that the only time a read transaction acquires a lock is when the SELECT statement ends with either FOR UPDATE or FOR SHARE. However, when looking at the AWS slow_query_logs, I see SELECT statements with a positive value for lock_time. According to the MySql docs, the lock_time is the time it takes for a transaction to acquire a lock. This is confusing as I am not expecting any locks for any SELECT statements not ending with FOR UPDATE or FOR SHARE.
If anyone has experience with Aurora and how to interpret the lock_time under the above conditions please share some insight. Thank you.


text:
Q: python function is not calling for every n seconds using threading.timer Class A:

  def get_data(self,arg1):

    ........

  def test(self):

    self.timer = threading.Timer(1,self.get_data, args=(arg1,))

    self.timer.start()
    ......

    self.timer.cancel()

While trying to call get_data(), for every one second, it is not calling.
Other part of the code is executing. No sytax or indentation errors are
observed. Please let me know the missing thing here.

A: That's because threading.Timer only calls the target function once (as documented here: https://docs.python.org/2/library/threading.html#timer-objects).
What you really want to do is create a threading.Thread instance whose target is a function with an endless loop that calls get_data and sleeps for 1 second.
And you want that loop to stop when a certain condition is reached -- like a running flag set to False. That way, you can stop the loop once you no longer need it to run.


text:
Q: Use javascript to open multiple windows and submit multiple requests on one button click I have a HTML file:

function runBatch() {

    document.form2.w_yyyymm.value=document.form1.w_yyyymm.value;
    window.open('', 'TheWindow2')
    document.form2.submit();

    document.form3.w_yyyymm.value=document.form1.w_yyyymm.value;
    window.open('', 'TheWindow3')
    document.form3.submit();

    document.form4.w_yyyymm.value=document.form1.w_yyyymm.value;
    window.open('', 'TheWindow4')
    document.form4.submit();
}
    <form name="form2" method="post" action="reportm02.do" ><input name="w_yyyymm" type="hidden" >
    <input name="method" value="view" type="hidden" >
    <input name="w_goods_id" value="9999" type="hidden" >
    </form>
    <form name="form3" method="post" action="reportm02.do" ><input name="w_yyyymm" type="hidden" >
    <input name="method" value="view" type="hidden" >
    <input name="w_goods_id" value="TX" type="hidden" >
    </form>
    <form name="form4" method="post" action="reportm02.do" ><input name="w_yyyymm" type="hidden" >
    <input name="method" value="view" type="hidden" >
    <input name="w_goods_id" value="TE" type="hidden" >
    </form>

    <input type="button" name="Submit3" value="run batch" onClick="runBatch();" >

Either Form submit will get a xls file , So I want to get all xls files on click one button. I try ajax but all fail~ How can I do? Thank you !!

function ajaxSubmit(form)
{
    var f = form;
    var postData = [];
    for (var i = 0; i < f.elements.length; i++) {
        postData.push(f.elements[i].name + "=" + f.elements[i].value);
    }
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "reportm02.do", true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.send(postData.join("&"));
}

function runBatch() {

    ajaxSubmit(document.form2);
    ajaxSubmit(document.form3);
    ajaxSubmit(document.form4);
}

.. But no xls file download to client side.
I also try the following code but still not work:

// Download a file form a url.
function saveFile(url) {
  // Get file name from url.
  var filename = url.substring(url.lastIndexOf("/") + 1).split("?")[0];
  var xhr = new XMLHttpRequest();
  xhr.responseType = 'blob';
  xhr.onload = function() {
    var a = document.createElement('a');
    a.href = window.URL.createObjectURL(xhr.response); // xhr.response is a blob
    a.download = filename; // Set the file name.
    a.style.display = 'none';
    document.body.appendChild(a);
    a.click();
    delete a;
  };
  xhr.open('GET', url);
  xhr.send();
}

A: I try the following code:
http://danml.com/download.html
And include the download.js from it as following:
 <script language="JavaScript" src="js/download.js"></script>
    <Script language="JavaScript">

        function saveFile(url,filename) {
            //
              // Get file name from url.
              //var filename = url.substring(url.lastIndexOf("/") + 1).split("?")[0];
            var x=new XMLHttpRequest();
            x.open("GET", url, true);
            x.responseType = 'blob';
            x.onload=function(e){download(x.response, filename, "text/plain" ); }
            x.send();
            }

        function runBatch() {
            if (!date_check_yyyymm(document.form1.w_yyyymm, "申報年月")) {
                return false;
            }

           saveFile("ReportMIB.do?method=view&w_yyyymm="+document.form1.w_yyyymm.value+"&w_goods_id=9999","880103_"+document.form1.w_yyyymm.value+"_9999.xls" )
           saveFile("ReportMIB.do?method=view&w_yyyymm="+document.form1.w_yyyymm.value+"&w_goods_id=TX","880103_"+document.form1.w_yyyymm.value+"_TX.xls" )
           saveFile("ReportMIB.do?method=view&w_yyyymm="+document.form1.w_yyyymm.value+"&w_goods_id=TE","880103_"+document.form1.w_yyyymm.value+"_TE.xls" )
           .....

            }

    </script>

This will work on the Chrome browser but IE and firefox.


text:
Q: Examples of Extreme Anti-Choice Axioms Axiom of Choice has many variants like the followings:

*

*There is a choice set for every family of non-empty sets.

*All sets are well-orderable.

Of course in many cases one don't need AC to prove existence of a choice set or well-ordering for a particular family or set. In such cases one can prove these facts in ZF.

Question: What are examples of set theoretic axioms which violate the axiom of choice badly? I mean examples of axioms which imply non-existence of choice sets (or well-orderings) on almost all families of non-empty sets (or sets) which existence of a choice set (or well-ordering) on them is not provable in ZF.

As it stated in comments, $AD$ is certainly a classic example of an anti-choice axiom. However I would like to know about other variants of such axioms and also the intuition behind them which illustrates why these axioms are violating $AC$ badly not merely implying $\neg AC$ which is possible just by producing a single set which has no well-ordering.

A: Well, you will always have a proper class of families with a choice function, so in what sense do we mean almost all? Here are a few interpretations.

*

*You could say, every family can be extended to one that doesn't have a choice function. But that is really just the failure of $\sf AC$. Fix one counterexample, and use that.
Other variants like "...by adding a countable family of pairs" equally just mean the failure of the axiom of choice for that type of families.

*You could say, the power set of every infinite set cannot be well-ordered. Since $X$ can be well-ordered if and only if there is a choice function from $\mathcal P(X)\setminus\{\varnothing\}$ this means that taking power sets ensures that an infinite set cannot be well-ordered.
But look closely, this just means that $\Bbb R$ cannot be well-ordered.

*You could say, one of the most basic families we know are enumerations of ordinals. So the failure to choose from there is considered quite severe. For example, it could be the case that we cannot choose an enumeration for each countable ordinal uniformly. This is true in the Solovay model, or in models were $\omega_1$ is singular. But similar things are true in models of $\sf AD$ where many successors are singular, while simultaneously
In fact this can be extended to the Gitik model where each successor cardinal has cofinality $\omega$ (so every limit cardinal too). And in that model we have some sort of absolute failure of countable choice.

*You could say, I want to take Gitik's work one step further. One question left open by Gitik is the consistency of Specker's $\sf (K)$ principle stating that $\mathcal P(\kappa)$ is the countable union of sets of size $\kappa$ for every infinite cardinal. In the Gitik model this is false since $\Bbb R$ is not the countable union of countable sets (but rather the countable union of countable unions of countable sets).
This too, in some (stronger) sense is some sort of absolute failure of countable choice.

*You could say, that you want to have countable choice fails in a bizarre way. Douglas Morris constructed a model which has the same cofinality structure as its $L$ (or whichever ground model you started with), but there was no bound on the cardinality of countable unions. Namely, for every ordinal $\alpha$, there is a set $X$ which is the countable union of countable sets, and $\mathcal P(X)$ can be mapped onto $\alpha$.
Morris did this from an inaccessible, but remarks in the announcement of the result (Notices of AMS 17 (1970), p. 577) that this use can probably be dispensed. This would be a weaker global failure of countable choice, but nonetheless a severe failure. For one, there is no way to extend this model to a model of choice without adding ordinals.

*You could say, let's go a different direction altogether. In the absence of choice we define cardinals of non-well orderable sets as those sets of least rank which were realized from that cardinality (namely, $|A|=\{B\mid\text{ there is a bijection }f\colon A\to B\land\operatorname{rank}(B)\text{ is minimal}\}$).
It is consistent that the axiom of choice fails and you cannot choose representatives for these classes. Namely, there is no function $C$ such that $|C(A)|=|A|$ for all $A$, and whenever $|A|=|B|$ we have $C(A)=C(B)$. It is consistent that such function exists, though. But this is some sort of failure which is hard to quantify in terms of almost all families, but rather "obvious" families.

*In a relatively similar way to the previous one, not quite a global failure as a local but strange failure. If you consider Spector's model for having the club filter of $\omega_1$ as an ultrafilter without large cardinals, the axiom of countable choice fails there. The reason is that the countable intersection of clubs of $\omega_1$ is always a club, but the existence of a countably complete ultrafilter implies a measurable.
The reason is that there is a sequence of sets, each contains a club, but we cannot choose uniformly a club for each one.
The list can probably be extended in several other directions. For my money, I'd go for Gitik's model or theoretically for Specker's $\sf (K)$ (whose consistency, as far as I know, remains open for now).


text:
Q: Is this correct usage of move semantics I have a function call
class MyClass {
    static std::string getName(void) {
        return getMyName(void); // Returning by value as well
    }
};

Now if I use this function in constructor of a class
class AnotherClass {
public:
    AnotherClass(void) :
        m_name(std::move(MyClass::getName())) {} // 1. std::move used

    const std::string& name(void) const {   // 2. Should I use std::string&& (without consts)
                                            //    .... but I also need to make sure value cannot be changed (e.g, name() = "blah";)
                                            //    if std::string&& will be used should I use it simply by calling name() to call function using move or should I leave it as is?
        return m_name;
    }
private:
    std::string m_name;
}

Is this correct usage of move semantics? How can I ensure a function is using move semantics?
I am trying to learn to implement efficiency by move semantics so apology if its dumb question.
I have checked
What are move semantics?
http://www.cprogramming.com/c++11/rvalue-references-and-move-semantics-in-c++11.html
Is this correct usage of C++ 'move' semantics?
a great explanation but need clarafication on ensuring if function is using move semantics.

A: There is no need to use std::move here:
   m_name(std::move(MyClass::getName())) {} // no need to use std::move

getName() returns a copy, which is already an rvalue.
Just do this like you normally would:
   m_name(MyClass::getName()) {}

The move constructor will be used automatically, if it is needed at all.  (The compiler may very well omit the copy altogether and construct the return value of MyClass::getName() directly into m_name, which is even better).
As for this:
const std::string& name() const { return m_name; }

there is no need to do anything special here either.  You don't want m_name to be changed, so you shouldn't use std::move, and you should be using a regular const lvalue reference.
The most common situation where you need std::move is when you are creating your own move constructor:
class AnotherClass {
public:
    AnotherClass(AnotherClass &&that) :
        m_name(std::move(that.m_name))
    {
    }
};

This is because even though that is declared as an rvalue reference, inside the constructor, that behaves like a regular lvalue reference.


text:
Q: link_to in .js.erb file For some reason, when I use link_to in my show.js.erb file, the javascript does not work...
This works:
$(".commentvotecount<%= params[:commentid]%>").html("<%= positiveVoteCount = @comment.plusminus %>");

This doesn't:
$(".commentvotecount<%= params[:commentid]%>").html("<%= positiveVoteCount = @comment.plusminus %> <%= link_to 'About', '/about' %>");

What is going wrong?
Thank you.

A: use escape_javascript so quotes are escaped.
$(".commentvotecount<%= params[:commentid]%>").html("<%= escape_javascript link_to('About', '/about') %>");


text:
Q: Average number of distinct values Let $q$ such that $q < n$. I pick at random $n$ values in $\mathbb{F}_q$.
What is the average number of distinct values ?
Thank you

A: Imagine that the picking is done one at a time, with replacement. Define random variable $X_i$ by $X_i=1$ if the object chosen at stage $i$ is different from all the objects chosen at stages $\lt i$. Let $X_i=0$ otherwise.
Then the number of distinct objects is $\sum_1^n X_i$.
So our mean is $\sum E(X_i)$.
For $E(X_i)$, the probability that $X_i=1$, this does not depend on the object picked at stage $i$. Let it be $1$. We want the probability that none of the objects chosen in stages $1$ to $i-1$ is equal to $1$. The probability of this is $\left(1-\frac{1}{q}\right)^{i-1}$. Now add up the geometric series, $i=1$ to $n$.

A: Each value in $\mathbb F_q$ is not drawn with probability $(1-q^{-1})^n$ hence the average number of distinct values in a sample of size $n$ is $q\cdot(1-(1-q^{-1})^n)$.
For example, when $q\to\infty$, the average number of distinct values in a sample of size $c\cdot q$ is approximately $(1-\mathrm e^{-c})\cdot q$.


text:
Q: String of 10 randomly chosen digits -- probability question Given a string of 10 randomly and independently chosen digits from 1-9.  Let N be the number of digits missing from the sequence.  Calculate expectation and variance of N.

A: Outline: Define random variable $X_i$ by $X_i=1$ if digit $i$ is missing, and $X_i=0$ otherwise. Then the number $N$ of digits missing is given by
$$N=X_1+X_2+\cdots +X_9.$$
By the linearity of expectation, we have
$$E(X_1+\cdots +X_9)=E(X_1)+\cdots +E(X_9).$$
For each $i$, the probability $i$ is missing is $\left(\frac{8}{9}\right)^{10}$.  Thus the expected number missing is $9\left(\frac{8}{9}\right)^{10}$.
For the variance, note that if $N$ is the number of digits missing, then
$$\text{Var}(N)=E(N^2)-(E(N))^2.$$
So we will be finished if we can find $E(N^2)$. By linearity, this is the sum of the $E(X_i^2)$, plus the sum of the $E(X_iX_j)$, as $(i,j)$ runs over all pairs with $i\ne j$.
The $E(X_i^2)$ are easy, since $X_i^2=X_i$.
For $XiX_j$ with $i\ne j$, we have $X_iX_j=1$ unless $i$ and $j$ $i$ are both missing. So $\Pr(X_iX_j=1)=\left(\frac{7}{9}\right)^{10}$.
Now put the pieces together.


text:
Q: Failed to process phase POST_MODULE of deployment I am deploying in jboss a simple web app with one servlet, a jsp file and an ease EJB. This is the code of the servlet:
package webejb;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ejb.Convert;
import java.math.BigDecimal;

import javax.ejb.EJB;
import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class test extends HttpServlet {
private static final long serialVersionUID = 1L;
@EJB(name = "ejb/Convert")
private Convert converter;
/**
 * @see HttpServlet#HttpServlet()
 */
public test() {
    super();
    // TODO Auto-generated constructor stub
}

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    String amount = request.getParameter("amount");
    if (amount != null && amount.length() > 0) {
        BigDecimal d = new BigDecimal(amount);
        BigDecimal rupeeAmount = converter.dollarToRupees(d);
        out.println("<p>" + amount + " Dollars are " + rupeeAmount + " Rupees.<p>");
        BigDecimal euroAmount = converter.rupeesToEuro(rupeeAmount);
        out.println(amount + " Dollars are " + euroAmount + " Euro.");
    }
}

When i include at the beginning of the class the annotation   @WebServlet("/test") a get this error:
10:12:21,253 INFO  [org.jboss.as.server] (DeploymentScanner-threads - 2) JBAS015870:
Deploy of deployment "WebEJB.war" was rolled back with failure message {"JBAS014671:
Failed services" => {"jboss.deployment.unit.\"WebEJB.war\".POST_MODULE" =>
"org.jboss.msc.service.StartException in service jboss.deployment.unit.\"WebEJB.war
\".POST_MODULE: Failed to process phase POST_MODULE of deployment \"WebEJB.war\""}}

And do not leave me deploy the app, when a erase the annotation all works.

A: I already discover my mistake. The problem was that i didn't know that i must deploy an EAR with the WAr end EJB.


text:
Q: How to delete a write protected file? When I try to delete an write protected file, I get an UnauthorizedAccessException. Permissions are fine, I can delete the file, if I remove the write-protection-box in Explorer->File properties.
How can I delete the file anyway?

A: As long as you have enough rights on that file (permissions), you can remove all attributes on that file and then delete it:
var fileName = "c:\\temp\\test.txt"
// Handle write protected files: Remove all special attributes.
File.SetAttributes(fileName, FileAttributes.Normal);
File.Delete(fileName);


text:
Q: Maximum/Minimum of a quadratic form on the unit sphere Prove that, the maximum/minimum of the quadratic form
$$
f(x, y, z)=A x^{2}+B y^{2}+C z^{2}+2 D y z+2 E z x+2 F x y
$$
on the unit sphere surface
$$
x^{2}+y^{2}+z^{2}=1
$$
is exactly the corresponding max/min eigenvalue of the matrix
$$
\Phi=\left(\begin{array}{lll}
A & F & E \\
F & B & D \\
E & D & C
\end{array}\right)
$$
I don't even know where to start. Can anyone help?

A: The key fact is that every real symmetric matrix is orthogonally diagonalisable, i.e. we can express $\Phi$ as $Q\Lambda Q^T$, where $Q$ is an orthogonal matrix and $\Lambda=\operatorname{diag}(\lambda_1,\lambda_2,\lambda_3)$ is a diagonal matrix whose diagonal entries the eigenvalues of $\Phi$. The proof of this fact can be found in most introductory texts on linear algebra.
Since $Q$ is orthogonal, $(x,y,z)\mapsto(u,v,w):=(x,y,z)Q$ is a bijective mapping on the unit sphere. Hence
$$
\max_{x^2+y^2+z^2=1}f(x,y,z)
=\max_{x^2+y^2+z^2=1}\pmatrix{x&y&z}\Phi\pmatrix{x\\ y\\ z}
=\max_{u^2+v^2+w^2=1}\pmatrix{u&v&w}\Lambda\pmatrix{u\\ v\\ w}
$$
and the rest should be straightforward.


text:
Q: Computing the union-closure of a finite discrete set You must excuse my notation if it is not stndard,
I have my background in Computer Science and not in Math.
Hope this topic still is in the right forum.
Let $U = {1,2,...,n}$ be our finite universe.
Let $\mathcal{F}$ be a family of subsets of $U$.
The union-closure of $\mathcal{F}$ is the unique minimal family $\mathcal{C}_{\mathcal{F}}$ such that:

*

*Every element in $\mathcal{F}$ is in $\mathcal{C}$.

*For every pair of elements in $\mathcal{C}$ their union is also in $\mathcal{C}$.

I have a couple of questions regarding the union-closure.

*

*How fast can we compute the union-closure?
It can be done in $O(|\mathcal{C}| \cdot \log{|\mathcal{C}|} \cdot n^2)$.

*Can we bound $\log_2{|\mathcal{C}|}/n$ as $n$ goes to infinite?
The set system can be modelled as a bipartite graph
(sets on one side and U on the other edges)
Then we can make a lower and upper bound based on the Maximum Matching
and Maximum Induced Matching (equivalent to VC-dimension).
Does anyone know of work related to this?