text:
Q: Combinatorics problem - selecting teams of two from two different groups There are 8 boys and 10 girls needed to form 5 boy-girl teams (2 people per team). How many different teams are possible?
My understanding is that $${\binom {8} 5}\times \binom {10} 5$$
would be the number of ways to select a group of ten people (5 boys and 5 girls). But to actually seperate into 5 teams of two, boy and girl in each, we would need to select each team
First team: $8\times 10$ choices,
Second team: $7 \times 9$ choices,
...
Fifth team: $4 \times 6 $ choices
Then finally, divide through by the number of permutations of 5 teams so
The answer should be:
$$
\frac{(8\times 10) \cdot (7\times 9) \cdot (6\times 8) \cdot (5\times 7) \cdot (4\times 6) }{5!} = \frac{^{10}P_5\cdot {^8}P_5}{5!}=1,693, 440
$$
Is this correct or is my logic flawed somewhere?

A: Your reasoning is sound, and your answer is correct. You could also have argued as follows, starting with your first observation. There are, as you say, $\binom85\binom{10}5$ ways to choose $5$ boys and $5$ girls. Now line up the boys. There are $5$ ways to pick a teammate for the first boy in line, $4$ ways to pick a teammate for the second boy in line, and so on, so there are $5!$ ways to match up the boys and the girls. That gives you a total of $\binom85\binom{10}55!=1\,693\,440$ different ways to form $5$ teams, each consisting of a boy and a girl.


text:
Q: Could not resolve resource in constructor After one of the project loads using MaterialDesign, problems started in VS19 - namely, the designer loads for a very long time, and after loading it produces the following:
Failed to resolve resource "MaterialDesignBody1TextBlock".
And similar with other MD StaticResource in the window.
In the App.xaml I added everything correctly:
<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary
                Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
...

When building and running a project, it looks fine, as it should look. However, the problems in the designer do not disappear, and it becomes impossible to work. How to fix it?

A: So, I found the answer to this question, it is necessary:

*

*Clear VS cache

*Create an UI in the AnyCPU configuration

*In the project settings, the target platform AnyCPU and check on
"Preferred 32-bit version"

*Use Release configuration to develop UI

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to create a custom permission level for Contribute + editing quick nav + footer nav links in SP Online? In SP Online modern sites, I want to to have a custom permission to be Contribute + the ability to edit those quick nav + footer links on the page. If you can fine tune it to be only the quick nav that is even better.
There is an article on this https://docs.microsoft.com/en-us/sharepoint/how-to-create-and-edit-permission-levels apparently for SP Online modern sites.
Does anyone know which specific permission to add to grant the nav links updating? We only want that to be included and preferably minimize adding in anything extra.
Edit rights grants this, but gives too much control which includes adding or removing lists and apps, and editing columns and views.

A: Per my test, SharePoint Online "EDIT LINKS" permission: You need the Manage Lists permission.
And in fact, there is only difference between Edit permission level and Contribute permission level is Manage Lists permission.

It is worth noting that the Manage Lists permission includes create and delete lists, add or remove columns in a list, and add or remove public views of a list.


text:
Q: "Some of your past questions have not been well-received". How to count the endpoint? I got a warning notification "Some of your past questions have not been well-received, and you're in danger of being blocked from asking any more." and I'm afraid to ask my next question, because I don't know if somebody downvote, no one will answer or flag question. How can it counts, I mean where is the border of "well-received questions"? It is total score of my questions or how system count when is enough to be blocked?
P.S. So sorry, if it is a little stupid question, but this is my first question on Meta and really want to understand it better.
Thanks.


text:
Q: Should all file structures in a ZIP file be consecutive? While reading a ZIP file, can we safely assume that all file structures (by that I mean Local File Header + file data (compressed or stored) + Data Descriptor) are exactly consecutive? Can there be any irrelevant data in between?

A: PkWare Appnote tells that

"Immediately following the local header for a file is the compressed
  or stored data for the file. The series of [local file header][file
  data][data descriptor] repeats for each file in the .ZIP archive."

So there should be no gaps between them.
However, I would recommend to parse and read central directory, not go through local file headers (except that you need streamed processing).


text:
Q: Java UDP socket configuration I've been working with trying to get a simple chat room client/server going with java UDP and I'm having a bit of trouble when it comes to changing my code from localhost to an ip address that I have port forwarded.
The problem occurs when the client is trying to receive the data back from the server. From my tests I can see that the data is initially making it from the client to the server and the server says it sent the data but I do not know if I am loosing the data over the web or if I have my IP addresses mixed up or if the client cannot receive the data.
Client
public class Client
{
    DatagramSocket clientSocket;
    InetAddress serverIP;
    int serverPort;

    public Client()
    {
        try
        {
            this.serverIP = InetAddress.getByName("my.ip.add.ress");
            this.serverPort = 6969;

            this.clientSocket = new DatagramSocket();//create client socket
        }
        catch (SocketException e)
        {
            e.printStackTrace();
        }
        catch (UnknownHostException e)
        {
            e.printStackTrace();
        }
    }

    public void start() throws IOException
    {
        Scanner scanner = new Scanner(System.in);

        while(true)
        {
            //get client message
            String message = scanner.nextLine();

            //convet to byte array
            byte[] sendData = new byte[1024];
            sendData = message.getBytes();

            //send data
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverIP, serverPort);
            clientSocket.send(sendPacket);

            //receive data
            byte[] receiveData = new byte[1024];
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            clientSocket.receive(receivePacket);

            //print
            System.out.println(new String(receivePacket.getData()));
        }
    }
}

Server
public class Server
{
DatagramSocket serverSocket;

ArrayList<InetAddress> clientIPs;
ArrayList<Integer> clientPorts;

public Server()
{
    try
    {
        //create and bind server socket
        serverSocket = new DatagramSocket(null);
        serverSocket.bind(new InetSocketAddress(InetAddress.getByName("comp.local.ip.add"), 6969));//the ip is port forwarded

        clientIPs = new ArrayList<InetAddress>();
        clientPorts = new ArrayList<Integer>();
    }
    catch (SocketException e)
    {
        e.printStackTrace();
    }
    catch (UnknownHostException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public void start() throws IOException
{
    while(true)
    {
        //receive data
        byte[] receiveData = new byte[1024];
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        serverSocket.receive(receivePacket);
        String message = new String(receivePacket.getData());
        System.out.println("From Client: " + message);
        InetAddress ipAddress = receivePacket.getAddress();
        int port = receivePacket.getPort();

        //add client ip and port to arrays if they dont already exist
        if(!(clientIPs.contains(ipAddress) && clientPorts.contains(port)))
        {
            clientIPs.add(ipAddress);
            clientPorts.add(port);
            System.out.println("Client added");
        }

        //create send data
        byte[] sendData = new byte[1024];
        sendData = message.toUpperCase().getBytes();

        //send data to all clients
        for(int i = 0; i < clientIPs.size(); i++)
        {
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientIPs.get(i), clientPorts.get(i));
            serverSocket.send(sendPacket);
            System.out.println("sent to " + clientIPs.get(i).getHostAddress() + ":" + clientPorts.get(i));
        }
    }
}
}


text:
Q: Find by filename rather than ID in data mapper class I have an abstract data mapper class:
<?php
abstract class ADataMapper
{
    abstract public function addNew($dataObj);
    abstract public function update($dataObj);
    abstract public function find($primaryKey);
    abstract public function delete($dataObj);
}
?>

In a sub-class of ADataMapper, I need to find a row by a column that is not the primary key, specifically: 'filename'.
Would it be best to implement a method like findByFilename($filename) or is there another, simpler alternative? I feel like I am just adding more complexity than necessary.

A: You could add a check within find(). If the argument is a string then call a private findByFileName() otherwise, findById()

A: Normally I go for getBySpecificKeyX methods (so getById()/getByParentId() kind of family), and a general search() method which takes a construct/array of multiple searchterms and queries dynamically. That is a personal choice though.


text:
Q: Slide stacklayout according to listview scroll.- Xamarin.forms In my Xamarin.Forms app, I have a StackLayout and ListView.
I want to hide/show this StackLayout depending on the ListView scrolling direction:
If the user scrolls down -> slide up the StackLayout and hide.
If the user scrolls up -> slide down the StackLayout and show.
What I have done is subscribe to OnAppearing event of ListView.
ObservableCollection<DistrictData> DistrictDatas = new ObservableCollection<DistrictData>();
int lastItemIndex;
int currentItemIndex;
private void FirstListview_ItemAppearing(object sender, ItemVisibilityEventArgs e)
{
    DistrictData item = e.Item as DistrictData;

    currentItemIndex = DistrictDatas.IndexOf(item);
    if (currentItemIndex > lastItemIndex)
    {
        SelectAllLayout.TranslationY -= 30;
        SelectAllLayout.IsVisible = false;
    }
    else
    {
        SelectAllLayout.TranslationY = 0;
        SelectAllLayout.IsVisible = true;
    }
    lastItemIndex = currentItemIndex;
}

My Xmal
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage  xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:touch="clr-namespace:TouchEffect;assembly=TouchEffect"
             xmlns:controls="clr-namespace:SampleApp.CustomRender"
             mc:Ignorable="d"
             x:Class="SampleApp.Views.Notification_Center.Add_New_Notification.Districts">
    <ContentPage.Content>
        <Grid>

            <Grid BackgroundColor="#076c9c">
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>
                <Grid x:Name="SelectAllLayout" Grid.Row="0" Margin="10,10,10,0">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto"/>
                            <RowDefinition Height="Auto"/>
                        </Grid.RowDefinitions>

                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>

                        <BoxView Grid.Row="0" Grid.Column="0" VerticalOptions="Center" HorizontalOptions="FillAndExpand" BackgroundColor="LightBlue" HeightRequest="0.1"></BoxView>

