text:
Q: Uniqueness of conjugates of a subgroup. This question is partly influenced by the question:
Are two subgroups that contain a common element conjugate iff they are conjugate under the normalizer?
If we have an arbitrary finite group $G$ and radical $p$-subgroups $A,B\leq G$ (so $A=O_{p}(N_{G}(A),p)$, $B=O_{p}(N_{G}(B),p)$ and the normalizers of $A$ and $B$ in $G$ are thus parabolic subgroups) such that $A\leq B\leq N_{G}(B)\leq N_{G}(A)\leq G$ (where $p\in\pi(G)$), is it the case that there is a unique conjugate of $A$ contained in $B$?
Clearly $A$ is normal in $B$, but I cannot seem to prove that there cannot be an elemnet $g\in G\setminus N_{G}(A)$ such that $A^{g}\ne A$ and $A^{g}\leq B$. Equally I have not found an example where uniqueness does not hold. Any hints would be greatly appreciated.
Edit:
Initially the question did not state that $A$ and $B$ were radical subgroups, as a greater understanding of the more general situation as deemed to be desirable.

A: It is true for groups of Lie type in defining characteristic
A unipotent subgroup of a connected, reductive linear algebraic group is called radical if it is the unipotent radical of its normalizer. One version of the Borel–Tits theorem is that the radical subgroups are the unipotent radicals of the parabolic subgroups. Hence the radical subgroups of a fixed Borel subgroup are indexed by subsets of the positive roots, and so we have the rather convenient $A \leq B \implies N_G(B) \leq N_G(A)$ whenever $A,B$ are radical subgroups of a connected, reductive linear algebraic group.  Alperin's fusion theorem (for unipotent subgroups of a connected, reductive linear algebraic group) shows that whenever $\langle A,A^g \rangle$ is unipotent, there are radical subgroups $B_i$ and elements $g_i \in N_G(B_i)$ such that $A^{g_1 \cdots g_{i-1}} \leq B_i$ and $g = g_1 \cdots g_n$. In particular, if $A$ itself is radical and $\langle A,A^g \rangle$ is unipotent, then $A=A^g$ since all the $g_i \in N_G(B_i) \leq N_G(A)$. In other words, every radical subgroup of a connected, reductive linear algebraic group is weakly closed in every maximal unipotent subgroup containing it.
It is false in general
However, when $G$ has a characteristic different from $p$ (or has no characteristic), then things loosen up considerably. We no longer have $A \leq B \implies N_G(B) \leq N_G(A)$ for radical subgroups, and this allows us to focus attention on the "wrong" $B$, while another $B$ takes care of the conjugation. $\newcommand{\Sym}{\operatorname{Sym}}\newcommand{\PSL}{\operatorname{PSL}}$
A few infinite families of counterexamples for $p=2$ include $\Sym(n)$ for at least half of $n\geq 7$, and $\operatorname{PSL}(3,q)$ for $|q| \geq 5$ odd. I assume counterexamples are quite common in general, but there appear to be a lot of "small exceptions" to my assumption, so beware.
For $G=\Sym(7)$, let $A=\langle (1,2) \rangle$, which has order 2 and normalizer $A \times \Sym(\{3,4,5,6,7\})$ and let $B=\langle (1,2), (3,4), (5,6), (3,5)(4,6) \rangle$ be a self-normalizing Sylow 2-subgroup. Clearly $A$ has many $G$-conjugates in $B$, including $\langle (3,4) \rangle$ and $\langle (5,6) \rangle$. This does not contradict Alperin's fusion theorem, since the conjugation that takes $A$ to $\langle (5,6) \rangle$ does not have to rely  only on the subgroup $B$. A similar construction works for most $n$: if $2,3 \equiv n \mod 4$ then more or less the exact construction works. I am a little unclear on how easily $\Sym(9)$ works while $\Sym(8)$ does not work at all.
For $G=\PSL(3,q)$, ($|q| \geq 5$ an odd prime power, $\PSL(3,-|q|) = \operatorname{PSU}(3,|q|)$ being the unitary group), there are two cases for the proof, but the choice of $A$ and $B$ is the "same."  Take $B$ to be a Sylow 2-subgroup and $A=Z(B)$ to be its center. For $q=1 \mod 4$, $B$ is a "wreathed" Sylow 2-subgroup, and $A=Z(B)$ is the "diagonal" subgroup of the base of $B$. $A$ is $G$-conjugate to all the direct factors of the base, but obviously is normal in $N_G(B)$.  Again this does not contradict Alperin's fusion theorem, since $A$ is contained in the base of $B$, a radical subgroup whose normalizer does not normalize $A$.  For $3 \equiv q \mod 4$, $B$ is quasi-dihedral and $A=Z(B)$ has order 2. $A$ is contained in a radical Klein 4-subgroup with full fusion, but any larger radical subgroup has smaller normalizer. I'm not entirely certain I understand why $q=3$ is an exception.


text:
Q: Using slidemenu: sliding back and padding don't work I am using the following library for my sliding menu (https://github.com/bk138/LibSlideMenu) in my app.
In my app the sliding menu works. I can slide from right to left and the menu will appear. But the problem is that when I am in the menu I can't slide back to the fragment were I came from.
The only way to get back is using back button. Also when you are in the menu I don't have the padding on the right where you see the previous fragment on the background.
I am searching for it like days. I have searched the example for the problem but couldn't find the essential thing that i am forgetting.
My main activity:
public class MainActivity extends SlidingFragmentActivity {

private Fragment rFrag;

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

    if (savedInstanceState != null)
        rFrag = getSupportFragmentManager().getFragment(savedInstanceState, "mContent");
    if (rFrag == null)
        rFrag = new RecentGridFragment();

    FragmentTransaction fragment = getSupportFragmentManager().beginTransaction();

    fragment.replace(R.id.content_frame, rFrag);

    MenuFragment mFrag = new MenuFragment();
    fragment.replace(R.id.menu_frame, mFrag);
    fragment.commit();

    //Sliding menu
    SlidingMenu sMenu = new SlidingMenu(this);
    sMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
    sMenu.setShadowWidthRes(R.dimen.shadow_width);
    sMenu.setShadowDrawable(R.drawable.shadow);
    sMenu.setBehindScrollScale(0.25f);
    sMenu.setFadeDegree(0.25f);
    sMenu.setSlidingEnabled(true);
    sMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // TODO Auto-generated method stub
    return super.onCreateOptionsMenu(menu);
}
@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    getSupportFragmentManager().putFragment(outState, "mContent", rFrag);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        toggle();
    }
    return super.onOptionsItemSelected(item);
}
public void switchContent(final Fragment inputFrag) {
    rFrag = inputFrag;
    FragmentTransaction fragment = getSupportFragmentManager().beginTransaction();
    fragment.replace(R.id.content_frame, inputFrag);
    fragment.commit();
    Handler h = new Handler();
    h.postDelayed(new Runnable() {
        public void run() {
            getSlidingMenu().showContent();
        }
    }, 50);
}}

Menu:
public class MenuFragment extends ListFragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.list, null);
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    String[] birds = getResources().getStringArray(R.array.birds);
    ArrayAdapter<String> colorAdapter = new ArrayAdapter<String>(getActivity(),
            android.R.layout.simple_list_item_1, android.R.id.text1, birds);
    setListAdapter(colorAdapter);
}}

The mainfragment that has the content
public class RecentGridFragment extends Fragment {

private int mImgRes;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    mImgRes = R.drawable.peacock;

    GridView gv = (GridView) inflater.inflate(R.layout.list_grid, null);
    gv.setBackgroundResource(android.R.color.black);
    gv.setAdapter(new GridAdapter());
    return gv;
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
}

private class GridAdapter extends BaseAdapter {

    @Override
    public int getCount() {
        return 30;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = getActivity().getLayoutInflater().inflate(R.layout.grid_item, null);
        }
        ImageView img = (ImageView) convertView.findViewById(R.id.grid_item_img);
        img.setImageResource(mImgRes);
        return convertView;
    }

}}

A: I have found my mistake:
I need to get the slidingactivity instead of making a new one.
SlidingMenu sMenu = this.getSlidingMenu();

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unwanted margins in Button I am trying to make a simple grid of 5 columns and 11 rows of squares with regular spacing between them that will work on all the resolutions. As you can see in the image I get squares alright (in red) but there is space between the rows. When I click on this "empty" space a button gets selected. Which is strange, as if there was some invisible margins or paddings on top and bottom of the button.
            <ScrollViewer x:Name="myScrollViewer">
                <Grid x:Name="aGrid" Background="#FF8AC731" >
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*" x:Name="aColumn"/>
                        <ColumnDefinition Width="*"/>
                        <ColumnDefinition Width="*"/>
                        <ColumnDefinition Width="*"/>
                        <ColumnDefinition Width="*"/>
                    </Grid.ColumnDefinitions>

                    <Grid.RowDefinitions>
                        <RowDefinition MinHeight="50" x:Name="aRow" />
                        <RowDefinition MinHeight="{Binding ActualWidth, ElementName=aColumn}"/>
                        <RowDefinition MinHeight="{Binding ActualWidth, ElementName=aColumn}"/>
                        <RowDefinition MinHeight="{Binding ActualWidth, ElementName=aColumn}"/>
                        <RowDefinition MinHeight="{Binding ActualWidth, ElementName=aColumn}"/>
                        <RowDefinition MinHeight="{Binding ActualWidth, ElementName=aColumn}"/>
                        <RowDefinition MinHeight="{Binding ActualWidth, ElementName=aColumn}"/>
                        <RowDefinition MinHeight="{Binding ActualWidth, ElementName=aColumn}"/>
                        <RowDefinition MinHeight="{Binding ActualWidth, ElementName=aColumn}"/>
                        <RowDefinition MinHeight="{Binding ActualWidth, ElementName=aColumn}"/>
                        <RowDefinition MinHeight="{Binding ActualWidth, ElementName=aColumn}"/>
                    </Grid.RowDefinitions>
        <!-- **********First Column**************-->
                    <!-- a-->
                    <Button Grid.Row="0" Grid.Column="0" Background="#FFF32929" BorderThickness="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MinWidth="50" Padding="0"  Margin="1" >
                        <Image Grid.Column="0" Grid.Row="0" Source="Assets/hiraganas/hiragana-bold-table_01 a.png" Canvas.ZIndex="100"/>
                    </Button>

...

