text:
Q: How to compare between the two images and highlight the difference? In my application, I need to compare 2 images and highlight the difference with color. For example, I am comparing UIImage1 with UIImage2, where both the images are same, except there is a small square in UIImage2. I need to highlight the extra square object with red color and display in the image view otherwise I want to know the x and y-direction of the difference.
I have tried this below code. in this code, I can only change the alpha value of the difference. can't change the color of the diff.
UIImage* bottomImage = [UIImage imageNamed:@"j1.jpg"];
UIImage* topImage    = [UIImage imageNamed:@"j2.jpg"];
UIImageView* imageView = [[UIImageView alloc] initWithImage:bottomImage];
UIImageView* subView   = [[UIImageView alloc] initWithImage:topImage];
subView.alpha = 0.5;  // Customize the opacity of the top image.
[imageView addSubview:subView];
UIGraphicsBeginImageContext(imageView.frame.size);
[imageView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage* blendedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
_imageview.image = blendedImage;

image 1:

image 2:

diff image:

but what I want is this:

I'm new to OpenCV the codes are in python. can anyone help me to change this code into objective-c? I tried but I'm getting the error only.
https://stackoverflow.com/a/27500479/6859041
im = cv2.imread('c:\\diff.jpg')
im1 = cv2.imread('c:\\Edited.jpg')

imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,127,255,0)
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

cv2.drawContours(im1, contours, -1, (0,255,0), 1)
cv2.imwrite("c:\\see_this.jpg", im1)

how to change this code into objective C?
thanks.

A: With ImageMagick, this is quite easy.
img1.jpg

img2.jpg

compare -fuzz 25% -metric rmse -lowlight-color transparent -highlight-color red img1.jpg img2.jpg diffimage.jpg
1562.23 (0.0238381)

You can do the same in Python Wand, which calls ImageMagick and gets the same image and value as above. (Credits to emcconville)
#!/bin/python3.7
from wand.image import Image
from wand.display import display
from wand.api import library

with Image(filename='img1.jpg') as bimg:
    with Image(filename='img2.jpg') as fimg:
        # We have to call the C method directly, and calculate the percentage.
        library.MagickSetImageFuzz(bimg.wand, 0.25 * bimg.quantum_range)
        bimg.artifacts['compare:highlight-color'] = 'red'
        bimg.artifacts['compare:lowlight-color'] = 'transparent'
        diff_img, diff_val =  bimg.compare(fimg, 'root_mean_square')
        print(diff_val)
        with diff_img:
            diff_img.save(filename='img1_img2_diff.jpg')