                        <Frame Grid.Row="0" HasShadow="False" BackgroundColor="White" Padding="7" CornerRadius="20" Grid.Column="1">
                            <Label Text="Step 1" FontSize="Micro" TextColor="Black" HorizontalOptions="Center" VerticalOptions="Center" Margin="10,0,10,0">
                                <Label.FontFamily>
                                    <OnPlatform x:TypeArguments="x:String">
                                        <On Platform="iOS" Value="Montserrat-Regular" />
                                        <On Platform="Android" Value="Montserrat-Regular.ttf#Montserrat-Regular" />
                                    </OnPlatform>
                                </Label.FontFamily>
                            </Label>
                        </Frame>
                        <BoxView Grid.Row="0" VerticalOptions="Center" Grid.Column="2" HorizontalOptions="FillAndExpand" BackgroundColor="LightBlue" HeightRequest="0.1"></BoxView>
                        <StackLayout  Grid.Row="1" HorizontalOptions="StartAndExpand" Orientation="Horizontal" Margin="12,0,0,0">
                            <CheckBox IsChecked="False" HorizontalOptions="Start" VerticalOptions="Center" Color="LightGreen"></CheckBox>
                            <Label Text="Select All" FontSize="Small" TextColor="White" HorizontalOptions="Start" VerticalOptions="Center" Margin="10,0,0,0">
                                <Label.FontFamily>
                                    <OnPlatform x:TypeArguments="x:String">
                                        <On Platform="iOS" Value="Montserrat-Regular" />
                                        <On Platform="Android" Value="Montserrat-Regular.ttf#Montserrat-Regular" />
                                    </OnPlatform>
                                </Label.FontFamily>
                            </Label>
                        </StackLayout>
                    </Grid>
                <StackLayout  VerticalOptions="Center" Grid.Row="1"   x:Name="ListLayout"  BackgroundColor="Transparent"
                         RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width}"
                         RelativeLayout.HeightConstraint="{ConstraintExpression Type=RelativeToParent, Property=Height}">

            <ListView
             x:Name="FirstListview"
             HasUnevenRows="True"
             HeightRequest="{Binding Path=Height, Source={x:Reference ListLayout}}"
             CachingStrategy="RecycleElement"
             HorizontalOptions="FillAndExpand"
             BackgroundColor="Transparent"
             ItemAppearing="FirstListview_ItemAppearing"
             ItemTapped="DistrictList_ItemTapped"
             VerticalOptions="FillAndExpand"
             Margin="7,7,7,0"
             SeparatorVisibility="None">
                        <ListView.ItemTemplate >
                            <DataTemplate >
                                <ViewCell >
                                    <ViewCell.View>
                                        <Frame HorizontalOptions="FillAndExpand"
                                           BorderColor="#4088CCF1" BackgroundColor="#4088CCF1"
                                                       Padding="10"
                                           Margin="3"
                                           CornerRadius="6">
                                            <Frame.HasShadow>
                                                <OnPlatform x:TypeArguments="x:Boolean" iOS="false" Android="true"/>
                                            </Frame.HasShadow>
                                            <StackLayout Orientation="Horizontal" HorizontalOptions="FillAndExpand">
                                                <CheckBox HorizontalOptions="Start" IsChecked="{Binding Selected}" Color="LightBlue" Margin="2,-6,0,0" VerticalOptions="Start"></CheckBox>
                                                <StackLayout Orientation="Vertical" VerticalOptions="StartAndExpand" >
                                                    <Label Text="District Name" FontSize="Micro" TextColor="LightBlue" Margin="10,0,0,0"></Label>
                                                    <Label Text="{Binding Heading}" VerticalOptions="Center" FontSize="12" HorizontalTextAlignment="Start" TextColor="White" Margin="10,5,5,5">
                                                        <Label.FontFamily>
                                                            <OnPlatform x:TypeArguments="x:String">
                                                                <On Platform="iOS" Value="Montserrat-Regular" />
                                                                <On Platform="Android" Value="Montserrat-Regular.ttf#Montserrat-Regular" />
                                                            </OnPlatform>
                                                        </Label.FontFamily>
                                                    </Label>
                                                </StackLayout>
                                                <Image Source="NC_rightarrow.png" HorizontalOptions="EndAndExpand" HeightRequest="15"  Margin="0,0,7,0" VerticalOptions="Center"></Image>
                                            </StackLayout>
                                        </Frame>
                                    </ViewCell.View>
                                </ViewCell>
                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>
                </StackLayout>
            </Grid>
        </Grid>
    </ContentPage.Content>
</ContentPage>

But it doesn't work as I intended.When We scroll, the layout shows and hide randomly. How to solve this? I referred this question Link. But no luck.

A: Well I must say that there is nothing wrong with your code except that you are constantly hitting visual element with updated values, and this in my opinion causes flickering. I was able to remove flickering by implementing viewmodel and reducing hits on grid. This was partial success because grid height binding was fired properly all the time, but grid itself seems to have problems with updating height when scrolling listview. In your case (in my opinion) the best solution is to use absolute layout as additional user menu. It works fine without causing described problems. You can find working basic example here.


text:
Q: flutter: Letting user to register using a specific qr I'm new to flutter development. I would like to know how do I create a QR code specifically for a user with QR in order for them to sign up? Let's say QR1 signup for user1.
QR2 signup for user2. Both are totally different QR code. Can I do this using firebase dynamiclink?


text:
Q: A Bash command to go through a list of files in a directory, find are replicates numbers 1-9, and concatenate them into a new file I have a directory with a bunch of files
Ex:
ExperimentA_Rep1.bed
ExperimentA_Rep2.bed
ExperimentA_Rep3.bed
ExperimentB_Rep1.bed
ExperimentD_Rep1.bed
ExperimentC_Rep1.bed
ExperimentC_Rep2.bed
.
.
.
ExperimentZ_Rep5.bed

I need to scan through the filenames in a directory and concatenate the files that are from the same experiment, but different replicates, into a new file.
I.e
cat ExperimentA_Rep1.bed ExperimentA_Rep2.bed > ExperimentA_merged.bed

If the Experiment only has 1 replicate, it should not do anything. But I can't hardcode this, it needs to be applicable for any dataset of experiments.
If I ran a python script that would be okay.

A: Try this shell script:
for f in *Rep1.bed
do
    cat "${f%Rep1.bed}"*.bed >"$f.merged"
done

How it works
Every experiment in your example had one file whose named ended in Rep1.bed.  To find all files in that experiment, we can use the glob ${f%Rep1.bed}"*.bed.  Those files are then concatenated to a single file.  This is repeated for each experiment.
The form ${f%Rep1.bed} is an example of suffix removal.  It takes the variable f and removes from the end any occurrence of the pattern that follows the % sign.  For example, let's create a shell variable:
$ f=ExperimentC_Rep2.bed
$ echo "${f}"
ExperimentC_Rep2.bed

Now, let's remove .bed from the end:
$ echo "${f%.bed}"
ExperimentC_Rep2

Or, as we need here, we can remove a longer string Rep2.bed:
$ echo "${f%Rep2.bed}"
ExperimentC_

What is left above is the experiment name with the replicant number removed.  We can use this to select all replicant files associated with that experiment name using the glob "${f%Rep1.bed}"*.bed
As a single line
When running code interactively, it is sometimes easier to run it as a single line.  The above code, as a single line, is:
for f in *Rep1.bed; do cat "${f%Rep1.bed}"*.bed >"$f.merged"; done

Making a merged file only for experiments with 2 or more replicants
Some experiments have just one replicant (*_Rep1.bed).  Others have several: _Rep1.bed, _Rep2.bed, ....  If we want to select only files that have two or more, we can select only files for which Rep2 exists:
for f in *Rep2.bed; do cat "${f%Rep2.bed}"*.bed >"$f.merged"; done


text:
Q: Can we generate sourcemaps using YUI compressor? Is there a way to generate sourcemaps using YUI compressor? I don't find any option to do that here -- http://yui.github.io/yuicompressor/

A: The YUI Compressor is no longer maintained by the YUI team but instead by a community member. The recommended compressor tool for YUI is Ugilfy 2 which has the option to generate source maps.

A: YUI compressor doesn't support generation of sourcemaps. Here is a nice wiki page that lists the tools and languages that compile to JS supporting source maps --
https://github.com/ryanseddon/source-map/wiki/Source-maps%3A-languages,-tools-and-other-info


text:
Q: MS ACCESS: Placing a field value of current record in the e-mail "Subject" I have the following code to send a report (pdf) as an e-mail.
The code works fine! However, i would like a field of the current record that im sending to be part of the emails subject. I have tried a bunch of things but nothing works.
The current subject is "Order is ready!"
I would like this to be "Order [ordernumber] is ready!"
Private Sub sendesoreq_Click()

Dim stDocName As String
stDocName = "orderfinished_2"

DoCmd.OpenReport stDocName, acPreview, , "[orderID] = " & Me.orderID

DoCmd.SendObject acSendReport, "orderfinished_2", ".pdf",
"mymail@gmail.com", , , "Order is ready!", "Success! The
following order is ready for shipment. Thank you!", False
Me.orderstatuscombo.Value = "ESO request sent"
End Sub

Thanks in advance guys!

A: Just use string concatenate to insert your field
Instead of :
 "Order is ready!"

Use
 "Order #" & Me.orderID & " is ready!"


text:
Q: Trying to use jquery to create text input with multiple wrong answers I'm trying to create a page for a friend with allergies, where users can input a food item and get a response as to whether or not my friend is allergic to it. I've created an array with all his food allergies and the intent is that when the user enters any given food and hits submit, the page will respond with an alert.
I'm new to jquery and have hacked together a couple of close examples, but clearly I'm missing some connecting piece. Any help would be appreciated!
Working demo: http://jsfiddle.net/ssprockett/Ct2TU/1/
Here is the jquery so far:
$('.submit').click(function () {
   if( $.inArray( $("input:text").val().toUpperCase(), ["cantaloupe", "almonds", "almond flour", "almond flour", "almond milk", "hazel nuts", "hazelnuts", "filberts", "pecans", "peanuts", "english walnuts", "watermelons", "grapefruit", "orange", "garlic", "mustard", "green pepper", "navy bean", "string bean", "cabbage", "carrot", "cauliflower", "lettuce", "bass", "peas", "sweet potatoes", "squash", "clams", "barley", "oat", "soy", "wheat", "rice", "gluten", "sea bass", "mustard seeds",  ] ) > -1 )  {
        alert("Nope. This will make him sick.");

    } else {

        alert("Yep. This is fine.");
    }

A: There are a few minor issues:

*

*You're not including jQuery in the jsfiddle

*You were missing a closing }) for the click binding function

*You should be using .toLowerCase, not .toUpperCase since all of the values of your array are lower-cased.

http://jsfiddle.net/Ct2TU/4/

A: toUpperCase() makes all of those values false. Try toLowerCase()

A: Here is one working example:
http://jsfiddle.net/jA7MB/
var allergy = ["cantaloupe", "almonds", "almond flour", "almond flour", "almond milk", "hazel nuts", "hazelnuts", "filberts", "pecans", "peanuts", "english walnuts", "watermelons", "grapefruit", "orange", "garlic", "mustard", "green pepper", "navy bean", "string bean", "cabbage", "carrot", "cauliflower", "lettuce", "bass", "peas", "sweet potatoes", "squash", "clams", "barley", "oat", "soy", "wheat", "rice", "gluten", "sea bass", "mustard seeds"];

$( ".submit" ).click(function() {
  if(($.inArray($('#food').val().toLowerCase(), allergy)) != -1){
   alert( "allergic!")
  } else alert("not allergic!");

});

You can try it.


text:
Q: Why does this return an invalid date with moment js This
moment(1420066800000);

returns a moment object with an invalid date, why?
EDIT:
moment(1420066800000).isValid()

returns true! But: the moments' property
_d.__proto__

is an "Invalid Date" object. That's what confused my, since I thought this was causing wrong behaviour in my application.