A: Yes, there are indeed margins on the standard button.
You can apply a custom style to your buttons.
The following button style has no margins, and works in WP7 (it might need tweaking for WP8.) Put it in your app.xaml and then set the style when you use the button with Style="{StaticResource CustomButtonStyle}"
<Application.Resources>
           <Style x:Key="CustomButtonStyle" TargetType="Button">
                <Setter Property="Background" Value="Transparent"/>
                <Setter Property="BorderBrush" Value="{StaticResource PhoneForegroundBrush}"/>
                <Setter Property="Foreground" Value="{StaticResource PhoneForegroundBrush}"/>
                <Setter Property="BorderThickness" Value="{StaticResource PhoneBorderThickness}"/>
                <Setter Property="FontFamily" Value="{StaticResource PhoneFontFamilySemiBold}"/>
                <Setter Property="FontSize" Value="{StaticResource PhoneFontSizeMediumLarge}"/>
                <Setter Property="Padding" Value="0"/>
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="Button">
                            <Grid Background="Transparent">
                                <VisualStateManager.VisualStateGroups>
                                    <VisualStateGroup x:Name="CommonStates">
                                        <VisualState x:Name="Normal"/>
                                        <VisualState x:Name="MouseOver"/>
                                        <VisualState x:Name="Pressed">
                                            <Storyboard>
                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentContainer">
                                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneBackgroundBrush}"/>
                                                </ObjectAnimationUsingKeyFrames>
                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="ButtonBackground">
                                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneForegroundBrush}"/>
                                                </ObjectAnimationUsingKeyFrames>
                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="ButtonBackground">
                                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneForegroundBrush}"/>
                                                </ObjectAnimationUsingKeyFrames>
                                            </Storyboard>
                                        </VisualState>
                                        <VisualState x:Name="Disabled">
                                            <Storyboard>
                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentContainer">
                                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneDisabledBrush}"/>
                                                </ObjectAnimationUsingKeyFrames>
                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="ButtonBackground">
                                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneDisabledBrush}"/>
                                                </ObjectAnimationUsingKeyFrames>
                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="ButtonBackground">
                                                    <DiscreteObjectKeyFrame KeyTime="0" Value="Transparent"/>
                                                </ObjectAnimationUsingKeyFrames>
                                            </Storyboard>
                                        </VisualState>
                                    </VisualStateGroup>
                                </VisualStateManager.VisualStateGroups>
                                <Border x:Name="ButtonBackground" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" CornerRadius="0" Margin="0">
                                    <ContentControl x:Name="ContentContainer" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" Foreground="{TemplateBinding Foreground}" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" Padding="{TemplateBinding Padding}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/>
                                </Border>
                            </Grid>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>

    </Application.Resources>

A: Button comes default with 12px margin, here is the style template of the offending Margin
<Border x:Name="ButtonBackground" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" CornerRadius="0" Margin="{StaticResource PhoneTouchTargetOverhang}">

Margin="{StaticResource PhoneTouchTargetOverhang}

Full Style override
<Style x:Key="Chubs_Style" TargetType="Button">
    <Setter Property="Background" Value="Transparent"/>
    <Setter Property="BorderBrush" Value="{StaticResource PhoneForegroundBrush}"/>
    <Setter Property="Foreground" Value="{StaticResource PhoneForegroundBrush}"/>
    <Setter Property="BorderThickness" Value="{StaticResource PhoneBorderThickness}"/>
    <Setter Property="FontFamily" Value="{StaticResource PhoneFontFamilySemiBold}"/>
    <Setter Property="FontSize" Value="{StaticResource PhoneFontSizeMedium}"/>
    <Setter Property="Padding" Value="10,5,10,6"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Grid Background="Transparent">
                    <VisualStateManager.VisualStateGroups>
                        <VisualStateGroup x:Name="CommonStates">
                            <VisualState x:Name="Normal"/>
                            <VisualState x:Name="MouseOver"/>
                            <VisualState x:Name="Pressed">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentContainer">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneButtonBasePressedForegroundBrush}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="ButtonBackground">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneAccentBrush}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="Disabled">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentContainer">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneDisabledBrush}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="ButtonBackground">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneDisabledBrush}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="ButtonBackground">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="Transparent"/>
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                        </VisualStateGroup>
                    </VisualStateManager.VisualStateGroups>
                    <Border x:Name="ButtonBackground" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" CornerRadius="0" Margin="0">
                        <ContentControl x:Name="ContentContainer" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" Foreground="{TemplateBinding Foreground}" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" Padding="{TemplateBinding Padding}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/>
                    </Border>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

A: Could it be with Margin -10 up and down?
            <Button Grid.Row="0" Grid.Column="0" Background="#FFF32929" BorderThickness="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MinWidth="50" Margin="1,-10" >
                <Image Grid.Column="0" Grid.Row="0" Source="Assets/hiraganas/hiragana-bold-table_01 a.png" Canvas.ZIndex="100"/>
            </Button>

As I know Buttons have margins by themselves