A: You can check code of facebook solution for testing called Snapshot: https://github.com/uber/ios-snapshot-test-case/
Look at categories folder.
- (UIImage *)fb_diffWithImage:(UIImage *)image
{
    if (!image) {
        return nil;
    }
    CGSize imageSize = CGSizeMake(MAX(self.size.width, image.size.width), MAX(self.size.height, image.size.height));
    UIGraphicsBeginImageContextWithOptions(imageSize, YES, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [self drawInRect:CGRectMake(0, 0, self.size.width, self.size.height)];
    CGContextSetAlpha(context, 0.5);
    CGContextBeginTransparencyLayer(context, NULL);
    [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
    CGContextSetBlendMode(context, kCGBlendModeDifference);
    CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
    CGContextFillRect(context, CGRectMake(0, 0, self.size.width, self.size.height));
    CGContextEndTransparencyLayer(context);
    UIImage *returnImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return returnImage;
}

A: You can directly look at the backing data of an image to get the RGBA value of any pixel and then use these to compare or construct a new image.  Its expensive to do this on the CPU though.  You may find its much faster to write a custom GPU shader that jsut compares the two inputs and writes the output based on whether or not they are equal.
func pixel(in image: UIImage, at point: CGPoint) -> (UInt8, UInt8, UInt8, UInt8)? {
    let width = Int(image.size.width)
    let height = Int(image.size.height)
    let x = Int(point.x)
    let y = Int(point.y)
    guard x < width && y < height else {
        return nil
    }
    guard let cfData:CFData = image.cgImage?.dataProvider?.data, let pointer = CFDataGetBytePtr(cfData) else {
        return nil
    }
    let bytesPerPixel = 4
    let offset = (x + y * width) * bytesPerPixel
    return (pointer[offset], pointer[offset + 1], pointer[offset + 2], pointer[offset + 3])
}

let image = UIImage(named: "t.png")!
if let (r,g,b,a) = pixel(in: image, at: CGPoint(x: 1, y:2)) {
    print ("Red: \(r), Green: \(g), Blue: \(b), Alpha: \(a)")
}


text:
Q: iOS FCM push notifications not received in TestFlight I have an issue with FCM and TestFlight. I have an app which is written via Objective C. It uses push notification service via Firebase. I use APNs key instead of certificates.
The issue is when I run my app in debug and in release mode via Xcode I get push notifications. When I sign app with distribution profile and send it to TestFlight and install it via TestFlight on same device push notifications not received.
We are using php server for the app. And push notifications are sent from that server via firebase. I have all the settings in AppDelegate file as it is stated in Firebase SDK docs. So all proper delegates are set and firapp configure called and so on like here. https://firebase.google.com/docs/cloud-messaging/ios/first-message Also I've checked entitlements file that APS-environment is set to Production when sending to TestFlight.
I've tried to set type of device token in didRegisterForRemoteNotificationsWithDeviceToken via [[FIRMessaging messaging] setAPNSToken: type:] to sandbox or prod whether it is debug or release mode of schema. Also I've using this code instead of that now [FIRMessaging messaging].APNSToken = deviceToken. But neither of the options work in TestFlight.
Our back-end dev says that on server push notifications are sent properly. So I suppose that it may be something related to device token.
Also I've update Firebase pods recently form version 3 to version 6. May be firebase lib on server should be updated as well?
Do you know what the issue can be? Any help is appreciated.

A: Update. I've found that this issue has began after updating firebase ios lib not from 3 to 6 version but from version 6.18 to 6.31.1. So my issue was bug stated in issue #6553 on official GitHub of Firebase iOS SDK. This bug was fixed in version 7.0.0. And after updating my issue was solved.
https://github.com/firebase/firebase-ios-sdk/issues/6553

redpajama_set_name: RedPajamaStackExchange


text:
Q: FXRuby move png image on canvas? I am writing a program in which the user needs to be able to move an
image around a canvas using his/her mouse. Is this possible to do in
FXRuby, and, if so, how? I'm relatively new to programming, so any help
would be appreciated. Thank you


text:
Q: Изменение текста ссылки подскажите как будет выглядеть код, который изменяет текст ссылки. Получение нового текста происходит с использованием синхронного запроса.
Старый текст

A: Пример, как это сделать на JavaScript:

let newTextLink = 'Новый текст ссылки';
let link = document.querySelector('a');
link.innerText = newTextLink;
Старый текст

Ну и ссылочка, где можно узнать об этом подробнее https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText


text:
Q: Confusion in college book on the introduction of PDE (method of characteristics) In my course book, the method of characteristics for solving 1st order PDE of the form $P \frac{\partial u}{\partial x} + Q\frac{\partial u}{\partial y} = R$ where $u$ is a function of $x$ and $y$ is presented as follows :
Suppose the value of $u$ in known on a parameterized curve $\Gamma \equiv (x(s), y(s))$ with $s$ being the parameter used to describe this curve.
First, the book says that if we knew the partials $\frac{\partial u}{\partial x}$ and $\frac{\partial u}{\partial y}$ on $\Gamma$, we could, in practice, find the values of $u$ near $\Gamma$ and then near those points and so on because of the following relation :
$u(x+dx, y+dy) = u(x,y) + dx\frac{\partial u}{\partial x}(x,y) + dy\frac{\partial u}{\partial y}(x,y)$
Indeed, because we know $u(s)$, we can write that $\frac{du}{ds} = \frac{\partial u}{\partial x}\frac{dx}{ds} + \frac{\partial u}{\partial y}\frac{dy}{ds}$ and then form with the PDE the following system :
$$
        \left(\begin{matrix}
        P & Q  \\
        \frac{dx}{ds} & \frac{dy}{ds} \\
        \end{matrix}\right) \left(\begin{matrix}
        \frac{\partial u}{\partial x} \\
        \frac{\partial u}{\partial y} \\
        \end{matrix}\right) = \left(\begin{matrix}
        R \\
        \frac{du}{ds} \\
        \end{matrix}\right)
$$
The Cauchy problem is then well-posed if the determinant of this 2 by 2 matrix is non zero for every point of $\Gamma$. This method to find $u(x,y)$ by knowing its partials is then discarded because it is not a very convenient way to find $u$.
Second, the book says that we now suppose that the problem is well-posed. Let's consider this time directions $(dx,dy)$ that are non parallel to $\Gamma$. The variation of $du$ associated with these directions is given by :
$du = \frac{\partial u}{\partial x}dx + \frac{\partial u}{\partial y}dy$
We can then form the following system with the PDE :
$$
        \left(\begin{matrix}
        P & Q  \\
        dx & dy \\
        \end{matrix}\right) \left(\begin{matrix}
        \frac{\partial u}{\partial x} \\
        \frac{\partial u}{\partial y} \\
        \end{matrix}\right) = \left(\begin{matrix}
        R \\
        du \\
        \end{matrix}\right)
$$
And then the book says (that's what really bugs me) : "Because the problem is well-posed, there exist for every point of $\Gamma$ a particular direction $(dx,dy)$ such that the determinant of this 2 by 2 matrix is zero, leading to the characteristic equation : $Pdy = Qdx$"
My question : Why there must exists a unique direction $(dx,dy)$ for which this determinant is zero? I don't see how the assumption of a well-posed problem leads to conclude that.

A: It seems to me that, modulo issues with differentials, this is purely a linear algebra point. You have the nonzero row vector $(P,Q)$. Introducing an additional row to this matrix fails to result in an invertible matrix iff the new row vector is a multiple of $(P,Q)$. There is a single line of such vectors. Strictly speaking I would say there are actually two directions, though (one "positive" one and one "negative" one).

A: Passing from
$\quad\left(\begin{matrix}
        P & Q  \\
        \frac{dx}{ds} & \frac{dy}{ds} \\
        \end{matrix}\right) \left(\begin{matrix}
        \frac{\partial u}{\partial x} \\
        \frac{\partial u}{\partial y} \\
        \end{matrix}\right) = \left(\begin{matrix}
        R \\
        \frac{du}{ds} \\
        \end{matrix}\right) \quad
$ to
$\quad \left(\begin{matrix}
        P & Q  \\
        dx & dy \\
        \end{matrix}\right) \left(\begin{matrix}
        \frac{\partial u}{\partial x} \\
        \frac{\partial u}{\partial y} \\
        \end{matrix}\right) = \left(\begin{matrix}
        R \\
        du \\
        \end{matrix}\right)$
you just multiply the last row of the matrix by $ds$ so that the determinant does not change.
Now, the resulting matrix having determinant null, means that the vector $(P,Q)$ is normal to the vector $(dx,dy)$, and, provided that $P$ and $Q$ are not both null, there is only one normal vector $(dx,dy)$, apart from a multiplication constant.
Hence the direction individuated by $(dx,dy)$ is unique.


text:
Q: Xcode adding more than one object to NSMutableArray replaces previous Keep finding similar questions here, but can't find this one
I want to put several objects into an NSMutableArray, and of course be able to retrieve them.
I can put individual strings (First line, Second Line, etc) into the array (as objects), and can see in debugger that they are all being stored - can retrieve them too.
(I don't actually need to put these individual strings in - I only need to put in my "Person" objects. Just thought it might help me to see what does work in terms of moving forward in the NSMutableArray)
Person *aPerson = [[Person alloc] init];

NSMutableArray *myArray = [[NSMutableArray alloc] init];
[myArray addObject:@"First line"];
[myArray addObject:@"Second line"];
[myArray addObject:@"Third line"];
[myArray addObject:@"Fourth line"];
[myArray addObject:@"Fifth line"];

When I put ONE object into the same array, it goes in fine.
aPerson.firstName = @"Jasper"; // Should be sixth
aPerson.lastName = @"John";

[myArray addObject:aPerson];

In the debugger when stopping at above point I see the "Jasper John" info in a Person object in the NSMutableArray
....
But when I put another object into that NSMutableArray, it replaces the last object - it's as those I didn't advance through the NSMutableArray.
aPerson.firstName = @"Izzie";// Should be seventh
aPerson.lastName = @"TheKitty";
[myArray addObject:aPerson];

aPerson.firstName = @"Roxie";
aPerson.lastName = @"The Pup";
[myArray addObject:aPerson];        // Should be eighth

When stopping at above point, I just get "Roxie The Pup" for all 3 objects in the NSMutable Array - though my original 5 strings are still filling up the buckets at the beginning.

A: Oh got it!
When I was adding my objects, I was really adding a POINTER to the object
And since I was using 'aPerson' object, I was simply changing the contents of the same object, as far as the compiler was concerned. So I was updating the contents of that pointer, every time I did an addObject
Person *aPerson2 = [[Person alloc] init];
aPerson2.firstName = @"Izzie";// Should be seventh
aPerson2.lastName = @"TheKitty";
[myArray addObject:aPerson2];

Person *aPerson3 = [[Person alloc] init];

aPerson3.firstName = @"Roxie";// Should be eightth
aPerson3.lastName = @"The Pup";
[myArray addObject:aPerson3];


text:
Q: jQuery, remove padding added to toggleClass element I am animating a hidden div with slideToggle.
since it has a fixed position on top, I want to add animate the padding top of that container div 'under it' with the current height of the hidden div.
However the class toggles correctly on click, and the padding is added with the correct amount of pixels, after toggling away the class the padding remains.
How come when I apply the padding on the toggled class it keeps being there even though the class is removed on 2nd click (toggling it away)?
js:
$('#myButton').click(function(e){
    e.preventDefault();

    $('#myDiv').slideToggle( function(){

        var myDivHeight = $(this).outerHeight();

        $('.containerDiv').toggleClass('myDivOpened');

        $('.myDivOpened').css('padding-top', myDivHeight + 15);

    });

});

Thanks very much.

A: What your method does, is adding a padding-top in the style attribute of the element in the end. It does not change the class in anyway.
Would be better to add the style in a class, yet if you really want to toggle the style with jquery, this is how it works.
$('.containerDiv').toggle(function () {
    $(".containerDiv").css({paddingTop: "20px"});
}, function () {
    $(".containerDiv").css({paddingTop: "0px"});
});

Edit:
I can see your logical problem and will try to elaborate..
First we have a div called containerDiv with no class and no padding. Then we set the class of it to myDivOpened and give all the elements of this class a paddingtop. Now what you do is removing the class again of the element containerDiv and expect it to remove the padding.
Why does it not remove the padding? Because you set it on the style attribute of containerDiv. You removed the class of it yet the style attribute is not really linked with that change and thus remains.
A proper solution would be to have two classes, one with the padding and one without and toggle between those two.

A: @Lain: Thanks for clarifying further. You are right, the toggle leaves the padding untouched, once inserted.
You could instead try adding and deleting the class manually.
This link may help:api.jquery.com/toggleclass.
Before deleting the class, remove the padding from the class manually, then delete the class from the body.
Just pasting in some code which may help:
$(this).click(function(e)
{
    if (!added)
    {
        $("body").addClass("myDivOpened");
        $('.myDivOpened').css('padding-top',15);
        added = true;
    } else {
        $('.myDivOpened').css('padding-top',0);
        $("body").removeClass("myDivOpened");
        added = false;
    }
});

A: I think I may have found a way to do so, since many ways lead to Rome, I'm guessing this one is valid as any other (or at least hoping it is).
$('#myButton').click(function(e){
    e.preventDefault();

     var $myDiv = $('#myDiv');
     var $containerDiv = $('.containerDiv');
     var myDivHeight = $myDiv.outerHeight();

     $myDiv.toggleClass('opened');

    $myDiv.slideToggle( function(){

        if($myDiv.hasClass('opened')){
            $containerDiv.css('padding-top', myDivHeight);
        }else{
            $containerDiv.css('padding-top', 0);
        }

    });

});

Updated fiddle


text:
Q: Ansible to reconnect after reboot I have a task that needs to run after a reboot. I know that checking connection can be done with wait_for_connection.
I have the following draft:
- name: Reboot host
  reboot:

- name: Wait 300 seconds, but only start checking after 60 seconds
  wait_for_connection:
    delay: 60
    timeout: 300

- name: Do some other stuff
  .
  ..

...
Does the wait_for_connection module automatically reconnects once available? Or do I have to have a seperate task for that? Is there a better way of doing this?
Thanks ahead!

A: as per reboot module documentation it does what you want out of the box:
 Synopsis
 - Reboot a machine, wait for it to go down, come back up, and respond to commands.
 ...

So you do not have to manage it with a separate task!
If server you try to reboot is very slow you can increase the timout of module to wait server go back on-line correctly.
So any task you need to run after a reboot the only think you have to do is insert it after the task reboot the machine.


text:
Q: MouseOver state for Border element I have a Border element on my page that contains some TextBlock elements contained in a grid, e.g. (simplified):
<Border Style="{StaticResource borderStyle}">
  <Grid Background="Transparent">
    <Grid.RowDefinitions>
      <RowDefinition/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
      <ColumnDefinition/>
      <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <TextBlock Text="Something" Grid.Column="0" Grid.Row="0" />
    <TextBlock Text="Something else" Grid.Column="1" Grid.Row="0" />
  </Grid>
</Border>

I have the following style defined:
<Style x:Key="borderStyle" TargetType="Border">
  <Setter Property="CornerRadius" Value="0,0,15,15"/>
  <Setter Property="Background" Value="Black"/>
  <Setter Property="Opacity" Value="0.6"/>
</Style>

How would I add a VisualStateGroup (or something similar) to the style to change the opacity on mouseover?  I can't seem to get it working for a Border element, is there a reason for this?

A: VSM will work inside ControlTemplate alone. Thats the reason. There is no template there that is the reason you are not able to get it working.
Alternatively, you can use EventTriggers. Like below.
<Grid x:Name="LayoutRoot" Background="White">
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="VisualStateGroup">
                <VisualStateGroup.Transitions>
                    <VisualTransition GeneratedDuration="0">
                        <Storyboard/>
                    </VisualTransition>
                </VisualStateGroup.Transitions>
                <VisualState x:Name="Normal"/>
                <VisualState x:Name="MouseOverState">
                    <Storyboard>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(Border.BorderThickness)" Storyboard.TargetName="border">
                            <DiscreteObjectKeyFrame KeyTime="0">
                                <DiscreteObjectKeyFrame.Value>
                                    <Thickness>3</Thickness>
                                </DiscreteObjectKeyFrame.Value>
                            </DiscreteObjectKeyFrame>
                        </ObjectAnimationUsingKeyFrames>
                    </Storyboard>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
        <Border x:Name="border" BorderBrush="Black" BorderThickness="1" Height="143" Margin="164,79,191,0" VerticalAlignment="Top">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="MouseEnter">
                    <ei:GoToStateAction StateName="MouseOverState" TargetObject="{Binding ElementName=userControl}"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </Border>
    </Grid>


text:
Q: REST Field filter use I'm designing a RESTful API and I'm asking myself question about the filter field.
On my gets queries I want the user to be able to select the fields he want to get in the response. I was pretty sure that it would be the field filter jobs to give me the requested field but, after some reshearch, I found that most of the time it's used to add criteria on the fields, as a IF. Is it the user that needs to make show or hide the fields ans the Api return the full ressource everytime ?
I got an other question which is about the URI representation of such filter. Should it be something like /foo?fields=[bar1,bar2] ?
Thanks

A: It's not common to have a resource where you can specify what fields you want returned, by default all fields will get returned. If your resource has a lot of fields or some fields have really big values, it can be a good idea to have a way to specify which fields you want returned.
In REST there are no strict rules about how you should design your URLs for filters. It is indeed common to use GET parameters because they can be optional and don't have to be in any specific order. Your proposal of /foo?fields=[bar1,bar2] seems fine, however i would personally leave off the brackets.

A: Google Compute Engine API uses the 'fields' request parameter (see the documentation). The syntax is flexible enough to let user select/restrict even the nested elements. You may find it useful.

A: Yoga is a framework that allows you to deploy your own REST API's with selectable fields. This can reduce roundtrips to the server, and improve performance.


text:
Q: How to dynamically load the cron expression for @scheduled annotation from an externally configurable property file I need to load the cron expression for @scheduled annotation dynamically from a property file.
I know the solution for this would be using property place holder, but my problem is that, property file which contains the cron expression can be modified dynamically and its location is derived from another property file.
application-context.xml looks something like this,
    <util:properties id="dynamicProps" location="${configurable.property.file.path}"
    <context:property-placeholder properties-ref="dynamicProps"  />

configurable.property.file.path property is present in a property file that is located under WEB-INF/classes and the value of this is something like this,
 configurable.property.file.path=${static.assets.path}/config/configuration.properties

With the above settings on start up server cribs with the following error,
  org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#1': Cannot resolve reference to bean 'dynamicProps' while setting bean property 'properties'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dynamicProps': Invocation of init method failed; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/${configurable.property.file}]

I am guessing the reason for this may be that property files are not yet visible at this point. What is the solution for this? Could someone pl help me on this?


text:
Q: Telerik RadGrid I have the following telerik  grid and need to pass the data value from the nested table into the ItemCommand so when the user clicks the grid button the code is executed
I am stuck on where to go with this
                <telerik:RadGrid ID="grdRegions" runat="server" Skin="Metro" AllowCustomSorting="True"
                ShowHeader="True" PageSize="10" ShowGroupPanel="False"     OnItemCommand="grdRegions_ItemCommand"
                ShowStatusBar="True" AutoGenerateColumns="False"
                AllowSorting="True" AllowPaging="True" DataSourceID="RegionDS" Width="500px">
                <PagerStyle Mode="Slider" />
                <MasterTableView DataSourceID="RegionDS" DataKeyNames="RegionCode" AllowMultiColumnSorting="True" Width="100%">

                    <DetailTables>
                        <telerik:GridTableView runat="server" DataKeyNames="RegionCode,DealerId" DataSourceID="DealerDS" AllowFilteringByColumn="True" >
                            <ParentTableRelation>
                                <telerik:GridRelationFields DetailKeyField="RegionCode" MasterKeyField="RegionCode"  />
                            </ParentTableRelation>
                            <Columns>
                                <telerik:GridBoundColumn SortExpression="DealerId" HeaderText="Dealer" HeaderButtonType="TextButton"
                                    DataField="Dealer" UniqueName="DealerId">
                                </telerik:GridBoundColumn>

                                <telerik:GridBoundColumn SortExpression="RegionCode" HeaderText="FDAF Region Code" HeaderButtonType="TextButton"
                                    DataField="RegionCode" UniqueName="RegionCode" AllowFiltering="False">
                                </telerik:GridBoundColumn>
                                <telerik:GridBoundColumn SortExpression="DealerId" HeaderText="DealerId" HeaderButtonType="TextButton"
                                    DataField="DealerId" UniqueName="Dealer">
                                </telerik:GridBoundColumn>
                               <telerik:GridTemplateColumn ItemStyle-Width="22px" AllowFiltering="false">
                                <ItemTemplate>
                                    <asp:ImageButton ID="EditDealer" runat="server" AlternateText="Edit Dealer" ToolTip="Edit Dealer"
                                        ImageUrl="Images/edit.png" CommandArgument='<%# DataBinder.Eval(Container,"DataItem.DealerId")%>'
                                        CommandName="EditDealer" CausesValidation="false" />
                                </ItemTemplate>
                                <ItemStyle Width="22px"></ItemStyle>
                            </telerik:GridTemplateColumn>
                            </Columns>
                        </telerik:GridTableView>
                    </DetailTables>
                    <Columns>
                        <telerik:GridBoundColumn SortExpression="RegionName" HeaderText="FDAF Region" HeaderButtonType="TextButton"
                            DataField="RegionName" UniqueName="RegionName" AllowFiltering="False">
                        </telerik:GridBoundColumn>
                        <telerik:GridBoundColumn SortExpression="RegionCode" HeaderText="FDAF Region Code" HeaderButtonType="TextButton"
                            DataField="RegionCode" UniqueName="RegionCode">
                        </telerik:GridBoundColumn>
                        <telerik:GridBoundColumn SortExpression="RegionDealerCount" HeaderText="Dealers In Region" HeaderButtonType="TextButton"
                            DataField="RegionDealerCount" UniqueName="RegionDealerCount" AllowFiltering="False">
                        </telerik:GridBoundColumn>
                    </Columns>
                </MasterTableView>
            </telerik:RadGrid>

                     protected void grdRegions_ItemCommand(object sender, GridCommandEventArgs e)
                        {
                            objDealerDL.DealerId = Convert.ToInt32((e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["DealerId"].ToString());
                            GridDataItem item = (GridDataItem)e.Item;
                            if (e.CommandName == "EditDealer")
                            {
                                try
                                {
                                  do work
                                }
                                catch (Exception ex)
                                {

                                }
                            }
                        }

A: You can use the ItemDataBound method.
Within this method you simply search for the control by name and set it's command argument.
protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
    {
        if (e.Item is GridDataItem)
        {
            // this is the grids current rows item data
            GridDataItem item = (GridDataItem)e.Item;

            // This next line finds the image button control from within the grid cell
            ImageButton  btn = (ImageButton )item["ColumnNameHere"].FindControl("EditDealer");

            // Cast the data item back to the type of item that you passed in as a datasource
            YourDataItemType val = (YourDataItemType) item.DataItem;

           // now set your command argument
            btn.CommandArgument = val.ChildValue;
        }
    }

When I say Cast the data item back to the type of item that you passed in as a datasource
Your data source is RegionDS.
For example if your RegionDS is a list of regions i.e.
List<Region>

Your cast would be:

Region val = (Region) item.DataItem;

i.e. the Single object from the larger collective
In the case of data tables you would Replace Region with DataRowView.
As you don't state what you are using as a datasource it's hard to provide any further information.


text:
Q: Describe Sylow subgroups of $D_4$ I should describe Sylow subgroups of $D_4$.
$|D_4| = 8 = 2^3$, so $D_4$ has just 2-subgroup.
But I don't understand, how can i prove it formally.

A: Let's go through the various parts of Sylow's theorems, one by one, and try to understand how they apply to $D_4$.

Part 1: If $|G| = p^n m$, where $p$ is prime and $p$ does not divide $m$, then $G$ has a subgroup of order $p^n$. (Any such subgroup of order $p^n$ is called a Sylow $p$-subgroup of $G$.)

As you correctly pointed out, $ D_4$ has order $2^3$, so $p = 2$ is the only prime that divides the order of $D_4$. And $2^3$ is the highest power of $2$ that divides the order of $D_4$. Therefore, a Sylow $2$-subgroup of $D_4$ is a subgroup of order $2^3$. Well, does $D_4$ contain a Sylow $2$-subgroup? Yes it does: the entire group $D_4$ is (trivially) a subgroup of $D_4$ of order $2^3$. So Part 1 is satisfied.

Part 2: All Sylow $p$-subgroups of $G$ are conjugate subgroups.

Well, the entire group $D_4$ is actually the only Sylow $2$-subgroup of $D_4$. And any subgroup is trivially conjugate to itself.

Part 3: Suppose $|G| = p^n m$, and let $n_p$ be the number of distinct Sylow $p$-subgroups of $G$. Then $n_p$ divides $m$ and $n_p \equiv 1 {\rm \ mod \ } p$.

In our example, we have $p = 2$, $n = 3$, $m = 1$ and $n_2 = 1$. And yes, $ 1$ divides $1$, and $ 1$ is congruent to $1$ modulo $2$. So everything works!


text:
Q: Writing to the database from LINQ in C# I am trying to write some content to my database via LINQ. Currently, I'm getting the following error:
Cannot insert explicit value for identity column in table 'MyTable' when IDENTITY_INSERT is set to OFF.
I understand this is a primary key related issue. My table has the identity specification set to "Yes" with Identity Increment set to "1". But I have successfully updated other tables using code that looks like the following:
using (DataModelDataContext context = new DataModelDataContext())
{
  List<MyTable> newRecords = new List<MyTable>();
  MyTable record1 = new MyTable();
  record1.CreatedBy = GetUserName();
  record1.Information = GetInformation();
  newRecords.Add(record1);

  MyTable record2 = new MyTable();
  record2.CreatedBy = GetUserName();
  record2.Information = GetInformation();
  newRecords.Add(record2);

  context.MyTables.InsertAllOnSubmit(newRecords);
  context.SubmitChanges();
}

What would cause this error? If I want to write new records, is there a way to set the primary key before it gets sent to the db? Something like "GetNextKey()" or something? Basically, I just need to insert these records. What am I doing wrong?
Thanks!

A: The code you have posted would work, assuming neither of those fields have the identity value. You basically need to assure you do not try to set the identity value before you add the item to the Table collection. (actually, you should never set the identity value from your code in most circumstances when it is to be generated in the DB).
So somewhere, the code that is having an error is trying to set the identity field's value.

A: If the ID is important (say you're importing data, and records you'll be inserting later will reference these records), then turn off the identity temporarily while you perform the insert. If having a particular ID on each record doesn't matter, and you can let the identity column pick one (which is 99.9 percent of the time), make sure you're not specifying a value for the ID before trying to save the record. Also make sure that your mapping between the object and the DB specifies that the ID is an identity, so EF knows not to try to insert the ID column.

A: Check to make sure your primary key/identity column has the following set within the DBML:

*

*Auto Generated Value:  True

*Auto-Sync:  OnInsert

This will make sure that LINQ-To-SQL will not try and insert the key value into that column and that it will update the value after an insert takes place.  These should be on when you added the table to the DBML.


text:
Q: LESS CSS @import for javascript Do you know if there's some kind of tool like LESS CSS but for Javascript that allows you to import for example "plugin-1.js"; in my .js file. I'm working with a sublime text 2 build for LESS (which references dotless.exe), so maybe if you've tried something like that it'll be awesome if you can share it with us.

A: If you're in HTML JavaScript in the web you can organize your imports with libraries like require.js or to simply include another script tag above the one you're already using in your HTML.
<script src="plugin-1.js" type='text/javascript'> </script>

Otherwise, if you're using node.js this is done with the require() directive as such
var otherModuleToRequire = require("plugin-1.js");

After which it will be available in the file.
It is worth mentioning that while this are similar to @import in functionality they behave differently by doing the importing in run time instead of bundling all the files into one which is what @import does.
If you really care about bundling the files (for example in production under load) you can use minifiers and optimizers like the closure compiler or the require.js optimizer if you chose to use require.js.


text:
Q: Exploding string containing 0x in PHP I've noticed something peculiar in some internal php functions.
Using PHP 5.6.26
$a = "1280x720";
$b = explode('x', $a);

$b array:1 [
  0 => "1280×720"
]
$c = strpos($a, 'x');

$c boolean false
This is most probably caused by 0x720 being viewed as a hex number in part of the internal workings of explode and strpos.
Mostly since it does work as intended with a resolution of "854x480" . .
Even things like str_replace('x', 'separator', $a); don't work for me.
Does anyone know of a way to reliably get width and height from a resolution string like "1280x720" in php because I've about exhausted my ideas . .
UPDATE: Yes, it was indeed a typo (or rather read-o) in some cases there was an x and in others × (the 'times' character) . .

A: × and x aren't the same character. This is not a issue with PHP itself.
The first one is unicode multiplication sign, the other is just plain "x" character.
The following would work:
$a = "1280×720";
$b = preg_split('~[×x]~u', $a);

print_r($b);

Output:
Array
(
    [0] => 1280
    [1] => 720
)


text:
Q: Workflow: send notification before due date I'm an inexperienced SP user and need have created a workflow.
I created a site containing Libraries. All the Libraries contain the same new fields, which I created at the Site level.
I need a workflow that will send an email to the person named in the Point of Contact field if the Contract End Date is 90 days from the current date.
The email should say something like " your document is due to expire in 90 days. Please....."
I'm using Sharepoint 2013/Office365
Please help.

A: You can create a SharePoint Designer workflow and let it automatically start on Item Add event.
Inside the workflow use Calculate action to find out the date the notification is suppose to be sent.
Now you can use Wait or Pause activity so that the workflow will wait
Next add a sent email action..

A: You may want to explore document retention policies for this.
In this feature, you can apply a retention policy to documents and design rules and stages as per your requirements.
For more details refer below links ->

*

*Link1

*Link2


text:
Q: PHP child class doesn't have parent methods(possible configuration issue?) EDIT: I'm adding a screenshot of the actual errors, as a proof that this is what happens.

Note, that the $post_id and $id properties are undefined, because the parent Y_CF class has a magic __get() method, but again - it's not available in the child class.

I've had a bunch of issues already(including one, where PHP would pretty much just ignore a portion of an included file, even if I threw a bunch of random characters in there, which should cause a fatal error), but I'm finally down to a single issue:
I have two classes - a parent and a main class.
The parent class is abstract and has a factory method that returns different child classes, based on parameters passed to it.
The odd thing happens, with one of the child classes - it doesn't have the methods of the parent class. I'm posting only the relevant pieces of code
abstract class Y_CF {
    // even if "public", it doesn't work
    protected function parse_attributes( $attributes, $core_atts = array() ) {
        $this->__settings['attributes'] = wp_parse_args( $core_atts, $attributes );
    }
}

class Y_CF_Text extends Y_CF {
    public function __construct( $settings ) {
        parent::__construct( $settings );
        // This is false
        var_dump( method_exists( $this, 'parse_attributes' ) );

        $this->parse_attributes( $this->attributes, array(
            'id' => "Y_field_{$this->id}",
            'class' => esc_attr( 'yotta-text-input ' . $this->class ),
            'type' => ! empty( $this->attributes['type'] ) ? $this->attributes['type'] : 'text',
            'value' => $this->format_value( $this->value ),
            'name' => $this->gen_name(),
        ) );
    }
}

As you can see, my main class is Y_CF and I'm extending it with Y_CF_Text.
Note, that I've tried this code on my local server(ubuntu 14) and it works just fine(as it should).
I'm suspecting that the problem is somewhere in the server configuration, but I don't have any clue where.
What I did so far:

*

*Updated PHP to 5.5.12 ( the issue was happening with 5.3 as well )

*Disabled opcache

*Disabled memcached

*Restarted php, nginx and the whole server

All of those had no effect whatsoever.
I've also looked all over the internet and couldn't find anything that remotely mimics my situation.

A: Well, I feel very unlucky now :)
As a final resort, I started putting each of the classes in their own file. I got to the main class and I suddenly got the following error:
Parse error:  syntax error, unexpected end of file in /path/to/site/wp-content/plugins/yotta-util/lib/class-y-cf.php on line 291

I was like WHAT?! So, I started going through the whole file and I finally pin-pointed the issue to a single method of the class. When I scrolled to the end of the method, I saw this:
{some javascript code}
</script>
<?

Notice the missing "php" part after the question mark - that's where all of those issues were coming from. A single opening tag mistyped.
Now, I don't usually use the short tags, but I guess most servers are already configured to handle them properly, so I never got a single problem. But the server I'm working on right now has them turned off.
Somehow, instead of triggering a fatal error or anything at all, this only caused the described puzzling mess.
So in the end - it was just a single typo that caused me to bang my head around for at least 6 hours.


text:
Q: ArcGIS Portal not working with LDAP users I have set user identity store of ArcGIS Portal administration page like following.
{
  "type": "LDAP",
  "properties": {
    "userPassword": "secret",
    "isPasswordEncrypted": "false",
    "user": "uid=gisuser,ou=systemusers",
    "userFullnameAttribute": "displayName",
    "userGivenNameAttribute": "givenName",
    "userSurnameAttribute": "cn",
    "ldapURLForUsers": "ldaps://10.0.0.5:636/ou=users,ou=ags,dc=example,dc=com",
    "userEmailAttribute": "mail",
    "usernameAttribute": "uid",
    "caseSensitive": "false",
    "userSearchAttribute": "cn",
  }
}

After save the configurations, I tried to add members based on existing enterprise users in Portal. But no users found. The search result is empty whatever I searched.
Why does this happen?


text:
Q: Power Shell Scripts that will delete logs on folder and subfolder Calling Power Shell Guru's =)
Can anybody help me on creating power shell scripts that will delete log file on folder including logs on sub-folder?

A: Assuming what you want is to delete all files with the extension log for a directory specified in the variable logpath:
$logpath = "C:\ExamplePath\MyLogFiles"
Get-ChildItem $logpath -recurse *.log -force | Remove-Item -force


text:
Q: How would I create a bar button item that has both title and image in iOS, with the image showing as is without a tint? I have found solutions on stackoverflow to create a bar button item in iOS that has both title and image, but the image has a blue tint instead of showing as is. I have found solutions on stackoverflow to show the image in a bar button item as is without showing a blue tint, but the bar button item does not show a title.
Is it possible to create a bar button item that has both title and image with the image showing as is?
Here is my code:
let image = UIImage(named: "iMessage Icon 40x30.png")
let button = UIButton(type: .custom)
button.frame = CGRect(x: 0, y: 0, width: 500, height: 30)
button.setTitle("Purchase iMessage Saved Messages", for: .normal)
button.setImage(image, for: .normal)
button.addTarget(self, action: #selector(self.tap), for: .touchUpInside)
button.sizeToFit()
let customBarButtonItem = UIBarButtonItem(customView: button)
navigationItem.leftBarButtonItem = customBarButtonItem

This code creates the bar button item with the image as is, without a blue tint, but the title doesn't show. If I change the second line of code and init the UIButton object as a type system, the title shows as well as the image, but the image has a blue tint, which I don't want.

A: As you already mentioned in question, with type as system, you can see the image and title both.
So, you UIButton of system type, and change the below line from your code
button.setImage(image, for: .normal)

to this one:
button.setImage(image.withRenderingMode(.alwaysOriginal), for: .normal)

This will not allow tint to apply over your image and will use original image.

A: I'm Agree with above answer but in my case below code working fine.
button.setImage(UIImage(named: "ImageName.png").withRenderingMode(.automatic), for: UIControl.State.normal)


text:
Q: Soap request stuck when run in container Application:
Java maven application that is running on a tomcat server. Is runs a daily job to synchronize data between two systems. The SOAP client has been generated using Eclipse.
I have an application that has been running on a VM for multiple years that I am currently trying to modernize. I have upgraded dependencies, updated some code and am now trying to containerize it as well.
The upgrade went and I can fully run it on a local tomcat server. The problem becomes when I try to run the application running in a container. The container starts up and I can trigger the servlet. The application runs as usual but it gets stuck when sending the SOAP request. This is not an issue when running it outside of the container.
It seems to only be an issue sending that SOAP request when it is inside the container. I receive no error message. It just gets stuck on that specific line.
What could be the issue?


text:
Q: Relation of compositum of fields Let $E/k$ be a finite field extension, $\operatorname{char}(k)=p>0$. Suppose that $E^p k = E$. Is it then true that $E^{p^n}k = E$ for any positive integer $n$? If yes, why?
Thanks.

A: Yes, it is true. I will show that $E=E^{p^2}k$ and leave to you the proof of the general case $E=E^{p^n}k$.
Since $E=E^{p}k$, any element $e\in E$ can be written as $e=\sum q_ie_i^p\;$ (for some $e_i\in k, q_i\in k$)   .
[This is due to the fact that the ring formed by the sums on the right is already a field, because that ring is a $k$-subalgebra of  the algebraic extension $E/k$]
In the same way, each  $e_i$ can be written as $e_i=\sum q_{ij}e_{ij}^p$.
Substituting yields $$e=\sum q_i(\sum q_{ij}e_{ij}^p)^p=\sum q_iq_{ij}^pe_{ij}^{p^2}$$
which shows that indeed $E=E^{p^2}k$


text:
Q: wordpress qtranslate flags dropdown I'm using "qtranslate" plugin for word press to use metalanguage in my site,
How can i create a combo that will display only the flags in it ?
i have tried using the following code to generate the dropdown but it only displays the flags in a list:
echo qtrans_generateLanguageSelectCode('image');
$header_shortcodes = html_entity_decode(get_option(PREFIX.'_header_shortcodes'), ENT_QUOTES, 'UTF-8');
echo $header_shortcodes = apply_filters('themefuse_shortcodes',$header_shortcodes);

Thanks

A: I eventually took one of the solutions here and combined it with msdropdown plugin
Step 1: Go to the plugin folder and open qtranslate/qtranslate_widget.php. There in line no. 112 you will find case:'both'; Now where that case ends its line no 123 Below that add the following code (another case written)
case 'bothkria': ?>

        <select name="langchooser" id="langchooser" onchange="$(window.location).attr('href',this.value);">
        <?php
            /************************
            * go over the enabled languages and create all the languages options
            * the first marked "selected" is reffered to the current chosen language
            * the value is the relevant url and the title is the url of the image.
            *
            * After creating the selectbox we will run the msdropdown plugin to make it a designed select box
            * Of corse dont forget to have a reference to the msdropdown js library
            *
            * you can find it here http://www.marghoobsuleman.com/jquery-image-dropdown
            *************************/
            foreach(qtrans_getSortedLanguages() as $language)
            {
                if($q_config['language']==$language) {?>
                    <option selected="selected" value="<?php echo qtrans_convertURL($url, $language);?>" title="<?php echo get_option('home');?>/wp-content/<?php echo $q_config['flag_location'];?><?php echo $q_config['flag'][$language] ?>"><?php print strtoupper($q_config['pre_domain'][$language]); ?></option>
          <?php } else {  ?>
                    <option value="<?php print qtrans_convertURL($url, $language);?>" title="<?php echo get_option('home');?>/wp-content/<?php echo $q_config['flag_location'];?><?php echo $q_config['flag'][$language] ?>"><?php print strtoupper($q_config['pre_domain'][$language]); ?></option>
          <?php }
            } ?>
        </select>

    <?php break; ?>

A: What i understand from your question is that you need a dropdown list with both flag image and language if it is so then use the below code.
This code i have written and tested on qtranslate version 2.5.28 although it will work for other version as well reference line numbers are given according to this version.
Step 1: Go to the plugin folder and open qtranslate/qtranslate_widget.php. There in line no. 112 you will find case:'both';
Now where that case ends its line no 123
Below that add the following code (another case written)
`
case 'bothkria':
            if($_REQUEST['lang']!=""){ $kria = $_REQUEST['lang'];}else{$kria = $q_config['default_language'];}
            echo ' '.$q_config['language_name'][$kria].'

';
            foreach(qtrans_getSortedLanguages() as $language){
                      echo '
'.$q_config['language_name'][$language].'
';
            }
                    echo '
';
            break;

Step 2: Where you want to display it just paste the below code

<?php echo qtrans_generateLanguageSelectCode('bothkria'); ?>

Step 3: CSS Classes it was accordingly designed given here for your help you can change according to your theme.
`
.s_switcher {
              z-index: 10;
              position: absolute;
              top:6px;
              right:255px;
              font-size: 11px;
              background: #f6f6f6 url(../images/dropdown.gif) no-repeat 100% 6px;
              border-top: 1px solid #e9e9e9;
              border-left: 1px solid #e9e9e9;
              border-right: 1px solid #f6f6f6;
              border-bottom: 1px solid #f6f6f6;
              border-radius: 3px;
              -moz-border-radius: 3px;
              -webkit-border-radius: 3px;
            }
            .s_switcher ul {
              margin-bottom: 0;
            }
            .s_switcher span.s_selected,
            .s_switcher li,
            .s_switcher li a
            {
              display: block;
              height: 22px;
              line-height: 20px;
              text-indent: 7px;
            }
            .s_switcher span.s_selected {
              cursor: default;
              color: #999;
            }
            .s_switcher .s_options {
              cursor: pointer;
              display: none;
            }
            .s_switcher img {
              display: inline;
              margin: -1px 3px 0 0;
              vertical-align: middle;
              margin-left:10px;
            }

            #language_switcher .s_selected, #language_switcher .s_options li a {
                font-family:"Lucida Sans Unicode", "Lucida Grande", sans-serif;
                text-decoration:none;
                font-size:12px;
                color:#333;
                }

            #language_switcher .s_options li a{
                color:#999;}
            #language_switcher .s_options li a:hover{
                color:#333;}

`
Done upload the files and check.
Hope this is what you wanted.
Enjoy
Thank you!


text:
Q: Is this a compact metric space? Consider a fixed set of finite discrete symbols $\mathcal{A}$. Equip $\mathcal{A}$ wit the discrete topology which we denote by $\theta$, and $\mathcal{A}^{\mathbb{Z}^d}$ with the product topology, denoted by $\tau$.
Is then $(\mathcal{A}^{\mathbb{Z}^d},\tau)$ a compact metric space?
I think this has something to do with Tychonoff.

A: It's not a metric space, because you haven't defined a metric. It is, however, a metrizable space: there are metrics on it that generate the product topology. It is homeomorphic to the middle-thirds Cantor set.
One compatible metric is obtained as follows. Let $\varphi:\Bbb N\to\Bbb Z^d$ be any bijection. Let $X=\mathcal{A}^{\Bbb Z^d}$. If $x$ and $y$ are distinct points of $X$, let
$$\delta(x,y)=\min\left\{n\in\Bbb N:x\big(\varphi(n)\big)\ne y\big(\varphi(n)\big)\right\}\;.$$
Then for $x,y\in X$ set
$$d(x,y)=\begin{cases}
0,&\text{if }x=y\\
2^{-\delta(x,y)},&\text{if }x\ne y\;;
\end{cases}$$
$d$ is a metric on $X$ that generates the topology $\tau$.


text:
Q: two tables different conditions I'm trying to make one table output from two different selects.
first one:
select NAME
  from PROVIDER_GROUP
 where ID=(select GROUP_ID
             from CUSTOMER_GROUP
            where CUSTOMER_ID=(select CUSTOMER_ID
                                 from CUSTOMER
                                where PHONE = 'MyNumber123'));

select PHONE
  from CUSTOMER
 where PHONE = "MyNumber123"

TABLES:
┌─────────────────────┐     ┌─────────────────────┐     ┌─────────────────────┐
│   PROVIDER_GROUP    │     │    CUSTOMER_GROUP   │     │       Customer      │
├─────────────────────┤     ├─────────────────────┤     ├─────────────────────┤
│        NAME         │     │      GROUP_ID       │     │     CUSTOMER_ID     │
│      GROUP_ID       │     │     CUSTOMER_ID     │     │        PHONE        │
└─────────────────────┘     └─────────────────────┘     └─────────────────────┘

Expected:
            ┌─────────────────────┬─────────────────────┐
            │       PHONE         │        NAME         │
            ├─────────────────────┼─────────────────────┤
            │    +12345678910     │ NameProviderGroup1  │
            │    +12345678910     │ NameProviderGroup2  │
            │    +12345678910     │ NameProviderGroup3  │
            └─────────────────────┴─────────────────────┘

A: I think I understand what you are asking now.  Let me know if this does the trick.
SELECT C.PHONE
    ,PG.NAME
FROM PROVIDER_GROUP PG
JOIN CUSTOMER_GROUP CG ON CG.GROUP_ID = PG.GROUP_ID
JOIN CUSTOMER C ON C.CUSTOMER_ID = CG.CUSTOMER_ID
WHERE C.PHONE = 'MyNumber123'

You may need to use LEFT JOIN depending on whether you want to see provider groups that don't have a customer phone number attached in the CUSTOMER_GROUP table.
Anecdotal, but the CUSTOMER_GROUP table is the middle-man between your CUSTOMER and PROVIDER_GROUP table. It's a many-to-many relationship between those two tables. The junction table CUSTOMER_GROUP defines the relationships between the two.
Also, your table diagrams are very nice.


text:
Q: How do I run xrandr? I'm running xubuntu and I'm trying to run xrandr but I get the error RandR extension is missing. I know that it is installed because I ran sudo aptitude install x11-xserver-utils. I just uninstalled the latest nvidia drivers. I read that Nvidia might interfere with xrandr over xinerama?
Is xrandr disabled? If so, how can I enable it?

A: Switching to NVIDIA binary driver - version 352.63 from nvidia-352 and then restarting fixed the issue.


text:
Q: How to extract the filename and path from sub directories and need to write the output into a csv file using unix shell script I need to extract the filenames as well as path in a csv file from different subdirectories in a parent directory using  unix shell script .
Requirement : I have different subfolders in a parent. Every subfolder ha one image file. Now , I need to list the filename and path of that file , And need to write the filenames and path into a csv file for all the sub directories.
Please help me out.
-Sudhir.

A: If I understand correct, you want write filename and path to csv file.
#!/bin/bash

echo "Dir, Name" > "csvfile.csv"

files=$(find /YOURPATH -type f)

for f in $files
do

dir=$(dirname $f)
name=$(basename $f)
echo "$dir, $name" >> "csvfile.csv"

done

Find all files in /YOURPATH, write path and filename to csvfile.csv.
Or If you want to find just image file and if you know type, you can use like this:
find /YOURPATH -type f -name *.jpg


text:
Q: Event Listener on Navigation with react router v6 I would like to add an event listener to a navigate event in react router v6. I have not found anything to it. Is there such a feature?
Edit: When the event is handled, I want to prevent the navigation and route the user to another destination, which depends on where he is comming from.

A: You can useLocation() and useEffect().
const location = useLocation();
useEffect(() => {
   console.log("url changed")
}, [location]);


text:
Q: Determine national carrier code using libphonenumber I need to determine the national carrier code (not the country code) of any phone number, using libphonenumber Java SDK. How can I do this?

A: This should help your case - PhoneNumberToCarrierMapper

*

*com.google.i18n.phonenumber.PhoneNumberToCarrierMapper
In the PhoneNumberToCarrierMapper class there is a method:
String getNameForValidNumber(PhoneNumber number, Locale languageCode)

This should give your the carrier code.
You can see the source code of that method in the related GitHub repository here.

A: libphonenumber-8.13.6 doesn't seem to come packaged with PhoneNumberToCarrierMapper class. The import will not work for com.google.i18n.phonenumbers.PhoneNumberToCarrierMapper
I had to add a separate jar to my build path to get this class to successfully import. If you are using maven, you would just need to add a new dependency to your pom file.
https://repo1.maven.org/maven2/com/googlecode/libphonenumber/carrier/


text:
Q: Custom HTML tag in Google Tag Manager with variables I have a custom html tag in my Google Tag Manager
<script>const d = 'sdfsf'; console.log(d);</script>

Now I want sdfsf to be a variable, passed to GTM from my HTML where I have GTM init snippet. Can this be achieved anyhow?

A: GTM supports the use of variables in GTM. Apart from the "usual" dataLayer method already described by Cthulchu:
window.dataLayer = window.dataLayer || [];
window.datalayer.push({
  "event":"upDateD",
  "d":"customValueForD"
})

Where the first line makes sure that the datalayer variable either exists or is declared, the payload is pushed as an object, and the "event" key reminds GTM to update it's internal variables to "d" becomes available as a variable in GTM.
Then you have to go to the "variables" section inside GTM, select "new", select the "dataLayer" variable type, and give it a name - to stay consistent let's use "d" and  then enter "d" as the dataLayer key.
Now you can use the value in GTM tags by wrapping the name of your variable in double curly brackets:
<script>console.log({{d}});</script>

An alternative way is to use the "Javascript" variable type, which you set to the name of a JS variable that exists in the global namespace. You can use in the same way as dataLayer variables.
The datalayer mostly serves as a namespace of its own, to encapsulate variable names and avoid naming collisions. If your variable already exists and has a use outside GTM, then I see nothing wrong with saving yourself a few lines and use the "Javascript" variable type (just make sure that you do not confuse this with the "Custom Javascript" type, which allows you to define an anonymous function and use the return value).

A: sure it can. With the dataLayer events. You push a new event to the dataLayer and certain variables with it. In GTM, you declare variables for each property you want to have access to from GTM and you use the event as a trigger.
Here, take a look:https://developers.google.com/tag-manager/devguide it explains it pretty well.


text:
Q: Usage of present perfect tense with other tenses A : How are you feeling ?
B : I have been feeling better since ............
a) the doctor has come
b) the doctor will come
c) the doctor had come
d) the doctor came
So which option is right and why?
Thanks

A: I have been feeling better is a statement about your present state; the present perfect construction indicates that that state started in the past. The since clause designates the start of that state, the point in time at which it began. In this case it began with an event, the doctor's coming, which was completed in the past.

*

*That cannot be expressed with a), the present perfect, the doctor has come, because that, again, designates a present state.

*It cannot be expressed with b), the future, the doctor will come, because that designates an event which has not happened yet.

*It cannot be expressed with c), the past perfect, the doctor had come, because that designates a past state which came after the doctor's coming.

It is properly expressed with the simple past form, answer d):

I have been feeling better since the doctor came.


text:
Q: I am trying to retrieve HTML Node.js to my react app I currently have a Node.js script that is getting html data from a website and putting it onto a local host server. I have that aspect working but I can't retrieve the HTML from my react app. I want to get the data from UND website and then be able to display some of the headlines onto my own website home page. My question is why am I not able to retrieve the HTML from my server into my react app.
Below is my react app
import React, {useEffect, useState} from "react";
import axios from "axios";

function Home() {
const [html, setHtml] = useState("");

useEffect(() => {
    axios
    .get("https://localhost:3000")
    .then((response) => {
        setHtml(response.data);
    })
    .catch((error) => {
        console.log("An error occurred:", error);
    });
}, []);

return
{html}
;
}

export default Home;

Below this is my Node.js file that is getting the html that I want.
    const express = require("express");
const cheerio = require("cheerio");
const axios = require("axios");

const app = express();
app.post("/post", (req, res) => {
    console.log("Connected to react");
    res.redirect("/");
})
const PORT = process.env.PORT || 3000;

const website = "https://und.com";

let options = {
headers: {
    "user-agent":
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36"
}
};

app.get("/", (req, res) => {
// Make the HTTP request using axios
axios(website, options)
.then(({data}) => {
    const $ = cheerio.load(data);
    const result = $(".post__meta h3 a:last-child")
    .map((_, e) => $(e).text().trim())
    .get();
    console.log(result);
    // Use cheerio to manipulate the HTML data

    // Set the content type of the response to "text/html"
    res.set("Content-Type", "text/html");

    // Send the HTML data as the response
    res.send(result);
    })
    .catch((error) => {
        // The HTTP request failed
        console.log("An error occurred:", error);

        // Set the status code of the response to indicate an error
        res.status(500);

        // Send an error message as the response
        res.send("An error occurred while making the HTTP request.");
    });
    })

app.listen(PORT, () => {
    console.log(`server is running on PORT: ${PORT} `);
})

A: Just use dangerouslySetInnerHTML.
So replace this:
return
{html}
;

With this:
return
;

But pay attention that setting HTML from code is risky because it's easy to inadvertently expose your users to a cross-site scripting (XSS) attack.


text:
Q: How to include specific locale from AngularJS I18n files using bower? I've downloaded the angular I18n repo using bower install angular-i18n which pulls it into my bower_compontents and updates the bower.json file with angular-i18n : 1.5.3, which is expected behavior.
I want to include a specific locale(ex. de-de.js) in my build process so that it gets included along with the other angular scripts, every time I run grunt serve which isn't happening at the moment. Any ideas how this can be achieved?
Thanks.

A: In my case, I added in my bower file the specific version that i need using the link of the raw version of the file angular-locale_es.js.
bower.json
"dependencies": {
    "angular": "^1.5.0",
    "angular-mocks": "^1.5.0",
    ...
    "angular-locale_es": "https://raw.githubusercontent.com/angular/bower-angular-i18n/master/angular-locale_es.js",
     ...
  }

A: In your bower.json you can add an overrides section and specify the i18n script you want to include.

{
  "name": "your application",
  "version": "1.1.2",
  "dependencies": {
    "angular": "#1.5.7",
    "angular-i18n": "#1.5.7",
 "moment": "#2.13.0",
  },
  "overrides": {
    "angular-i18n":{
      "main":[
        "angular-locale_de-ch.js"
      ]

    },
    "moment": {
      "main": [
        "moment.js",
        "locale/de.js"
      ]
    },
  }
}

A: So to answer my own question, if you only want one of the locales you can copy and replace the contents of the de-de.js locale into the main angular-i18n file, which is hassle free and does not require a complicated approach.
However if you have multiple locales and want to make a decision based on a condition, you can set a default locale using this library
https://github.com/lgalfaso/angular-dynamic-locale/
after which all you have to do is add a base location for your locale files(I'm using the CDN for example):     tmhDynamicLocaleProvider.localeLocationPattern('https://cdnjs.cloudflare.com/ajax/libs/angular-i18n/1.5.5/angular-locale_{{locale}}.js');
check for your condition and pass the locale as $translate.use('de');
Hope that helps!


text:
Q: Asp.net Textbox dynamic adding dash - i have 1 TextBox is Asp.net this textbox is Zip-Code / Postal code like "41-200"
How i can dynamic(when user writes this) add dash "-" after 2 character.
I try used update panel but doesnt work


text:
Q: How change space only columns to null I have a database with four tables that has a number of columns (VARCHAR) that contains one or more spaces. I would like to replace these spaces with NULL.
I can do it if I specify the table and each column
UPDATE LaserData
SET Kant = NULL
WHERE Kant= ''

But is there a way that I can use a list of tables and a list of columns and do this for all without writing a query for each?

A: That's an odd question, but you could go with something like this:
USE YourDatabaseName
GO

CREATE TABLE #TempColumns (
    id int,
    tname varchar(50),
    cname varchar(50))

INSERT INTO #TempColumns (
    id,
    tname,
    cname)
SELECT
    ROW_NUMBER() OVER (ORDER BY t.name) AS ColId,
    t.name,
    c.name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID

DECLARE @ColumnCount INT =
(
    SELECT COUNT(*) FROM #TempColumns
),
@i INT = 1,
@TableName VARCHAR(MAX),
@ColumnName VARCHAR(MAX),
@DataType VARCHAR(20),
@AllowNull INT;

WHILE (@i <= @ColumnCount)
BEGIN
    SET @TableName = (
        SELECT t.tname
        FROM #TempColumns t
        WHERE t.id = @i);
    SET @ColumnName = (
        SELECT t.cname
        FROM #TempColumns t
        WHERE t.id = @i);
    SET @DataType = (
        SELECT t.name
        FROM sys.columns AS c INNER JOIN sys.types AS t ON c.user_type_id=t.user_type_id
        WHERE OBJECT_NAME(c.OBJECT_ID) = @TableName AND c.name = @ColumnName);
    SET @AllowNull = (
        SELECT COLUMNPROPERTY(OBJECT_ID(@TableName), @ColumnName, 'AllowsNull'));

    IF (@DataType = 'varchar')
    BEGIN
        IF (@AllowNull = 1)
        BEGIN
            EXEC('UPDATE ' + @TableName + ' SET ' + @ColumnName + ' = NULL WHERE ' + @ColumnName + '= ''''')
        END
    END
    SET @i = @i + 1;
END

This will create a temporary table to store all the table names and their respective columns, it will then perform an update (in this case) per every column on every table only when datatype is VARCHAR.


text:
Q: How to subtract two strings? I have a long string, which is basically a list like str="lamp, bag, mirror," (and other items)
I was wondering if I can add or subtract some items, in other programming languages I can easily do: str=str-"bag," and get str="lamp, mirror," this doesnt work in python (I'm using 2.7 on a W8 pc)
Is there a way to split the string across say "bag," and somehow use that as a subtraction? Then I still need to figure out how to add.

A: you could also just do
print "lamp, bag, mirror".replace("bag,","")

A: How about this?
def substract(a, b):
    return "".join(a.rsplit(b))

A: You can do this as long as you use well-formed lists:
s0 = "lamp, bag, mirror"
s = s0.split(", ") # s is a list: ["lamp", "bag", "mirror"]

If the list is not well-formed, you can do as follows, as suggested by @Lattyware:
s = [item.strip() for item in s0.split(',')]

Now to delete the element:
s.remove("bag")
s
=> ["lamp", "mirror"]

Either way - to reconstruct the string, use join():
", ".join(s)
=> "lamp, mirror"

A different approach would be to use replace() - but be careful with the string you want to replace, for example "mirror" doesn't have a trailing , at the end.
s0 = "lamp, bag, mirror"
s0.replace("bag, ", "")
=> "lamp, mirror"

A: you should convert your string to a list of string then do what you want. look
my_list="lamp, bag, mirror".split(',')
my_list.remove('bag')
my_str = ",".join(my_list)

A: If you have two strings like below:
t1 = 'how are you'
t2 = 'How is he'

and you want to subtract these two strings then you can use the below code:
l1 = t1.lower().split()
l2 = t2.lower().split()
s1 = ""
s2 = ""
for i in l1:
  if i not in l2:
    s1 = s1 + " " + i
for j in l2:
  if j not in l1:
    s2 = s2 + " " + j

new = s1 + " " + s2
print new

Output will be like:

are you  is he

A: from re import sub

def Str2MinusStr1 (str1, str2, n=1) :
    return sub(r'%s' % (str2), '', str1, n)

Str2MinusStr1 ('aabbaa', 'a')
# result 'abbaa'

Str2MinusStr1 ('aabbaa', 'ab')
# result 'abaa'

Str2MinusStr1 ('aabbaa', 'a', 0)
# result 'bb'

# n = number of occurences.
# 0 means all, else means n of occurences.
# str2 can be any regular expression.

A: Using regular expression example:
import re

text = "lamp, bag, mirror"
word = "bag"

pattern = re.compile("[^\w]+")
result = pattern.split(text)
result.remove(word)
print ", ".join(result)

A: Using the following you can add more words to remove (["bag", "mirror", ...])
(s0, to_remove) = ("lamp, bag, mirror", ["bag"])
s0 = ", ".join([x for x in s0.split(", ") if x not in to_remove])
=> "lamp, mirror"


text:
Q: How to select n number of random integers within a specific summary I need to get list of random integer like below...
select FunctionNeeded(min_num, max_num, row count, sum of rows);

What I want to get as the result is
select FunctionNeeded(1, 10, 5, 30);
-----------------------------------------
5
6
7
10
2

Is there any function or something?
Any of altanative way would be also appreciated.
Thanks in advance.

A: You can use something like this. I didn't understand what the 30 is for though:
create function FunctionNeeded(
  value_from int, value_to int,
  number_of_values int, something_else int) returns setof int as $$
select floor(random() * (1+$2-$1))::int + $1
from generate_series(1,$3)
$$ language sql;


text:
Q: grep in pipeline: why it does not work I want to extract certain information from the output of a program. But my method does not work. I write a rather simple script.
#!/usr/bin/env python

print "first hello world."
print "second"

After making the script executable, I type ./test | grep "first|second". I expect it to show the two sentences. But it does not show anything. Why?

A: Escape the expression.
$ ./test | grep "first\|second"
first hello world.
second

Also bear in mind that the shebang is #!/usr/bin/env python, not just #/usr/bin/env python.

A: use  \| instead  of |
./test | grep "first\|second"


text:
Q: preg_match echo not working I have this page which I am using to post (rotas.php):

SBGL 	KMIA 	B763 	UM409 EKUBA UM409 DADOT UM409 VUMPI UM409 	959 	N0460 	310 	H 	EET/SBBS0030 SBAZ0230 SVZM0425

SBGL 	KMIA 	B763 	UM409 EKUBA UM409 DADOT UL304 ISANI UL304 	727 	N0490 	360 	H 	EET/SBBS0018 SBAZ0157 SVZM0400

SBGL 	KMIA 	B763 	UM409 EKUBA UM409 DADOT UL304 ISANI 	837 	N0470 	320 	H 	EET/SBBS0030 SBAZ0230 SVZM0425

SBGL 	KMIA 	A332 	UM409 EKUBA UM409 DADOT UM409 VUMPI UM409 	849 	N0480 	360 	H 	EET/SBBS0025 SBAZ0222 SVZM0442

4 registro(s) encontrado(s)

and this is my page:
<?php

$adep = $_GET['adep'];
$ades = $_GET['ades'];

$postdata = http_build_query(
    array(
        'adep' => $adep,
        'ades' => $ades
    )
);

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);

$context  = stream_context_create($opts);

$result = file_get_contents('http://www.cgna.gov.br/sistemas/harpia/rotas.php', false, $context);

preg_match_all("'
".$adep." 	".$ades." 	(.*?)<\/tr>'si", $result, $match1);
preg_match_all("'
".$adep." 	".$ades." 	(.*?)<\/tr>'si", $result, $match2);

foreach($match1[1] as $rota)

    {
         preg_match("'(.*?)<\/td>'si", $rota, $match_rota1);
         echo $match_rota1[1];

    }

    foreach($match2[1] as $rota)

    {
         preg_match("'(.*?)<\/td>'si", $rota, $match_rota2);
         echo $match_rota2[1];

    }

?>

When I use $match_rota1[1]; AND $match_rota2[1]; it works properly, showing the result B763 B763 B763 A332
But when I try to use $match_rota1[2]; AND $match_rota2[2]; I get a blank page instead of the results, like UM409 EKUBA UM409 DADOT UL304 ISANI UL304
-EDIT-
From each line like this

SBGL 	KMIA 	B763 	UM409 EKUBA UM409 DADOT UM409 VUMPI UM409 	959 	N0460 	310 	H 	EET/SBBS0030 SBAZ0230 SVZM0425

I expect this UM409 EKUBA UM409 DADOT UM409 VUMPI UM409 instead of this B763
Why is my code not working??

A: I see only one set of matching parens, so I'm not sure why there would be a second match. Where are you expecting $match_rota2[2]; to come from?

A: Problem solved, sorry:
foreach($match2[1] as $rota)

    {
         preg_match_all("'(.*?)<\/td>'si", $rota, $match_rota2);  // preg_match_all instead of preg_match
         echo $match_rota2[1][1]."
"; // added [1]

    }

A: You can try this:
$result = file_get_contents('http://www.cgna.gov.br/sistemas/harpia/rotas.php', false, $context);

$pattern = <<<LOD
~
(?(DEFINE) (?  )) # define the opening tag subpattern

  \g $adep \s*
  \g $ades \s*
  \g [^<]* 	 \g \K                  # the \K reset all the match before
  [^<]+
  (?= \s+ < )
~xi
LOD;

preg_match_all($pattern, $result, $matches);
print_r($matches[0]);


text:
Q: Customize permalink wordpress category id I'm looking to add "ID" for tags And category in the URL permalink.
Our link right now is:
example.com/lastnews
example.com/hashtag/{tagname}

We looking to change it to:
example.com/{cat-id}/lastnews
example.com/hashtag/{tag-id}/{tagname}

Can any one help us to do that any code,plugin?


text:
Q: How to set dynamic key while updating via mongoose in NodeJS, Express Since there are a lot of keys that I want to update from just one function.
I need to understand how I can set the key to update dynamically.
static async updateProfile(req, res, next) {

    const userId = req.body.userId;

    // I am receiving the key in body that needs to be updated
    const key = req.body.key;
    const value = req.body.value;

    const toUpdate = {
        userId: userId,
        //here I want the key to be dynamic
        key: value
    };

    try {
        const updateNow = await Profile.findOneAndUpdate(
          { userId: userId },
          toUpdate,
          { upsert: true }
        );
    } catch (err) {
        console.log(err);
    }
}

A:

const toUpdate = {
  ...
  [key]: value
}

or

toUpdate[key] = value;

or

toUpdate[`${key}`] = value;

any of the above works


text:
Q: php exec won't execute what is executable in console regarding audio and video I have php to run a shell command to start an audio/video stream via ffmpeg. I tried the syntax in the console (as the same user as php [www-data] and from the same location as the php-script:
pi@raspberrypi:/var/www/html/ $ sudo -H -u www-data ffmpeg {parameters}
This works nicely. Both audio and video is visible on youtube. When I execute from php with exactly the same parameters
$pid = exec("ffmpeg {parameters} 2> out.txt");

the response is
cannot open audio device hw:1,0 (No such file or directory)
My first guess was that this had something to do with users and groups, but I can't tell what. I even put www-data in the sudo group. Still not working.
If I do
exec("whoami 2> user.txt");

the file user.txt is created (with owner www-data) but remains empty. Can anyone help me out?
UPDATE
When I reboot the pi it works only one time. I think that somehow after closing the stream
exec("kill -9 ".$pid);

the audio is still busy. The error message is changed in
cannot open audio device hw:1,0 (Device or resource busy)

The video (via uv4l: localhost:port/stream/video.mjpeg) is available.


text:
Q: Variable with assigned value is still undefined when checked with typeof I'm doing a simple exchange rate buttons for a website and I'm testing it with a set value under a variable. I'm still getting errors though due to the fact that when I check this variable it shows as undefined. What may be the cause? I know it's basic stuff but I don't see what could be the issue here. Thanks for helping solve this!
Component.ts:
public price: number = 500;
public exchangeUsd;
public priceUsd;

countUsd() {
  fetch("https://api.nbp.pl/api/exchangerates/rates/a/usd/?format=json")
    .then((resp) => resp.json())
    .then(function(data) {
      let exchangeUsd = data.rates[0].mid
      console.log("Exchange rate: " + exchangeUsd)
      console.log(this.price) //here the typeof shows undefined
      priceUsd = exchangeUsd * this.price //and it also makes this simple multiplication impossible
    })
}

Stackblitz: https://stackblitz.com/edit/flight-date-picker-with-service-done

A: Could not test it but it is mostly because of .then(function(data). Replace this with arrow function
.then((data) => {
let exchangeUsd = data.rates[0].mid
}

A: This is a scope problem. You have two options. Or you use an arrow function in then(...) or you carry the scope to the function by capturing it with a variable:
Option 1: Arrow function
function countUsd() {
  fetch("https://api.nbp.pl/api/exchangerates/rates/a/usd/?format=json")
    .then((resp) => resp.json())
    .then((data) => {
      let exchangeUsd = data.rates[0].mid
      console.log("Exchange rate: " + exchangeUsd)
      console.log(price) //here the typeof shows undefined
      priceUsd = exchangeUsd * price //and it also makes this simple multiplication impossible
    })
}

Option 2: capture the scope with a variable
function countUsd() {
  const classScope = this;
  fetch("https://api.nbp.pl/api/exchangerates/rates/a/usd/?format=json")
    .then((resp) => resp.json())
    .then(function(data) {
      let exchangeUsd = data.rates[0].mid
      console.log("Exchange rate: " + exchangeUsd)
      console.log(classScope.price) //here the typeof shows undefined
      priceUsd = exchangeUsd * price //and it also makes this simple multiplication impossible
    })
}

A: You've this.price in the console.log which should be price instead.
The code below will work for you:
public price: number = 500;
public exchangeUsd;
public priceUsd;

function countUsd() {
  fetch("https://api.nbp.pl/api/exchangerates/rates/a/usd/?format=json")
    .then((resp) => resp.json())
    .then(function(data) {
      let exchangeUsd = data.rates[0].mid
      console.log("Exchange rate: " + exchangeUsd)
      console.log(price) //here the typeof shows undefined
      priceUsd = exchangeUsd * price //and it also makes this simple multiplication impossible
    })
}


text:
Q: What is TimeHash and How it Works? I am doing my rapport of a final year project.
I have used time-hash algorithm in my project, unlike geo-hash, i didn't find a clear explanation about time-hash and how that works ?

A: From my github.com project timehash:
timehash is an algorithm (with multiple reference implementations) for calculating variable precision sliding windows of time. When performing aggregations and correlations on large-scale data sets, the ability to convert precise time values into 'malleable intervals' allows for many novel analytics.
Using sliding windows of time is a common practice in data analysis but prior to the timehash algorithm it was more of an art than a science.

*

*convert epoch miliseconds into an interval of time, depicted by an ASCII character 'hash' (a 'timehash')

*timehash values are well suited to referencing time intervals in
key-value stores (e.g. Hbase, Acculumo, Redis)

*The creation of a compound key of space and time (e.g.
geohash_timehash) is a powerful primitive for understanding
geotemporal patterns

https://github.com/abeusher/timehash


text:
Q: Why does randomness exhibit a pattern in the long run? !!! Layman here so please avoid complex math and answers.
Random (usually pseudorandom) events are usually characterized along these lines:

*

*Each outcome in a trial experiment must be i.i.d.; i.e. it has no effect on subsequent outcomes, thus individual outcomes cannot be predicted using past data as there is no obvious causal link

*Large sequences of outcomes are predictable, because they exhibit a pattern of stabilizing relative frequencies, such that no individual outcome is "preferred" and dominates the rest
The prevailing thought in probability theory (frequentism) is that stabilizing relative frequencies are an objective phenomenon, independent of human thought. This assumption has served statisticians, casinos and insurance companies well. What this basically implies is that large sequences of similar random events are consistent and their averages can be confidently predicted within a "sufficiently" large sample.
Why can we predict the averages of big samples of individually unpredictable random events?

A: The single determining characteristic that is required for the emergence of the Law of large Numbers is that the various random events are independently random (or at least sufficiently so).
If I had a coin that I flip once, and then observe repeatedly, then those observations won't be independent. They'll be random, for sure: I cannot predict the result of the 2nd observation up front, but I can predict the result of all future observations after I observed the coin once. The LLN does not hold here.
But if I flip the coin as little as once every 1000 observations, then those observations are already sufficiently independent for the LLN to kick in. After all, the first observation now predicts only a minuscule fraction of the next million observations.

A: Toss a fair coin. For a single drawing the expected proportion of heads is distributed as follows (for $0$ and $1$):
$$\frac12, \frac12$$
For ten drawings in a row, by simple probability computation (from $0$ to $10$):
$$\frac{1}{1024}, \frac{10}{1024}, \frac{45}{1024}, \frac{120}{1024}, \frac{210}{1024}, \frac{252}{1024}, \frac{210}{1024}, \frac{120}{1024}, \frac{45}{1024}, \frac{10}{1024}, \frac{1}{1024}$$
The probability of very skewed drawings, like 10 heads in a row, goes decreasing with the length of the sequence, and the more "compliant" distributions are much more likely.
So completely deviating means are still possible, but with a smaller and smaller probability. The probability distribution always tend to concentrate around the mean. (The standard deviation is divided by the square root of the sequence length.)

A: Note that as empirical scientists, physicists don't really need any more than the ability to make testable predictions to justify a theory.
According to our current understanding, the most basic laws of nature (quantum theories) are probabilistic. As far as we know, that's just how the world works, and if there's a deeper reason behind it, we haven't been able to find it.
The prime example for a probabilistic system due to quantum effects would be radioactive decay.
At macroscopic levels, there are several ways for probabilities to emerge, and here are two ways I thought of:
First, we can have a family of interacting periodic systems. If you look at them only for a short time, they appear random; but if you waited for the least common multiple of the periods (or any time 'long enough'), they'll behave perfectly regularly.
A second example would be chaotic systems, which are effectively unpredictable - but this does not mean that you're equally likely to find the system in any particular region of phase space.
Now, what happens when you have a large number of such systems? Then, we have results like the law of large numbers or the central limit theorem. From a practical point of view, in many cases, you just end up either with random noise or a bell curve.
Now, let's look at a particular example: Tossing a coin.
Let's assume we're operating under ideal conditions, and the result of any toss only depends on two parameters: The coin's spin and its velocity.
The result will be periodic in both initial conditions, and if you overlay a source of noise, it's easy to see how you can end up with 50/50 probabilities if the parameters are right. The randomness of the coin toss got pushed back to the randomness of the noise.


text:
Q: Utility of consumption with mortality and finite termination In [Calvo, Guillermo A., and Maurice Obstfeld. Optimal time-consistent fiscal policy with finite lifetimes. Econometrica: Journal of the Econometric Society (1988): 411-432], the authors derive
$$
\mu(b)\equiv\int_{b}^{\infty}u\left[c(b,t)\right]\left[1-F(t-b)\right]e^{-\beta(t-b)}dt
$$
as the utility of an individual where $b$ is the birth time of the individual, $c$ is their consumption, $F$ is the CDF of a random variable corresponding to the length of their life, $u$ is their utility, and $\beta$ is their discount rate.
I would like to instead study the case in which there is a terminal time $T>b$ beyond which we do not care about the individual's utility.
How can I formulate this as an integral?

A: Calvo and Obstfeld's problem
In [Calvo, Guillermo A., and Maurice Obstfeld. Optimal
time-consistent fiscal policy with finite lifetimes.
Econometrica: Journal of the Econometric Society (1988): 411-432],
they study
$$
\mu(b) \equiv \int_{b}^{\infty}u\left[c(b,t)\right]\left[1-F(t-b)\right]e^{-\beta(t-b)}dt
$$
where $b$ is the birth time of an individual, $c$ is their consumption, $F(n)$ is the CDF of the random variable $\tilde{n}$ corresponding to the length of their life, $u$ is their utility, and $\beta$ is their discount rate.
Assumptions. $F(0)=0$, $\tilde{n}$ is absolutely continuous (with density function $f$), and $u \geq 0$. All measurability requirements for the integrals to be well-defined should also be satisfied.
The definition of $\mu(b)$ is motivated by noting that
\begin{align*}
\mathbb{E}\left[\int_{b}^{b+\tilde{n}}u\left[c(b,t)\right]e^{-\beta(t-b)}dt\right] & =\int_{0}^{\infty}\left(\int_{b}^{b+n}u\left[c(b,t)\right]e^{-\beta(t-b)}dt\right)f(n)dn\\
 & =\int_{0}^{\infty}\left(\int_{b}^{\infty}u\left[c(b,t)\right]e^{-\beta(t-b)}\boldsymbol{1}_{(t-b,\infty)}(n)dt\right)f(n)dn\\
 & =\int_{b}^{\infty}u\left[c(b,t)\right]e^{-\beta(t-b)}\left(\int_{0}^{\infty}f(n)\boldsymbol{1}_{(t-b,\infty)}(n)dn\right)dt\\
 & =\int_{b}^{\infty}u\left[c(b,t)\right]e^{-\beta(t-b)}\mathbb{P}(n>t-b)dt\\
 & =\int_{b}^{\infty}u\left[c(b,t)\right]e^{-\beta(t-b)}\left[1-\mathbb{P}(n\leq t-b)\right]dt\\
 & =\int_{b}^{\infty}u\left[c(b,t)\right]e^{-\beta(t-b)}\left[1-F(t-b)\right]dt
 \equiv \mu(b)
\end{align*}
where we have used the fact that $\boldsymbol{1}_{(t-b,\infty)}(n)=1$
if and only if $t\leq b+n$ and the Fubini-Tonelli theorem for nonnegative functions to switch the order of integration (I am assuming that $u \geq 0$).
Your problem
For brevity, let $a\wedge b=\min\{a,b\}$ and $a\vee b=\max\{a,b\}$.
From my understanding, you want to study the expectation
$$
\mathbb{E}\left[\int_{b}^{T\wedge(b+\tilde{n})}u\left[c(b,t)\right]e^{-\beta(t-b)}dt\right]
$$
where there is an expiry time $T > b$ beyond which we do not care about the individual's utility from consumption.
Note that unlike the original problem, we only track the individual's utility on the time horizon $[b, T \wedge (b + \tilde{n})]$, corresponding to the time between $b$ (birth) and the smaller of $T$ (expiry) and $b + \tilde{n}$ (death).
Remark. Note that this is not the same thing as what you wrote in your original question (in fact, I was unable to understand the expectation you wrote down; we can chat about this if necessary).
One way to handle this would be to split up the expectation into two parts (one corresponding to the individual living beyond $T$ and one not).
Then, under the same assumptions as above,
\begin{multline}
\mathbb{E}\left[\int_{b}^{T\wedge(b+\tilde{n})}u\left[c(b,t)\right]e^{-\beta(t-b)}dt\right]\\
=\mathbb{E}\left[\boldsymbol{1}_{\{T\leq b+\tilde{n}\}}\int_{b}^{T}u\left[c(b,t)\right]e^{-\beta(t-b)}dt+\boldsymbol{1}_{\{T>b+\tilde{n}\}}\int_{b}^{b+\tilde{n}}u\left[c(b,t)\right]e^{-\beta(t-b)}dt\right]\\
=\boxed{\left(1-F(T-b)\right)\int_{b}^{T}u\left[c(b,t)\right]e^{-\beta(t-b)}dt+\int_{b}^{\infty}u\left[c(b,t)\right]e^{-\beta(t-b)}\left[F(T-b)-F(t-b)\right]dt} \tag{*} \label{eq:result}
\end{multline}
where the second expectation is obtained by a Fubini's argument as in the previous paragraph:
\begin{align*}
\mathbb{E}\left[\boldsymbol{1}_{\{T>b+\tilde{n}\}}\int_{b}^{b+\tilde{n}}u\left[c(b,t)\right]e^{-\beta(t-b)}dt\right] & =\int_{0}^{T-b}\left(\int_{b}^{b+n}u\left[c(b,t)\right]e^{-\beta(t-b)}dt\right)f(n)dn\\
 & =\int_{0}^{T-b}\left(\int_{b}^{\infty}u\left[c(b,t)\right]e^{-\beta(t-b)}\boldsymbol{1}_{(t-b,\infty)}(n)dt\right)f(n)dn\\
 & =\int_{b}^{\infty}u\left[c(b,t)\right]e^{-\beta(t-b)}\left(\int_{0}^{T-b}\boldsymbol{1}_{(t-b,\infty)}(n)f(n)dn\right)dt\\
 & =\int_{b}^{\infty}u\left[c(b,t)\right]e^{-\beta(t-b)}\mathbb{P}(t-b\leq n\leq T-b)\\
 & =\int_{b}^{\infty}u\left[c(b,t)\right]e^{-\beta(t-b)}\left[F(T-b)-F(t-b)\right]dt.
\end{align*}
Relationship to original problem
Note that the second problem is a generalization of the first.
You can retrieve the original problem by formally taking $T \rightarrow \infty$:
\begin{multline*}
=\left(1-F(\infty)\right)\int_{b}^{T}u\left[c(b,t)\right]e^{-\beta(t-b)}dt+\int_{b}^{\infty}u\left[c(b,t)\right]e^{-\beta(t-b)}\left[F(\infty)-F(t-b)\right]dt\\
=\int_{b}^{\infty}u\left[c(b,t)\right]e^{-\beta(t-b)}\left[1-F(t-b)\right]dt
\equiv \mu(b).
\end{multline*}
This formal limit can be made rigorous using the dominated convergence theorem:
Proposition. Under the assumptions stipulated above, if $t \mapsto u(c(b,t))$ is of polynomial growth in $t$ and $\beta > 0$, then \eqref{eq:result} converges to $\mu(b)$ as $T \rightarrow \infty$.
Proof. This follows immediately from the fact that
$$
\left|\int_{b}^{\infty}u(c(b,t))e^{-\beta(t-b)}\right|\leq\int_{b}^{\infty}\left|u(c(b,t))\right|e^{-\beta(t-b)}dt\leq C\int_{b}^{\infty}\left(1+t^{d}\right)e^{-\beta(t-b)}dt
$$
is finite.
Memoryless instantaneous probability of death
Suppose
$$
F(t)=\lambda\int_{0}^{s}e^{-\lambda s}ds=1-e^{-\lambda t}.
$$
is your mortality CDF (i.e., the survival function is $S(t)=1-F(t)=1-(1-e^{-\lambda t})=e^{-\lambda t}$).
In this case, direct substitution gives you the following expression:
\begin{multline*}
\left(1-F(T-b)\right)\int_{b}^{T}u\left[c(b,t)\right]e^{-\beta(t-b)}dt+\int_{b}^{\infty}u\left[c(b,t)\right]e^{-\beta(t-b)}\left[F(T-b)-F(t-b)\right]dt\\
=e^{-\lambda(T-b)}\int_{b}^{T}u\left[c(b,t)\right]e^{-\beta(t-b)}dt+\int_{b}^{\infty}u\left[c(b,t)\right]e^{-\beta(t-b)}\left[e^{-\lambda(t-b)}-e^{-\lambda(T-b)}\right]dt \\
= e^{\alpha b}\left(\int_{b}^{\infty}u\left[c(b,t)\right]e^{-\alpha t}dt-e^{-\lambda T}\int_{T}^{\infty}u\left[c(b,t)\right]e^{-\beta t}dt\right)
\end{multline*}
where $\alpha = \beta + \lambda$.
The last line reveals that the problem is equivalent to the difference of two integrals without a terminal time (one with discount factor $\beta$, and one with $\alpha$).


text:
Q: How to geocode non-standard business addresses I have small database of business and their addresses.  Using the Google Geocode API, I've been abel to get maybe 80% accuracy.  If a business has a simple address on a street, Google usually does a good job.  However, many business have odd addresses, which are presented differently depending on the database.  Example:
Royal Copenhagen
Manly 1
Shop 2A, The Corso (Wharf End)
Manly NSW 2095
(02) 9977 1618

Google's Geocoder fails to find a good address for this location.  However, if I Google for 'Royal Copenhagen, Manly NSW 2095', I can easily find the address, and the pin has the correct location:
2 The Corso
Manly New South Wales 2095, Australia
(02) 9977 1618

Right now, I have my geocoding program trying various combinations of the address fields in attempt to get the best location.  Note, on Google Maps, entering the phone number and city returns very good results, but the geocoder returns much different results.
Has anyone had any success programatically geocoding databases like this?

A: Personally I use YAHOO's geocoder for getting the long/lat information and I use Google's API to map the data.  I ran into the same issue where Google just wasn't quite up to the job of more complicated addresses but the Yahoo API has more flexibility. I'm also running a very small application and its not an issue using both but your mileage may vary.

A: It's possible that the Google API is not sufficiently sophisticated for this purpose.
I once used a commercial product for geocoding. The product included a stack of DVDs, updated monthly, for geocode data for as much of the world as you might wish to pay for. This was not a trivial system to use, but it got its parsing and geocoding data from the Postal Authorities of countries around the world, so could stay up to date. The theory was that any address which would permit a letter to be delivered could be parsed and geocoded.
I do not recommend this product. I will tell you the name only so that you can search and find their competitors. The product was Trillium.

A: I found I could use the Google AJAX Search API for my purposes.  It's design to be used from within JavaScript, but it's possible to call directly from Python.  For a search, it will return a list of matching business, and their geocoded locations.

A: google only can geocode those address which is in there database , it is not dynamic
if you want to do this i think that yopu have to write an application to find the latitude and longitude and save to your database then it will be easy.......... :)


text:
Q: $\pi(X)\geq [\log_2(\log_2X)]+1$ Let $\pi(X)$ be the prime counting function.I want to show that$\pi(X)\geq [\log_2(\log_2X)]+1$,where $[ $ $]$ denotes the greatest integer function.I am not able to figure out how to start the proof?Can someone guide me how to show this?

A: This proof can be adapted from the one found in Ireland and Rosen's A Classical Introduction to Modern Number Theory:
Let $p_1, \dots, p_n$ be distinct primes in order. We know $p_{n + 1} \leq p_1 \cdots p_n + 1$. Thus by induction,  we obtain $p_{k + 1} \leq 2^{2^k}$, for $p_{k + 1} \leq p_1 \cdots p_k + 1 \leq 2^{\sum_{0}^{k-1} 2^j} + 1 = 2^{2^k - 1} + 1\leq 2^{2^k}$, so that $\pi{(2^{2^k})} \geq k + 1$. Now choose $n$ such that $2^{2^n} \geq x \geq 2^{2^{n-1}}$. Then we have $\pi{(x)} \geq n$, which is the expression you wanted.


text:
Q: Is it technically possible, and does it even make sense to use Dart with Lift? I like what I read about Lift, and I like the concept of Dart, but have little experience in both to be able to decide if thinking about using them in the same project is even making sense.
I want both writing structured client side code, and not having to worry about the OWASP top 10 as much
Can they work together? Does it make sense at all? Did anyone try?

A: I have integrated Dart with Lift using REST services together with Dart's XmlHTTPRequest and liked the result. I would say that any web framework that makes making RESTful services as easy as Lift does is a perfect match for Dart. On the other hand web frameworks such as JSF which requires components to take part of a advanced life cycle are probably not a good fit.
That being said, having the same language on the client and the server side is definitely a win, so when the Dart VM matures a bit more and starts to include RESTful functionality similar to what Express does for NodeJS then I would probably use that instead.
Already now baby steps are being taken for including HTTP support in Dart semilar to what Node provides on V8. Another important point for Dart is that it allows the browser and server to share rich objects, like what GWT does for Java, and this should further ease building advanced web applications with Dart.


text:
Q: Using SharePoint and Microsoft Access Web services as an alternate interface I have an application that currently uses Microsoft Access 2013 as a front end with SQL Server 2012 as a back end.  When in the office, that's fine for the users, but some of the users need to be able to access (no pun intended) the application from other sites.
Is it possible to publish the Access front-end to the web while retaining the connection to the back-end tables in SQL Server, and allow the access from SharePoint as an alternate means of getting to the application?
There are firewall issues to contend with, so I was hoping that we'd only have to worry about a firewall opening between the SharePoint server (network A) and the SQL Server (network B).  I'm sorry I can't be more specific than that.