A: What is wrong with Wed Dec 31 2014 23:00:00 GMT+0000 (UTC) ?
> d = moment(1420066800000);
{ _isAMomentObject: true,
  _i: 1420066800000,
  _f: undefined,
  _l: undefined,
  _strict: undefined,
  _isUTC: false,
  _pf:
  { empty: false,
    unusedTokens: [],
    unusedInput: [],
    overflow: -2,
    charsLeftOver: 0,
    nullInput: false,
    invalidMonth: null,
    invalidFormat: false,
    userInvalidated: false,
    iso: false },
  _d: Wed Dec 31 2014 23:00:00 GMT+0000 (UTC) }


text:
Q: Is traffic exiting a VPN node encrypted? If I am using a VPN connection, does the traffic exiting its node remain encrypted?

A: In reference to the encryption a VPN provides, it is only valid in the tunnel it creates.  So once the traffic leaves the tunnel, it is no longer encrypted by the VPN.


text:
Q: How to display three rows within a table row, not three colums I have an application here for you to be able to see the layout of a problem I am having. When you open the application, if you click on the "Add Question" button, you will see that it displays a table row with three columns showing the content.
The first column shows Options textbox, second is a number textbox and third is 2 buttons. The problem is that it is displaying three columns in row going side by side.
It should be instead be showing within the table row, three rows, not three columns.
So currently it is showing this for each table row:
Option Textbox | Number Textbox | 2 Buttons

Instead it should be inside a table row:
Option Textbox

Number Textbox

2 Buttons