text:
Q: Add header to SOAP message I need add custom soap header, like login
I do it in way like this
class Foo implements SOAPHandler<SOAPMessageContext> {
    public boolean handleMessage(SOAPMessageContext context) {
        try {
            SOAPMessage soapMsg = context.getMessage();
            SOAPEnvelope soapEnv = soapMsg.getSOAPPart().getEnvelope();
            soapEnv.addHeader().addAttribute(new QName("login"), "bob");

            soapMsg.writeTo(System.out);//tracing OUT
            return true;
        } catch (SOAPException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

@HandlerChain(file="handler-chain.xml")//I describe Foo in this file
public class GreeterService

By tracing out I get message
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Header login="bob"/><S:Body><ns2:sayGoodbye xmlns:ns2="http://example.com/"><arg0>SOAP</arg0></ns2:sayGoodbye></S:Body></S:Envelope>

with header
 <S:Header login="bob"/>

But server received it without any header
 <?xml version="1.0" ?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><ns2:sayGoodbye xmlns:ns2="http://example.com/"><arg0 xmlns="">SOAP</arg0></ns2:sayGoodbye></S:Body></S:Envelope>

What I make wrong?

A: I had the similar issue few days ago, there was a need to send user id by header.
I resolved this problem with special parameter - wsimport -XadditionalHeaders  when generating code.


text:
Q: VB6 PDF printing on webserver This is a strange one and is a bit tricky to explain.
We have a website that creates PDF files for users. We already have a DLL from another application that allows us to create the PDF files with what we want in them and are trying to utilize this in our website to avoid a lengthy re-write of said DLL code. The catch is the DLL is in VB6. We are having the issue that when the user clicks print the moment our DLL touches the printer then we get an exception (but only if there is no user logged onto the webserver).
We have a similar thing in the .NET code that runs doing a smaller job but essentially it's the same thing, and this appears to work fine.
Has anyone done or seen anything like this and do they have any idea if what we are doing can be done and if so where we would look in an attempt to fix the issue.


text:
Q: Sage Pay form integration encoding
<form name="pp_form" action="https://test.sagepay.com/Simulator/VSPServerGateway.asp?Service=VendorRegisterTx" method="post">
    <input name="VPSProtocol" type="hidden" value=2.23 />
    <input name="TxType" type="hidden" value=PAYMENT />
    <input name="Vendor" type="hidden" value="myusername" />
    <input name="VendorTxCode" type="hidden" value="thevendortxcode" />
    <input name="Amount" type="hidden" value="30" />
    <input name="Currency" type="hidden" value="GBP" />
    <input name="Description" type="hidden" value="Test payment" />
    <input name="NotificationURL" type="hidden" value="myurl" />
    BillingFirstnames: <input name="BillingFirstnames" type="text" />

    BillingSurname: <input name="BillingSurname" type="text" />

    BillingAddress1: <input name="BillingAddress1" type="text" />

    BillingCity: <input name="BillingCity" type="text" />

    BillingPostCode: <input name="BillingPostCode" type="text" />

    BillingCountry: <input name="BillingCountry" type="text" />

    DeliverySurname: <input name="DeliverySurname" type="text" />

    DeliveryFirstnames: <input name="DeliveryFirstnames" type="text" />

    DeliveryAddress1: <input name="DeliveryAddress1" type="text" />

    DeliveryCity: <input name="DeliveryCity" type="text" />

    DeliveryPostCode: <input name="DeliveryPostCode" type="text" />

    DeliveryCountry: <input name="DeliveryCountry" type="text" />

Click here to submit
        <input type="submit" value="here">

</form>

This form currently works using the simulator. Clearly, none of this is being encoded. Firstly, will this work on the test/live environment? Secondly, am I allowed to do it this way and if not, how can I correct it?
Thanks
Alex

A: It's not going to work. Firstly, the simulator is so far out of date that it doesn't even support protocol 3.00 (earlier ones are deprecated and will cease to function in the live environment from July). Some key features are also missing.
Secondly, you appear to want to use the Server protocol. The registration post for this consists of the values you have above as name-value pairs, posted as the request body to https://test.sagepay.com/gateway/service/vspserver-register.vsp
I recommend having a look at the Server protocol document on sagepay.co.uk - using the simulator isn't going to help.


text:
Q: Require user to go through login screen before giving access to iPhone app? On iPhone, how do I show a login screen to get username and password before giving access to iPhone app?  Also, does the iPhone store a cookie to the secure website like a web browser?
I was thinking of giving users to my website a long API key to store in the settings of their iPhone instead of asking them to login with a username/password (seems to be the Slicehost iPhone app approach.)  Which is the best way to get a user to login securely?  I have full control over the design of the iPhone app and website so have a lot of flexibility.

A: I have this need in a couple of apps, and I use the following pattern:
In the controller for the first view that gets presented to the user, I have the following test, where UserPrefsManager is a singleton that knows the user credentials.  This call causes a modal view to appear (FirstTimeWelcomeViewController) which tells the person that they need to register.
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    UserPrefsManager * prefs = [UserPrefsManager sharedInstance];
    if (![prefs isLoggedIn])
    {
        FirstTimeWelcomeViewController * vc = [[[FirstTimeWelcomeViewController alloc] initWithNibName:@"FirstTimeWelcomeViewController" bundle:nil] autorelease];
        [self presentModalViewController:vc animated: false];
    }
    else
    {
        if (![[RWXLocationSingleton sharedInstance] hasLocation]) {
            [[RWXLocationSingleton  sharedInstance] findLocationWithAccuracy:kCLLocationAccuracyThreeKilometers withObject:self andSelector:@selector(updateLocationsView)];
        }
        [[self tableView ]reloadData];
    }
}
FirstTimeWelcomeViewController is basically a screen with buttons that greets people and takes them to the various ways to log in:
-(IBAction) createAccount
{
    UIViewController * parent = [self parentViewController];
    CreateAccountViewController * vc = [[[CreateAccountViewController alloc] initWithNibName:@"CreateAccountViewController" bundle:nil] autorelease];
    [self dismissModalViewControllerAnimated:false];
    [parent presentModalViewController:vc animated: false];
}
imagine that these also exist for forgotPassword, and loginACcount... same pattern.  This causes the current view to be replaced by a view handling the specific case that they've pressed the button for.
taking the 'loginAccount' method, you've opened the LoginAccountViewController, and it has a method called loginButton, which works something like this...
-(IBAction) loginButton
{
    NSString * u = [self.username text];
    NSString * p = [self.password text];

        //
        // app specific logic that tests various inputs and creates a user object.
        //
        // goes here...
        //

        if([user checkValid])
    {
       UserPrefsManager * prefs = [UserPrefsManager sharedInstance];
       [prefs setPassword:p];
       [prefs setUsername:u];
       [self dismissModalViewControllerAnimated:FALSE];
    }
        //
        // more app specific stuff
        //
}

And that's pretty much that.  You have to use one of the standard ways for putting stuff in the keychain or user defaults to save your information.  check that the one you pick lasts between restores if it is something that is annoying for the user to recreate.  The first part is the most useful bit, thought the rest might be useful for context.

A: I'd recommend looking at a technology such as OAuth (http://oauth.net/). This enables the user to authorize access to their account to an application without having to actually enter their username and password into it. Also means you dont have to worry about secure storage of the users credentials, and if their passwords change etc it doesn't matter.
It's used by facebook / twitter and a lot of other big name companies so its not going away (Its actually in the process of getting approved as an offical standard).

A: You can't restrict access to the app itself but it is trivial to present an initial view that ask for the username and password. If the user does not present the correct information then the app will not allow them to progress to the next view which actually loads the web site.
Likewise, it would be trivial to store a key in the app's sandboxed folders such that neither the user nor anyone else could access it save through the app.


text:
Q: Customization of the InputField on the FormPage I want to understand how to set up input fields on the pages so that you can insert large texts. How can I make Input Field the higher? For example for this code:
CloudDeploy[
    FormPage[{"text"->"String"},
    Column[StringSplit[#text]]&]
]

I can use the custom controls:
FormPage[
    {"text100x100" ->
    <|
        "Interpreter"->"String",
        "Control"->InputField[#, FieldSize-> {100,100}]&
    |>},
    Column[StringSplit[#text100x100]]&
]

But it does not work:


text:
Q: Java SLF4J→Logback→Logstash→Datadog— Host, Service, and Source? Java app, built with Gradle, implementing SLF4J and Logback, exporting with Logstash to Datadog agentless logging.
Can't seem to get the host, service, or source properties to transmit:

build.gradle
implementation 'ch.qos.logback:logback-classic:1.2.3'
implementation 'net.logstash.logback:logstash-logback-encoder:6.6'
implementation 'org.slf4j:log4j-over-slf4j:1.7.13'
implementation 'org.slf4j:slf4j-api:1.7.5'

logback.xml
Note where I've included the <host> and <service> tags. I also tried <property name=".." value=".."> and <KeyValuePair key="service" value="java-app" /> to no avail.
<appender name="JSON_TCP" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
  <remoteHost>intake.logs.datadoghq.com</remoteHost>
  <service>my-favorite-service</service>
  <host>${HOSTNAME}</host>
  <port>10514</port>
  <keepAliveDuration>20 seconds</keepAliveDuration>
  <encoder class="net.logstash.logback.encoder.LogstashEncoder">
    <prefix class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
      <layout class="ch.qos.logback.classic.PatternLayout">
        <pattern>abc123abc123abc123abc123abc123 %mdc{keyThatDoesNotExist}</pattern>
      </layout>
    </prefix>
  </encoder>
</appender>

Docs
Here are the docs I'm reading from Datadog:

*

*https://docs.datadoghq.com/logs/log_collection/java/?tab=log4j#agentless-logging

*https://docs.datadoghq.com/tracing/connect_logs_and_traces/java?tab=log4j2

*https://www.datadoghq.com/blog/java-logging-guide/

*https://docs.datadoghq.com/logs/log_collection/?tab=host

*https://docs.datadoghq.com/getting_started/tagging/unified_service_tagging/?tab=kubernetes
Also, the docs for logstash-logback-encoder itself states:
By default, each property of Logback's Context (ch.qos.logback.core.Context) will appear as a field in the LoggingEvent.

By default, each property of Logback's Context (ch.qos.logback.core.Context) will appear as a field in the LoggingEvent.

So, how do I add a property to Logback's Context?

A: This is what I've got so far. Everything but the source.

import ch.qos.logback.classic.LoggerContext;

// Add context to logs
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
lc.setPackagingDataEnabled(true);
lc.putProperty("source", "java");
lc.putProperty("service", "thing-doer");
lc.putProperty("host", "prd1.do.things"));
lc.putProperty("env", "production");


text:
Q: Dashboards de usuários logados utilizando user do django admin Bom Dia
Estou utilizando o model de users padrão do Django, e gostaria de ter um dashboard de usuários logados, para verificar quem esta utilizando o sistema, sabem me informar se o django possui essa informação?
Eu verifiquei que possuem uma tabela de sessões mas esta tudo criptografado.
Desde já obrigada

A: Que eu veja dá pra fazer isso de duas formas:

*

*Salvar alguma informação dos clientes atualmente ativos no banco de dados

*Utilizar javascript para fornecer esses dados em tempo real

1º Opção
Esses links para pesquisa podem te ajudar nesse quesito:

*

*Django Signals - Fornece uma maneira de observar certos acontecimentos como o loggin e o logout

*Link com um exemplo da funcionalidade que vc queira executar(Obs.: Exemplo de código não tão recente. Talvez seja necessário realizar mudanças em relação a versão do código): Exemplo do Django Signals
2º Opção
Javascript atualmente fornece API's para aplicações que necessitam de funcionalidades que se comunicam em tempo real e talvez seja outra possibilidade de resolver seu problema fazendo alguma verificação quando o usuário logar e o javascript comunicar isso ao backend.

*

*Biblioteca que pode ser útil: Socket.io

*Exemplo de implementação da comunicação em tempo real(Obs.: está com o backend em Node.js mas a lógica talvez de dê uma luz): Exemplo de comunicação em tempo real)

A: É um método assíncrono, você pode registrar em um modelo próprio tanto o login quanto o logout do usuário, salvando esta informação antes de chamar as funções login() (registra que o usuário entrou) e logout() (registra que os usuário saiu) durante o processo de autenticação.


text:
Q: Could this ever cause a segmentation error message? If I have the following code, could a segmentation error ever be caused?
 #include <stdio.h>
 #include <stdlib.h>

int main() {
    int i;
    int n = 30;

    while(i < n) {
            printf("%d ", i);
            if(i % 3 == 0) {
            n--;
            } else {
            n = n -2;
            }
   i = i + 2;

    }
return 0;
}

When I ran it, I don't get any segmentation errors but I also don't get any output. And are we always to assume that integer i could be any number in memory? I understand that it will not be initialized to 0, correct?

A: Yes for local variable (which is allocated in the stack, the value is undefined)
See answer: What happens to a declared, uninitialized variable in C? Does it have a value?
if "int i" was declared outside the main (as a global or static variable, it would be zero and your output would be as follows
"0 2 4 6 8 10 12 14 16"
So this code is unlikely to cause seg fault, though compilers can chose to crash. But you are not really accessing out of bounds memory, just some value on the stack. In the case i was a pointer, and you tried to dereference it, then it most likely could cause a seg fault.

A:
When I ran it, I don't get any segmentation errors but I also don't
  get any output. And are we always to assume that integer i could be
  any number in memory during that time?

The value of i is indeterminate. So using uninitialized variables leads to undefined behavior.So there is a possibility of a crash because of undefined behavior. Yes the value of i can be anything

I understand that it will not be initialized to 0, correct?

Yes an unintialized variable is a unintialized one it doesn't have any assured value until you set it explicitly. (There are exceptions like global/static which are intilialized to 0)
The below link might help:
(Why) is using an uninitialized variable undefined behavior?


text:
Q: Formtastic: Validation error messages not translating locale template vars to value Rails v2.3.8
formtastic v1.1.0
Forms draw correctly, validation works, but the validation messages for anything involving the length of a string are showing up as:
is too short (minimum is {{count}} characters)

Basically {{count}} is not getting filled in. In irb, I can see that the value is in the @options of the ActiveRecord::Errors:
>> u.errors
=> #<ActiveRecord::Errors:0x7f98785b4ab0 @errors=#<OrderedHash {"password"=>[#<ActiveRecord::Error:0x7f9878561b30 @type=:too_short, @options={:default=>nil, :count=>4},...

Note that this is a validation on a User model being performed by authlogic v2.1.6 (which may not be relevant).
--- UPDATE --------- :
After some more digging, I copied the en.yml locale file out of the activerecord-2.3.8 gem dir and into my local app config/locales dir. After changing all the {{count}} to %{count} things are now displaying properly.
Maybe a bug with formtastic v1.1.1 working with rails v2.3.8? The changelog speaks to a few things generally that it could possibly fall under.  There are several newer versions of formtastic available. I unfortunately cannot upgrade this environment so I am going to setup another to test the newer formtastic versions.

A: Messages that display things like {{count}} and also {{model}} and {{attributes}} have been seen a lot recently and can also be due to servers having Rails3 apps on them.
There are a couple of common fixes:
1) Bump up from 2.3.8 to 2.3.9 or 2.3.10  Very minor change, should not affect anything else (though test of course). So just change your rails version in environment.rb
2) include the gem for a version specific il8n, e.g. (0.4.2), in environment.rb, add a line for:
gem il8n, :version => '0.4.2'
bundler can help a lot too, Though standard with Rails3, I believe the steps to change an existing 2.3.x app to use it (isn't that what you usually need to know?) are as follows.
Well, obviously install it, prob. gem install bundler
then take (eventually deleting them there) all your existing 'gem...' statements from your environment.rb file and put them in a Gemfile then with commands like:
bundle install
or
bundle update
you can create a 'bundle'.
The above command create a Gemfile.lock that has the versions you're using.
Also if you have multiple cucumber versions or issues tests running in IDE's the next commands may be needed:
bundle exec cucumber features/user_can_login.feature
or
bundle exec cucumber features/user_can_login.feature:6   (specific line number).


text:
Q: Moving files from one SQL Server to another through FTP by using a stored procedure and bulk copy program (bcp) utility Below is the procedure I am trying to write:

*

*First I need to generate a file in the SQL Server 1 with some data that can be queried from the same server

*Then I need to move the file to a FTP server from SQL Server 1, from there I need to fetch the details of the file from SQL Server 2.
How can I do with the help of the bcp utility?

A: Create a file in sql server with queried data
    DECLARE @FileName varchar(1000),@bcpCommand varchar(1000),
            @FileGeneratePath varchar(100)
    DECLARE @exe_path4 VARCHAR(200) = ' cd C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\110\Tools\Binn & ';

    Set @FileGeneratePath = '\\192.168.XX.XXX\Files\'
    Set @FileName = REPLACE('SampleFile'+ CONVERT(varchar(10),GETDATE(),100)+'.xls',' ','') --'\\192.168.29.111\Files\authors'+ Convert(varchar(40),Getdate(),121) + '.csv'

    SET @bcpCommand = @exe_path4 +' bcp.exe "SELECT top 10 * from [192.168.XX.XXX].DATABASE.dbo.FamilyAccountDetails where Convert(varchar(10),LastUpdatedon,100)  > Convert(varchar(10),Getdate()-30,100)" queryout "'
    SET @bcpCommand = @bcpCommand + @FileGeneratePath + @FileName + '" -c -t"|" -Uusername -Ppassword -S192.168.XX.XXX'

    EXEC master..xp_cmdshell @bcpCommand, no_output

exe_path4  is the path of bcp exe.
For more details of bcp utility check this. and also this
xp_cmdshell is an extended stored procedure and it allows you to execute an operating system command via a SQL Statement. Extended stored procedures are programs written in langauges like C++ that are then attached to an instance of SQL Server. Once attached, they can be referenced just like a regular stored procedure.
no_output in the xp_cmdshell act like set nocount on.
Stored procedure to move a file from sql server to an ftp
In the below store procedures , i created a text file to execute in command prompt to move file to the ftp and vice versa. Both files generated in the SQL Server temp folder, not in the local temp. you can also give a particular folder for the file generation.
/*
    Exec spPullFileToFTP
    @FTPServer = '192.168.YY.YYY' ,
    @FTPUser = 'username' ,
    @FTPPWD = 'password' ,
    @SourcePath = '\\192.168.YY.YYY\Files\' ,
    @SourceFiles = 'SampleFileJan16201.xls' ,
    @DestPath = 'FileToCopy/New/'

        */
Create Procedure spPullFileToFTP
 @FTPServer varchar(128),
 @FTPUser varchar(128),
 @FTPPwd varchar(128),
 @SourcePath varchar(128),
 @SourceFiles varchar(128),
 @DestPath varchar(128),
 @FTPMode varchar(10)=''
as

Set Nocount On

SET @FTPMode = 'binary' -- ascii, binary or blank for default.

DECLARE @cmd varchar(1000)
DECLARE @workfile varchar(128)
DECLARE @nowstr varchar(25)

-- Get the %TEMP% environment variable.
DECLARE @tempdir varchar(128)
CREATE TABLE #tempvartable(info VARCHAR(1000))
INSERT #tempvartable EXEC master..xp_cmdshell 'echo %temp%'
SET @tempdir = (SELECT top 1 info FROM #tempvartable)
IF RIGHT(@tempdir, 1) <> '\' SET @tempdir = @tempdir + '\'

DROP TABLE #tempvartable

-- Generate @workfile
SET @nowstr = replace(replace(convert(varchar(30), GETDATE(), 121), ' ', '_'), ':', '-')
SET @workfile = 'FTP_SPID' + convert(varchar(128), @@spid) + '_' + @nowstr + '.txt'

-- Deal with special chars for echo commands.
select @FTPServer = replace(replace(replace(@FTPServer, '|', '^|'),'<','^<'),'>','^>')
select @FTPUser = replace(replace(replace(@FTPUser, '|', '^|'),'<','^<'),'>','^>')
select @FTPPwd = replace(replace(replace(@FTPPwd, '|', '^|'),'<','^<'),'>','^>')
select @DestPath = replace(replace(replace(@DestPath, '|', '^|'),'<','^<'),'>','^>')
IF RIGHT(@SourcePath, 1) <> '\' SET @SourcePath = @SourcePath + '\'

-- Build the FTP script file.
select @cmd = 'echo ' + 'open ' + @FTPServer + ' > ' + @tempdir + @workfile
EXEC master..xp_cmdshell @cmd

select @cmd = 'echo ' + @FTPUser + '>> ' + @tempdir + @workfile
EXEC master..xp_cmdshell @cmd

select @cmd = 'echo ' + @FTPPwd + '>> ' + @tempdir + @workfile
EXEC master..xp_cmdshell @cmd

select @cmd = 'echo ' + 'prompt ' + ' >> ' + @tempdir + @workfile
EXEC master..xp_cmdshell @cmd

IF LEN(@FTPMode) > 0
BEGIN
 select @cmd = 'echo ' + @FTPMode + ' >> ' + @tempdir + @workfile
 EXEC master..xp_cmdshell @cmd

END
IF LEN(@DestPath) > 0
BEGIN
 select @cmd = 'echo ' + 'cd ' + @DestPath + ' >> ' + @tempdir + @workfile
 EXEC master..xp_cmdshell @cmd

END
select @cmd = 'echo ' + 'mput ' + @SourcePath + @SourceFiles + ' >> ' + @tempdir + @workfile
EXEC master..xp_cmdshell @cmd
print @cmd
select @cmd = 'echo ' + 'quit' + ' >> ' + @tempdir + @workfile
EXEC master..xp_cmdshell @cmd

-- Execute the FTP command via script file.
select @cmd = 'ftp -s:' + @tempdir + @workfile
create table #a (id int identity(1,1), s varchar(1000))
insert #a
EXEC master..xp_cmdshell @cmd
select id, ouputtmp = s from #a

-- Clean up.
drop table #a
select @cmd = 'del ' + @tempdir + @workfile
EXEC master..xp_cmdshell @cmd
go

**Output File **
open 192.168.YY.YYY
Username
Password
prompt
binary
cd FileToCopy/AdvisoryPortal/
mput \\192.168.YY.YYY\Files\SampleFileJan16201.xls
quit

Stored Procedure to move a file from ftp to SQL Server
/*
    exec spPullFileFromFTP
    @FTPServer = '192.168.YY.YYY' ,
    @FTPUser = '11111' ,
    @FTPPWD = 'FtpPassword' ,
    @SourcePath = '/FileToCopy/Sample/' ,
    @SourceFiles = 'SampleFileJan12201.xls' ,
    @DestPath = '\\192.168.XX.XXX\Files\New\'

        */
Create procedure spPullFileFromFTP
 @FTPServer varchar(128),
 @FTPUser varchar(128),
 @FTPPwd varchar(128),
 @SourcePath varchar(128),
 @SourceFiles varchar(128),
 @DestPath varchar(128),
 @FTPMode varchar(10)=''
as
Begin

    SET @FTPMode = 'binary' -- ascii, binary or blank for default.

    DECLARE @cmd varchar(1000)
    DECLARE @workfile varchar(128)
    DECLARE @nowstr varchar(25)

    -- Get the %TEMP% environment variable.
    DECLARE @tempdir varchar(128)
    CREATE TABLE #tempvartable(info VARCHAR(1000))
    INSERT #tempvartable EXEC master..xp_cmdshell 'echo %temp%'
    SET @tempdir = (SELECT top 1 info FROM #tempvartable)
    IF RIGHT(@tempdir, 1) <> '\' SET @tempdir = @tempdir + '\'
    DROP TABLE #tempvartable

    -- Generate @workfile
    SET @nowstr = replace(replace(convert(varchar(30), GETDATE(), 121), ' ', '_'), ':', '-')
    SET @workfile = 'FTP_SPID' + convert(varchar(128), @@spid) + '_' + @nowstr + '.txt'

    -- Deal with special chars for echo commands.
    select @FTPServer = replace(replace(replace(@FTPServer, '|', '^|'),'<','^<'),'>','^>')
    select @FTPUser = replace(replace(replace(@FTPUser, '|', '^|'),'<','^<'),'>','^>')
    select @FTPPwd = replace(replace(replace(@FTPPwd, '|', '^|'),'<','^<'),'>','^>')
    select @SourcePath = replace(replace(replace(@SourcePath, '|', '^|'),'<','^<'),'>','^>')
    IF RIGHT(@DestPath, 1) = '\' SET @DestPath = LEFT(@DestPath, LEN(@DestPath)-1)

    -- Build the FTP script file.
    select @cmd = 'echo ' + 'open ' + @FTPServer + ' > ' + @tempdir + @workfile
    EXEC master..xp_cmdshell @cmd
    select @cmd = 'echo ' + @FTPUser + '>> ' + @tempdir + @workfile
    EXEC master..xp_cmdshell @cmd
    select @cmd = 'echo ' + @FTPPwd + '>> ' + @tempdir + @workfile
    EXEC master..xp_cmdshell @cmd
    select @cmd = 'echo ' + 'prompt ' + ' >> ' + @tempdir + @workfile
    EXEC master..xp_cmdshell @cmd

    IF LEN(@FTPMode) > 0
    BEGIN
        select @cmd = 'echo ' + @FTPMode + ' >> ' + @tempdir + @workfile
        EXEC master..xp_cmdshell @cmd
    END

    select @cmd = 'echo ' + 'lcd ' + @DestPath + ' >> ' + @tempdir + @workfile
    EXEC master..xp_cmdshell @cmd

    IF LEN(@SourcePath) > 0
    BEGIN
        select @cmd = 'echo ' + 'cd ' + @SourcePath + ' >> ' + @tempdir + @workfile
        EXEC master..xp_cmdshell @cmd
    END

    select @cmd = 'echo ' + 'mget '  + @SourceFiles + ' >> ' + @tempdir + @workfile
    --select @cmd = 'echo ' + 'mget ' + @SourcePath + @SourceFiles + ' >> ' + @tempdir + @workfile
    EXEC master..xp_cmdshell @cmd

    select @cmd = 'echo ' + 'quit' + ' >> ' + @tempdir + @workfile
    EXEC master..xp_cmdshell @cmd

    -- Execute the FTP command via script file.
    select @cmd = 'ftp -s:' + @tempdir + @workfile
    create table #a (id int identity(1,1), s varchar(1000))
    insert #a
    EXEC master..xp_cmdshell @cmd
    select id, ouputtmp = s from #a

    -- Clean up.
    drop table #a
    select @cmd = 'del ' + @tempdir + @workfile
    EXEC master..xp_cmdshell @cmd

End

**Output File **
open 192.168.YY.YYY
Username
Password
prompt
binary
lcd \\192.168.XX.XXX\Files\New
cd /FileToCopy/AdvisoryPortal/
mget SampleFileJan12201.xls
quit

If any doubts in the commands, please check this.
To bulk copy from file to Database table
        Declare @SQL varchar(500)
        set @SQL = 'BULK INSERT  BGL_CRM_FamilyAccountDetails  FROM '+''''+'//192.168.YY.XXX/Files/New/'+ @FileName +''''+
        ' WITH (DATAFILETYPE =' +''''+'char' +''''+', FIELDTERMINATOR = '+''''+'|'+''''+', ROWTERMINATOR = '+''''+'\n'+''''+')'

        EXEC(@SQL)


text:
Q: how to do 3d matrix to 3d multiplication in python without loops? I am doing segmentation part in my project, where I need to multiply a 3 dimensional mask to a color image.
What am doing now:
maskedFrame=np.zeros((rgbFrame.shape))
maskedHsvFrame=np.zeros((rgbFrame.shape))
for color in range(0,3):
    maskedFrame[:,:,color]=rgbFrame[:,:,color]*biscuitMask
    maskedHsvFrame[:,:,color]=hsvFrame[:,:,color]*biscuitMask

Is it possible to multiply without any loops in python?

A: AFAIK, numpy can braodcast biscuitMask along the color dimension to fit the shape of the frame.
This broadcasting is done automatically. Thus,
maskedFrame = rgbFrame * biscuitMask
maskedHsvFrame = hsvFrame * biscuitMask

Should work without any loops or modifications.
PS,
If you are familiar with matlab, broadcasting is very much like applying bsxfun only numpy does it automatically for you.


text:
Q: AngularJS with html5 color input - set value dynamically I have an input with type color defined in my controller scope:
HTML:
<div ng-controller="MyCtrl">
    <input type="color" value="#f0f0f0" />
    <input type="color" value={{getColor()}} />
</div>

JS:
function MyCtrl($scope) {
    $scope.getColor = function () {
        return "#f0f0f0";
    };
}

The problem is the color don't get updated when its set by Angular, although when inspecting I see this:

See: FIDDLE.
How to update html5 input color dynamically?

A: Try to bind it to your controller with ng-model instead of value.
function MyCtrl($scope) {
    $scope.mycolor = "#f0f0f0";

    $scope.$watch('mycolor', function(newVal) {
        console.log('newVal ' + newVal);
    });
}

Here is updated and working fiddle.

A: You don`t even need a $watch, just a $timeout.
function MyCtrl($scope, $timeout) {
    $timeout(() => {
        $scope.mycolor = "#f0f0f0";
    })
}

working fiddle http://jsfiddle.net/3ukL3suf/


text:
Q: Почему метод выводит только последний элемент массива? Само задание:
Есть класс Cat с полем имя (name, String).
Создать коллекцию HashMap.
Добавить в коллекцию 10 котов, в качестве ключа использовать имя кота.
Вывести результат на экран, каждый элемент с новой строки.
public static void main(String[] args) throws Exception {
    String[] cats = new String[]{"васька", "мурка", "дымка", "рыжик", "серый", "снежок", "босс", "борис", "визя", "гарфи"};

    HashMap<String, Cat> map = addCatsToMap(cats);

    for (Map.Entry<String, Cat> pair : map.entrySet()) {
        System.out.println(pair.getKey() + " - " + pair.getValue());
    }
}

public static HashMap<String, Cat> addCatsToMap(String[] cats) {
    HashMap<String, Cat> map = new HashMap<String, Cat>();
    String name = "Vaskya";
    for(int i = 0; i < cats.length; i++) {
       map.put(name, new Cat(cats[i]));
    }
    return map;
}

public static class Cat {
    String name;

    public Cat(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name != null ? name.toUpperCase() : null;
    }
}

Вывод:
Vaskya - ГАРФИ

A:
map.put(name, new Cat(cats[i]));

map.put(cats[i], new Cat(cats[i]));


text:
Q: Export GridView to Excel using Matt's util code
(a bit edited for Unicode text)
    public class GridViewExportUtil
{
    /// <param name="fileName"></param>
    /// <param name="gv"></param>
    public static void Export(string fileName, GridView gv)
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ContentType = "application/ms-excel";
        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        HttpContext.Current.Response.Charset = System.Text.Encoding.Unicode.EncodingName;
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Unicode;
        HttpContext.Current.Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
        HttpContext.Current.Response.AddHeader(
             "content-disposition", string.Format(//"content-disposition",
                "attachment; filename=Report.xml"));//, fileName)); // Need .XLS file

        using (StringWriter sw = new StringWriter())
        {
            using (HtmlTextWriter htw = new HtmlTextWriter(sw))
            {
                //  Create a form to contain the grid
                Table table = new Table();

                //  add the header row to the table
                if (gv.HeaderRow != null)
                {
                    GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);
                    table.Rows.Add(gv.HeaderRow);
                }

                //  add each of the data rows to the table
                foreach (GridViewRow row in gv.Rows)
                {
                    GridViewExportUtil.PrepareControlForExport(row);
                    table.Rows.Add(row);
                }

                //  add the footer row to the table
                if (gv.FooterRow != null)
                {
                    GridViewExportUtil.PrepareControlForExport(gv.FooterRow);
                    table.Rows.Add(gv.FooterRow);
                }

                //  render the table into the htmlwriter
                table.RenderControl(htw);

                //  render the htmlwriter into the response
                HttpContext.Current.Response.Write(sw.ToString());
                HttpContext.Current.Response.End();
            }
        }
    }

    /// <summary>
    /// Replace any of the contained controls with literals
    /// </summary>
    /// <param name="control"></param>
    private static void PrepareControlForExport(Control control)
    {
        for (int i = 0; i < control.Controls.Count; i++)
        {
            Control current = control.Controls[i];
            if (current is LinkButton)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
            }
            else if (current is ImageButton)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
            }
            else if (current is HyperLink)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
            }
            else if (current is DropDownList)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
            }
            else if (current is CheckBox)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
            }

            if (current.HasControls())
            {
                GridViewExportUtil.PrepareControlForExport(current);
            }
        }
    }

Question : How to make downloaded file editable (not Read only)
And ... XLS wont opens with Unicode format. When I changing format to UTF8 I can't see Russian words :S
Second question : How to make Unicode for .xls
Third question : How can I save table lines ?
Thank you.
4 - how to create table in the NPOI sheet
            int i =0;
            if (gv.HeaderRow != null)
            {
                GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);
                sheet1.CreateRow(1).CreateCell(i).SetCellValue(gv.HeaderRow.ToString());
                //table.Rows.Add(gv.HeaderRow);
                i++;
            }

like it ?

A: HTML is not the same thing as XML.
The SpreadsheetML language used by Excel 2002/2003 is a completely different language. If you even get Excel to open the file, it's only because it tends to recognize HTML files regardless of the file extension.
As for the Unicode issue, I think the problem is your StringWriter's Encoding setting when calling ToString().
I recommend looking into the NPOI project, which contains everything you need to create binary/BIFF (Excel 97/2000), SpreadsheetML (Excel 2002/2003), and OOXML (Excel 2007) files from .NET:
http://npoi.codeplex.com/


text:
Q: Download deb packages with download manager instead of apt? Hi there I know that deb packages I downloaded are in: /var/cache/apt/archives/
And I can save them for future use. However, there is a problem when I download a package using the apt-get command, download speed is too slow. When I download files with a download manager I can get up to 1MB/s!
How can I get the URL of the package and download it with a download manager?

A: You can find the packages you want to download (and their dependencies) on the Ubuntu Packages site. Though it's not recommended - you should be able to gather the links from there and use a download manager to retrieve them.

Dependencies are listed first, then the download section is shown below the related packages
If you're having slow download times from the official mirrors - try updating your mirror location as it may be that the particular mirror you're fetching from is far away or having latency issues.

A: synapitc allows you to save url download list, then you can supply it to download manager. you can also save your selection. later load the download list to synaptic.


text:
Q: Specifiy sslmode in Bitnami Keycloak Helm chart I'm currently working on redirecting an existing Keycloak instance to an existing (but empty) PostgreSQL database. To deploy Keycloak we are using the Bitnami Helm chart, which worked great so far. My only problem is that I cannot find an option to specify sslmode=require in the chart.
I've specified the database options in the values.yml like this (credentials are being added at a later stage):
externalDatabase:
  host: host
  port: 5432
  database: postgres

I've tried adding it to the database name like database: postgres?sslmode=require but that messed up Keycloaks process to recognize it being a PostgreSQL database and resulted in Keycloak using its h2 database.
Since I'm able to connect to that database with my local keycloak instance, I tried deploying a 'ready-to-go' standalone-ha.xml to the pod and then tried changing the KEYCLOAK_CONF_FILE value in the values.yml:
extraEnvVars:
  - name: 'KEYCLOAK_CONF_FILE'
    value: '/custom/standalone-ha.xml'

But that didn't work either.
Disabling SSL is not an option.
Update:
Since KEYCLOAK_CONF_FILE seemed to be the wrong variable, I've tried using KEYCLOAK_MOUNTED_CONF_DIR and added my prebuild standalone-ha.xml to it. Apparently that didn't work either.

A: I've created a github issue here: https://github.com/bitnami/charts/issues/6217
It seems like the feature doesn't exist.


text:
Q: Import Contact From Yahoo Using Angularjs??Any Sample code? I'm trying to find any tutorial or resources to import contacts from Yahoo. For example, you are asked to authenticate via Yahoo and then you can select the contacts(emails) to import. Thanks for any help.

A: Perhaps satellizer is a good option.
https://github.com/sahat/satellizer


text:
Q: What is the use of @relayhash value in graphql JS I am performing code review on one of the source codes.
While going through a JS file (graphql.js) I found a value "@relayhash" along with some hash value as below:
@relayHash 00950038252b25a368700738a31fled7
I am not sure what this relay hash value is generally used for. Is it a threat from security perspective to display this public source code.

A: While I'm not sure how the hash is calculated exactly (I suspect some combination of the contents of the fragments in the component and the schema definitions) it does use this hash to determine if a warning should be displayed if the compiled Relay files (.graphql.js) are not up to date with the schema.graphql/schema.json definitions.
In summary, not a security risk, it is instead used to display a helpful warning message when developing an application using Relay when files are out of date.


text:
Q: Setting default value to user extended field in Modx Basically I want the value of a TV (a.k.a. Template Variable) to default to the value of a user's extended field. I tried making a snippet named get_author with the following content:
$user = $modx->getUser();
if (!$user) return '';
    $profile = $user->getOne('Profile');
if (!$profile) return '';
    $extended = $profile->get('extended');
return(isset($extended['author_page'])) ? $extended['author_page'] : '';

And add the following code to a TV's default value property:
@EVAL return $modx->runSnippet('get_author');

It looks like the code itself works, but the value doesn't default to the desired value until the user clicks the 'set to default' button in the manager. But when I fill in a static value like 8 (so without the @eval) the value immediately defaults on form load. Can anyone tell me how this has to be done?
Thanks in advance!

A: It is not possible, the way you trying this. The default value is calculated during rendering the template variable and not during saving the resource, only clicking on set to default will help as you mentioned above.
There are two solutions possible: Set the template variable value to the value in a plugin running on OnDocFormSave
$user = $modx->getUser());
($user) {
  $profile = $user->getOne('Profile');
  if ($profile) {
    $extended = $profile->get('extended');
    if (isset($extended['author_page'])) {
      $resource->setTVValue('my_tv', $extended['author_page']);
    }
  }
}

or run your code in a snippet 'AuthorPage' that uses the value of createdby or editedby as userId parameter.
$output = '';

$userId = $modx->getOption('userId', $scriptProperties, 0);
$user = $modx->getUser($userId);
($user) {
  $profile = $user->getOne('Profile');
  if ($profile) {
    $extended = $profile->get('extended');
    if (isset($extended['author_page'])) {
      $output = $extended['author_page'];
    }
  }
}
return $output;

Call that snippet like this:
[[AuthorPage? &userId=`[[*createdby]]`]]


text:
Q: Woocommerce Rest API - How to add new response? I am trying to insert the $addresscustom to the Woocommerce REST API, but it displays the Error:
> I/flutter (19003): FormatException: Unexpected character (at character 1)
> I/flutter (19003): <style type="text/css"> .wp-die-message {display: none; }
> I/flutter (19003): ^

Why it is saying the response is not json decoded (Flutter FormatException: Unexpected character (at character 1)), when it is indeed decoded? For instance, when I use the code 2, it works and displays the URL in the REST API:
The code:
function get_address_store( $response, $order_obj, $request, $object) {
    if( empty( $response->data ) )
        return $response;

    $order = WC_Order(  $order_obj->get_order_number() );
    $items = $order->get_items();
    foreach ( $items as $item ) {
        $product_id = $item['product_id'];
        $itemdata = $item->get_data();
        $item_id = $itemdata['id'];
    }

    $gift_wrap = wc_get_order_item_meta(    $item_id, 'anbieter',true);
    $vendor_data_new = get_page_by_title($gift_wrap, '', 'wpsl_stores');
    $addresscustom = get_post_meta( $vendor_data_new->ID, 'wpsl_address', true );

    $response->data['line_items'][0]['store_address'] = $addresscustom;
    return $response;
}
add_filter( "woocommerce_rest_prepare_shop_order_object","get_address_store", 10, 3 );

Code 2 (working):
function get_product_order_image( $response, $object, $request ) {
    if( empty( $response->data ) )
        return $response;

    $order_pid= $response->data['line_items'][0]['product_id'];
    $l_w_product_meta = get_post_meta($order_pid);
    $order_imgUrl= wp_get_attachment_url( $l_w_product_meta['_thumbnail_id'][0], 'full' );

    $response->data['line_items'][0]['cover_image'] = $order_imgUrl;
    return $response;
}
add_filter( "woocommerce_rest_prepare_shop_order_object","get_product_order_image", 10, 3 );

Thanks for taking a time to read it :)


text:
Q: Unty Canvas not representative of actual layout I have a canvas on the screen which for some reason is very small compared to my scene. I have a major issue placing UI components in the correct place on the canvas so that they appear in the correct place on the actual game screen.
If you take a look at the 2 attached screen grabs it may make more sense.

the issue I have is that when I run this on my 1080p tv the text does not get positioned correctly at all. if I place it as in the first image then it ends up 8 squares from the top and 15 squares from the right, if I place it as in the second image then it appears 12 squares from the top and 21 from the right.....
I just want the text to be near the top corner.
How do I get the edit screen and actual game to match positioning?

A: Ok, along with some pointers from Catwood above I worked out the issue. I had not set the canvas to stretch with screen!
So it was placing the text correctly it was just that the canvas was staying a fixed size rather than filling the screen.

A: Thats exactly why you have to debug your game with your actual anticipated aspect ratio. This must be set explicitly and it can change alot about your game as the canvas can change itself drastically to accomidate.

A: On your canvas, set the Canvas Scaler component's Ui Scale Mode to Scale with Screen Size. Then you can define a Reference Resolution of 1080p, i.e. 1920 x 1080.
To see the canvas fit into the camera's size in the scene, change the Canvas component's Render Mode to Screen Space - Camera, and drag the camera from the hierarchy to it.


text:
Q: Why isn't VS Code respecting TypeScript paths? In my TypeScript project that's running tests via ts-node and jasmine I have defined some paths in tsconfig.json
{
  "compilerOptions": {
      "baseUrl": "src",
      "target": "es5",
      "module": "commonjs",
      "lib": [
          "es5",
          "es2015",
          "DOM"
      ],
      "moduleResolution": "Node",
      "outDir": "./dist/cjs",
      "declaration": true,
      "sourceMap": true,
      "esModuleInterop": true,
      "forceConsistentCasingInFileNames": true,
      "noImplicitAny": false,
      "removeComments": true,
      "strict": true,
      "paths": {
            "@common": ["common/index"],
            "@crashes": ["crashes/index"]
      }
  },
  "files": [
      "./src/index.ts"
  ]
}

I am able to import via paths @common and @crashes in my production code, but for some reason VS Code gives me the error Cannot find module '@common' or its corresponding type declarations. in my spec.ts files.
How can I get VS Code to recognize TypeScript paths in my tests?

A: This is because VS Code's intellisense will follow the rules in tsconfig.json. In this instance, I was not including the spec.ts files in the TypeScript compilation. Additionally, I did not want to include the TypeScript files in my project's build output.
The solution was as follows:

*

*Remove the files property from tsconfig.json

*Introduce a new tsconfig.dist.json that extends tsconfig.json and add the files property here

{
    "extends": "./tsconfig.json",
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "outDir": "./dist/cjs",
    },
    "files": [
        "./src/index.ts"
    ]
  }

*Use the new tsconfig.dist.json in the publish script

Additionally, once I did all this, I got the following error when I tried to run jasmine tests with ts-node:
> ts-node node_modules/jasmine/bin/jasmine --config=spec/support/jasmine.spec.json

Error: Cannot find module '@common'

The solution to this error was to install tsconfig-paths and update my test script in package.json
{
   "scripts": {
        "test": "ts-node -r tsconfig-paths/register node_modules/jasmine/bin/jasmine --config=spec/support/jasmine.spec.json"
    }
}


text:
Q: Safe authentication in codeigniter I'm trying to roll my own authentication system in codeigniter, and have stumbled onto a couple of roadblocks.
If I have the sessions set to use a database, is userdata stored in the database alone or in the cookie as well? I'd like to store the hashed password in it to verify each page load that a user is actually logged in with the correct pass, and I do not want the hash to be accessible clientside at all.
How can I prevent sessions from being stolen? I've enabled IP and hostname verification, is that stuff automatic or do I have to perform the checks myself? Will that be enough to stop people from stealing session data?

A: Userdata can be stored in the Session. If you have sessions setup to use a database, the only cookie will be a ci_session cookie or whatever you specify, and the cookie + ip/hostname will be matched to the database sessions table.
Storing the hashed password in-session will be completely safe, its in your own database. No problems.
Preventing sessions to be stolen should use a ip or hostname match (either every page load or a little less often, some people have dynamic IPs), not sure about automatic verification, but it's always nice if you check by yourself.
Preventing session data stealing is pretty much like that. Unless someone intercepts your cookie, and magically reports a false IP (or, well, shares an IP/hostname with the target), it's enough. You could also do another check, match the user_agent. That you'll have to do manually.
That's pretty much everything.


text:
Q: Is it possible to calculate grand totals in BigQuery for repeated fields w/ rollup? There is a similar question ( Is BigQuery ROLLUP supports grouping by repeated fields ), but it lacks an example.
Consider following code:
SELECT    user_segments AS user_segments,
SUM(impressions) AS imps,
SUM(clicks) AS clicks,
FROM [theTable]
GROUP BY ROLLUP (user_segments)
ORDER BY imps DESC
LIMIT 1000

Where theTable contains impressions and clicks of two users (table only has 10 rows, and impressions = 1 on every row):
{"impressions": 1, "user_segments": [0, 1], "user_id": "A0", "clicks": 0}
{"impressions": 1, "user_segments": [1, 2], "user_id": "A1", "clicks": 1}
{"impressions": 1, "user_segments": [0, 1], "user_id": "A0", "clicks": 2}
{"impressions": 1, "user_segments": [1, 2], "user_id": "A1", "clicks": 0}
{"impressions": 1, "user_segments": [0, 1], "user_id": "A0", "clicks": 1}
{"impressions": 1, "user_segments": [1, 2], "user_id": "A1", "clicks": 2}
{"impressions": 1, "user_segments": [0, 1], "user_id": "A0", "clicks": 0}
{"impressions": 1, "user_segments": [1, 2], "user_id": "A1", "clicks": 1}
{"impressions": 1, "user_segments": [0, 1], "user_id": "A0", "clicks": 2}
{"impressions": 1, "user_segments": [1, 2], "user_id": "A1", "clicks": 0}

Query output is:
user_segments imps clicks
null          20   18
1             10   9
2             5    4
0             5    5

But there are only 10 (ten!) impressions in the table. In my opinion correct values for totals would be:
user_segments imps clicks
null          10   9
1             10   9
2             5    4
0             5    5

Is there any way to get to the correct totals w/o a separate query? Thanks!

A: below is obvious workaround you most likely using already - but still posting just in case
SELECT * FROM (
  SELECT
    user_segments AS user_segments,
    SUM(impressions) AS imps,
    SUM(clicks) AS clicks
  FROM theTable
  GROUP BY user_segments
), (
  SELECT
    NULL AS user_segments,
    SUM(impressions) AS imps,
    SUM(clicks) AS clicks
  FROM theTable
)
ORDER BY imps DESC, user_segments


text:
Q: NLP (topic modeling) with PLSA Im trying to understand PLSA (probabilistic latent semantic analysis), to do text modeling (NLP), the problem in every article i red, it's only maths (probabilities), without any semi-algorithme or anything to help you understand that, is there any link where i can understand PLSA please ?

A: The P in PLSA stands for probablistic and hence I am afraid you may not find any article that does not talk about these. The model itself is a probablistic model and some knowledge of joints, conditionals, independence etc are expected. I would recommend https://medium.com/nanonets/topic-modeling-with-lsa-psla-lda-and-lda2vec-555ff65b0b05 which I found to be the best online resource. There is a bit of Math but most of it is explained well. About PLSA algorithm - I am not sure. It is not used that often and one almost always prefers LDA. I could find a GitHub implementation of solving PLSA using EM here: https://github.com/laserwave/plsa.


text:
Q: ActionBar onNavigationItemSelected not called when selected item remains the same I am using the ActionBar drop-down navigation with OnNavigationListener implemented.
The requirement is to fire the onNavigationItemSelected() method every time, also when the same drop-down item is selected. The default Android implementation prevents the onNavigationItemSelected() method from running when the same item is selected.
I have seen the solutions to this requirement only for the standard Spinner implementation here and here, however not for the specific ActionBar drop-down navigation implementation.
Any suggestions how to overcome this default Android behaviour would be most appreciated.
Here is my code:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mPosition = -1;
    actionBar = getActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
    ....

and
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.eventmenu, menu);

    SpinnerAdapter mSpinnerAdapter = ArrayAdapter.createFromResource(actionBar.getThemedContext(), R.array.s_events,
              android.R.layout.simple_spinner_dropdown_item);
    OnNavigationListener mOnNavigationListener = new OnNavigationListener() {

          @Override
          public boolean onNavigationItemSelected(int position, long itemId) {

              if (mPosition > -1) {     // to prevent opening the data entry fragment when the Events fragment is initially opened

                ...
                  startActivity(newEvent);
              }
              mPosition = position;
              return true;
          }

    };
    actionBar.setListNavigationCallbacks(mSpinnerAdapter, mOnNavigationListener);
    return true;
}


text:
Q: How to read a .pdf file programmatically and convert it into audio (.mp3 format)? I want to parse a PDF file from my C# app and create an audio file off it.
How would I do that ?
I'm particularly looking for a good pdf to text library or a way to strip a pdf file off its text.

A: You preferably have a tagged PDF document as your input document. This means that the document contains tags to mark up the logical structure of the document (typically a PDF document will only contain visual information).
This PDF could then be converted into DAISY format, which is a standard for digital talking books, i.e. an intermediate XML format storing the text of books along with the logical structure and navigation features.
This Daisy XML format can be either converted to an audio format, or you could be using a Daisy reader, a physical device like an MP3 player to listen to the book.
There is a presentation available at the Daisy web site explaining the principles of this toolchain:

Accessible PDF to DAISY/NIMAS Conversion

A: Use Festival for the text to speech. Various pdf to text api's exist...

A: You need the Speech SDK from Microsoft. Read an instruction here

A: As the other posters outlined, first you have to extract the text from the .pdf file.   pdf files are an open format now, so you can probably find a parser through Google.
Then you have to extract the text you want to convert to speech from the file, ignoring things like figure titles, page headers, table of contents etc.
Once you've got the text, you need to convert it to speech.   This is probably the hardest part.
A while ago I was fiddling around with generating voice files for a gaming mod, since I'm a rotten voice actor.
Cepstral had the best TTS converters I could find.   (The free ones had an annoying tendency to insert Cepstral advertisements in the speech, but I could manually edit this out for what I was doing.)
It turns out that there's a speech synthesis markup language which can be used to provide clues to the TTS converter about which syllable to place accents, etc.  Here's a linky:
http://www.w3.org/TR/speech-synthesis/
How you go about automatically adding the SSML to the text is a bit beyond me.
Anyway, the TTS converter will produce an audio file, and the final step would be to compress the audio at the desired bit rate in mp3 format.

A: If your sole task is to listen to speech synthesized text from a PDF, how about the Acrobat "Read out loud" function at the bottom of the "View" menu?

A: I guess it's a hard thing to do. Firstly you need to read the text in that pdf, and then use some mechanism of synthetic voice generation to create the audio content. Then you have to store it as an mp3.

A: On Mac OS X, you can extract the text of the pdf and then pipe it in "say". You should find equivalent synthetisers on other OS.

A: It's not all that complicated to do, provided that you don't re-invent the wheel, but instead simply reuse existing technology (i.e. text to speech engines like festival), as well as OCR engines to process the PDF files.
The most complicated thing probably is to work with different PDF layouts (columns, rows, embedded graphics,foot notes, URLs etc), which may obfuscate the text recognition process.
However, in general (if this is not supposed to be a learning experience), it is certainly easier to just resort to using existing software solutions:

*

*Visual Text to Speech

*Text to speech tools

*zero 2000


text:
Q: How can I ensure that an object embedded as a property is either Valid or Null? I have this project with an entity A that holds a property b that should be a valid B or null.
B has itself a mandatory property.
How can I assert that b is valid or null? I tried using the Valid assertion, but null is not valid, so it complains about mandatoryItem being null.
<?php
// use statements

class A
{
    /**
     * @ORM\OneToOne(targetEntity="B")
     * @Assert\Valid
     */
    private b;
}

// meanwhile, in another file...
class B
{
   /**
    * @Assert\NotBlank
    */
   private $mandatoryItem;
}

A: Before doing anything below make sure you have Assert enabled. If thats already the cause the steps below might be helpful to you.
If you use a form to submit the data and got a formType for that form, but the Valid constraint is not working, you can do this:
Remove the Valid assert.
Inside the AType class buildForm() block you add it like this:
...
$builder->add('B', new BType(), array(
    'required' => false,
));
...

Also in the AType class add this function:
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'Your\AppBundle\Entity\A',
        'cascade_validation' => true,
    ));
}

'cascade_validation' => true, Does the same as Valid but then within the form.


text:
Q: Python: Primes using Sieve of Eratosthenes and dictionary Hey I was trying to write some code to get primes using the Sieve of Eratosthenes.
Employing a dictionary with numbers for the range to check I set the value to True when I checked it is not a prime. But something is not working correctly and instead of skipping to the next number if the value is True (= already checked) it tests it again.
What am I doing wrong?

max=12
checked={}
primes =[]
numbers=[]

for i in xrange(2,max):
    numbers.append(i)
    checked[i] = False

for i in numbers:
    if checked[i] == True:
        continue
        #if the number was already checked continue with next
    else:
        primes.append(i)
        #lowest unchecked number is always a prime
        checked[i] = True
        for x in numbers:
            if x%i==0:
            #checking off all the multiples of the prime
                checked[x]=True
                print x

print primes

Now I get this Output
2
4
6
8
10
3
6
9
5
10
7
11
[2, 3, 5, 7, 11]

Clearly the 6 and 10 are checked twice instead of skipped.

A: It works for me.
Just replace the sixth line with:
for i in xrange(2,max+1):

The +1 is because without it the algorithm does not check the max number the user gave.
Also:
numbers = range(2,max+1)

It doesnt really matter if you use the generator xrange, but then save all the numbers in a list anyway, so why not do it in one line.
To address the OP's clarification in the comments:
It checks 6 and 10 twice because 6 is a multiple of the primes 2 and 3 and 10 is a multiple of the primes 5 and 2. If you dont want it to do that add:
if x%i==0 and checked[x] is not True:

although it wont save you anything performance-wise..

A: Here is the correct code:
max=12
checked={}
primes =[]
numbers=[]

for i in xrange(2,max):
    numbers.append(i)
    checked[i] = False

for i in numbers:
    if checked[i] == True:
        continue
        #if the number was already checked continue with next
    else:
        primes.append(i)
        #lowest unchecked number is always a prime
        checked[i] = True
        for x in numbers:
            if x%i==0 and checked[x]==False:
            #checking off all the multiples of the prime
                checked[x]=True
                print x

print primes


text:
Q: PHP MVC (Manual) with Datatable I am new with mvc and I am not using any PHP framework because I need to create my project using my OWN mvc.
The problem now is, I am stuck how to pass database records into the Datatable.
All my previous projects are not using mvc which I can copy-paste directly.
URL:
http://localhost/project/public/user/showAll

View:

        StaffNo
        StaffName
        EmailAddress

        StaffNo
        StaffName
        EmailAddress

Controller:
public function showAll() {
    //to model
    $data['data'] = $this->model('User')->getAllUsers(); //from model's method

    //troubleshoot
    //echo '
';
    //print_r($data);
    //echo '
';
    //die();

    //Yes, this return data

    $this->view('user/showAll', $data);
}

Model:
public function getAllUsers() {
    $output = array();

    $query = $this->pdo->prepare('select * from tims_user_dtl');
    $query->execute();
    $result = $query->fetchAll(PDO::FETCH_ASSOC);
    if ($result) {
        foreach ($result as $column) {
            $output[] = array('StaffNo' => $column['staff_no'], 'StaffName' => $column['staff_name'], 'EmailAddress' => $column['email_address']);
        }
    }

    $results = array(
        "sEcho" => 1,
        "iTotalRecords" => count($output),
        "iTotalDisplayRecords" => count($output),
        "aaData" => $output
    );

    return json_encode($results); //pass to datatable
}

Datatable setting:
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css">

Please guide me, thanx

A: Datatable ajax option expects JSON yet the url you passed returns html (I guess that's what '$this->view()' does).
Keep that controller action to generate and render your view and add a new route where you'll fetch data, encode it in JSON and return it.


text:
Q: Google Photos API - a permanent url to an uploaded item for static content I'm trying to refactor a Java application using the Picasa Web Albums API
to using the new Google Photos api.
In Picasa API you had the PhotoEntry object, which represented the uploaded entity
and one could access the URL to the uploaded image as follows:
photoEntry.getMediaThumbnails().get(0).getUrl();

This url could be used in a website as static content.
Currently I'm at a loss how to get a permanent url to an uploaded image
with Google Photos API.
There is the MediaItem object, which represents an uploaded image,
but I can't figure out how to get a permanent url from it.
I find 2 types of url in the MediaItem API:
mediaItem.getBaseUrl()

This url expires after 60 minutes and
mediaItem.getProductUrl()

cannot be used for static content, since it requires to be logged in.
Anybody can tell me what I overlooked ?
Thanks
Regards

A: The Google Photos Library API is not designed for image hosting. If you'd like to embed images in another site, you may need to look at other hosting solutions, like Google Cloud Storage, Firebase Cloud Storage or similar.
You are correct, base URLs expire after 60 minutes and need to be refreshed. However, if you need a permanent URL to a media item that points to Google Photos, you can create a new album, share it and use the shareableURL that's returned as part of the shareInfo property. This URL is accessible without sign in and opens the shared album in Google Photos. You can find out more in the share media developer guide.


text:
Q: jQuery Mobile popup data-dismissible="false" problems This is my first time using the jQUery Mobile popups. I've found documentation here and here. How I'm looking to create the following:

Now according to the doc's, the following code should work:
Open Popup

This is a completely basic popup, no options set.

But given the code above I still keep getting the stock standard popup:

Any idea what I am doing wrong?

A: data-dismissible means whether you want the popup to close once clicked outside it. The default value is true, if you set it to false, you have to add a button with data-rel="back" to close it, jQM wont add a close button dynamically/automatically.
Change your markup to the following.

Click button to close this.

  Close

Note that data-theme and data-overlay-theme are different, the latter changes the color of the popup's overlay.
Or, you can close it programmatically.
$("#popupBasic").popup("close");

Demo


text:
Q: 503 error logging in using Python MechanicalSoup I want to scrape some information behind a login page but I get a 503
This is what happens when I try to login with mechanicalsoup (same result with robobrowser):
>>> import mechanicalsoup
>>> browser = mechanicalsoup.StatefulBrowser(user_agent='Mozilla/5.0')
>>> page = browser.get('https://X.com')
>>> page.status_code
200
>>> page = browser.get('https://X.com/wp-login.php')
>>> page.status_code
503

I've tried a couple of different user_agents, how can I get around this? moving cookies around?

A: OK I managed to do this using https://github.com/Anorov/cloudflare-scrape
import cfscrape
from bs4 import BeautifulSoup

# log in
scraper = cfscrape.CloudflareScraper()
scraper.get('https://X.com/wp-login.php')
tokens = cfscrape.get_tokens('https://X.com')
browser = mechanicalsoup.StatefulBrowser(session=scraper, user_agent=tokens[1])
browser.select_form('#loginform')
browser['log'] = 'X'
browser['pwd'] = 'X'
browser.submit_selected()
browser.open('https://X.com/page/')

A: It's protected by CloudFlare which is denying a pure GET request to that URL. You need a non-headless browser in order to access the page, otherwise it will reject it. Use a library such as Selenium that provides a GUI and you should be fine.
from selenium import webdriver
browser = webdriver.Firefox() # or whichever browser you prefer
browser.get('https://hacked.com/wp-login.php')

Note that there is no way to fetch a status code with Selenium. However, you have many more ways to interact with the page, and confirm that you have reached the page.


text:
Q: CentOS7, SELinux, Apache, PHP-FPM: Access denied for file_put_contents to a user dir I have a CentOS7/Apache multi-user (userdir) setup with SELinux enabled and the following directory structure:
/home/USER/public_html/resources/css

The whole /home/USER directory and everything underneath is owned by USER. All files and directories have a SELinux context of httpd_user_content_t except the aforementioned directory which I've set to httpd_user_rw_content_t. The apache server runs under the user apache and the apache user is member of the USER group. Everything under /home/USER has 0775 permissions (group writable). One of my scripts uses php's file_put_contents to create a file named test_fpc.txt in the /home/USER/public_html/resources/css directory but only if the directory is owned by apache:apache will the file_put_contents succeed. If the directory is owned by USER:USER the file_put_contents fails with failed to open stream: Permission denied warning. The audit log reads:
type=SYSCALL msg=audit(1483602823.639:155208): arch=c000003e syscall=2 success=no exit=-13 a0=7f0e5d9f1478 a1=241 a2=1b6 a3=73656372756f7365 items=2 ppid=855 pid=992 auid=4294967295 uid=48 gid=48 euid=48 suid=48 fsuid=48 egid=48 sgid=48 fsgid=48 tty=(none) ses=4294967295 comm="php-fpm" exe="/usr/sbin/php-fpm" subj=system_u:system_r:httpd_t:s0 key="apache_user_access"
type=CWD msg=audit(1483602823.639:155208):  cwd="/home/USER/public_html"
type=PATH msg=audit(1483602823.639:155208): item=0 name="/home/USER/public_html/resources/css/" inode=65290545 dev=08:12 mode=040775 ouid=1002 ogid=1002 rdev=00:00 obj=system_u:object_r:httpd_user_rw_content_t:s0 objtype=PARENT
type=PATH msg=audit(1483602823.639:155208): item=1 name="/home/USER/public_html/resources/css/test_fpc.txt" objtype=CREATE

When I login with the apache user with sudo -u apache bash and execute echo "test" > /home/USER/public_html/resources/css/test_bash.txt it works and the audit log output is:
type=SYSCALL msg=audit(1483602552.156:155207): arch=c000003e syscall=2 success=yes exit=3 a0=f607c0 a1=241 a2=1b6 a3=0 items=2 ppid=13539 pid=13540 auid=0 uid=48 gid=48 euid=48 suid=48 fsuid=48 egid=48 sgid=48 fsgid=48 tty=pts0 ses=207 comm="bash" exe="/usr/bin/bash" subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 key="apache_user_access"
type=CWD msg=audit(1483602552.156:155207):  cwd="/home/USER/public_html"
type=PATH msg=audit(1483602552.156:155207): item=0 name="/home/USER/public_html/resources/css/" inode=65290545 dev=08:12 mode=040775 ouid=1002 ogid=1002 rdev=00:00 obj=system_u:object_r:httpd_user_rw_content_t:s0 objtype=PARENT
type=PATH msg=audit(1483602552.156:155207): item=1 name="test_bash.txt" inode=65273889 dev=08:12 mode=0100644 ouid=48 ogid=48 rdev=00:00 obj=unconfined_u:object_r:httpd_user_rw_content_t:s0 objtype=CREATE

I've also tried setting the context of the /home/USER/public_html/resources/css directory to httpd_sys_rw_content_t but it makes no difference.
I haven't tried setting setsebool -P httpd_unified 1 as I'd really like to keep the current restrictive SELinux configuration and I feel like SELinux is not the real problem here. What could be the cause of the group writable directory not being writable by the apache user which IS a member of the USER group?

A: I needed to logout and log back in or restart the system. Found the clue here Linux Group Permissions not being enforced correctly.


text:
Q: Junction tables in T-SQL In my database application, when I try to attach a page to a site, I get the following error:
System.InvalidOperationException: Can't perform Create, Update or Delete operations on 'Table(Junc_Page_Site)' because it has no primary key.

I intend a page to be able to be added to multiple sites - by using a junction table.
Below is the schema for the three tables in question (T-SQL). Any advice will be appreciated!
CREATE TABLE Site (
    Id     INTEGER    NOT NULL IDENTITY ,
    FkSiteId    INTEGER   ,
    Name     NVARCHAR(64)  NOT NULL ,
    Domain     NVARCHAR(128) ,
    Theme     NVARCHAR(32) ,
    ThemeVariation  NVARCHAR(32) ,
PRIMARY KEY(Id) ,
FOREIGN KEY(FkSiteId)
    REFERENCES    Site(Id));
GO

CREATE TABLE Page (
    Id      INTEGER    NOT NULL IDENTITY ,
    Title    NVARCHAR(64)  NOT NULL ,
    Description   NVARCHAR(256)  NOT NULL ,
    Keywords   NVARCHAR(1024)  NOT NULL ,
    ScriptName   NVARCHAR(64) ,
PRIMARY KEY(Id));
GO

CREATE TABLE Junc_Page_Site (
    FkPageId   INTEGER     NOT NULL ,
    FkSiteId   INTEGER    NOT NULL  ,
FOREIGN KEY(FkSiteId)
    REFERENCES Site(Id),
FOREIGN KEY(FkPageId)
    REFERENCES Page(Id));
GO

A: You're almost there.  You just need to create what's called a "composite primary key", which is to say that you need to tell the database that the conbination of FkPageId and FkSiteId will be unique:
CREATE TABLE Junc_Page_Site (
    FkPageId INTEGER NOT NULL ,
    FkSiteId INTEGER NOT NULL  ,
FOREIGN KEY(FkSiteId)
    REFERENCES Site(Id),
FOREIGN KEY(FkPageId)
    REFERENCES Page(Id),
PRIMARY KEY (FkPageId, FkSiteId));


text:
Q: How to prove matrix obeying certain relation is invertible? Let $n$ be a positive integer, $M$ be an $n\times n$ matrix with complex entries, which may or may not be diagonalizable, and assume that for some $\lambda\in\mathbb{C}-\mathbb{R}$, we have that $$ -\frac{\Im\left(M\right)}{\Im\left(\lambda\right)}$$ is a positive definite matrix, where $$ \Im\left(M\right) \equiv\frac{1}{2i}\left(M-M^{\ast}\right) $$ and $$ \Im\left(\lambda\right)\equiv \frac{1}{2i}\left(\lambda-\bar{\lambda}\right)$$
Question: How to prove that $\lambda$ is not an eigenvalue of $M$?
The case that $n=1$ is clear, and I think so is the case that $M$ is diagonalizable, but otherwise I am a bit stuck.

A: Let $\mu$ be an eigenvalue of $M$, and $x$ a corresponding eigenvector with unit magnitude. Then $Mx = \mu x$ and $x^*M^* = (Mx)^* = \bar \mu x^*$, so that
\begin{align*}
x^* \Im(M) x &= \dfrac{1}{2i}(x^*\mu x - \bar \mu x^*x)\\
& = \dfrac{1}{2i}(\mu - \bar \mu)\\
& = \Im(\mu)
\end{align*}
(since $x^*x = 1$).
This implies that
$$x^* \left( - \dfrac{\Im(M)}{\Im(\lambda)} \right) x = - \dfrac {\Im(\mu)} {\Im(\lambda)}.$$
If $\mu = \lambda$, this would have value $-1$, which is not possible since $- \dfrac{\Im(M)}{\Im(\lambda)}$ is positive definite. Therefore, $\lambda$ cannot be an eigenvalue of $M$.


text:
Q: What happens when Phusion PassengerMaxPoolSize is reached? The subject of my post pretty much sums up my question: What happens when PassengerMaxPoolSize is reached?
For Example:
PassengerMaxPoolSize is configured to 40 based off our system specs
What happens if all 40 sessions are active (processing a request) and our load balancer passes another session to this particular web server? This would send a 41st session to be processed without an available Passenger process.

A: The requests queued.
You might want to read this http://blog.phusion.nl/2008/10/29/phusion-passenger-now-with-global-queuing/


text:
Q: How to change spring session (redis) cookie name? We have two projects behind same domain ( zuul proxy in front of them ), both uses spring session project with sessions kept in redis.
Those two sessions should be different, but seems they are overwriting each other id in cookie named 'SESSION'. How to change that name? Is there any easy way to do that through configuration?

A: I know that this is an old question, but I just want to put that this option also works.
You can add server.servlet.session.cookie.name in your application.yml. Take a look at this spring docs link, it has other cookie properties that you can change as well.
Spring Common Application Properties

A: ok, I did not find any property in configuration to change that. I dig in a bit in spring-session source code, and finally do:
@Bean
public <S extends ExpiringSession> SessionRepositoryFilter<? extends ExpiringSession> springSessionRepositoryFilter(SessionRepository<S> sessionRepository, ServletContext servletContext) {
    SessionRepositoryFilter<S> sessionRepositoryFilter = new SessionRepositoryFilter<S>(sessionRepository);
    sessionRepositoryFilter.setServletContext(servletContext);
    CookieHttpSessionStrategy httpSessionStrategy = new CookieHttpSessionStrategy();
    httpSessionStrategy.setCookieName("MY_SESSION_NAME");
    sessionRepositoryFilter.setHttpSessionStrategy(httpSessionStrategy);
    return sessionRepositoryFilter;
}

"SESSION" name is a default set in source of CookieHttpSessionStrategy.

A: I found a blog post about this, spring-session学习
This post explains how to change session id name with Spring XML.
like following:
<bean class="org.springframework.session.web.http.DefaultCookieSerializer">
        <property name="cookieName" value="SYSTEM_SESSION_ID" />
</bean>

And, I actually tested it and it worked.

A: @Bean
public CookieSerializer cookieSerializer() {
    DefaultCookieSerializer serializer = new DefaultCookieSerializer();
    serializer.setCookieName("YOUR_COOKIE");
    serializer.setCookiePath("/");
    serializer.setDomainNamePattern("^.+?\\.(\\w+\\.[a-z]+)$");
    return serializer;
}

A: In Spring Boot Web (spring-boot-starter-web) you have property named server.servlet.session.cookie.name which work fine, however for me
turns out that the server.servlet.session.cookie.name property is not working by default for Spring Boot WebFlux (spring-boot-starter-webflux Spring Boot v2.5.2, Spring v5.3.8). I've created a  WebSessionManager bean which use it:
  @Bean
  public WebSessionManager webSessionManager(
      final ServerProperties serverProperties, final WebFluxProperties webFluxProperties) {
    final DefaultWebSessionManager webSessionManager = new DefaultWebSessionManager();
    final CookieWebSessionIdResolver webSessionIdResolver = new CookieWebSessionIdResolver();
    webSessionIdResolver.setCookieName(
        serverProperties.getServlet().getSession().getCookie().getName());
    webSessionIdResolver.addCookieInitializer(
        (cookie) -> {
          cookie.sameSite(webFluxProperties.getSession().getCookie().getSameSite().attribute());
        });
    webSessionManager.setSessionIdResolver(webSessionIdResolver);
    return webSessionManager;
  }

A: seems like that Spring now supports some yaml properties to set fine-grained properties of cookies and session on webflux / reactive servers (eg. Spring Gateway based applications).
Referring to this request they implemented a dual set of properties:

*

*spring.webflux.session (to be deprecated in favour to the next one)

*server.reactive.session

I was able to set the cookie name writing this line in the application.yaml:
server.reactive.session.cookie.name: "MYSESSIONID"