So like I said, I need three rows within the row, not three columns. But how can i achieve this with the code I have below:
var $tbody = $('#qandatbl > tbody');
            var $tr = $("

");
            var $noofanswers = $("

");
            var $options = $("

");
            var $answer = $("

");
            var $extratr = $("

");

        /*Below is an example of a function that worked before I included the
 tag
 but stopped working after including the
 tags */

      $('.numberAnswerTxt', context).each(function() {
            var $this = $(this);
            var $noofanswersText = '';

            if ($questionType == 'True or False' || $questionType == 'Yes or No'){

        $noofanswersText = $("Only 1 Answer<input type='text' class='numberAnswerTxtRow answertxt' style='display: none;' onkeyup='numberKeyUp(this)' onkeypress='return isNumberKey(event)' onChange='getButtons()'>").attr('name', $this.attr('name')).attr('value', $this.val());

        }else{

        $noofanswersText = $("Only 1 Answer<input type='text' class='numberAnswerTxtRow answertxt' style='display: block;' onkeyup='numberKeyUp(this)' onkeypress='return isNumberKey(event)' onChange='getButtons()'>").attr('name', $this.attr('name')).attr('value', $this.val());

        }

            $noofanswers.append($noofanswersText);

            });

            $tr.append($extratr);
            $extratr.append($options);
            $extratr.append($noofanswers);
            $extratr.append($answer);
            $tbody.append($tr);

A: A table row is denoted by an opening and closing tr so you need to make this change:
var $noofanswers = $("

");
var $options = $("

");
var $answer = $("

");

each of those will create a row in your table.

A: Why not put a table within the cell and give it three rows, or try useing the rowspan attribute with the other cells so that the span 3 rows.


text:
Q: Avoiding duplicated arguments when running a Docker container I have a tensorflow training script which I want to run using a Docker container (based on the official TF GPU image). Although everything works just fine, running the container with the script is horribly verbose and ugly. The main problem is that my training script allows the user to specify various directories used during training, for input data, logging, generating output, etc. I don't want to have change what my users are used to, so the container needs to be informed of the location of these user-defined directories, so it can mount them. So I end up with something like this:
docker run \
  -it --rm --gpus all -d \
  --mount type=bind,source=/home/guest/datasets/my-dataset,target=/datasets/my-dataset \
  --mount type=bind,source=/home/guest/my-scripts/config.json,target=/config.json \
  -v /home/guest/my-scripts/logdir:/logdir \
  -v /home/guest/my-scripts/generated:/generated \
  train-image \
  python train.py \
  --data_dir /datasets/my-dataset \
  --gpu 0 \
  --logdir ./logdir \
  --output ./generated \
  --config_file ./config.json \
  --num_epochs 250 \
  --batch_size 128 \
  --checkpoint_every 5 \
  --generate True \
  --resume False

In the above I am mounting a dataset from the host into the container, and also mounting a single config file config.json (which configures the TF model). I specify a logging directory logdir and an output directory generated as volumes. Each of these resources are also passed as parameters to the train.py script.
This is all very ugly, but I can't see another way of doing it. Of course I could put all this in a shell script, and provide command line arguments which set these duplicated values from the outside. But this doesn't seem a nice solution, because if I want to anything else with the container, for example check the logs, I would use the raw docker command.
I suspect this question will likely be tagged as opinion-based, but I've not found a good solution for this that I can recommend to my users.

A: As user Ron van der Heijden points out, one solution is to use docker-compose in combination with environment variables defined in an .env file. Nice answer.


text:
Q: Xamarin.iOS native project error: I am starting a new Xamarin.iOS project. I am on latest version of Xamarin as of the time of writing this question(4.5 build I believe).
I have a local Mac(El Captain) connected.
The following is my project structure:

Weirdest thing that happens here is, when I build my project I get the following errors:
Please help me solve this issue.

A: To build for iOS, you need Xcode installed on the connected Mac. Your error message calls for Xcode 8.0 or later.
You will also need to sign up for an Apple Developer account and connect it to Xcode in the Accounts tab of the Xcode Preferences.


text:
Q: How to put a windows installable program on Heroku for user download in a Rails web application? I have a rails web application that contains a Windows executable file the user can download and install on his PC. This program will communicate with certain peripherals on the user's PC using web services to the web application.
Where should I put such a program in my Rails tree, and how should I make this "available" for users to download?

A: Assets
Alternatively to putting them in the public dir, you may wish to create a downlods folder in the asset pipeline: /app/assets/downloads
This will give you the ability to call downloads_path, and precompile each file.
In order to get this to work, you'll be best creating a helper method like this:
#app/helpers/application_helper.rb
def downloads_path path
    asset_path("/downloads/#{path}")
end

#app/views/application/index.html.erb
<%= downloads_path("download.exe") %>

This has the added benefit of allowing you to precompile the files, and having them accessible from the likes of CDN's, as Michael Szyndel recommended


text:
Q: Using Power Shell to Connect to Sharepoint I tried to add the Snapin (very basic step) and I am getting the following error.
Users>Add-PSSnapin Microsoft.SharePoint.PowerShell
---Add-PSSnapin : No snap-ins have been registered for Windows PowerShell version 2.
At line:1 char:13
+ Add-PSSnapin <<<<  Microsoft.SharePoint.PowerShell
    + CategoryInfo          : InvalidArgument: (Microsoft.SharePoint.PowerShell:String) [Add-PS
   ption
    + FullyQualifiedErrorId : AddPSSnapInRead,Microsoft.PowerShell.Commands.AddPSSnapinCommand


text:
Q: What would I get when sudo a kernel-destructive program? It suddenly comes to me how easy it will be for a sudoer to crash the kernel, so I tried something like this:
#include<stdio.h>

int main(){
    printf("hello world");
    int a;
    printf("%p", &a);
    int *p = (int*)0xffff000000000000; //x86_64, somewhere in the kernel space
    printf("%p:%d", p,*p);
    *p = 1;
    printf("%p:%d", p,*p);
}

Understandably, without sudo, running the program turns out a segment fault. However, I got NOTHING when execute it via sudo ./a.out! Even the hello world in first line is suppressed without any error or warnings at all.
Can someone explain what's happening?

A:
Understandably, without sudo, running the program turns out a segment fault. I got NOTHING when execute it via sudo ./a.out!

Are you sure it ran at all?
#include <stdio.h>

int main (void) {
    fprintf(stderr,"Attempting out-of-bounds access.\n");
    int *p = (int*)0xffff000000000000;
    fprintf(stderr,"%d\n", *p);
    *p = 666;
    fprintf(stderr,"%d\n", *p);
    return 0;
}

This one uses stderr, since it is not buffered, to avoid the problems described by warl0ck.
me@home> ./a.out
Attempting out-of-bounds access.
Segmentation fault
me@home> su root
Password:
root@home> ./a.out
Attempting out-of-bounds access.
Segmentation fault

Exactly what should happen.  The system will never let anyone do this.  This line:
int *p = (int*)0xffff000000000000;

When compiled and run gets a SIGSEGV, aka. a "segmentation fault".

A: Of course it won't crash the kernel, you're writing to the virtual memory space of your own program, not the real kernel memory space.
Learn more about virtual memory here
P.S:
Why printf doesn't print anything? By default standard output is line-buffered, and your hello world doesn't contain a line separator.
So if the program crashed, you will not observe that output (Try use puts or adding a \n in your message)


text:
Q: python pandas how to drop duplicates selectively I need to look at all the rows in a column ['b'] and if the row is non-empty go to another corresponding column ['c'] and drop duplicates of this particular index against all other rows in that third column ['c'] while preserving this particular index. I came across drop_duplicates, however I was unable to find a way to only look for duplicates of a highlighted row as opposed to all duplicates in a column. I can't use drop_duplicates on the whole column because I want to retain duplicates in this column that may correspond to only empty values in column ['b'].
So possible scenarios would be: if in ['b'] you find a non empty value, you may go to the current index in ['c'] and find all duplicates of that ONE index and drop those. These duplicates could correspond to empty OR non-empty values in ['b'].  If in ['b'] you find empty value skip to next index. This way it is possible that empty value indices in ['b'] get removed indirectly because they are duplicates of an index in ['c'] corresponding from a non empty ['b'] value.
Edited With Sample Data:
Preprocessed:
df1 = pd.DataFrame([['','CCCH'], ['CHC','CCCH'], ['CCHCC','CNHCC'], ['','CCCH'], ['CNHCC','CNOCH'], ['','NCH'], ['','NCH']], columns=['B', 'C'])

df1

    B     C
0         CCCH
1   CHC   CCCH
2   CCHCC CNHCC
3         CCCH
4   CNHCC CNOCH
5         NCH
6         NCH

Post Processing and dropping correct duplicates:
df2 = pd.DataFrame([['CHC','CCCH'], ['CCHCC','CNHCC'], ['CNHCC','CNOCH'], ['','NCH'], ['','NCH']], columns=['B', 'C'])

df2

    B     C
1   CHC   CCCH
2   CCHCC CNHCC
4   CNHCC CNOCH
5         NCH
6         NCH

Above we see the result that the only rows removed were rows 0,3 as they are duplicates in column ['C'] of row 1 which has a non zero 'B' value. Row 5,6 are kept even though they are duplicates of each other in column ['C'] because they have no non zero 'B' value. Rows 2 and 4 are kept because they are not duplicates in column ['C'].
So the logic would be to go through each row in column 'B' if it is empty then move down a row and continue. If it is not empty then go to its corresponding column 'C' and drop any duplicates of that column 'C' row ONLY while preserving that index and then continue to the next row untill this logic has been applied to all values in column 'B'.
Column B value empty --> Look at next value in Column B
| or if not empty |
Column B not empty --> Column C --> Drop all duplicates of that index of Column C while keeping the current index --> Look at next value in Column B

A: Say you group your DataFrame according to the 'C' column, and check each group for the existence of a 'B'-column non-empty entry:

*

*If there is no such entry, return the entire group

*Otherwise, return the group, for the non-empty entries in 'B', with the duplicates dropped
In code:
def remove_duplicates(g):
    return g if sum(g.B == '') == len(g) else g[g.B != ''].drop_duplicates(subset='B')

>>> df1.groupby(df1.C).apply(remove_duplicates)['B'].reset_index()[['B', 'C']]
       B      C
0    CHC   CCCH
1  CCHCC  CNHCC
2  CNHCC  CNOCH
3           NCH
4           NCH


text:
Q: Visual Studio error message: NUnit3.TestAdapter.dll is missing I have an issue with Visual Studio and NUnit Test Adapter which I cannot find the answer for. Every morning and sometimes during the day, when I try to build my solution I get an error message that the dll under NUnit3TestAdapter folder is missing:

...\AppData\Local\Temp\VisualStudioTestExplorerExtensions\NUnit3TestAdapter.3.10.0\build\net35\NUnit3.TestAdapter.dll

The only way to fix it (temporarily) is to close and reopen Visual Studio.
Any idea why this is happening all of a sudden and how to solve it?

A: I stumbled into a similar problem and found your post. I wasn't able to get it going again just by closing and reopening, but the accepted answer to this question seems to point to a known bug, and deleting the folder it mentions did get me back up and running again, might be worth trying that.


text:
Q: python reduce return function reference and not the value of the function Learning Python.  I was learning reduce() and was playing with the initialization parameter.  The code simply outputs a SHA256 hash of a list of strings.  At first I used a for loop to generate the hash. Then, I used functools.reduce() to try and do the same thing.
import functools
import hashlib

def hash_two_strings(a,b):
  c = a + b
  h = hashlib.sha256(c.encode()).hexdigest()
  return h

c1 = ['3', 'sha256', 'C=US,O=Entrust', 'CN=review.mysite.com', '1c:08:ea:51', '2/11/2022', '2/11/2023', 'RSA', '2048']

h = hashlib.md5(c1[0].encode()).hexdigest()

for i in range(1, len(c1)):
  s = h+c1[i]
  h = hashlib.sha256(s.encode()).hexdigest()

print (h)

h = functools.reduce(lambda a, b: hash_two_strings, c1[1:], hashlib.sha256(c1[0].encode()).hexdigest())
print (h)

Output:
2b9d651fee9c0ddc75477be6dba8d1d3600551cf2e355e9f4788d3c728d237a3
<function hash_two_strings at 0x000001FF9B6A3E20>
However, reduce() seems to want to return a reference to the function I wrote hash_two_strings(), not the actual hash I was expecting. Any thoughts on how I'm using reduce() incorrectly because I can't see it.

A: There are two ways to fix your problem:
h = functools.reduce(hash_two_strings, c1[1:], hashlib.sha256(c1[0].encode()).hexdigest())
print (h)

Or:
h = functools.reduce(lambda a, b: hash_two_strings(a, b), c1[1:], hashlib.sha256(c1[0].encode()).hexdigest())

Because lambda as you used it before ignored the a,b arguments and just returned the hash_two_strings function object.
Remember that if you write function without the parenthesis that is just a function object, not the result of calling the function:
>>> def round_3_point_5(): return round(3.5)
...
>>> round_3_point_5
<function round_3_point_5 at 0x7f04d347b700>
>>> round_3_point_5()
4


text:
Q: How to find the index of next matching element in list using LINQ i have a list say :
List<string> list = new List<string>(){"Oracle","SQL Server","Java","Oracle","Python"};

Now i'm trying to get index of the second "Oracle" from the list using LINQ:
var indexFirefox = list.FindIndex(a => a.Text == "Oracle");

But this will give you only the first instance that is index 0. I want index as 4 in my result. Will using Skip help or there is a more simplistic way of getting the index. The example above is just a demo, i have a list with over 300 values.

A: So many Linq answer when there already exists one method doing the job (given in the first comment)
List<T>.FindIndex has an overload which takes an additional index parameter to search only from that index.
So to get the second occurrence of an item you just have to use that overload with the result of a "regular" FindIndex.
(Note: in your question's sample you used a.Text but items are string so there is no Text property)
var firstIndex = list.FindIndex (item => item == "Oracle");
if (firstIndex != -1)
{
    var secondIndex = list.FindIndex (firstIndex, item => item == "Oracle");
    // use secondIndex (can be -1 if there is no second occurrence)
}

And with your sample example secondIndex will be 3 (and not 4 as stated in your question, indexes are zero-based)
Alternatively if you want to get occurrence indexes in turn you can loop using that same method.
// defined here to not have to repeat it
Predicate<string> match = item => item == "Oracle";

for (var index = list.FindIndex (match); index > -1; index = list.FindIndex (index + 1, match))
{
    // use index here
}

Or if you prefer a while loop
var index = list.FindIndex (match);

while (index > -1)
{
    // use index here

    index = list.FindeIndex (index + 1, match);
}

A: list.Where(x => x == "Oracle").ElementAt(1);

*

*Will crash if ther is no second find , you can just check the size of the enumerable before returning second element.

A: here i find index of next of matching element
list.Select((value, index) => new { value, index = index + 1 }).Where(x => x.value == "Oracle").Skip(1).FirstOrDefault().index

A: This does it nicely for me:
var result =
    list
        .Select((x, n) => new { x, n })
        .Where(xn => xn.x == "Oracle")
        .Select(xn => xn.n)
        .Skip(1)
        .FirstOrDefault();

This gives 3 given the input List<string> list = new List<string>(){"Oracle","SQL Server","Java","Oracle","Python"};.


text:
Q: flutter navigation pop always pop to root I'm new on flutter and I got a problem with navigation pop system. I don't understand what's wrong on my code but what should I check on my code if every time I pressed back button on phone(not on AppBar or anything else), it goes back to the root of my page, not the previous page. but it works perfectly when I press back using the app bar back button that created automatically.
I've tried to fix this issue by passing some unpassed BuildContext to my separated widget hoping that's the problem but still doesn't works
Example:
I have three pages A, B, C
A->B->C
A->B->D
A->B->E
when I press smartphone's back button on B it goes to A (works).
when I press Scaffold appbar back button on C it goes to B (still works),
But, when I press smartphone's back button on C, D, or E it goes to A (not works)
//this is where I initialize my route
class _LoginPageState extends State<LoginPage>{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      routes: <String, WidgetBuilder> {
      '/main': (BuildContext context) => MainPage(),
      // '/b': (BuildContext context) => MyPage(title: 'page B'),
      // '/c': (BuildContext context) => MyPage(title: 'page C'),
    },
.....

// and this is how I push
onPressed: () {
  Navigator.of(context).pushNamed('/main');
}

A: Thanks to @HassanSaleh giving me a little clue about the material app. I have misunderstood about using material app route. I initialize material app route on every page and I read carefully on flutter dev cookbook about navigating page and found out that I should just put materialapp only on the very top of my widget stack. So the fix for me is Removed material app on every widget and only put one material app and its route on very root app Widget. Maybe I have bad explanation hope u guys understand


text:
Q: just_audio plugin is giving MissingPluginException for Flutter windows application I am trying to play audio file from asset using just_audio plugin with latest version. When I try to set the audio source it is giving the following error: Error1
The plugin documentation clearly shows that it supports windows platform then why it is giving this missing plugin exception.
This is my piece of code:

playAudio()
{
  final player = AudioPlayer();
 await player.setAsset('sound/tone.mp3');
 player.play();

}

This is my asset file declaration in pubspec.yaml file

 assets:
    - img/
    - sound/tone.mp3

Any could help me to solve this issue please.
Thanks

A: Did you add the just_audio_libwinmedia dependency to pubspec.yaml?
The document says need this dependency too.

Add the just_audio_libwinmedia dependency to your pubspec.yaml alongside just_audio:


text:
Q: Cross product invariance of four concurrent planes I think I have the proof and I just need a second check (and some advice to make it less messy).
Given four concurrent planes, for any straight line interesecting the four planes in the points $a,b,c,d$ the cross product defined as ${\frac {ac} {bc}} / {\frac {ad} {bd}}$ is costant, regardless of the position of the straight line.
I will use a double projection.
PROOF:
Let $A,B,C,D$ be four planes concurrent in the straight line $l$.
Let $r,r'$ be two straight lines intersecting the planes in $a,b,c,d$ and $a',b',c',d'$, respectively, and laying ont the planes $P$ and $P'$ which in turn intersect the $l$ in $O$ (we can choose, without loss of generality, a single point on $l$ in which the two planes $P$ and $P'$ and the straight line $l$ intersect).
Choose a third straight line $r''$ such that it is parallel to $r'$ and intersecting with $r$. Then $r''$ will lay on $P$. By means of a projection from $O$, we find the points $a'',b'',c'',d''$ on $r''$. Then, for previous results (invariance of the cross product after a central projection) we will have $${\frac {a'c'} {b'c'}} / {\frac {a'd'} {b'd'}} = {\frac {a''c''} {b''c''}} / {\frac {a''d''} {b''d''}}$$
We can now prove the proposition. By means of a parallel projection of $r''$ into $r$, we find that $a'',b'',c'',d''$ will correspond to $a,b,c,d$, respectively. In fact, having chosen $r''$ on as concurrent to $r$, these two straight lines will lay on the same plane $Q$ that intersects $A,B,C,D$ in four parallel straight lines $p,q,r,s$ where $a,b,c,d$ and $a'',b'',c'',d''$ lay.
But then, for the fact that a parallel projection holds the cross product of any four points, we have $${\frac {ac} {bc}} / {\frac {ad} {bd}} = {\frac {a''c''} {b''c''}} / {\frac {a''d''} {b''d''}}$$ and therefore, for transitivity, the conclusion.
$${\frac {a'c'} {b'c'}} / {\frac {a'd'} {b'd'}} = {\frac {a'c'} {b'c'}} / {\frac {a'd'} {b'd'}}$$
Q.E.D.


text:
Q: How can I match "key://string?list" or value="key://string?detail" strings? How could i have a regex matching a string like :
value="key://string?list"

or
value="key://string?detail"

I have tried something like :
new Regex("value=\\w.")

String is a string value and is not the constant value String.
an ex. would be
value="samplekey://samplestring?list"

A: use this regex value="key://string\?\w+"
edit:
value="\w+://\w+?\?\w+"

A: Please don't take this as patronizing, but I think you should practice with test-driven development. It would help you define the specifications for your problem.
For instance, in the way you state your question, this could be an answer:
value="\w+://\w+\?(list|detail)"

or in scala:
scala> val r = """value="\w+://\w+\?(list|detail)"""".r
r: scala.util.matching.Regex = value="\w+://\w+\?(list|detail)"

Note that these match:
value="key1://string1?list"
value="key1://string1?detail"

but these DON'T match:
value="my-key://my-string?list" // hint: it's the "-". \w does not match it
value="mykey://mystring?test" // hint: list or details are matched but "test" is not

There may be a lot of other corner cases (do you want case-sensitive matches or not? Can there be spaces around the equal sign, as in  value = "?)
That's why it would be best to define you problem in terms of "this should work, this should be rejected". It will help you avoid subtle issues further along in your program.


text:
Q: boost signal with min_element I am writing a little example to try to understand multiple return values of boost::signal. However, the result seems weired to me.
#include <boost/signal.hpp>
#include <iostream>
#include <algorithm>

int func1()
{
    return 3;
}

int func2()
{
    return 4;
}

int func3()
{
    return 2;
}

template <typename T>
struct min_element
{
    typedef T result_type;  //result_type is required by boost::signal

    template <typename InputIterator>
    T operator()(InputIterator first, InputIterator last) const
    {
        std::cout<<*std::min_element(first, last)<<std::endl;  //I got 3 here
        return T(first, last);
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    boost::signal<int (), min_element<std::vector<int> > > s;
    s.connect(func1);
    s.connect(func2);
    s.connect(func3);
    std::vector<int> v = s();
    std::cout<<*std::min_element(v.begin(),v.end())<<std::endl; //I got 2 here
    return 0;
}

The first min_element would output "3" while the second would output "2". Obviously "2" is the smallest number among those three. I don't know what's wrong with the first one. In operator() I also tried to iterate from first to last and I got the sequence "3,4,2" which seems correct. But why would min_element give me "3" instead?
The code was compiled with VS2010 SP1. The version of Boost is 1.46.1 which is the latest one.
Thanks in advance.
Michael

A: Weird. Replacing operator():
T operator()(InputIterator first, InputIterator last) const
{
    InputIterator result = first;

    while (++first != last) {
//      *result;
        std::cout<<*first<<std::endl;
    }

    return T();
}

Works, but as soon as you dereference result, first and result both get stuck at 3. This is what std::min_element is doing; I found my implementation's source and stripped it down to what you've seen above.
I have no idea what's going on.
This is Boost 1.38.0 on GCC 4.5.0.


text:
Q: Singleton UIManagedDocument is not writing transaction logs to cloud I have an app that uses a single UIManagedDocument as the data store which I access through  a singleton using the method in Justin Driscoll's blog.
This works fine, but when I set my ubiquity keys for the persistentStoreOptions and change state notifications, the app only runs in the sandbox and there is no network activity.
Here is the execution flow ...
1. App opens to a landing screen where the singleton is created.
2. Once the UIManagedDocument is open I check for cloud permissions and if all is good to go and we have a ubiquity container, I overwrite the persistentStoreOptions with the cloud contentNameKey and contentUrlKey options.
Here is the code …
//  DataStore.h

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>

typedef void (^OnDocumentReady) (UIManagedDocument *appDataStore);

@interface DataStore : NSObject

@property (strong, nonatomic) UIManagedDocument *appDataStore;

+ (DataStore *)sharedDocumentHandler;
- (void)performWithDocument:(OnDocumentReady)onDocumentReady;

@end

//  DataStore.m
#import "DataStore.h"
#import "HashDefines.h"

@interface DataStore ()

@property (nonatomic)BOOL preparingDocument;
@property (nonatomic, strong) NSFileCoordinator *coordinator;

@property (strong, nonatomic) NSString *localDocumentsPath;
@property (strong, nonatomic) NSURL *localDocumentsURL;
@property (strong, nonatomic) NSURL *localFileURL;

@end;

@implementation DataStore

@synthesize appDataStore = _appDataStore;
@synthesize localDocumentsPath = _localDocumentsPath;
@synthesize localDocumentsURL = _localDocumentsURL;
@synthesize localFileURL = _localFileURL;

static DataStore *_sharedInstance;
@synthesize coordinator = _coordinator;

#define LOCAL_DATA_STORE_FILE_NAME @"QR App DataStore"

#pragma mark - synthesiser overiders

+ (DataStore *)sharedDocumentHandler
{
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        _sharedInstance = [[self alloc] init];
    });

    return _sharedInstance;
}

#pragma mark - Key Paths

#pragma mark Local Documents
- (NSString *) localDocumentsPath
{
    if (!_localDocumentsPath) {
        _localDocumentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    }

    return _localDocumentsPath;
}

- (NSURL *) localDocumentsURL
{
    if (!_localDocumentsURL) {
        _localDocumentsURL = [NSURL fileURLWithPath:self.localDocumentsPath];
    }

    return _localDocumentsURL;
}

#pragma mark - File URLs

- (NSURL *) localFileURL: (NSString *) filename
{
    if (!filename) return nil;
    NSURL *fileURL = [[self localDocumentsURL] URLByAppendingPathComponent:filename];
    return fileURL;
}

#pragma mark - the juicy bits

#pragma mark - initialisers

- (id)init
{
    self = [super init];
    if (self) {

        NSLog(@"appDataStore does NOT exist ... building one now");

        [self initCoreDataInTheSandbox];

    }
    return self;
}

- (void)initCoreDataInTheSandbox
{
    NSURL *localURL = [self localFileURL:LOCAL_DATA_STORE_FILE_NAME];
    self.appDataStore = [[UIManagedDocument alloc] initWithFileURL:localURL];

    // Set our document up for automatic migrations
    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                             [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                             [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
    self.appDataStore.persistentStoreOptions = options;

    NSLog(@"1. DS persistentStoreOptions: %@", self.appDataStore.persistentStoreOptions);
}

- (void)performWithDocument:(OnDocumentReady)onDocumentReady
{
    NSLog(@"1. DS Begin performWithDocument: %@", self.appDataStore);

    void (^OnDocumentDidLoad)(BOOL) = ^(BOOL success) {
        onDocumentReady(self.appDataStore);
        NSLog(@"2. DS into the block ... onDocumentReady:");
        self.preparingDocument = NO; // release in completion handler
    };

    if(!self.preparingDocument) {
        NSLog(@"3. DS preparing document: dataStore.appDataStore: %@", self.appDataStore);

        // "lock", so no one else enter here
        self.preparingDocument = YES;

        if(![[NSFileManager defaultManager] fileExistsAtPath:[self.appDataStore.fileURL path]]) {
            NSLog(@"4. DS creating document: dataStore.appDataStore: %@", self.appDataStore);
            [self.appDataStore saveToURL:self.appDataStore.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:OnDocumentDidLoad];
            [self.appDataStore openWithCompletionHandler:OnDocumentDidLoad];
        } else if (self.appDataStore.documentState == UIDocumentStateClosed) {
            NSLog(@"5. DS dataStore.appDataStore.documentState: %d ... closed", self.appDataStore.documentState);
            [self.appDataStore openWithCompletionHandler:OnDocumentDidLoad];
        } else if (self.appDataStore.documentState == UIDocumentStateSavingError) {
            NSLog(@"6. DS dataStore.appDataStore.documentState: %d ... saving error", self.appDataStore.documentState);
            [self.appDataStore openWithCompletionHandler:OnDocumentDidLoad];
        } else if (self.appDataStore.documentState == UIDocumentStateNormal) {
            NSLog(@"7. DS dataStore.appDataStore.documentState: %d ... open", self.appDataStore.documentState);
            OnDocumentDidLoad(YES);
        }
    } else {
        // try until document is ready (opened or created by some other call)
        NSLog(@"8. DS preparing document - NOT ... trying again");
        [self performSelector:@selector(performWithDocument:) withObject:onDocumentReady afterDelay:0.5];
    }

    NSLog(@"9. DS Exiting performWithDocument: %@", self.appDataStore);
}

@end

// CloudConnector.h
#import "DataStore.h"

@interface CloudConnector : NSObject

- (void)hookUpCloudForDocument:(UIManagedDocument *)document;

(NSManagedObjectContext*)managedObjectContext;
- (NSString *) documentState: (int) state;

@end

#define ICLOUD_TOKEN_KEY @"com.apple.QR-App.UbiquityIdentityToken"
#define CLOUD_IS_UBIQUITOUS @"sweet ubiquity"
#define LOCAL_DATA_STORE_FILE_NAME @"QR App DataStore"
#define CLOUD_DATA_STORE_FILE_NAME @"com~app~QR-App~cloudstore"

//CloudConnector.m
#import "CloudConnector.h"
#import "HashDefines.h"

@interface CloudConnector ()

@property (strong, nonatomic) NSString *localDocumentsPath;
@property (strong, nonatomic) NSURL *localDocumentsURL;
@property (strong, nonatomic) NSURL *localFileURL;
@property (strong, nonatomic) NSURL *ubiquityDataFileURL;

@property (nonatomic)BOOL preparingDocument;
@property (nonatomic, strong) NSFileCoordinator *coordinator;

- (NSURL *) localFileURL: (NSString *) filename;
- (NSURL *) ubiquityDataFileURL: (NSString *) filename;
- (BOOL) isLocal: (NSString *) filename;
- (NSString *) documentState: (int) state;

@end;

@implementation CloudConnector

@synthesize coordinator = _coordinator;
@synthesize localDocumentsPath = _localDocumentsPath;
@synthesize localDocumentsURL = _localDocumentsURL;
@synthesize localFileURL = _localFileURL;
@synthesize  ubiquityDataFileURL = _ubiquityDataFileURL;

#pragma mark - synthesiser overiders

#pragma mark - the juicy bits

- (void)checkUbiquityStatus
{
    id currentiCloudToken = [[NSFileManager defaultManager] ubiquityIdentityToken];

    if (currentiCloudToken) {
        NSData *newTokenData =
        [NSKeyedArchiver archivedDataWithRootObject: currentiCloudToken];
        [[NSUserDefaults standardUserDefaults]
         setObject: newTokenData
         forKey: ICLOUD_TOKEN_KEY];
    } else {
        [[NSUserDefaults standardUserDefaults]
         removeObjectForKey: ICLOUD_TOKEN_KEY];
    }
}

#pragma mark - Key Paths

#pragma mark Local Documents
- (NSString *) localDocumentsPath
{
    if (!_localDocumentsPath) {
        _localDocumentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    }

    return _localDocumentsPath;
}

- (NSURL *) localDocumentsURL
{
    if (!_localDocumentsURL) {
        _localDocumentsURL = [NSURL fileURLWithPath:self.localDocumentsPath];
    }

    return _localDocumentsURL;
}

#pragma mark - File URLs
- (NSURL *) localFileURL: (NSString *) filename
{
    if (!filename) return nil;
    NSURL *fileURL = [[self localDocumentsURL] URLByAppendingPathComponent:filename];
    return fileURL;
}

- (NSURL *) ubiquityDataFileURL: (NSString *) filename forContainer: (NSString *) container
{
    if (!filename) return nil;
    NSURL *fileURL = [[self ubiquityDataURLForContainer:container] URLByAppendingPathComponent:filename];
    return fileURL;
}

- (NSURL *) ubiquityDataFileURL: (NSString *) filename
{
    return [self ubiquityDataFileURL:filename forContainer:nil];
}

#pragma mark Ubiquity Data
- (NSURL *) ubiquityDataURLForContainer: (NSString *) container
{
    return [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:container];
}

- (NSArray *) contentsOfUbiquityDataFolderForContainer: (NSString *) container
{
    NSURL *targetURL = [self ubiquityDataURLForContainer:container];
    if (!targetURL) return nil;

    NSArray *array = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:targetURL.path error:nil];
    return array;
}

- (BOOL) isLocal: (NSString *) filename
{
    if (!filename) return NO;
    NSURL *targetURL = [self localFileURL:filename];
    if (!targetURL) return NO;
    return [[NSFileManager defaultManager] fileExistsAtPath:targetURL.path];
}

- (NSString *) documentState: (int) state
{
    if (!state) return @"Document state is normal";

    NSMutableString *string = [NSMutableString string];
    if ((state & UIDocumentStateClosed) != 0)
        [string appendString:@"Document is closed\n"];
    if ((state & UIDocumentStateInConflict) != 0)
        [string appendString:@"Document is in conflict"];
    if ((state & UIDocumentStateSavingError) != 0)
        [string appendString:@"Document is experiencing saving error"];
    if ((state & UIDocumentStateEditingDisabled) != 0)
        [string appendString:@"Document editing is disbled" ];

    return string;
}

#pragma mark - initialisers

- (void)hookUpCloudForDocument:(UIManagedDocument *)document
{
    // checking for ubiquity
    NSLog(@"checking for ubiquity");

    [self checkUbiquityStatus];

    // THE FOLLOWING CODE DOESN'T WORK
    if ([[NSUserDefaults standardUserDefaults] objectForKey:ICLOUD_TOKEN_KEY]) {
        // cloud permissions are good to go.
        NSLog(@"cloud permissions are good to go.");

        dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
            NSURL *url = [[NSFileManager defaultManager]
                          URLForUbiquityContainerIdentifier: nil];

            NSLog(@"bikky url: %@", url);

            if (url) { // != nil) {
                // Your app can write to the ubiquity container

                dispatch_async (dispatch_get_main_queue (), ^(void) {
                    // On the main thread, update UI and state as appropriate

                    [self setupCoreDataInTheCloudForDocument:document];
                });
            }
        });
    }
}

- (void) setupCoreDataInTheCloudForDocument:(UIManagedDocument *)document
{
    NSLog(@"1. cc.setupCoreDataInTheCloudForDocument: %@", document);

    NSURL *localURL = [self localFileURL:LOCAL_DATA_STORE_FILE_NAME];
    NSURL *cloudURL = [self ubiquityDataFileURL:CLOUD_DATA_STORE_FILE_NAME];

    // Set the persistent store options to point to the cloud
    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
//                             [document.fileURL lastPathComponent], NSPersistentStoreUbiquitousContentNameKey,
                             localURL, NSPersistentStoreUbiquitousContentNameKey,
                             cloudURL, NSPersistentStoreUbiquitousContentURLKey,
                             [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                             [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
                             nil];

    document.persistentStoreOptions = options;
    NSLog(@"2. cc.document.persistentStoreOptions: %@", document.persistentStoreOptions);

    // Register as presenter
    self.coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:document];
    [NSFileCoordinator addFilePresenter:document];

//    // THIS CODE IS INLINE FROM iOS 5 COOK BOOK
//    // I EXECUTE THIS IN (void)performWithDocument:(OnDocumentReady)onDocumentReady
//
//    // Check at the local sandbox
//    if ([self isLocal:LOCAL_DATA_STORE_FILE_NAME])
//    {
//        NSLog(@"Attempting to open existing file");
//        [document openWithCompletionHandler:^(BOOL success){
//            if (!success) {NSLog(@"Error opening file"); return;}
//            NSLog(@"File opened");
//        }];
//    }
//    else
//    {
//        NSLog(@"Creating file.");
//        // 1. save it out, 2. close it, 3. read it back in.
//        [document saveToURL:localURL
//                    forSaveOperation:UIDocumentSaveForCreating
//                   completionHandler:^(BOOL success){
//                       if (!success) { NSLog(@"7. Error creating file"); return; }
//                       NSLog(@"File created");
//                       [document closeWithCompletionHandler:^(BOOL success){
//                           NSLog(@"Closed new file: %@", success ? @"Success" : @"Failure");
//
//                           [document openWithCompletionHandler:^(BOOL success){
//                               if (!success) {NSLog(@"Error opening file for reading."); return;}
//                               NSLog(@"File opened for reading.");
//                           }];
//                       }];
//                   }];
//    }
//}

@end

I call the singleton as follows …
- (void)viewDidLoad
{
    [super viewDidLoad];

    if (!self.codeGeneratorDataStore) {

        NSLog(@"MVC.viewDidLoad: Grab local instance of document from data store singleton");

        [[DataStore sharedDocumentHandler] performWithDocument:^(UIManagedDocument *document) {
            self.codeGeneratorDataStore = document;
            // Do stuff with the document, set up a fetched results controller, whatever.
//            NSLog(@"IN:  _codeGeneratorDataStore.documentState : %u", _codeGeneratorDataStore.documentState);

            if (![self.codeGeneratorDataStore.persistentStoreOptions objectForKey:NSPersistentStoreUbiquitousContentNameKey]) {
                NSLog(@"MVC.viewDidLoad: We have a document, hooking up cloud now ... \n%@", document);
                [self.cloudConnector hookUpCloudForDocument:self.codeGeneratorDataStore];
            }

            [self setupFetchedResultsController];
        }];

        NSLog(@"GVC.viewDidLoad: Subscribing to notifications");
        [self subscribeToCloudNotifications];

    }

    [self checkDocumentStatus];
}

Then I check the document status …
- (void)checkDocumentStatus {

    NSLog(@"MVC.checkDocumentStatus\n Document: %@\n persistentStoreOptions: %@", self.codeGeneratorDataStore, self.codeGeneratorDataStore.persistentStoreOptions);
    if (![[
           NSFileManager defaultManager] fileExistsAtPath:[self.codeGeneratorDataStore.fileURL path]]) {
        [self.codeGeneratorDataStore saveToURL:self.codeGeneratorDataStore.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
            NSLog(@"1. MVC self.codeGeneratorDataStore.documentState: %@", [NSString stringWithFormat:@"%u", self.codeGeneratorDataStore.documentState]);
        }];
    } else if (self.codeGeneratorDataStore.documentState == UIDocumentStateClosed) {
        [self.codeGeneratorDataStore openWithCompletionHandler:^(BOOL succes) {
            NSLog(@"2. MVC self.codeGeneratorDataStore.documentState: %@", [NSString stringWithFormat:@"%u", self.codeGeneratorDataStore.documentState]);
        }];
    } else if (self.codeGeneratorDataStore.documentState == UIDocumentStateNormal) {
        NSLog(@"3. MVC self.codeGeneratorDataStore.documentState: %@", [NSString stringWithFormat:@"%u", self.codeGeneratorDataStore.documentState]);
    }
}

Setup and register for notifications ...
- (void)subscribeToCloudNotifications
{
    // subscribe to the NSPersistentStoreDidImportUbiquitousContentChangesNotification notification
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(documentStateChanged:)
                                                 name:UIDocumentStateChangedNotification
                                               object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(documentContentsDidUpdate:)
                                                 name:NSPersistentStoreDidImportUbiquitousContentChangesNotification
                                               object:nil];

    NSLog(@"MVC.subscribeToCloudNotifications: notification subscriptions are good to go");
}

- (void) documentContentsDidUpdate: (NSNotification *) notification
{
    NSLog(@"CMVC notification: documentContentsDidUpdate");

    NSDictionary *userInfo = notification.userInfo;
    [self.codeGeneratorDataStore.managedObjectContext performBlock:^{[self mergeiCloudChanges:userInfo forContext:self.codeGeneratorDataStore.managedObjectContext];}];
}

// When notified about a cloud update, start merging changes
- (void)documentStateChanged: (NSNotification *)notification
{
    NSLog(@"CMVC notification: documentStateChanged");
//    NSLog(@"Document state change: %@", [CloudHelper documentState:self.codeGeneratorDataStore.documentState]);

    UIDocumentState documentState = self.codeGeneratorDataStore.documentState;
    if (documentState & UIDocumentStateInConflict)
    {
        // This application uses a basic newest version wins conflict resolution strategy
        NSURL *documentURL = self.codeGeneratorDataStore.fileURL;
        NSArray *conflictVersions = [NSFileVersion unresolvedConflictVersionsOfItemAtURL:documentURL];
        for (NSFileVersion *fileVersion in conflictVersions) {
            fileVersion.resolved = YES;
        }
        [NSFileVersion removeOtherVersionsOfItemAtURL:documentURL error:nil];
    }
}

// Merge the iCloud changes into the managed context
- (void)mergeiCloudChanges:(NSDictionary*)userInfo forContext:(NSManagedObjectContext*)managedObjectContext
{
    @autoreleasepool
    {
        //        NSLog(@"Merging changes from cloud");

        NSMutableDictionary *localUserInfo = [NSMutableDictionary dictionary];

        NSSet *allInvalidations = [userInfo objectForKey:NSInvalidatedAllObjectsKey];
        NSString *materializeKeys[] = { NSDeletedObjectsKey, NSInsertedObjectsKey };

        if (nil == allInvalidations)
        {

            // (1) we always materialize deletions to ensure delete propagation happens correctly, especially with
            // more complex scenarios like merge conflicts and undo.  Without this, future echoes may
            // erroreously resurrect objects and cause dangling foreign keys
            // (2) we always materialize insertions to make new entries visible to the UI

            int c = (sizeof(materializeKeys) / sizeof(NSString *));
            for (int i = 0; i < c; i++)
            {
                NSSet *set = [userInfo objectForKey:materializeKeys[i]];
                if ([set count] > 0)
                {
                    NSMutableSet *objectSet = [NSMutableSet set];
                    for (NSManagedObjectID *moid in set)
                        [objectSet addObject:[managedObjectContext objectWithID:moid]];

                    [localUserInfo setObject:objectSet forKey:materializeKeys[i]];
                }
            }

            // (3) we do not materialize updates to objects we are not currently using
            // (4) we do not materialize refreshes to objects we are not currently using
            // (5) we do not materialize invalidations to objects we are not currently using

            NSString *noMaterializeKeys[] = { NSUpdatedObjectsKey, NSRefreshedObjectsKey, NSInvalidatedObjectsKey };
            c = (sizeof(noMaterializeKeys) / sizeof(NSString*));
            for (int i = 0; i < 2; i++)
            {
                NSSet *set = [userInfo objectForKey:noMaterializeKeys[i]];
                if ([set count] > 0)
                {
                    NSMutableSet *objectSet = [NSMutableSet set];
                    for (NSManagedObjectID *moid in set)
                    {
                        NSManagedObject *realObj = [managedObjectContext objectRegisteredForID:moid];
                        if (realObj)
                            [objectSet addObject:realObj];
                    }

                    [localUserInfo setObject:objectSet forKey:noMaterializeKeys[i]];
                }
            }

            NSNotification *fakeSave = [NSNotification notificationWithName:NSManagedObjectContextDidSaveNotification object:self userInfo:localUserInfo];
            [managedObjectContext mergeChangesFromContextDidSaveNotification:fakeSave];

        }
        else
            [localUserInfo setObject:allInvalidations forKey:NSInvalidatedAllObjectsKey];

        [managedObjectContext processPendingChanges];

        //        [self performSelectorOnMainThread:@selector(performFetch) withObject:nil waitUntilDone:NO];
    }
}

and we're good to go - the app runs but with no network activity. Why aren't the transaction logs being uploaded?
Any assistance would be greatly appreciated here. Its been doing my head in for a week now and i'm at my wit's end.

A: I answered this question previously in email, but I'm positing my answer here as well for completeness.
Is this an iOS 7-only app, or does it need to support iOS 5 or 6 as well?
I would not recommend mixing iCloud and Core Data in anything that still has to support iOS 5 and 6. However, the new support for iOS 7 seems pretty solid. I haven't deployed a multi-million user app with it—so I wouldn't say it's battle tested, but it seems to be a lot more robust. In my preliminary testing, it handled everything I threw at it with no problems.
Also, is the sample code that you're following up-to-date for iOS 7? It looks like it's following some older patterns. This could cause a lot of problems, since the way the system operates has changed considerably in iOS 7.
For example, in iOS 7, we generally only need to set the NSPersistentStoreUbiquitousContentNameKey. Unless we're trying to support a legacy core data stack, we don't need to set the content URL key.
Also, there is a huge difference in how the core data stack is set up under iOS 7. When we first set up an iCloud persistent store, iOS 7 will create a local copy (the fallback store) for us automatically. We can use the store—but the changes will only be stored locally. When the iCloud version is ready, it will then send a NSPersistentStoreCoordinatorStoresWillChangeNotification. We're supposed to save any changes and then reset our managed object context.
Again, it looks like your code is manually setting up its own fallback store—which may be part of the problem.
If you're working from old examples, I'd actually recommend throwing that code away and starting over. Watch the "What's New in Core Data and iCloud" video from WWDC 2013. It does a great rundown on the new technologies, and the current best practices.
My guess is that you're getting the fallback store, but it's never switching over to the iCloud store. Look in the console log when you run the app. You should see something like the following:
-[PFUbiquitySwitchboardEntryMetadata setUseLocalStorage:](754): CoreData: p Ubiquity:
 mobile~C9C8554A-BD44-43C3-AC54-603046EF0162:com~freelancemad p science~HealthBeat

Using local storage: 1

Here, "Using local storage: 1" means you're using the fallback store. In a minute or two (or sometimes longer) you'll see a similar message with "Using local storage: 0". That means you're now using the iCloud store.
Also, when you run the application, be sure to open the Debug Navigator in Xcode. It should have a profiler for iCloud, that shows you whenever data was uploaded to or downloaded from the cloud.
I hope that helps,
-Rich-


text:
Q: Cfhttp and mailgun api I've been trying to configure Mailgun API with Coldfusion's Cfhttp and can't figure out the format to pass the variables. I configured it in about 5 minutes with Python, and have to roll it to a Coldfusion front end. I've used the same basic structure as I did in Python, and it all works great in Python.
I've been able to make a connection, but I have not been able to send mail. I know it has to do with the structure, and I can't find a working example anywhere.
How do you build the cfhttp to pass the required data?  Is the data=data I would use in the request in Python the same as a cfhttpparam in ColdFusion?  And is it a header, or a body?
My Coldfusion code is below, i've replaced secret information with domain.com

<cfscript>
mailgun_variables = '{
    "company_id": 1008,
    "company_contact": "Joe Smith",
    "random_key": "91A303C8-91FB-AA1D-DE07F18782594721"
    }';

data= '{
    "from": "email@domain.com",
    "to": "email@domain.com",
    "subject": "Subject line",
    "template": "welcome",
    "o:tag": ["welcome", "welcome-countdown", "welcome-alt", "coldfusion"],
    "h:X-Mailgun-Variables": #mailgun_variables#}';
</cfscript>

<cfhttp url="https://api.mailgun.net/v3/domain.com/messages"
        method="POST"
        username="api"
        password="APIKEY"
        result="response" >
    <cfhttpparam type="header" name="Content-Type" value="application/json" />
    <cfhttpparam type="header" name="data" value="#serializeJSON(data)#">
</cfhttp>

My error message is a 400 Bad request, {"message":"from parameter is missing"}.
Any guidance or links to examples would be much appreciated. Or maybe you can obviously spot what I am doing wrong?

A: I ended up having to do a lot of trial and error, but have working code if anyone else ever runs into this issue.  Mailgun support was no help.
The answer ended up being that everything had to be passed as cfhttpparam formfields.  I also ran into a lot of challenges with tagging and using template variables, but got it all worked out.
I added it to Github for anyone to use, and will continue to improve it there as I get more in-depth with it.
https://github.com/convurt/Mailgun-Coldfusion-Sendmail
cfhttp(method="POST", url="https://api.mailgun.net/v3/DOMAIN.COM/messages", result="response", username="api", password="MAILGUN API KEY") {
cfhttpparam(name="from", type="formfield", value="#email_from#");
cfhttpparam(name="h:Reply-To", type="formfield", value="#reply_to#");
cfhttpparam(name="to", type="formfield", value="#email_to#");
cfhttpparam(name="subject", type="formfield", value="#email_subject#");
// loop over tag list, I could not get it to work correctly as a list
for (t in tags) {
    cfhttpparam(name="o:tag", type="formfield", value="#t#");
}
cfhttpparam(name="template", type="formfield", value="#template#");
// custom paramamter for template
cfhttpparam(name="t:variables", type="formfield", value="#t_variables#");


text:
Q: How to pivot this tables using entity framework linq My table structure is here
Product table (Repo.Products)
ID ProductName
02 Computer
Property table (Repo.Properties)
ID PropertyName
03 CPU
04 RAM
Product Property table (Repo.ProductProperties)
ID ProductID PropertyID Value
01 02 03 1300
02 02 04 1024
My target output is
Product Name CPU RAM
Computer 1300 1024
How to do using Entity Framework 4.0 ?


text:
Q: Puppeteer: Make browser seem less like a robot/script So basically I was just wondering if there are any ways to make a Puppeteer browser more believeable to a website in that they think it's an actual user and not a script. I already have a user-agent set using:
await page.setUserAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3844.0 Safari/537.36");

But almost all the buttons on the site that result in POST requests such as login buttons do nothing because it recognises the clicks, etc as not a legitimate user hence me wondering if there is anything else I can do when launching the browser to fix this apart from setting a user-agent...
Any help is appreciated!

A: Have you tried using {slowMo: intValue} in puppeteer.launch() options?
Maybe instead of using page.click() on the element, specify a mouse position, and move it a few times over the button, before clicking?
Try navigating the page yourself, within the puppeteer browser - using on keypresses (tab etc..) and see if that works? Then combine it w/ slowMo in a script?
I know there's also a puppeteer-extra-stealth library out there which does a lot of extra things in an attempt to obscure the client.


text:
Q: I have problems defining logarithmic axis values I'm using matplotlib, pyplot to draw some functions with plot.
I need y axis to be between (0.0001,0.1) and x axis to be between (100,10000), so I'm using axis([100, 10000, 0.0001, 0.1]).
But this does not work with my defined values.
I try:
plt.plot((100,10000),(0.0001,0.1))
plt.axis([100, 10000, 0.0001, 0.1])
plt.show()

and I get:


text:
Q: Multithreading with an database (mysql or oracle) Am writing a multithreading application that has several threads(approxiamately 25) with each thread performing a specific process and then updating the database in the which then gives the next thread the permission to process another process and do the same. Basically, thread1 does process then updates db as complete then when thread two reads the db as complete it begins processing and the process continues until thread 25. Anyone know how this is possible in java?

A: You can retrieve data (using select query) with a simple logic in each threads, but for updating the data, it is recommended to execute the query in a synchronized block. Since other threads are dependent on the data being modified by this thread, it may cause problem while fetching the records.

A: Why 25 exactly?
Anyway what you are saying is certainly possible but you might want to create a special thread  which gets the resulting value each thread has computed and submit it to the database.
That way you need to have one thread which may access the database and all the other threads don't have to wait for the database.

A: Your question is incredibly general but the approach I'd take would be something like:

*

*designate one thread as the controller thread.  It's job is to listen for the worker threads to complete their processing.  The simplest way to do with is with a semaphore object and the wait/notify methods - the controller thread would take a lock on the semaphore and then call wait.

*create your worker threads, each with its own semaphore object against which each thread takes a lock on and again calls wait.

*the trigger to start the processing (this could be the application running, the user clicking a button, etc) obtains a lock on the controller's semaphore and calls notify against it waking the controller thread.  The controller's job is to pick one of the worker threads from the pool, obtain a lock on its semaphore and the call notify causing the worker to awake.  The controller then calls wait on its own semaphore.

*the worker thread can then read the database, does the processing and write back to the database before it calls notify on the controller's semaphore causing the process to start again with the controller calling notify on one of the worker threads' semaphores and wait against its own .
Finally a word of warning, this is a very brief outline of what's required to implement the general behaviour you've described.  Threading is possbily the most misunderstood topics in computer science imho and very very easy to get wrong.  Before leaping into a multi-threaded system make sure at the very least you've read Brian Goatz's - Java Concurrency In Practice

A: I am not sure I get your requirements fully, but here is a high level algorithm:

*

*Create the required number of threads and put them in an Array.

*Now starting from the second thread to the last, each thread must do a join() on the previous thread; this will facilitate that each thead runs it processing and updating part after its previous has finished.
Possible code:
Thread class declaration
class WaitingThread extends Thread
{
    private Thread previousThread;

    public WaitingThread(final Thread previous)
    {
        this.previousThread = previous;
    }

    public void run()
    {
        doParallelTask();

        if(previousThread != null)
        {
             previousThread.join();
        }

        doProcesingAndUpdating();
    }
}

The array declaration and initialisation;
    final Thread [] threads = new Thread[25];

    for(int i = 0; i < 25; i++)
    {
        if(i == 0)
        {
            threads[i] = new WaitinThread(null);
        }
        else
        {
            threads[i] = new WaitingThread(threads[i - 1]);
        }
    }

Hope this helps.
PS: I must admit, in the above model it makes more sense to do the doParallelTask() using multiple threads, and doing the 25 doProcessingAndUpdate() using a single thread.


text:
Q: Member specialization does not match any template declaration The code below compiles except for the lines
template <> std::map<std::string, std::function<Goo*(Foo*)>>& Factory::getMap<Goo, Foo*>() {
    return gooMap;
}

What is wrong here, and how would it be fixed?  The compiler (GCC 11.2) states that the member specialization does not match any template declaration, but to me it looks like it does.
#include <map>
#include <functional>

struct Foo;  struct Goo;

struct Factory {
    std::map<std::string, std::function<Foo*()>> fooMap;
    std::map<std::string, std::function<Goo*(Foo*)>> gooMap;

    template <typename T, typename U, typename... Args>
    std::function<T*(Args&&...)> create() {
        return [](Args&&... args) -> T* { return new U(std::forward<Args>(args)...); };
    }

    template <typename T, typename... Args>
    std::map<std::string, std::function<T*(Args&&...)>>& getMap();

    template <typename T, typename U, typename... Args>
    void registerFunction (const std::string& name) {
        getMap<T, Args...>()[name] = create<T, U, Args...>();
    }
};
template <> std::map<std::string, std::function<Foo*()>>& Factory::getMap<Foo>() {
    return fooMap;
}
template <> std::map<std::string, std::function<Goo*(Foo*)>>& Factory::getMap<Goo, Foo*>() {
    return gooMap;
}

int main() {}


text:
Q: unconverted data remains: 15 I am trying to generate a random date and the add some days to that date, but I am facing this error. I guess it has to do with the format of my date but I can't find the solution.
I thought it was because I needed double digit numbers for the day and month, here is my code which produces an error.
start_day = randint(1,31)
strt_day = []
strt_day.append("%02d" % start_day)
start_day = strt_day

strt_moth = []
start_month = randint(2,4)
strt_moth.append("%02d" % start_month)
start_month = strt_moth

start_date = ""+start_month[0]+"/"+start_day[0]+"/2015"
depart = datetime.datetime.strptime(start_date, "%m/%d/%y")

Any idea on what I am doing wrong?
Thanks

A: Because %y is for a two-digit year, so 2015 is interpreted as 20 (i.e. 2020) and the 15 is left over:
>>> import datetime
>>> datetime.datetime.strptime("01/02/20", "%d/%m/%y")
datetime.datetime(2020, 2, 1, 0, 0)
>>> datetime.datetime.strptime("01/02/2015", "%d/%m/%y")

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    datetime.datetime.strptime("01/02/2015", "%d/%m/%y")
  File "C:\Python27\lib\_strptime.py", line 328, in _strptime
    data_string[found.end():])
ValueError: unconverted data remains: 15

You want %Y (note case!), which is a four-digit year:
>>> datetime.datetime.strptime("01/02/2015", "%d/%m/%Y")
datetime.datetime(2015, 2, 1, 0, 0)

You should read through the docs, which explain the various format directives.

However, the extra steps involving strings seem pointless, why not just pass the integers you create to datetime.datetime?
>>> import random
>>> random.seed(0)
>>> datetime.datetime(2015, random.randint(2, 4), random.randint(1, 31))
datetime.datetime(2015, 4, 24, 0, 0)

Note that this might generate invalid dates (e.g. February doesn't have a 30th!):
>>> random.seed(8)
>>> datetime.datetime(2015, random.randint(2, 4), random.randint(1, 31))

Traceback (most recent call last):
  File "<pyshell#28>", line 1, in <module>
    datetime.datetime(2015, random.randint(2, 4), random.randint(1, 31))
ValueError: day is out of range for month


text:
Q: Limit when $x$ converges to $0$ Can someone please help me with this simple limit problem, I do not know what to do here because its undefined $0/0$
$$\lim_{x \to 0} \frac{e^{1/x}}{\sqrt{x}}.$$

A: $$\lim_{x\rightarrow0^+}\frac{e^{\frac{1}{x}}}{\sqrt{x}}=\lim_{x\rightarrow+\infty}\sqrt{x}e^{x}=+\infty$$

A: $$\lim_{x\to0}\frac{e^{1/x}}{\sqrt{x}} = \frac{\lim_{x\to0} e^{1/x}}{\lim_{x\to0} \sqrt{x}} = \frac{\infty}{0} = \infty$$


text:
Q: Using Python module cffi in Yocto recipe I am trying to use the Python module cffi in a Yocto/OE recipe. I want to use the module in the recipe, not include it in the target image.
It works on my local machine, but fails on our build server with the following message:
Exception: Exception: Version mismatch: this is the 'cffi' package version 1.14.5, located in '<build directory of recipe that uses cffi>/1.0-r0/recipe-sysroot-native/usr/lib/python3.8/site-packages/cffi/api.py'.  When we import the top-level '_cffi_backend' extension module, we get version 1.11.5, located in '/usr/lib/python3/dist-packages/_cffi_backend.cpython-36m-x86_64-linux-gnu.so'.  The two versions should be equal; check your installation.

The problem seems to be that there are two Python versions on the build server. The host machine has version 3.6 installed. And OE also builds version 3.8 itself ("native"). What happens is that the cffi backend is built using the native Python version. (The script setup.py that seems to control the build process for the backend explicitly calls the native Python in distutils3.bbclass.)
However the task in the recipe where I want to use cffi is executed with the host Python - although I inherit python3native. This version seems to look for shared libraries in /usr/lib/python3 where it finds an outdated version of the cffi backend.
Why are different Python versions used for building cffi and for executing the depending recipe?
Which one should really be used - the host system's or the native one?
How can I control which one is used?


text:
Q: Can you add or remove Service Fabric statefull service named partitions It is mentioned in the documentation that we cannot change the partition count on service fabric statefull services after the service is deployed. Is it the similar case if named partitions are used. Can we add or remove new named partitions to the statefull service in its lifetime, is there a side effect ?

A: As a general rule, no, the partitions cannot be modified after the service is created regardless of how you approach it (e.g. Int64, Named, or Singleton). The definition is indicated in your ApplicationManifest.xml and should not change.
That said if you estimated the partition count incorrectly when you originally designed the solution, there's no particular reason you can't simply create a v2 of your service with the newly realized partition count and either introduce logic in it or create a (likely singleton) stateless migration service to move your data from one service to the other, mapping the data between the partitions as you see fit.
Once migrated, you could save a backup of your state in either service (just in case), update the references in your solution to point to the new service and delete the old.
It's not as clean as some provided migration experience, but it does get the job done.


text:
Q: GameObjects and Code Structure I have the following GameObject interface:
public interface GameObject {
     void viewDetails();
}

Character Interface:
interface Character{
    void pickUp(Weapon weapon);
    void use(Weapon weapon);
}

and abstract Weapon class:
public abstract class Weapon implements GameObject {

  //left out constructor to focus on methods

   @Override
   public abstract void viewDetails();
   public abstract void attack(Enemy enemyObj);
   //Could be bullets, could be a mystical item.
   public abstract void replenish(ReplenishItem rpItem);
}

The problem with this is, a GameObject sometimes can be used in different ways.
For example, the primary use of a game weapon is to attack a target, but what if I wanted to reload? How do I let my character interface reload or beware that reload is an option?

A: I would use the following approach.
I would declare interfaces:
interface MeleeWeapon {
    void hit();
    void cut();
}

interface FirearmWeapon {
   void fire();
   void reload();
}

interface MagicWeapon {
   void throw();
   void apply();
   void recharge();
}

Then implement classes, like these:
class Knife implements MeleeWeapon {
     public void hit() {

     }

     public void cut() {

     }
}

class Dagger implements MeleeWeapon {
     public void hit() {

     }

     public void cut() {

     }
}

class GarandRifle implements FirearmWeapon {
     public void fire() {

     }

     public void reload() {

     }
}

class Fireball implements MagicWeapon {
     public void throw() {

     }

     public void apply() {

     }

     public void recharge() {

     }
}

Then, I would declare these interfaces:
interface MeleeWeaponUser {
    void use(MeleeWeapon weapon);
}

interface  FirearmWeaponUser {
    void use(FirearmWeapon weapon);
}

interface MagicWeaponUser {
    void use(MagicWeapon weapon);
}

And, I would declare character classes:
class Peasant implements MeleeWeaponUser {
    public void use(MeleeWeapon weapon) {

    }
}

class Marine implements MeleeWeaponUser, FirearmWeaponUser {
    public void use(FirearmWeapon weapon) {

    }

    public  void use(MeleeWeapon weapon) {

    }
}

class Sorcerer implements MeleeWeaponUser, MagicWeaponUser {
    public  void use(MeleeWeapon weapon) {

    }

    public  void use(MagicWeapon weapon) {

    }
}

This approach let us add new weapons and characters without sufficient effort later.
In your use() method you can call reload() if there is no more ammo in the weapon dispenser.
But if your game character receives signal from outside, for example, reload the gun, even there is enough ammo to fire, then have an Event->Listener approach implemented.
Create a WeaponEvent class, extend this class to have FirearmWeaponEvent, MeleeWeaponEvent etc.
Make your game character class(es) as a listener to WeaponEvent events, then in your game character class have a method processEvent(WeaponEvent event), and act accordingly to the event you have received.


text:
Q: How to instantiate Path object using clojure since a Path class does not have public constructor ,so path object are created using get factory method in Paths object.
e.g
Path p2 = Paths.get("/home/admin","Migrations","/blog/tables/6-rating.xml");

//or

Path p2 = Paths.get(new URI("file://home/debianaut/Migrations/blog.sakhunzai/tables/6-rating.xml"));

how we can do this in clojure way ?

A: user> (java.nio.file.Paths/get "/home/justin" (into-array [".lein" "profiles.clj"]))
#<UnixPath /home/justin/.lein/profiles.clj>

varargs java methods need an array containing all remaining args as their final argument.
The first string outside the array is needed in order for the method dispatch to match the right method.
For completeness, here is an example using a URI (much more straightforward):
user> (java.nio.file.Paths/get (java.net.URI. "file:///home/justin"))
#<UnixPath /home/justin>


text:
Q: How to make a background with 45 degree lines with css? Using CSS or CSS3, how can i make the folowing background ?

If possible, i'd like ie6,7,8 support. I can use a javascript based tool to simulate CSS3 for old browsers (like css3pie).

A:
If possible, i'd like ie6,7,8 support.

Use a background image. Even if you could use pure CSS3 to create such a pattern for a background (I highly doubt that is possible), it's not worth the hassle to use a bunch of JavaScript libraries and such just to get it to work in those versions of IE.

A: I use this.
Then you just do background-image:url(blahblahblah.gif)
Any reason you're still supporting IE6? It would be easy to do without IE6 support. IE really sucks for gradient support, so you'll need to use an image, but here's the CSS anyway.
background-color: #0ae;
background-image: -webkit-gradient(linear, 0 0, 0 100%, color-stop(.5, rgba(255, 255, 255, .2)), color-stop(.5, transparent), to(transparent));
background-image: -moz-linear-gradient(rgba(255, 255, 255, .2) 50%, transparent 50%, transparent);
background-image: -o-linear-gradient(rgba(255, 255, 255, .2) 50%, transparent 50%, transparent);
background-image: linear-gradient(rgba(255, 255, 255, .2) 50%, transparent 50%, transparent);

I know this probably doesn't match your image. I'm sorry, but your image host is blocked by my work, so you'll have to interpret from here. This will work with webkit browsers and FF3.6, and will fall back to the color specified in background-color for non-compliant browsers.

A: You have to use a repeating texture square. Find a small ping and use a repeating backround.